我有一些使用faker(http://www.joke2k.net/faker/)进行单元测试的模型,它在shell中是随机的:
In [50]: get_random()
Out[50]: 22347376
In [51]: get_random()
Out[51]: 66840240
In [52]: import factory, random, time
In [53]: from factory import DjangoModelFactory, lazy_attribute
In [54]: from faker import Faker
In [55]: FAKER = Faker(locale='en_US')
In [60]: FAKER.email()
Out[60]: u'anderson.meaghan@jonesharvey.org'
In [61]: FAKER.seed(get_random())
In [62]: FAKER.email()
Out[62]: u'ubeatty@gmail.com'
In [63]: FAKER.seed(get_random())
In [64]: FAKER.email()
Out[64]: u'klocko.martha@gmail.com'
In [65]: FAKER.email()
Out[65]: u'lebsack.zela@homenick.info'
In [66]: FAKER.email()
Out[66]: u'lance90@bauch.com'
播种是可选的。但是当我制作一个新对象时,我总是会发现它发出了相同的电子邮件:
In [2]: u = User()
In [3]: u
Out[3]: <User: Ut fugiat quasi aperiam provident error iure. Enim dolor totam quia sint. Porro laudantium aut non ducimus veritatis.>
In [5]: u.email
Out[5]: 'Alfie_Lemke@example.com'
In [6]: u = User()
IntegrityError: duplicate key value violates unique constraint "users_user_email_key"
DETAIL: Key (email)=(Alfie_Lemke@example.com) already exists.
模型看起来像:
../users.py:
import factory, time
from factory import DjangoModelFactory, lazy_attribute
from faker import Faker
FAKER = Faker(locale='en_US')
class User(DjangoModelFactory):
class Meta:
model = 'users.User'
first_name = FAKER.first_name()
last_name = FAKER.last_name()
email = FAKER.email()
现在我有:
import factory, random, time
from factory import DjangoModelFactory, lazy_attribute
from faker import Faker
FAKER = Faker(locale='en_US')
def get_random():
return int((random.SystemRandom(random.seed()).random())*100000000)
class User(DjangoModelFactory):
class Meta:
model = 'users.User'
FAKER.seed(get_random())
first_name = FAKER.first_name()
last_name = FAKER.last_name()
email = FAKER.email()
这没有任何区别。如何在 shell 中随机化一些东西,而不是在创建对象时随机化,即使提供了种子?谢谢