利用Factory-boy来生成实例数据

 

库和版本:
Faker==2.0.0
factory-boy==2.12.0

官方文档:
https://factoryboy.readthedocs.io/en/latest/index.html

1. 新建两个object:User和School

user.py

 

1 class User():
2     def __init__(self, name, num, age, school, city, phone):
3         self.name, self.num, self.age, self.school, self.city, self.phone = \
4             name, num, age, school, city, phone

 

school.py

1 class School:
2     def __init__(self,schoolName):
3         self.schoolName=schoolName

2. 给对象创建factory

 1 import factory
 2 import factory.fuzzy
 3 from demo_factory_boy.fbobject.user import User
 4 from demo_factory_boy.fbobject.school import School
 5 from demo_factory_boy.fbprivader.numpv import NumProvider
 6 
 7 factory.Faker.add_provider(NumProvider)  #添加自定义的NumProvider
 8 
 9 
10 class SchoolFactory(factory.Factory):
11     class Meta:
12         model = School
13 
14     schoolName = factory.sequence(lambda n: 'school%04d' % n)#factory.sequence
15 
16 
17 class UserFactory(factory.Factory):
18     class Meta:
19         model = User
20 
21     name = factory.Faker("name", locale="zh_CN")#factory.Faker 
22     num = factory.Faker("num")
23     age = factory.fuzzy.FuzzyInteger(42)#factory.fuzzy.FuzzyInteger
24     city = factory.Faker("address", locale="zh_CN")
25     phone = factory.fuzzy.FuzzyText("138", 7, "1", "1234567890")#factory.fuzzy.FuzzyText
26     school = factory.SubFactory(SchoolFactory)#factory.SubFactory
27 
28     class Params:
29         shipped = factory.Trait(
30             name=None
31         )

3.编写自定义Provider(如果没有Provider需求,可以跳过这个步骤

 1 from faker import Faker
 2 from faker.providers import BaseProvider
 3 import random
 4 
 5 fake = Faker()
 6 
 7 class NumProvider(BaseProvider):
 8     def num(self):
 9         ri = self.randomInt()
10         return str(ri())
11 
12     def randomInt(self):
13         return lambda a=1,b=30:random.randint(a,b)
14 
15     def randomStr18(self,num):
16         ri = lambda a=0, b=9: random.randint(a, b)
17         s = ''
18         for i in range(18):
19             s = s + str(ri())
20         return s

4.使用

 1 import factory
 2 from demo_factory_boy.fbfactory.userfc import UserFactory
 3 
 4 if __name__ == "__main__":
 5     # 单个生成
 6     seq = []
 7     uf = UserFactory()
 8     print(uf.__dict__)
 9     seq.append(uf.__dict__)
10     seq.append(UserFactory().__dict__)
11     print(seq)
12 
13     ##批量生成
14     list = []
15     fss = factory.build_batch(UserFactory, 4)
16     for fs in fss:
17         list.append(fs.__dict__)
18     print(list)
19     ##部分字段修改
20     uff = UserFactory(shipped=True)
21     print(uff.school.__dict__)
22     print(uff.__dict__)
23     print(uff.__dir__())

结果:

 

posted @ 2019-08-14 16:14  月色深潭  阅读(979)  评论(0编辑  收藏  举报