Creating a temporary directory in PyTest

You just have to pass the tmpdir as a function parameter as it is a py.test fixture.

def test_foo(tmpdir):
    # do things with tmpdir

UPDATE: Use tmp_path instead of tmpdir. tmp_path is a pathlib.Path/pathlib2.Path. tmpdir is a py.path (Actually LocalPath), which has offered syntax very similar to pathlib.Path. See pytest issue.

Usage of py.path is no longer recommended by the developers.

Syntax is similar, eg:

def test_something_else(tmp_path):
    #create a file "myfile" in "mydir" in temp directory
    f1 = tmp_path / "mydir/myfile"
    f1.parent.mkdir() #create a directory "mydir" in temp folder (which is the parent directory of "myfile"
    f1.touch() #create a file "myfile" in "mydir"


    #write to file as normal 
    f1.write_text("text to myfile")

    assert f1.read() == "text to myfile" 

ORIGINAL: I looked into it an also found the behaviour peculiar, and I summarize what I learned below, for others who don't find it so intuitive.

tmpdir is a predefined fixture in pytest similar to how setup is defined here:

import pytest

class TestSetup:
    def __init__(self):
        self.x = 4

@pytest.fixture()
def setup():
    return TestSetup()

def test_something(setup)
    assert setup.x == 4

Thus tmpdir is a fixed name defined in pytest which is passed on to your testfunction if you have it as an argument name.

Example usage:

def test_something_else(tmpdir):
    #create a file "myfile" in "mydir" in temp folder
    f1 = tmpdir.mkdir("mydir").join("myfile")

    #create a file "myfile" in temp folder
    f2 = tmpdir.join("myfile")

    #write to file as normal 
    f1.write("text to myfile")

    assert f1.read() == "text to myfile"

This works when you run it using pytest, eg running py.test test_foo.py in the terminal. The file generated in this way has read and write access, and can be viewed later in your systems temporary folder (for me this was /tmp/pytest-of-myfolder/pytest-1/test_create_file0)

Tags:

Python

Pytest