Factory boy + Profile + Signals

/, Testing/Factory boy + Profile + Signals

Factory boy + Profile + Signals

Factory boy + Profile + Signals

The problem for me was to create users and profiles with factory boy.

I have a User model, and then two profiles, only one of each will be attached to the user.

Only some relevant fields will be listed in the code.

project.apps.authentication.models.py

project.apps.entities.models.py

So after having a quick look at how the models looked like, lets go straight to the solution of how to create factories for this models.

We will have to disable this signals, so we can have factory for the user, and the related factories for the types of user.

It is quite long to read, but (maybe there is a better way to do it, because like this is like harcoded with types of user, but for the purpose of the exercise, it works)

We will have two factories for creating users (users that will be of type 1 and users that will be of type 2) : UserTesterFactory , and UserCompanyFactory

Then we will have the related factories, the ones that create the profiles that have a O2O relation (or M2O could be to) : TesterFactory and CompanyFactory

In Both factories we have to disable signals, and also we are using get_or_create just in case there is some user with same data on a unique=True field.

As a side note, we cann see how with LazyAttribute, we can call an external function. =)

project/utilities_test.py

And then to test it , a simple test like this would work.

project/apps/authentication/tests/test_creation.py

When running the test we should obtain something similar to this:

References:

https://medium.com/@splatEric/django-user-profile-factories-8c835ca6eb5b

https://factoryboy.readthedocs.io/en/latest/orms.html#disabling-signals

 

By |2018-11-10T13:30:20+00:00noviembre 10th, 2018|Categories: Django, Testing|Tags: , , , , |0 Comments

About the Author:

Leave A Comment