Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

(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?

like image 373
Ram Rachum Avatar asked Nov 16 '10 22:11

Ram Rachum


People also ask

How do I create a tmp file?

To create and use a temporary file The application opens the user-provided source text file by using CreateFile. The application retrieves a temporary file path and file name by using the GetTempPath and GetTempFileName functions, and then uses CreateFile to create the temporary file.

Where does Python store temporary files?

This function returns name of directory to store temporary files. This name is generally obtained from tempdir environment variable. On Windows platform, it is generally either user/AppData/Local/Temp or windowsdir/temp or systemdrive/temp. On linux it normally is /tmp.


1 Answers

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) 
like image 59
hpk42 Avatar answered Sep 22 '22 23:09

hpk42