Creating a temporary directory in PyTest

Viewed 38280

My Python project imports pytest 2.9.0 fine without any issues.

I want to create a new empty directory that will last only the life of the test session. I see that pytest offers temporary directory support:

https://pytest.org/latest/tmpdir.html

You can use the tmpdir fixture which will provide a temporary directory unique to the test invocation, created in the base temporary directory.

tmpdir is a py.path.local object which offers os.path methods and more. Here is an example test usage:

The source-code for pytest shows that def tmpdir is a global/module function: https://pytest.org/latest/_modules/_pytest/tmpdir.html

However my test file fails:

import pytest

# ...

def test_foo():
    p = pytest.tmpdir()

With error:

AttributeError: 'module' object has no attribute 'tmpdir'

Doing from pytest import tmpdir fails with:

ImportError: cannot import name tmpdir

2 Answers
Related