You may write very clear tests with functions using pytest. To do so,
- Make your python modules to be importable in the test files (an example given in part 1)
- Create
test_x.py
modules with test_y()
functions, and run them with python -m pytest
.
1. Folder structure & setup for writing tests
When writing code that you want to be tested, you need to ensure that your modules are importable by the test modules. Easiest way to do it would be to use folder structure like this:
.
│ setup.py
│
├───mypackage
│ readTool.py
│ __init__.py
│
├───tests
│ test_readtool.py
│
└───venv
where setup.py
is a file used to make your package installable. In this example, the file contents would be just
import setuptools
setuptools.setup(
name='mypackage',
packages=setuptools.find_packages(),
)
You also probably want to create a virtual environment (venv
), activate it, and then install your package (mypackage
) in an editable state with
pip install -e .
Then, install pytest
pip install pytest
(for more information on the usage of setup.py
, see for example this answer)
2. Testing functions with functions
Write into tests/test_readtool.py
:
from mypackage.readTool import extract_frame_dr
def test_extract_frame_dr():
frame_id = 1963
dr_who = {
(0, frame_id): 'William Hartnell',
(1, frame_id): 'Patrick Troughton',
}
extracted = extract_frame_dr(dr_who, frame_id)
assert extracted[0] == 'William Hartnell'
assert extracted[1] == 'Patrick Troughton'
and run the tests using
python -m pytest
(with just running pytest
you may encounter into ModuleNotFoundError
s)
3. Auto-discovery of test modules and functions
This is part of pytest. Just
- Put your test files into the
.\tests\
directory
- Name your test modules as
test_x.py
where as x
a good convention would be to use the name of the module / package you are testing.
- Name your test functions as
test_y()
, where as y
good convention is to write a short description for the test.