DEV Community

Cover image for Python Dev Environment Part 2: Testing with pytest
Jonathan Bowman
Jonathan Bowman

Posted on

Python Dev Environment Part 2: Testing with pytest

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
Enter fullscreen mode Exit fullscreen mode

Install pytest

Let's install pytest to make writing tests easy.

pip install pytest
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Hopefully, the result includes:

tests/test_greet.py .                                     [100%]

======================= 1 passed in 0.01s =======================
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)