PyTest Use Cases

Gota Morishita
1 min readFeb 14, 2022

Hi, I’m Gota. I’m a Ph.D. candidate in the University of Melbourne. Mostly, I use Python for the research purpose.

This is a personal note about pytest, which is a framework that makes it easy to write small, readable tests. I will add use cases of pytest I encountered in real programming.

Test if an expected error is raised

Source: Assertions about expected exceptions

If you want to check if an expected error is raised or not, use pytest.raises .
For example, you define a function that only takes int as an argument and raises TypeError if other type is given.

def take_int(n: int) -> None:
if not isinstance(n, int):
raise TypeError(f"You gave me something bad: {n}")
print("Good, int is given:)")

To check if this function actually raises TypeError if a string is given, you can use pytest.raises as a context manager like this:

import pytest


def test_type_error():
with pytest.raises(TypeError):
take_int('3')

If you want to access to an error information, you can use like this:

def test_zero_division():
with pytest.raises(TypeError) as error_info:
take_int('3')
assert "You gave me something bad" in str(excinfo.value)

Comparing floating-point values

Computers are not good at dealing with decimal points. For example, the following statement is False in Python.

0.1 + 0.2 == 0.3

When writing a test that compares floating-point values, you should use pytest.approx

from pytest import approxassert 0.1 + 0.2 == approx(0.3)

--

--

Gota Morishita

Hi, I'm currently a Ph.D. candidate in the University of Melbourne. I study behavioral science and computational neuroscience.