Django Factoryboy-随机选择不使用LazyFunction



我正在为我们的Django应用程序构建许多测试,并且我正在使用Factoryboy

Profile模型具有gender字段,该字段定义如下:

class Profile(models.Model):
  GENDER_CHOICES = (
    (u'm', _(u'Male')),
    (u'f', _(u'Female')),
  ) 
 gender = models.CharField(
   max_length=2, choices=GENDER_CHOICES, verbose_name=_("Gender"),
   null=True, blank=True
 ) 

我想在工厂男孩中随机化该字段的价值,并具有以下代码行:

class ProfileFactory(factory.Factory):
   (...)
   gender = factory.LazyFunction(random.choice(['f', 'm']))

但是,这引发了TypeError: 'str' object is not callable错误然后,我尝试使用以下解决方案,该解决方案有效:

gender = factory.LazyAttribute(lambda x: random.choice(['f', 'm']))

这解决了问题,但我不清楚为什么这样做。

factory.LazyFunction的文档指出:

The LazyFunction is the simplest case where the value of an attribute
 does not depend on the object being built.
It takes as argument a method to call (function, lambda…); that method 
should not take any argument, though keyword arguments are safe but 
unused, and return a value.

我的理解是random.choice(['f', 'm'])构成了一个方法调用,因此应该按照我的期望工作。

,但由于我对LazyFunction的理解没有存在缺陷,我希望有人可以解释我在这里做错了什么

两者之间的区别是

lambda x: random.choice(['f', 'm'])

返回功能和

random.choice(['f', 'm'])

评估语句并返回字符串。

如果您要在没有lambda的情况下复制行为,则可以使用

进行操作
def foo():
  return random.choice(['f', 'm'])
# ...
gender = factory.LazyFunction(foo)

LazyFunction需要 callable :它可以调用的东西。

random.choice(['f', 'm'])返回字符串;为了使其成为可可,解决方案是LazyFunction(lambda: random.choice(['f', 'm']))

但是,解决问题的最佳解决方案是使用专为您的用户酶设计的factory.fuzzy.FuzzyChoice

gender = factory.fuzzy.FuzzyChoice(['f', 'm'])

这将自行执行随机调用,并支持适当的播种/随机性管理 - 请参阅https://factoryboy.readthedocs.io/en/latest/reference.html#randomness-management.

最新更新