Pytest

Anh-Thi Dinh
draft
⚠️
This is a quick & dirty draft, for me only!

Install

1pip install pytest

Rules

  • (ref) Name all testing files with test_*.py or _test.py.
  • Name all "be tested" functions with def test_*.

Executing

  • rf: list files having bugs.
1pytest test_sample.py
2pytest -q test_sample.py # quiet mode
1# ignore all files in folder statistics
2pytest -k "not statistics"

Simple

1# test_sample.py
2def func(x):
3    return x + 1
4
5def test_answer():
6    assert func(3) == 5
1# then run
2pytest test_sample.py

With parameters

1# test_sample.py
2@pytest.mark.parametrize(
3    "input, param_1, param_2, result",
4    [
5        (df_1, 'date', np.mean, df_result_1),
6        (df_2, 'date', np.mean, df_result_2),
7    ]
8)
9
10def test_run(input, param_1, param_2, result):
11    spts = SPTS(param_1=param_1, param_2=param_2)
12    df_tmp = spts.run(df)
13    assert isinstance(df_tmp, pd.DataFrame)
14    assert df_tmp.equals(result)
1# To get all combinations
2@pytest.mark.parametrize("x", [0, 1])
3@pytest.mark.parametrize("y", [2, 3])
4
5def test_foo(x, y):
6    pass
7
8# Then the arguments set to `x=0/y=2`,
9#    `x=1/y=2`, `x=0/y=3`, and `x=1/y=3`.
Note that, @pytest.mark.parametrize must be placed right before the function who uses it. Otherwise, there is an error fixture not found.
1# ERROR
2@pytest.mark.parametrize("x", [0, 1])
3def test_foo(x):
4    pass
5
6def test_bar(x):
7    pass
1# FIX
2@pytest.mark.parametrize("x", [0, 1])
3def test_foo(x):
4    pass
5
6@pytest.fixture
7def test_bar(x):
8    pass

Custom marker

Run tests who have a specific marker. ref
1@pytest.mark.marker_1
2def test_func1():
3    pass
4
5@pytest.mark.marker_2
6def test_func2():
7    pass
8
9@pytest.mark.marker_1
10def test_func3():
11    pass
1# with tag 'marker_1'
2pytest -v -m marker_1
3
4# except tag 'marker_1'
5pytest -v -m 'not marker_1'

Errors

1# ImportError: No module named atomicwrites
2python -m pytest
3python3 -m pytest

Ignore warning

1# eg: RuntimeWarning: numpy.ufunc size changed,
2@pytest.mark.filterwarnings('ignore::RuntimeWarning')
3@pytest.mark.level_1
4def test_load(df_test, report):

References