Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/doc/en/explanation/goodpractices.rst

raw
1 .. highlight:: python
2 .. _`goodpractices`:
3
4 Good Integration Practices
5 =================================================
6
7 Install package with pip
8 -------------------------------------------------
9
10 For development, we recommend you use :mod:`venv` for virtual environments and
11 :doc:`pip:index` for installing your application and any dependencies,
12 as well as the ``pytest`` package itself.
13 This ensures your code and dependencies are isolated from your system Python installation.
14
15 Create a ``pyproject.toml`` file in the root of your repository as described in
16 :doc:`packaging:tutorials/packaging-projects`.
17 The first few lines should look like this:
18
19 .. code-block:: toml
20
21 [build-system]
22 requires = ["hatchling"]
23 build-backend = "hatchling.build"
24
25 [project]
26 name = "PACKAGENAME"
27 version = "PACKAGEVERSION"
28
29 where ``PACKAGENAME`` and ``PACKAGEVERSION`` are the name and version of your package respectively.
30
31 You can then install your package in "editable" mode by running from the same directory:
32
33 .. code-block:: bash
34
35 pip install -e .
36
37 which lets you change your source code (both tests and application) and rerun tests at will.
38
39 .. _`test discovery`:
40 .. _`Python test discovery`:
41
42 Conventions for Python test discovery
43 -------------------------------------------------
44
45 ``pytest`` implements the following standard test discovery:
46
47 * If no arguments are specified then collection starts from :confval:`testpaths`
48 (if configured) or the current directory. Alternatively, command line arguments
49 can be used in any combination of directories, file names or node ids.
50 * Recurse into directories, unless they match :confval:`norecursedirs`.
51 * In those directories, search for ``test_*.py`` or ``*_test.py`` files, imported by their `test package name`_.
52 * From those files, collect test items:
53
54 * ``test`` prefixed test functions or methods outside of class.
55 * ``test`` prefixed test functions or methods inside ``Test`` prefixed test classes (without an ``__init__`` method). Methods decorated with ``@staticmethod`` and ``@classmethods`` are also considered.
56
57 For examples of how to customize your test discovery :doc:`/example/pythoncollection`.
58
59 Within Python modules, ``pytest`` also discovers tests using the standard
60 :ref:`unittest.TestCase <unittest.TestCase>` subclassing technique.
61
62
63 .. _`test layout`:
64
65 Choosing a test layout
66 ----------------------
67
68 ``pytest`` supports two common test layouts:
69
70 Tests outside application code
71 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
72
73 Putting tests into an extra directory outside your actual application code
74 might be useful if you have many functional tests or for other reasons want
75 to keep tests separate from actual application code (often a good idea):
76
77 .. code-block:: text
78
79 pyproject.toml
80 src/
81 mypkg/
82 __init__.py
83 app.py
84 view.py
85 tests/
86 test_app.py
87 test_view.py
88 ...
89
90 This has the following benefits:
91
92 * Your tests can run against an installed version after executing ``pip install .``.
93 * Your tests can run against the local copy with an editable install after executing ``pip install --editable .``.
94
95 For new projects, we recommend to use ``importlib`` :ref:`import mode <import-modes>`
96 (see which-import-mode_ for a detailed explanation).
97 To this end, add the following to your ``pyproject.toml``:
98
99 .. code-block:: toml
100
101 [tool.pytest.ini_options]
102 addopts = [
103 "--import-mode=importlib",
104 ]
105
106 .. _src-layout:
107
108 Generally, but especially if you use the default import mode ``prepend``,
109 it is **strongly** suggested to use a ``src`` layout.
110 Here, your application root package resides in a sub-directory of your root,
111 i.e. ``src/mypkg/`` instead of ``mypkg``.
112
113 This layout prevents a lot of common pitfalls and has many benefits,
114 which are better explained in this excellent `blog post`_ by Ionel Cristian Mărieș.
115
116 .. _blog post: https://blog.ionelmc.ro/2014/05/25/python-packaging/#the-structure>
117
118 .. note::
119
120 If you do not use an editable install and use the ``src`` layout as above you need to extend the Python's
121 search path for module files to execute the tests against the local copy directly. You can do it in an
122 ad-hoc manner by setting the ``PYTHONPATH`` environment variable:
123
124 .. code-block:: bash
125
126 PYTHONPATH=src pytest
127
128 or in a permanent manner by using the :confval:`pythonpath` configuration variable and adding the
129 following to your ``pyproject.toml``:
130
131 .. code-block:: toml
132
133 [tool.pytest.ini_options]
134 pythonpath = "src"
135
136 .. note::
137
138 If you do not use an editable install and not use the ``src`` layout (``mypkg`` directly in the root
139 directory) you can rely on the fact that Python by default puts the current directory in ``sys.path`` to
140 import your package and run ``python -m pytest`` to execute the tests against the local copy directly.
141
142 See :ref:`pytest vs python -m pytest` for more information about the difference between calling ``pytest`` and
143 ``python -m pytest``.
144
145 Tests as part of application code
146 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
147
148 Inlining test directories into your application package
149 is useful if you have direct relation between tests and application modules and
150 want to distribute them along with your application:
151
152 .. code-block:: text
153
154 pyproject.toml
155 [src/]mypkg/
156 __init__.py
157 app.py
158 view.py
159 tests/
160 __init__.py
161 test_app.py
162 test_view.py
163 ...
164
165 In this scheme, it is easy to run your tests using the ``--pyargs`` option:
166
167 .. code-block:: bash
168
169 pytest --pyargs mypkg
170
171 ``pytest`` will discover where ``mypkg`` is installed and collect tests from there.
172
173 Note that this layout also works in conjunction with the ``src`` layout mentioned in the previous section.
174
175
176 .. note::
177
178 You can use namespace packages (PEP420) for your application
179 but pytest will still perform `test package name`_ discovery based on the
180 presence of ``__init__.py`` files. If you use one of the
181 two recommended file system layouts above but leave away the ``__init__.py``
182 files from your directories, it should just work. From
183 "inlined tests", however, you will need to use absolute imports for
184 getting at your application code.
185
186 .. _`test package name`:
187
188 .. note::
189
190 In ``prepend`` and ``append`` import-modes, if pytest finds a ``"a/b/test_module.py"``
191 test file while recursing into the filesystem it determines the import name
192 as follows:
193
194 * determine ``basedir``: this is the first "upward" (towards the root)
195 directory not containing an ``__init__.py``. If e.g. both ``a``
196 and ``b`` contain an ``__init__.py`` file then the parent directory
197 of ``a`` will become the ``basedir``.
198
199 * perform ``sys.path.insert(0, basedir)`` to make the test module
200 importable under the fully qualified import name.
201
202 * ``import a.b.test_module`` where the path is determined
203 by converting path separators ``/`` into "." characters. This means
204 you must follow the convention of having directory and file
205 names map directly to the import names.
206
207 The reason for this somewhat evolved importing technique is
208 that in larger projects multiple test modules might import
209 from each other and thus deriving a canonical import name helps
210 to avoid surprises such as a test module getting imported twice.
211
212 With ``--import-mode=importlib`` things are less convoluted because
213 pytest doesn't need to change ``sys.path`` or ``sys.modules``, making things
214 much less surprising.
215
216
217 .. _which-import-mode:
218
219 Choosing an import mode
220 ^^^^^^^^^^^^^^^^^^^^^^^
221
222 For historical reasons, pytest defaults to the ``prepend`` :ref:`import mode <import-modes>`
223 instead of the ``importlib`` import mode we recommend for new projects.
224 The reason lies in the way the ``prepend`` mode works:
225
226 Since there are no packages to derive a full package name from,
227 ``pytest`` will import your test files as *top-level* modules.
228 The test files in the first example (:ref:`src layout <src-layout>`) would be imported as
229 ``test_app`` and ``test_view`` top-level modules by adding ``tests/`` to ``sys.path``.
230
231 This results in a drawback compared to the import mode ``importlib``:
232 your test files must have **unique names**.
233
234 If you need to have test modules with the same name,
235 as a workaround you might add ``__init__.py`` files to your ``tests`` folder and subfolders,
236 changing them to packages:
237
238 .. code-block:: text
239
240 pyproject.toml
241 mypkg/
242 ...
243 tests/
244 __init__.py
245 foo/
246 __init__.py
247 test_view.py
248 bar/
249 __init__.py
250 test_view.py
251
252 Now pytest will load the modules as ``tests.foo.test_view`` and ``tests.bar.test_view``,
253 allowing you to have modules with the same name.
254 But now this introduces a subtle problem:
255 in order to load the test modules from the ``tests`` directory,
256 pytest prepends the root of the repository to ``sys.path``,
257 which adds the side-effect that now ``mypkg`` is also importable.
258
259 This is problematic if you are using a tool like tox_ to test your package in a virtual environment,
260 because you want to test the *installed* version of your package,
261 not the local code from the repository.
262
263 The ``importlib`` import mode does not have any of the drawbacks above,
264 because ``sys.path`` is not changed when importing test modules.
265
266
267 .. _`buildout`: http://www.buildout.org/en/latest/
268
269 .. _`use tox`:
270
271 tox
272 ---
273
274 Once you are done with your work and want to make sure that your actual
275 package passes all tests you may want to look into :doc:`tox <tox:index>`, the
276 virtualenv test automation tool.
277 ``tox`` helps you to setup virtualenv environments with pre-defined
278 dependencies and then executing a pre-configured test command with
279 options. It will run tests against the installed package and not
280 against your source code checkout, helping to detect packaging
281 glitches.
282
283 Do not run via setuptools
284 -------------------------
285
286 Integration with setuptools is **not recommended**,
287 i.e. you should not be using ``python setup.py test`` or ``pytest-runner``,
288 and may stop working in the future.
289
290 This is deprecated since it depends on deprecated features of setuptools
291 and relies on features that break security mechanisms in pip.
292 For example 'setup_requires' and 'tests_require' bypass ``pip --require-hashes``.
293 For more information and migration instructions,
294 see the `pytest-runner notice <https://github.com/pytest-dev/pytest-runner#deprecation-notice>`_.
295 See also `pypa/setuptools#1684 <https://github.com/pypa/setuptools/issues/1684>`_.
296
297 setuptools intends to
298 `remove the test command <https://github.com/pypa/setuptools/issues/931>`_.
299
300 Checking with flake8-pytest-style
301 ---------------------------------
302
303 In order to ensure that pytest is being used correctly in your project,
304 it can be helpful to use the `flake8-pytest-style <https://github.com/m-burst/flake8-pytest-style>`_ flake8 plugin.
305
306 flake8-pytest-style checks for common mistakes and coding style violations in pytest code,
307 such as incorrect use of fixtures, test function names, and markers.
308 By using this plugin, you can catch these errors early in the development process
309 and ensure that your pytest code is consistent and easy to maintain.
310
311 A list of the lints detected by flake8-pytest-style can be found on its `PyPI page <https://pypi.org/project/flake8-pytest-style/>`_.
312
313 .. note::
314
315 flake8-pytest-style is not an official pytest project. Some of the rules enforce certain style choices, such as using `@pytest.fixture()` over `@pytest.fixture`, but you can configure the plugin to fit your preferred style.