3.1. Testing with pytest#

In this section, we introduce the pytest package to write test for your Python code.
The extent of this tutorial is limited, avid readers should refer to this additional material:

3.1.1. Writing a simple function and test.#

Let’s write a simple function to greet users. For now, the function will do nothing.

We want the function to greet the given user; or say “Hello World!” if no user is given.

%%file greeting.py
"""Minimal function to demonstrate pytest."""


def greet(username: str | None = None) -> str:
    """Greet a given user.

    When no user is given, this function will return "Hello World!".

    Parameters
    ----------
    username: Optional[str]
        Name of the user.

    Returns
    -------
    str
        Personalized greeting.
    """
    return ""
Overwriting greeting.py

Then, let’s write a test that will make sure our function works as expected.

%%file test_greeting.py
"""Minimal test to demonstrate pytest."""
import pytest

from greeting import greet


def test_greet() -> None:
    assert greet("Alice") == "Hello Alice!"
    assert greet("Bob") == "Hello Bob!"
    if greet() != "Hello World!":
        pytest.fail()
Overwriting test_greeting.py

Let’s execute the test we wrote. In a terminal run the command

! pytest
============================= test session starts ==============================
platform linux -- Python 3.10.9, pytest-7.2.1, pluggy-1.0.0
rootdir: /home/runner/work/big-data-tutorial-101/big-data-tutorial-101/book/chapters/04
plugins: anyio-3.6.2
collecting ... 
collected 1 item                                                               

test_greeting.py F                                                       [100%]

=================================== FAILURES ===================================
__________________________________ test_greet __________________________________
    def test_greet() -> None:
>       assert greet("Alice") == "Hello Alice!"
E       AssertionError: assert '' == 'Hello Alice!'
E         - Hello Alice!

test_greeting.py:8: AssertionError
=========================== short test summary info ============================
FAILED test_greeting.py::test_greet - AssertionError: assert '' == 'Hello Alice!'
  - Hello Alice!
============================== 1 failed in 0.08s ===============================

The test should fail as expeceted since the function does nothing for now.

Let’s write the core of our function and run the test suite again.

%%file greeting.py
"""Minimal function to demonstrate pytest."""


def greet(username: str | None = None) -> str:
    """Greet a given user.

    When no user is given, this function will return "Hello World!".

    Parameters
    ----------
    username: Optional[str]
        Name of the user.

    Returns
    -------
    str
        Personalized greeting.
    """
    username = username if username else "World"
    return f"Hello {username}!"
Overwriting greeting.py
! pytest
============================= test session starts ==============================
platform linux -- Python 3.10.9, pytest-7.2.1, pluggy-1.0.0
rootdir: /home/runner/work/big-data-tutorial-101/big-data-tutorial-101/book/chapters/04
plugins: anyio-3.6.2
collecting ... 
collected 1 item                                                               

test_greeting.py .                                                       [100%]

============================== 1 passed in 0.01s ===============================

This time, the test succeeded. Our implementation is successful 🎉