Using pytest to write tests in Django

Harsh Bhimjyani
2 min readFeb 18, 2017

--

Testing is a boring subject. It is often ignored by a lot of developers, although it has picked up recently as everyone is recommending it.

What is pytest? or rather why pytest

Django’s official documentation has a whole big section about testing, so they insist you to do testing in your projects. They are using unittest and if you have read those docs then it looks something like this.

Now lets look at a pytest code sample.

You see that, easier syntax. Another thing is that pytest finds all the files in test_*.py format in your project. Just type py.test in your terminal and it executes tests within those files.

Pytest in Django

To be able to use pytest in Django you will need the following packages.

pytest-django is a pytest plugin which provides tools using writing tests in django. pytest-cov is another plugin which shows how much of your code is covered in tests. This is really important. You don’t really need 100% test coverage in your projects but it is good to have everything covered.

Before we start writing tests, we need to create some config files for pytest. First we create a test_settings.py file. Here we can override the necessary settings to be used while testing.

Next we need a pytest.ini file in our project root. This is is a initialisation file which tells pytest to follow certain rules before running.

Here we are telling pytest to use our test_settings.py for the Django settings. The 2nd line is very important. Those are the flags that we have to use every time when we run py.test command. The — nomigrations flag tells pytest not to run any database migrations while testing. — cov=. denotes the project path and — cov-report is basically the format of your test coverage report.

One more thing we will need is the .coveragerc file in your project root.

Here you will specify what files or folders to omit in your tests.

Testing

As this is only an intro article, I will only cover some of the basics.

Lets write test for a model.

Basically the way you write tests won’t differ from the way it is shown in Django docs, just the syntax changes a little. Here you can see we have added a line pytestmark = pytest.mark.django_db. In pytest if you want to allow database access, you will have to mark it like this.

That’s it. You can now run the py.test command in your terminal and see if the test passes. This is will also generate the coverage report for you. It will create a folder named htmlcov/ in your project root. You can open the index.html file in your browser and check your coverage.

Happy testing!

--

--