FactoryBoy:如何使用Params设置可选属性的权重

问题描述 投票:0回答:1

我想使用 FactoryBoy 创建一些带有可选属性的假数据。我希望能够覆盖该属性为

None
的概率。

python pytest faker factory-boy
1个回答
0
投票
import random
from dataclasses import dataclass

import factory


@dataclass
class Data:
    address: str | None


def optional(decider: str, declaration):
    return factory.Maybe(
        factory.LazyAttribute(
            lambda o: random.random() <= getattr(o, decider)
        ),
        declaration,
        None,
    )


class DataFactory(factory.Factory):
    class Meta:
        model = Data

    class Params:
        has_address_probability = 0.5

    address = optional(
        "has_address_probability",
        factory.Faker("address"),
    )


if __name__ == "__main__":
    data = DataFactory(
        # Optionally override the probability
        has_address_probability=0
    )
    print(data)
© www.soinside.com 2019 - 2024. All rights reserved.