Aug. 24, 2022

How to create temporary directories with pytest


More on:   
Go back

Post Image
My objective was to test a script that finds files of a specific type, in many nested subdirectories. The test should make sure that all the files are found. I could not rely on a permanent directory in my drive to test the script, as I needed to share the test.

I used the pytest library and its tmp_path_factory fixture. This creates a temporary directory in the default base temporary directory of the system.

The following figure shows the result of running the test script. The created directories were not erased when the test was done. It keeps the last 3, if I run the test 3 or more times, that is.

Shutting down my laptop, erases all of them. But I'll explain below what I did to erase them.

Post Image
temp_directories

So the first function create_dir1 uses the tmp_path_factory fixture. This function yields the temporary directory.

After test_1 is done, the instruction under yeld will be executed. This deletes the created temporary directory. The result is shown in the directory pytest-6 above, which is empty.

The function test_1 copies a file to the temporary directory with shutil. The assert checks that the function get_names returns the correct file.

The function get_names was the function I wanted to test. It is not relevant for this explanation, so it won’t be included here.

Remember that to run just one test with pytest from the terminal, it can be done with:

pytest test_tmp_path.py::test_1

import pathlib
import pytest
import shutil
from pics_frompath import get_names

DIRECTORY1 = "Test_dir1/"


@pytest.fixture(scope="module")
def create_dir1(tmp_path_factory):
    newtemp_dir = tmp_path_factory.mktemp(DIRECTORY1, numbered=False)
    yield newtemp_dir
    shutil.rmtree(str(newtemp_dir), ignore_errors=False)


def test_1(create_dir1):
    file = 'X661.jpg'
    path_with_file = shutil.copy(file, create_dir1, follow_symlinks=True)
    assert get_names(create_dir1) == [(path_with_file, str(create_dir1))]
    return