Pytest - clean up resources at the end of a test session


Python clean test tip:

Clean up resources needed for test after the pytest session is finished -- i.e., drop test database, remove files added to the file system.

Example:

import csv
import os
import pathlib

import pytest


def list_users_from_csv(file_path):
    return [
        {field_name: field_value for field_name, field_value in row.items()}
        for row in csv.DictReader(
            file_path.open(),
            skipinitialspace=True,
            fieldnames=["first_name", "last_name"],
        )
    ]


@pytest.fixture
def users_csv_path():
    # before test - create resource
    file_path = pathlib.Path("users.csv")
    file_path.write_text("Jan,Giacomelli")
    yield file_path
    # after test - remove resource
    file_path.unlink()


def test_all_users_are_listed(users_csv_path):
    assert list_users_from_csv(users_csv_path) == [
        {"first_name": "Jan", "last_name": "Giacomelli"}
    ]