Search code examples
pythonpython-3.xfactoryfixturespython-dataclasses

Any suggestions on how to write factories for DTOs in Python


I use DTO to communicate data between different layers/classes in my application. So during the testing of these classes, I had to manually create objects of these data classes with some dummy data which is one serious pain point for me any suggestion on automating this stuff like factoryboy for Django models.


Solution

  • I have a user DTO like below.

    import dataclasses
    @dataclasses.dataclass
    class UserDetailsDto:
        user_id: int
        user_name: str
        profile_pic: str
        is_admin: bool
    

    for that DTO, I write a factory like this.

    import factory
    import factory.fuzzy
    class UserDetailsDtoFactory(factory.Factory):
        class Meta:
            model = UserDetailsDto
    
        user_id = factory.sequence(lambda n: n)
        user_name = factory.sequence(lambda n: 'Username-%s' % n)
        profile_pic = factory.sequence(lambda n: 'Dummy Profile Pic %s' % n)
        is_admin = factory.Iterator([True, False])
    

    I'm using this approach successfully. You can also try this. Hope this helpful to you.