Python Friday #44: Start With Pytest

Flask is a great framework, but before I continue with more elaborate parts I need to make sure that the code I wrote until now keeps working. Let’s look how we can test our code in Python.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

(Unit) testing in Python

In Python you have two main testing frameworks: unittest and pytest. Both do a good job and help you to improve the quality of your application. I choose pytest because it looks more like Python and less like a XUnit clone.

 

Install pytest

You can install pytest in your virtual environment using the pip installer:

 

The first test

One of the benefits of pytest is that you can concentrate on the tests and not on the ceremony of creating the right infrastructure for your test framework. You can put your testcase in a file called test_start.py:

That is basically all you need to write. To run your test, you can type this command in the folder of your test file:

 

How does pytest find our test case?

Pytest uses a few basic rules to discover tests. These are mainly to search for files matching test_*.py or *_test.py in the current folder (including subdirectories) and there it looks for functions named like test*(). Check the documentation for more details and an explanation on how to modify the test case discovery.

 

Where should you put your tests?

The pytest documentation suggests that you put your test files into a folder called tests on the same level as your application:

setup.py
mypkg/
    __init__.py
    app.py
    view.py
tests/
    test_app.py
    test_view.py
    …

This layout makes it easy to find your tests for other developers and you do not need to configure pytest to look at other places.

 

What can we assert?

In pytest we can use the standard python assert statement to verify expectations. Be aware, that the assert statement is not a function or a method and therefore does not need () around the expression we want to check. We can check whatever we want, as long as it evaluates to a Boolean.

This assert statement is a convenient way to debug your code. We can see why as soon as our test fails (and returns False instead of True):

assert shows exactly where the problem is

The assert statement unpacks lists and shows the values with enough details so that you can see what is wrong without starting the debugger.

 

Next

With the basics of pytest covered, we can now start to write our own tests. In the next week I explain what you need to do if you no longer find your print() output in the console.

2 thoughts on “Python Friday #44: Start With Pytest”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.