将Factory-boy生成的复杂对象转成dict的方法

最近在做接口测试,使用Factory-boy来生成接口对象实例,接着将对象转成dict,最后通过requests发送请求。

对象转成dict,目前知道的方法就是object.__dict__ 。这个方法用于普通对象(这边指的是,属性值都是str和int)还挺方便的,一旦遇到复杂的对象(属性值是其它对象实例)就不适用了。

在网上没有找到适用的代码,所以只能自己写个勉强能用的,目前支持属性值是str 、 int  、object 和 list的情况

 1 def objecttodict(obj):
 2     dict_o=obj.__dict__
 3     for key, value in dict_o.items():
 4         print(key,type(value))
 5         if isinstance(value, (str,int)):#不处理str,int的情况
 6             pass
 7         elif value is None:
 8             pass
 9         elif isinstance(value, list):#处理list的情况
10             valuelist=[]
11             for l in value:
12                 if isinstance(l, (str,int)):
13                     valuelist.append(l)
14                 else:
15                     valuelist.append(objecttodict(l))
16             dict_o[key] = valuelist
17         elif isinstance(value, dict):
18             pass#不处理dict的情况
19         else:#处理普通对象
20             dict_o[key]=objecttodict(value)
21     return dict_o

 

 

比如下面结构的对象,可以通过上面的方法转成dict

 

 

 下面是试验使用的Factory-boy例子

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

 

posted @ 2019-09-03 19:02  月色深潭  阅读(391)  评论(0编辑  收藏  举报