Pytest notes
From raju
Contents
assert actual expected template
template 1
assert Actual == Expected,\ 'Expected = {}, Actual = {}'.format(Expected, Actual)
template 2
from pandas.util.testing import assert_frame_equal assert_frame_equal(df_actual, df_expected)
template 3
import pytest @pytest.mark.parametrize('input, expected_output', [ ('foo', bar), ('foo2', bar2), ]) def test_fancy_func(input, expected_output): got = fancy_func(input) assert got == expected_output, 'Expected = {}, got = {}'.format(expected_output, got)
assert that a function returns float
val = foo() assert isinstance(val, float), \ 'val is {} but expecting {}' \ .format(type(val), 'float')
Install pytest on Linux
pip3 install -U virtualenv python3 -m virtualenv venv source venv/bin/activate pip install pytest
Install pytest on Windows
pip3 install -U virtualenv # Create a new virtual environment called venv python3 -m virtualenv venv venv\Scripts\activate.bat pip install pytest
a trivial test
tags | hello world, trivial example
$ cat tests/test_trivial.py import pytest def test_multiply(): assert 3*4 == 12
To run it
$ python -m pytest tests
running tests
1. cd into the project's root directory
2a. To run a single test
python -m pytest tests/test_foo.py
2b. To run all the tests in a directory and subdirectories within
python -m pytest tests/utils
2c. To run all the tests in tests directory and subdirectories within
python -m pytest tests
2d. To run all the tests in tests directory but not the tests in subdirectories such as tests/utils
pytest tests
useful links
- Source code - https://github.com/pytest-dev/pytest
- Official documentation - https://docs.pytest.org
- http://pythontesting.net - Brian Okken's website on pytest and code testing in general
- To get it from PyPI - https://pypi.python.org/pypi/pytest
- T. Ben Thompson's python testing set up - http://tbenthompson.com/post/how_i_test/
links related to parameterization
- Parametrizing fixtures and test functions - https://docs.pytest.org/en/latest/parametrize.html#parametrize-basics
- Parametrizing tests - https://docs.pytest.org/en/latest/example/parametrize.html
- parametrizing tests where functions have default arguments - https://stackoverflow.com/questions/35844791/how-to-write-a-test-for-a-function-with-optional-arguments
books on pytest
- pytest Quick Start Guide by Bruno Oliveira, published by Packt - https://github.com/PacktPublishing/pytest-Quick-Start-Guide
- Python Testing with pytest: Simple, Rapid, Effective, and Scalable 1st Edition by Brian Okken - https://www.amazon.com/Python-Testing-pytest-Effective-Scalable/dp/1680502409/