tmp_file_type

pytest_tmp_files.tmp_file_type(type: str)[source]

Teach pytest_tmp_files how to make a new kind of file.

Parameters

type – The string that will identify this kind of file in the specification dictionary.

This function is a decorator. When a file of the given type is requested, the decorated function will be called with two arguments: path and meta. The former is the path to create, and the latter is a free-form dictionary containing any user-specified information about the requested file. These arguments directly correspond to the key and value of an item in the specification dictionary. The function should create the requested file and return nothing.

Example

The following snippet defines a custom file type called “json”. It expects the metadata to include a “content” field, which it will encode as JSON and write to the indicated path.

>>> from pytest_tmp_files import *
>>> @tmp_file_type('json')
... def make_json_file(path, meta):
...     import json
...     with open(path, 'w') as f:
...         json.dump(meta['content'], f)
...

Here’s how this custom file type could be used:

>>> from pathlib import Path
>>> make_files(Path.cwd(), {
...     'demo.json': {
...         'type': 'json',
...         'content': {'a': 1},
...     }
... })
>>> (Path.cwd() / 'demo.json').read_text()
'{"a": 1}'

Note that this is just an example; in real applications I’d recommend writing JSON files like this by hand.