工厂男孩-如何创建工厂所需的数据(预生成挂钩)

时间:2019-02-05 08:24:00

标签: python django unit-testing factory factory-boy

注意:我将尝试用简化的场景来解释用例(这对您来说可能真的很奇怪)。

我有2个模型(相关但没有外键):

# models.py
class User(models.Model):
    name = models.CharField()
    age = models.IntegerField()
    weight = models.IntegerField()
    # there are a lot more properties ... 

class Group(models.Model):
    name = models.CharField()
    summary = JSONField()

    def save(self, *args, **kwargs):
        self.summary = _update_summary()
        super().save(*args, **kwargs)
    def _update_summary(self):
        return calculate_group_summary(self.summary)

# this helper function is located in a helper file
def calculate_group_summary(group_summary):
   """calculates group.summary data based on group.users"""
   # retrieve users, iterate over them, calculate data and store results in group_summary object
   return group_summary

对于以上型号,我有这个工厂:

# factories.py
class UserFactory(factory.DjangoModelFactory):
    class Meta:
        model = User

    name = factory.Sequence(lambda n: "user name %d" % n)
    age = randint(10, 90))
    weight = randint(30, 110))

class GroupFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Group

    name = factory.Sequence(lambda n: "group name %d" % n)
    summary = {
        "users": [34, 66, 76],
        "age": {
            "mean": 0,
            "max": 0,
            "min": 0,
        },
        "weight": {
            "mean": 0,
            "max": 0,
            "min": 0,
        } 
    }

特别之处在于,我在group.save()上的字段 group.summary 中更新了JSON数据。
注意:我不喜欢将其移至post_save信号,因为我想避免“双重”保存(我有创建/修订字段)。

所以当我使用GroupFactory()时,我必须要有“用户”。

我正在查看后代挂钩https://factoryboy.readthedocs.io/en/latest/reference.html#post-generation-hooks,但我需要“前代挂钩”。

在创建 GroupFactory 之前是否有“最佳实践”来生成用户数据(在测试用例中无需手动创建它们)?像“后钩”但“前”的东西? :|

1 个答案:

答案 0 :(得分:3)

尝试使用_create()挂钩。像这样:

class GroupFactory():
    ...


    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        # Create the prerequisite data here. 
        # Use `UserFactory.create_batch(n)` if multiple instances are needed.
        user = UserFactory()

        group = model_class(*args, **kwargs)

        # Update other fields here if needed.
        group.foo = bar

        # Required operation.
        group.save()

        return group

参考:https://factoryboy.readthedocs.io/en/latest/reference.html#factory.Factory._create