In Part 1, we built a Python distribution package. It worked. However, we are not done without writing tests.
Activate virtual environment
Making sure that pygreet
from Part 1 is the current working directory, activate the environment if it is not active already, using source ./venv/bin/activate
(Bash) or .\venv\Scripts\Activate.ps1
(PowerShell).
Create tests
directory
Once we create a tests
directory, the directory tree should look something like this:
pygreet/
├── setup.py
├── src
│ └── greet.py
├── tests
└── venv
Install pytest
Let's install pytest to make writing tests easy.
pip install pytest
This should result in pytest and several dependent packages being installed.
Write tests
With pytest, any functions that start with test_
in a file with a name that starts with test_
and is in the tests
directory will run by default.
So, we create a test_greet.py
file in the tests
directory:
import greet
def test_greet():
result = greet.greet()
assert "Hello" in result
In this file, we import greet, then, in a test function (note the naming scheme, beginning with test_
), call the function we want to test. The assert
statement will fail if not true.
Run the test
If pygreet
is the current working directory, then run
pytest
Hopefully, the result includes:
tests/test_greet.py . [100%]
======================= 1 passed in 0.01s =======================
Dev environment thus far
At this point, our dev environment looks something like this:
pygreet/
├── setup.py
├── src
│ └── greet.py
├── tests
│ └── test_greet.py
└── venv
While simple, this basic structure should serve you well as a foundation for your next Python project. Write more tests, write more code, segment and organize the code, and enjoy yourself.
You may also enjoy Part 3, an introduction to Python dependency management with install_requires
and requirements.txt
.
Top comments (0)