I want to test a function to see if it's working properly.
I found many answers such as how to write a unit testing function for my function? & unittest
But they all write the test functions under a certain class, while mine function isn't a member a any class.
for example I have this under readTool.py:
def extract_frame_dr(dr, frameID):
return dr[0, frameID], dr[1, frameID]
How do I write a test_extract_frame_dr for it? I want to have the feature of Auto-discovery of test modules and functions: Run all the tests in readTool.py at once without calling them one by one in the main function.
Thanks
You may write very clear tests with functions using pytest. To do so,
test_x.py modules with test_y() functions, and run them with python -m pytest.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)
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 ModuleNotFoundErrors)
This is part of pytest. Just
.\tests\ directorytest_x.py where as x a good convention would be to use the name of the module / package you are testing.test_y(), where as y good convention is to write a short description for the test.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With