Skip to content

Bug: Model coverage generation and __use_examples__ do not compose well #745

@bokrosbalint

Description

@bokrosbalint

Description

When creating instances via factory.coverage(), fields with examples aren't using a random element from the provided ones.

URL to code causing the issue

No response

MCVE

Using:

from typing import Literal

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


class Payment(BaseModel):
    amount: int = Field(0)
    currency: str = Field(examples=['USD', 'EUR', 'INR'])

class PaymentFactory(ModelFactory[Payment]):
    __use_examples__ = True

class Transaction(BaseModel):
    type: Literal['income', 'expense']
    payment: Payment

class TransactionFactory(ModelFactory[Transaction]):
    __use_examples__ = True

while the output of TransactionFactory.build is something like:

Transaction(type='expense', payment=Payment(amount=840, currency='USD'))

the output of list(TransactionFactory.coverage()) is:

[Transaction(type='income', payment=Payment(amount=3948, currency='YOQTUkvMHIgchtSaxKlS')),
 Transaction(type='expense', payment=Payment(amount=3948, currency='YOQTUkvMHIgchtSaxKlS'))]

instead of something like

[Transaction(type='income', payment=Payment(amount=3948, currency='EUR')),
 Transaction(type='expense', payment=Payment(amount=3948, currency='EUR'))]

Same result with adding __set_as_default_factory_for_type__ = True to PaymentFactory or removing it entirely, and relying on TransactionFactory dynamically creating one.

Can be worked around using:

class PaymentFactory(ModelFactory[Payment]):
    __set_as_default_factory_for_type__ = True

    currency = Use(ModelFactory.__random__.choice, Payment.model_fields['currency'].examples)

Seems this is a new addition in #679, so I think it probably just needs some extra wiring to ensure coverage() calls the same things under the hood as build() does?

Steps to reproduce

Screenshots

No response

Logs

Release Version

2.22.2

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

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions