Skip to content

Bug: Examples in union types are not found when using coverage #851

Description

@bullfest

Description

For union types where one of the subtypes are annotated with examples I'd expect those examples to be used when generating values from that subtype.

This works for .build() and .batch(), but breaks when generating coverage.

MCVE

from typing import Annotated

import pydantic
from polyfactory.factories.pydantic_factory import ModelFactory
from pydantic import AfterValidator, Field

the_list = ["foo", "bar", "baz"]  # Some dynamically populated list


def l_validator(v):
    if v not in the_list:
        raise ValueError(f"{v} not in {the_list}")
    return v


TheListType = Annotated[str, AfterValidator(l_validator), Field(examples=the_list)]


class WithoutNone(pydantic.BaseModel):
    f: TheListType


class WithNone(pydantic.BaseModel):
    f: TheListType | None


class WithoutNoneFactory(ModelFactory[WithoutNone]):
    __check_model__ = True
    __use_examples__ = True


class WithNoneFactory(ModelFactory[WithNone]):
    __check_model__ = True
    __use_examples__ = True

# These three works fine
print("Without, batch:", WithoutNoneFactory.batch(2))
print("With, batch:", WithNoneFactory.batch(2))
print("Without, coverage:", list(WithoutNoneFactory.coverage()))
# Breaks here
print("With, coverage:", list(WithNoneFactory.coverage()))

Logs

Without, batch: [WithoutNone(f='bar'), WithoutNone(f='bar')]
With, batch: [WithNone(f='bar'), WithNone(f=None)]
Without, coverage: [WithoutNone(f='foo'), WithoutNone(f='bar'), WithoutNone(f='baz')]
Traceback (most recent call last):
...
pydantic_core._pydantic_core.ValidationError: 1 validation error for WithNone
f
  Value error, JtYDrNsNdqcQNeGCBrfN not in ['foo', 'bar', 'baz'] [type=value_error, input_value='JtYDrNsNdqcQNeGCBrfN', input_type=str]
    For further information visit https://errors.pydantic.dev/2.13/v/value_error

Release Version

3.3.0

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions