pytest Tutorial – Part 2

In my last article pytest Tutorial Part 1  I showed some basic concepts.

Here are two additional concepts

Parameterize

Test parameterization follows the concept of DRY – Don’t repeat yourself

Instead of writing a new testcase for every different value you annotate your test function and handover the different values. The test will be executed as often as there are values:

import pytest

@pytest.mark.parametrize(
    "data, expected_mean",
    [
        ([1], 1),
        ([1, 2], 1.5)
    ]
)
def test_calculate_mean(data, expected_mean):
    pass

Markers

With markers you can control test case execution:

import pytest


@pytest.mark.windows
def test_win_ver():
    pass

@pytest.mark.linux
def test_lin_ver():
    pass

@pytest.mark.mac_os
def test_stuff_mac_os():
    pass
# content of pytest.ini
[pytest]
markers =
    windows: tests code under win
    linux: tests code under lin
    mac_os: tests code under mac os