what is it?

Following along with this series

Pytest is a testing framework for python. There’s also a version of pytest that caters for testing within the django framework.

Some general testing philosophy

Other python test frameworks

  • Robot
  • Unittest
  • DocTest
  • Nose2
  • Testify

Pytest pros

  • Opensource
  • Works with built-in Unittests
  • Simpler syntax than Unittests - less boilerplate code
  • Large community support
  • Large plugin ecosystem
  • Fixture support - simplifies setup and teardown

Installation and config

  • Base installation

    pip install pytest-django
  • create pytest.ini file in project root

    [pytest]
    DJANGO_SETTINGS_MODULE = fica_face.settings
    # define where tests are collected from
    python_files = test_*.py *_tests.py

Writing a simple test

  • create test_example.py

    import pytest
     
    def test_example():
    	assert 1 == 1
  • run test

  • remember to run from the project’s root directory

    pytest

  • failed test

    import pytest
     
    def test_example():
    	assert 1 == 1
     
    def test_example1():
    	assert 1 == 2

  • To stop testing after first failure: pytest -x

  • To log output from passing tests: pytest -rP

  • Running individual tests: pytest tests/test_ex1.py::test_example

Marks

pytest marks

Fixtures

pytest fixtures

Testing for an exception

import pytest
from common_functions.views import handle_exception
 
def test_handle_exception_raises_value_error():
    with pytest.raises(ValueError) as excinfo:
        handle_exception()
 
    # Optionally, you can assert further details about the exception if needed
    assert str(excinfo.value) == "An error occurred"

testing media using a temporary directory

@pytest.fixture(scope="function", autouse=True)
def tmp_media(tmpdir, settings):
    settings.MEDIA_ROOT = tmpdir.mkdir("media")