Jan 272016
 

In a recent post Amit talked about temporary files and gave a number of scenarios where they can be quite handy. In testing, I occasionally need temporary files and prefer to use mkstemp however, the clean up of the file was bothersome and I found that I often needed to write something into the files before the test.

from dhp.test import tempfile_containing

contents = 'I will not buy this record, it is scratched.'
with tempfile_containing(contents) as fname:
    do_something(fname)

Thus tempfile_containing was my solution. It uses mkstemp, writes contents to the file and is implemented as a context manager so it returns a path and file name that is cleaned up when it goes out of scope. (Note: NamedTemporary and others, return a file-like object tempfile_containing returns a path/filename of an existing file) After the file is written to it is closed so no inadvertent lock contentions occur on some OSs. If it sounds like something that would make writing tests faster for you, check it out at:

* documentation
* Source
* pip install dhp

 Posted by at 3:14 am

  One Response to “dhp.test – tempfile_containing”

  1. You could use py.test’s ‘tmpdir’ as well: http://stackoverflow.com/a/4205449

Sorry, the comment form is closed at this time.