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

Ram Rachum picture Ram Rachum · Nov 16, 2010 · Viewed 27.2k times · Source

(I'm using Python 2.6 and nose.)

I'm writing tests for my Python app. I want one test to open a new file, close it, and then delete it. Naturally, I prefer that this will happen inside a temporary directory, because I don't want to trash the user's filesystem. And, it needs to be cross-OS.

How do I do it?

Answer

hpk42 picture hpk42 · Nov 17, 2010

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)