In my last article pytest Tutorial Part 1 I showed some basic concepts of testing with pytest.
Here are two additional concepts
Table of Contents
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
Assert almost equal
import pytest
assert 2.2 == pytest.approx(2.3)
# fails, default is ± 2.3e-06
assert 2.2 == pytest.approx(2.3, 0.1)
# passes
Testing for Exceptions
import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
Next part: pytest Tutorial – Part 3






