在 Django 的数据模型工厂的字典中使用 Factory Boy?或者,让 FactoryBoy 按需评估子工厂?

Using Factory Boy inside a dict for a data model factory in Django? Alternatively, getting FactoryBoy to evaluate subfactory on demand?

我有以下模型工厂:

class ProjectDataModelFactory(DjangoModelFactory):
    project = factory.SubFactory("projects.factories.ProjectModelFactory")
    version = "1"
    content = {
        "id": {"value": fuzzy.FuzzyText(length=7, chars=string.ascii_letters).fuzz().upper(), "type": "string"},
        "win_probability": {"value": fuzzy.FuzzyInteger(0, 100).fuzz(), "type": "number"},
        "bid_value": {
            "value": fuzzy.FuzzyInteger(0, 10000000).fuzz(),
            "type": "number",
        },
        "status": {"value": random.choice(["Won", "Lost"]), "type": "string"},
        "sector": {
            "value": random.choice(
                ["Construction", "Technology", "Finance", "Consulting", "Agriculture", "Engineering"]
            ),
            "type": "string",
        },
    } 

content["id"] 中,我想让 value 成为 project.external_id 而不是 fuzzy.FuzzyText(length=7, chars=string.ascii_letters).fuzz().upper(). external_idProjectModel. 的一部分 但是当我把 project.external_id 放在模糊器的地方时,我得到这个错误:

AttributeError: 'SubFactory' object has no attribute 'external_id

这似乎只是听写的问题。我们在其他情况下使用它没有遇到问题。

我没有太多使用 FactoryBoy 的经验,所以它很容易成为微不足道的东西。有什么想法吗?

您遇到第一个问题:当 class 已导入:每个实例将使用完全相同的值。

为了执行延迟评估,您必须将它们包装在一些 factory_boy 提供的声明中:

class ProjectDataModelFactory(DjangoModelFactory):
    project = factory.SubFactory("projects.factories.ProjectModelFactory")
    version = "1"
    content = factory.Dict(
        id=factory.Dict(
            value=fuzzy.FuzzyText(length=7, chars=string.ascii_uppercase),
            type="string",
        ),
        win_probability=factory.Dict(
            value=fuzzy.FuzzyInteger(0, 100),
            type="number",
        ),
        bid_value=factory.Dict(
            value=fuzzy.FuzzyInteger(0, 10_000_000),
            type="number",
        ),
        status=factory.Dict(
            value=fuzzy.FuzzyChoice(["Won", "Lost"]),
            type="string",
        ),
        sector=factory.Dict(
            value=fuzzy.FuzzyChoice(
                ["Construction", "Technology", "Finance", "Consulting", "Agriculture", "Engineering"],
            ),
            type="string",
        ),
    )

factory.Dict(**kwargs) 基本上是 factory.SubFactory(DictFactory, **kwargs) 的别名;然后你可以像使用简单的 SubFactory.

一样使用任何声明

对于您最初的目标,您现在可以轻松使用所有功能:

class ProjectDataModelFactory(DjangoModelFactory):
    project = factory.SubFactory("projects.factories.ProjectModelFactory")
    version = "1"
    content = factory.Dict(
        id=factory.Dict(
            # . is the {"value": x, "type": "string"} dict;
            # .. is {"id": {"value": x, ...}} dict;
            # ... is the ProjectData(content={"id": {...}}) object.
            value=factory.SelfAttribute('...project.external_id'),
            type="string",
        ),
        # Other fields here
    )