Skip to content
holzkohlengrill edited this page Dec 15, 2023 · 2 revisions

I personally do NOT recommend using pytest. I never enjoyed using it.

Pytest

Basic usage

Test functions

pytest sees all functions starting with test_ as a test case.

import pytest

def test_blah(blub)
    assert blub == 42

Fixtures

Fixtures are used in order to prepare identical and consistent test conditions for unit testing. That is initialisation, configuration, preparing preconditions, providing data (used pytest caching mechanisms automatically) etc.

Register a fixture by decorating an object:

import pytest

@pytest.fixture
def toolInit()
    # Do some stuff

# Due to the fixture decorator toolInit is found by pytest
def test_myTest(toolInit)
    # Do some stuff
    a = ...
    yield a                         # Provide a; end of normal init
    # Teardown sequence begins
    print("Teardown", a, "...")

Teardown actions can be set via yield within a fixture. Use it instead of return to give back the generated object.

It is not called in case of previous exceptions. An alternative is the addfinalizer function which is always called regardless of an exception event plus you can register multiple finaliser functions.

Find fixtures

You can find available fixutres with pytest --fixtures test_myTests.py. Private fixtures (having a leading underscore (_) can be found using the verbose (-v) option)

File-cross fixtures

Accessing fixtures accross multiple files gets handier moving those fixtures to a file named conftest.py without importing the file. Pytest discovers is automatically.

Performance

Fixtures are invoked by default per test function.

Defining the fixtures scope can save performance. @pytest.fixture(scope="module") will invoke the fixture only once per module.

Available options are (and are instantiated in this order):

  1. session
  2. module
  3. function
  4. class
  5. package (runs when the last test was done)
Clone this wiki locally