Python: PyTest fixtures - temporary directory - tmpdir
When writing tests you often need to create files that are need by the test (e.g. a configuration file, or the output of a command) Creating in the current directory can problematic for several reasons.
For example if you have more than one test scripts and each use the same filename then you cannot run the tests in parallel.
In the same way you cannot just designate a directory where you store these temporary files as that would mean running the tests on the same computer isn't possible. Even in two separate environments.
Fixtures, is a generic term in the testing world to create a known environment in which the test can run. PyTest has a rich set of Fixures, one of the, called tmpdir makes it easy to create a temporary diriectory for each test run.
In order to use this facility, the only thing you need to do is to declare your testing function accepting the parameter tmpdir. (The exact name is important here as PyTest used introspection to look at your testing function.
When it sees that you are expecting a tmpdir it will create a temporary directory and a Python object represnting it and it will pass it to your testing function.
This is also called dependency injection.
You can then put whatever you like in that directory. You can be sure that it will only be used by the current test process. (It is not a random directory name so other processes can easily find it, but unless someone actively tries to break your test system, you'll be ok.)
examples/python/test_json.py
import json import os def test_round_trip(tmpdir): print(tmpdir) filename = tmpdir.join('abc.json') print(filename) data = { 'name': 'Foo Bar', 'grades': [27, 38, 12], } with open(filename, 'w') as fh: json.dump(data, fh) with open(filename) as fh: new_data = json.load(fh) assert data == new_data
Published on 2019-04-09