Python Django FactoryBoy-随机选择不使用LazyFunction
我正在为django应用程序构建大量测试,并使用FactoryBoyPython Django FactoryBoy-随机选择不使用LazyFunction,python,django,factory-boy,Python,Django,Factory Boy,我正在为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
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
)
我想用以下代码行在factory boy中将此字段的值随机化:
class ProfileFactory(factory.Factory):
(...)
gender = factory.LazyFunction(random.choice(['f', 'm']))
但是,这会抛出一个TypeError:“str”对象不可调用
然后,我使用一篇旧博客文章尝试了以下解决方案,效果很好:
gender=factory.LazyAttribute(lambda x:random.choice(['f','m'))
这解决了问题,但我不清楚为什么会这样
forfactory.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'])
构成了一个方法调用,因此应该像我预期的那样工作
但由于没有,我对懒散功能的理解显然有缺陷,我希望有人能解释我在这里做错了什么
lambda x: random.choice(['f', 'm'])
返回一个函数和
random.choice(['f', 'm'])
对语句求值并返回字符串
如果要在没有lambda的情况下复制行为,可以使用
def foo():
return random.choice(['f', 'm'])
# ...
gender = factory.LazyFunction(foo)
LazyFunction
需要一个可调用的:它可以调用的东西
random.choice(['f','m'])
返回一个字符串;要使其成为可调用函数,解决方案是LazyFunction(lambda:random.choice(['f','m'])
但是,解决您的问题的最佳解决方案是使用专门为您的用例设计的工厂.fuzzy.FuzzyChoice
:
gender=factory.fuzzy.FuzzyChoice(['f','m'])
这将自行执行随机调用,并支持正确的种子设定/随机性管理-有关详细信息,请参阅