Python: How do I make temporary files in my test suite?

FWIW using py.test you can write:

def test_function(tmpdir):
    # tmpdir is a unique-per-test-function invocation temporary directory

Each test function using the “tmpdir” function argument will get a clean empty directory, created as a sub directory of “/tmp/pytest-NUM” (linux, win32 has different path) where NUM is increased for each test run. The last three directories are kept to ease inspection and older ones are automatically deleted. You can also set the base temp directory with py.test --basetemp=mytmpdir.

The tmpdir object is a py.path.local object which can also use like this:

sub = tmpdir.mkdir("sub")
sub.join("testfile.txt").write("content")

But it’s also fine to just convert it to a “string” path:

tmpdir = str(tmpdir)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)