Debian Codegraph @

doc/en/how-to/tmp_path.rst

raw
1
2 .. _`tmp_path handling`:
3 .. _tmp_path:
4
5 How to use temporary directories and files in tests
6 ===================================================
7
8 The ``tmp_path`` fixture
9 ------------------------
10
11 You can use the ``tmp_path`` fixture which will provide a temporary directory
12 unique to each test function.
13
14 ``tmp_path`` is a :class:`pathlib.Path` object. Here is an example test usage:
15
16 .. code-block:: python
17
18 # content of test_tmp_path.py
19 CONTENT = "content"
20
21
22 def test_create_file(tmp_path):
23 d = tmp_path / "sub"
24 d.mkdir()
25 p = d / "hello.txt"
26 p.write_text(CONTENT, encoding="utf-8")
27 assert p.read_text(encoding="utf-8") == CONTENT
28 assert len(list(tmp_path.iterdir())) == 1
29 assert 0
30
31 Running this would result in a passed test except for the last
32 ``assert 0`` line which we use to look at values:
33
34 .. code-block:: pytest
35
36 $ pytest test_tmp_path.py
37 =========================== test session starts ============================
38 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
39 rootdir: /home/sweet/project
40 collected 1 item
41
42 test_tmp_path.py F [100%]
43
44 ================================= FAILURES =================================
45 _____________________________ test_create_file _____________________________
46
47 tmp_path = PosixPath('PYTEST_TMPDIR/test_create_file0')
48
49 def test_create_file(tmp_path):
50 d = tmp_path / "sub"
51 d.mkdir()
52 p = d / "hello.txt"
53 p.write_text(CONTENT, encoding="utf-8")
54 assert p.read_text(encoding="utf-8") == CONTENT
55 assert len(list(tmp_path.iterdir())) == 1
56 > assert 0
57 E assert 0
58
59 test_tmp_path.py:11: AssertionError
60 ========================= short test summary info ==========================
61 FAILED test_tmp_path.py::test_create_file - assert 0
62 ============================ 1 failed in 0.12s =============================
63
64 By default, ``pytest`` retains the temporary directory for the last 3 ``pytest``
65 invocations. Concurrent invocations of the same test function are supported by
66 configuring the base temporary directory to be unique for each concurrent
67 run. See `temporary directory location and retention`_ for details.
68
69 .. _`tmp_path_factory example`:
70
71 The ``tmp_path_factory`` fixture
72 --------------------------------
73
74 The ``tmp_path_factory`` is a session-scoped fixture which can be used
75 to create arbitrary temporary directories from any other fixture or test.
76
77 For example, suppose your test suite needs a large image on disk, which is
78 generated procedurally. Instead of computing the same image for each test
79 that uses it into its own ``tmp_path``, you can generate it once per-session
80 to save time:
81
82 .. code-block:: python
83
84 # contents of conftest.py
85 import pytest
86
87
88 @pytest.fixture(scope="session")
89 def image_file(tmp_path_factory):
90 img = compute_expensive_image()
91 fn = tmp_path_factory.mktemp("data") / "img.png"
92 img.save(fn)
93 return fn
94
95
96 # contents of test_image.py
97 def test_histogram(image_file):
98 img = load_image(image_file)
99 # compute and test histogram
100
101 See :ref:`tmp_path_factory API <tmp_path_factory factory api>` for details.
102
103 .. _`tmpdir and tmpdir_factory`:
104 .. _tmpdir:
105
106 The ``tmpdir`` and ``tmpdir_factory`` fixtures
107 ----------------------------------------------
108
109 The ``tmpdir`` and ``tmpdir_factory`` fixtures are similar to ``tmp_path``
110 and ``tmp_path_factory``, but use/return legacy `py.path.local`_ objects
111 rather than standard :class:`pathlib.Path` objects.
112
113 .. note::
114 These days, it is preferred to use ``tmp_path`` and ``tmp_path_factory``.
115
116 In order to help modernize old code bases, one can run pytest with the legacypath
117 plugin disabled:
118
119 .. code-block:: bash
120
121 pytest -p no:legacypath
122
123 This will trigger errors on tests using the legacy paths.
124 It can also be permanently set as part of the :confval:`addopts` parameter in the
125 config file.
126
127 See :fixture:`tmpdir <tmpdir>` :fixture:`tmpdir_factory <tmpdir_factory>`
128 API for details.
129
130
131 .. _`temporary directory location and retention`:
132
133 Temporary directory location and retention
134 ------------------------------------------
135
136 The temporary directories,
137 as returned by the :fixture:`tmp_path` and (now deprecated) :fixture:`tmpdir` fixtures,
138 are automatically created under a base temporary directory,
139 in a structure that depends on the :option:`--basetemp` option:
140
141 - By default (when the :option:`--basetemp` option is not set),
142 the temporary directories will follow this template:
143
144 .. code-block:: text
145
146 {temproot}/pytest-of-{user}/pytest-{num}/{testname}/
147
148 where:
149
150 - ``{temproot}`` is the system temporary directory
151 as determined by :py:func:`tempfile.gettempdir`.
152 It can be overridden by the :envvar:`PYTEST_DEBUG_TEMPROOT` environment variable.
153 - ``{user}`` is the user name running the tests,
154 - ``{num}`` is a number that is incremented with each test suite run
155 - ``{testname}`` is a sanitized version of :py:attr:`the name of the current test <_pytest.nodes.Node.name>`.
156
157 The auto-incrementing ``{num}`` placeholder provides a basic retention feature
158 and avoids that existing results of previous test runs are blindly removed.
159 By default, the last 3 temporary directories are kept,
160 but this behavior can be configured with
161 :confval:`tmp_path_retention_count` and :confval:`tmp_path_retention_policy`.
162
163 - When the :option:`--basetemp` option is used (e.g. ``pytest --basetemp=mydir``),
164 it will be used directly as base temporary directory:
165
166 .. code-block:: text
167
168 {basetemp}/{testname}/
169
170 Note that there is no retention feature in this case:
171 only the results of the most recent run will be kept.
172
173 .. warning::
174
175 The directory given to :option:`--basetemp` will be cleared blindly before each test run,
176 so make sure to use a directory for that purpose only.
177
178 When distributing tests on the local machine using ``pytest-xdist``, care is taken to
179 automatically configure a `basetemp` directory for the sub processes such that all temporary
180 data lands below a single per-test run temporary directory.
181
182 .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html