Using Pytest with Django and Django Rest Framework

This article is inspired by article here.

What is Pytest

Pytest is testing framework for Python. Very popular with Django.

Killer feature : Fixtures

Fixtures are the killer feature of Pytest. Fixtures are functions that run before and after each test, like setUp and tearDown in unitest and labelled pytest killer feature. Fixtures are used for data configuration, connection/disconnection of databases, calling extra actions, and so on.

All fixtures have scope argument with available values:

  • function run once per test
  • class run once per class of tests
  • module run once per module
  • session run once per session

Note: Default value of scope is function

How to create fixtures

Example of simple fixture creation:

Another kind of fixture is yield fixture which provides access to test before and after the run, analogous to setUp and tearDown.

Example of simple yield fixture creation:

Note: normal fixtures can use yield directly so the yield_fixture decorator is no longer needed and considered deprecated. is the file present in the root of tests folder. Here put all the fixtures that you want to be present in all of you test modules.

Example of fixture creation in

Here, I created fixtures like json_error, json_success etc. If I now create test modules like, etc, these fixtures will be globally available in all of these modules.

How to use Fixtures with test in Pytest?

To use fixture in test, you can put fixture name as function argument:

No Comments

You can leave the first : )

Leave a Reply

Your email address will not be published. Required fields are marked *