Setup Pytest
Background/Problem
So, I had a little trouble to setup pytest. Therefore I made up a minimal example to show how it works. There are absolutely no advanced tests or anything, this is just about the basic setup.
Solution
Note: For me it was important to separate the scripts that are being tested and the tests themselves in different directories. The idea is to have a “src” directory with the scripts under test and a “tests” directory with the test files. The folder structure in “tests” should match the structure in “src”. Both, “src” and “tests”, are in the same root directory.
So the (very) basic structure looks like this:
~/pytest_demo/
├── src
│ ├── module.py
└── tests
└── test_module.py
In this example module.py contains the following code:
def add(a, b):
return a + b
And test_module.py:
from src import module
def test_add():
assert module.add(5, 7) == 12
I use virtual environments for my projects. Within the virtual environment, make sure pytest is installed. To do that run:
pip install pytest
With pytest install run the following command in the root directory (~/pytest_demo/ in this case):
python -m pytest
That’s it!
P.S.: By the way I found the solution to make this run here [1]. It might be worth checking out this site more.
Change Log
2022-09-20:
- Changed wording a little bit.
Take care,
Andreas
References
- A. Knight, “Python Testing 101: Pytest,” 14-Mar-2017. [Online]. Available at: https://automationpanda.com/2017/03/14/python-testing-101-pytest/. [Accessed: 06-Dec-2021].
Leave a comment