You want to get started with Django tests, you've heard all the good things. You know that testing is a good thing and should be done because it will make your life a lot easier once you get it done. Testing your Django app will help you identify bugs, find bugs you didn't know where there, increase your code quality, find unused code, upgrade with confidence and beyond. But you probably have heard all of that before.
Sometimes people hear all the good things testing can do for them, but aren't exactly sure what to test. People newer to testing especially tend to suffer from a mindset of "well, it works locally - and I can see it works - so what should I be testing exactly?" Most people are at that point at sometime.
Testing in Django is pretty flexible. I personally prefer using pytest for my testing - but this checklist is not particular to any specific library you may be using and can be useful to anyone testing any Django application.
I think breaking up your tests into various test_ files helps to keep things a little more organized instead of the default tests.py
file that Django gives you out of the box.
Since Django takes the approach of 'fat models', I think testing your model methods that get the data is some of the most important testing you can do! because if that data is wrong - your application is not going to do anyone any good.
There are obviously a few spots where you might want to mock up some dummy data (I prefer to use factory_boy
for that). In most cases you can just create the models you need in the setUp
method of the TestCase. For most average sized apps - you can just instanciate the model(s) you need in the setUp
method and that is enough.
For larger apps with a lot of complexicity, I actually go through the process of creating a little file named data_setup.py
where I create an 'apps worth' of dummy data complete with users of various permission levels and respective data. This helps tremendously with the integration testing for the most part, but can take a few extra seconds at the start of a test. To keep the data persistant through the duration of the TestCase instead of being torn-down/recreated for every test, I use the setUpTestData
method.