In the last post, I introduced you to testing in Django and we looked at best practices as well as a few examples. This time, I’ll show you a bit more complicated example and introduce you to Model Mommy for creating sample data.
Why should you care?
In the last post, I said that, “factory_boy, model_mommy, and mock are all are used in place of fixtures or the ORM for populating needed data for testing. Both fixtures and the ORM can be slow and need to be updated whenever your model changes.”
To summarize, the Django Testing Fixtures are problematic because they-
- must be updated each time your model/schema changes,
- are really, really slow, and
- sometimes hard-coded data can cause your tests to fail in the future.
So, by using Model Mommy you can create fixtures that load quicker and are much easier to maintain over time.
Django Testing Fixtures
Let’s start by looking at our example for testing the model in the last post:
1 2 3 4 5 6 7 8 9
Here we simply created a
Whatever() object and asserted that the created title matched the expected title.
If you downloaded the Project from the repo, fire up the server and run the tests:
You will see that the above tests pass:
Now, instead of having to create a new instance, with each attribute, each time (boring!), we can use Model Mommy to streamline the process.
Remember what our model looks like?
1 2 3 4 5 6 7
Now we can re-write the above test in a much easier fashion:
1 2 3 4 5 6 7 8 9 10
Run it. Did it pass?
How easy was that? No need to pass in arguments.
Let’s look at a bit more complicated example.
Create a new app:
Add the app to the
Installed_Apps in the settings.py file
Create the model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Sync the DB.
What does our coverage report look like?
Add the tests:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Re-run your tests (which should pass), then create the coverage report:
Care to try running the above tests using JSON fixtures to see just how to set the tests up using the Django Testing Fixtures?
I’m not sure what we’ll have in store for the next tutorial, so let me know what you’d like to see. Grab the code here. Be sure to comment below if you have questions. Cheers!