FactoryBoy / factory_boy

A test fixtures replacement for Python
https://factoryboy.readthedocs.io/
MIT License
3.48k stars 392 forks source link

Easy way to build a nested dict from factory? #629

Open simkimsia opened 5 years ago

simkimsia commented 5 years ago

The problem

My situation is similar to this one raised https://github.com/FactoryBoy/factory_boy/issues/68#issuecomment-363268477

I have nested factories that use SubFactory

When I want to use factory.build to create a dict, the nested factory comes out as object rather than as a dict.

Proposed solution

Is there a way to improve with a build_nested_dict function or there's a workaround?

chanyou0311 commented 4 years ago

@simkimsia I had a similar situation.

I wrote the code that works for SubFactory based on the code shared in https://github.com/FactoryBoy/factory_boy/issues/68#issuecomment-444530001.

I wrote the actual code in https://github.com/FactoryBoy/factory_boy/issues/68#issuecomment-636452903. It may be useful to you.

simkimsia commented 4 years ago

Thanks mate @chanyou0311

devProdigy commented 3 years ago

I think you can do smth like this:

import json
factory_as_dict = json.loads(json.dumps(target_factory, default=lambda o: o.__dict__))