Testing in Python with Pytest

Introduction

Recently I’ve been working with Python 3 to perform some functional tests on a piece of code that I wrote. I’d like to drive you through the basic testing you can do with Pytest, like testing the output of a function or ensuring that an error is raised when passing certain arguments. I will also show you how to use these features from terminal and within Pycharm.

If you are not really familiar with Python, the process may be a little more complicated, but if you have any question/problem, leave a message at the end of the article and I’ll help you.

For this tutorial I’ll be using Python 3.5 on Ubuntu 17. The process is the same on windows and Python 2.7.

Setting up the environment

In this section we will install all the packages needed for the tutorial.

  1. Open the terminal
  2. Run in terminal pip install pytest
import pytest

class Operations(object):

    @staticmethod
    def sum(a, b):
        #we want the input to be positive otherwise we raise an error
        if a >= 0 and b >= 0:
            return a + b
        else:
            raise ValueError('The input numbers should be positive')

class TestOperations(object):

    def test_sum(self):
        assert Operations.sum(10, 15) == 25

    def test_exception(self):
        with pytest.raises(ValueError):
            Operations.sum(10, -1)

 

In my terminal I used pip3 because I have both Python 2 and 3 installed, and I want to specifically install it in python 3

pytest install packages

Let’s start using Pytest

Ok now we are ready to write our first program. For this really short example I will use the built-in text editor and run  the tests from terminal. I will explain you the basic syntax and command arguments to perform the tests, if you want to read more, I recommend reading through the documentation.

Tests collection

When running pytest, the tests are collected from the specified folder or file using the following rules:

  • The test methods should start with test_ or end with _test   e.g. test_sum 
  • If the methods are in a class, the class name should start with Test  e.g. TestFunctions
  • The name of the file should also start with test_ unless you have a single file used for testing and you give it as argument in the terminal (I will show this in a sec)

The first program

Let’s find a case to use all the rules explained in the sub-section above. Here’s the code in case you wanted to try it yourself:

and save the document as test_operations.py

From the code you can see we have a class Operations which contains a static method to sum two positive numbers (it would also work with negative numbers but I wanted to find an excuse to raise an error) and a class TestOperations that contains two test methods. The first calls the method sum with two arguments and asserts the result. Assert is the main keyword used in testing which means “if the assertion is true, the test passed, otherwise it failed”. The second method instead is the basic syntax to check if some code raises the specified error. In this case the second test passes if and only if the sum method with those arguments raises a ValueError (which is the case).

Now go back to the terminal, navigate to the folder where you have saved the file and run simply pytest

Now let’s try to change the name of the file, so that it doesn’t match the collection requirements. I will just remove the test_ prefix, here’s the output now:

As expected no tests were collected. Here’s a workaround for that: specify the name of the file as argument

Set up Pytest in Pycharm

Open Pycharm and add the file we’ve been using so far to the project.

  1. Add a new execution configuration

2. From the list choose Python >> py.test

3. Choose a suitable name for the configuration and set the target to the file we want to test. Then press “OK”

4. Make sure that the configuration you just created is selected and click on the start button. A window will appear on the bottom showing the progress and results of the tests

Conclusions

I hope this article was useful, please comment and give me some feedback. I like graphics in the tutorials therefore I try to document step by step what I do with screenshots, I hope you find it useful too.

Thank you for reading

Leave a Reply