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.


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(
            fieldnames=["first_name", "last_name"],

def users_csv_path():
    # before test - create resource
    file_path = pathlib.Path("users.csv")
    yield file_path
    # after test - remove resource

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