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

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

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

我有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信号上,因为我想避免“ double”保存(我有创建/修订字段)。

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

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

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

python django unit-testing factory factory-boy
1个回答
0
投票

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

class GroupFactory():
    ...


    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        # Execute required 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
        group.save()

        return group

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

© www.soinside.com 2019 - 2024. All rights reserved.