简单模型(models.py):
from django.db import models
class MyModel(models.Model):
start_date = models.DateField()
简单工厂(test_factories.py):
from datetime import date
import factory
from .models import MyModel
class MyModelFactory(factory.django.DjangoModelFactory):
class Meta:
model = MyModel
start_date = date.today()
在
manage.py shell
中:In [1]: from datetime import date
In [2]: from freezegun import freeze_time
In [3]: from polls.test_factories import MyModelFactory
In [4]: date.today()
Out[4]: datetime.date(2017, 8, 16)
In [5]: with freeze_time(date(1999,9,9)):
...: print(date.today())
...: m = MyModelFactory()
...: print(m.start_date)
...:
1999-09-09
2017-08-16
当前日期为2017-08-16,假日期为1999-09-09。在
freeze_time
内,date.today()
给出了伪造的日期,但factoryboy不受Frozengun的影响。它仍然给出实际的当前日期。MyModelFactory(start_date=date.today())
创建带有假日期的模型。)Frozengun版本:0.3.9
factoryboy版本:2.8.1
最佳答案
问题是当python解析工厂声明时会评估date.today()
;而factory_boy仅接收结果日期实例。
这是Python核心行为的一部分-不能被factory_boy覆盖。
解决此问题的正确方法是使用 factory.LazyFunction
声明:
class MyModelFactory(factory.django.DjangoModelFactory):
class Meta:
model = MyModel
# Note that we simply pass a callable.
start_date = factory.LazyFunction(date.today)
您可能还想看看
factory.fuzzy.FuzzyDate
,它将在给定的时间范围内生成随机日期。关于python - factoryboy不使用freezegun,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45718624/