Debian Codegraph @

doc/en/explanation/pythonpath.rst

raw
1 .. _pythonpath:
2
3 pytest import mechanisms and ``sys.path``/``PYTHONPATH``
4 ========================================================
5
6 .. _`import-modes`:
7
8 Import modes
9 ------------
10
11 pytest as a testing framework needs to import test modules and ``conftest.py`` files for execution.
12
13 Importing files in Python is a non-trivial process, so aspects of the
14 import process can be controlled through the :option:`--import-mode` command-line flag, which can assume
15 these values:
16
17 .. _`import-mode-prepend`:
18
19 * ``prepend`` (default): The directory path containing each module will be inserted into the *beginning*
20 of :py:data:`sys.path` if not already there, and then imported with
21 the :func:`importlib.import_module <importlib.import_module>` function.
22
23 It is highly recommended to arrange your test modules as packages by adding ``__init__.py`` files to your directories
24 containing tests. This will make the tests part of a proper Python package, allowing pytest to resolve their full
25 name (for example ``tests.core.test_core`` for ``test_core.py`` inside the ``tests.core`` package).
26
27 If the test directory tree is not arranged as packages, then each test file needs to have a unique name
28 compared to the other test files, otherwise pytest will raise an error if it finds two tests with the same name.
29
30 This is the classic mechanism, dating back from the time Python 2 was still supported.
31
32 .. _`import-mode-append`:
33
34 * ``append``: the directory containing each module is appended to the end of :py:data:`sys.path` if not already
35 there, and imported with :func:`importlib.import_module <importlib.import_module>`.
36
37 This better allows users to run test modules against installed versions of a package even if the
38 package under test has the same import root. For example:
39
40 ::
41
42 testing/__init__.py
43 testing/test_pkg_under_test.py
44 pkg_under_test/
45
46 the tests will run against the installed version
47 of ``pkg_under_test`` when :option:`--import-mode=append` is used whereas
48 with ``prepend``, they would pick up the local version. This kind of confusion is why
49 we advocate for using :ref:`src-layouts <src-layout>`.
50
51 Same as ``prepend``, requires test module names to be unique when the test directory tree is
52 not arranged in packages, because the modules will be put in :py:data:`sys.modules` after importing.
53
54 .. _`import-mode-importlib`:
55
56 * ``importlib``: this mode uses more fine control mechanisms provided by :mod:`importlib` to import test modules, without changing :py:data:`sys.path`.
57
58 Advantages of this mode:
59
60 * pytest will not change :py:data:`sys.path` at all.
61 * Test module names do not need to be unique -- pytest will generate a unique name automatically based on the ``rootdir``.
62
63 Disadvantages:
64
65 * Test modules can't import each other.
66 * Testing utility modules in the tests directories (for example a ``tests.helpers`` module containing test-related functions/classes)
67 are not importable. The recommendation in this case is to place testing utility modules together with the application/library
68 code, for example ``app.testing.helpers``.
69
70 Important: by "test utility modules", we mean functions/classes which are imported by
71 other tests directly; this does not include fixtures, which should be placed in ``conftest.py`` files, along
72 with the test modules, and are discovered automatically by pytest.
73
74 It works like this:
75
76 1. Given a certain module path, for example ``tests/core/test_models.py``, derives a canonical name
77 like ``tests.core.test_models`` and tries to import it.
78
79 For non-test modules, this will work if they are accessible via :py:data:`sys.path`. So
80 for example, ``.env/lib/site-packages/app/core.py`` will be importable as ``app.core``.
81 This happens when plugins import non-test modules (for example doctesting).
82
83 If this step succeeds, the module is returned.
84
85 For test modules, unless they are reachable from :py:data:`sys.path`, this step will fail.
86
87 2. If the previous step fails, we import the module directly using ``importlib`` facilities, which lets us import it without
88 changing :py:data:`sys.path`.
89
90 Because Python requires the module to also be available in :py:data:`sys.modules`, pytest derives a unique name for it based
91 on its relative location from the ``rootdir``, and adds the module to :py:data:`sys.modules`.
92
93 For example, ``tests/core/test_models.py`` will end up being imported as the module ``tests.core.test_models``.
94
95 .. versionadded:: 6.0
96
97 .. note::
98
99 Initially we intended to make ``importlib`` the default in future releases, however it is clear now that
100 it has its own set of drawbacks so the default will remain ``prepend`` for the foreseeable future.
101
102 .. note::
103
104 By default, pytest will not attempt to resolve namespace packages automatically, but that can
105 be changed via the :confval:`consider_namespace_packages` configuration variable.
106
107 .. seealso::
108
109 The :confval:`pythonpath` configuration variable.
110
111 The :confval:`consider_namespace_packages` configuration variable.
112
113 :ref:`test layout`.
114
115
116 ``prepend`` and ``append`` import modes scenarios
117 -------------------------------------------------
118
119 Here's a list of scenarios when using ``prepend`` or ``append`` import modes where pytest needs to
120 change :py:data:`sys.path` in order to import test modules or ``conftest.py`` files, and the issues users
121 might encounter because of that.
122
123 Test modules / ``conftest.py`` files inside packages
124 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
125
126 Consider this file and directory layout::
127
128 root/
129 |- foo/
130 |- __init__.py
131 |- conftest.py
132 |- bar/
133 |- __init__.py
134 |- tests/
135 |- __init__.py
136 |- test_foo.py
137
138
139 When executing:
140
141 .. code-block:: bash
142
143 pytest root/
144
145 pytest will find ``foo/bar/tests/test_foo.py`` and realize it is part of a package given that
146 there's an ``__init__.py`` file in the same directory. It will then search upwards until it can find the
147 last directory which still contains an ``__init__.py`` file in order to find the package *root* (in
148 this case ``foo/``). To load the module, it will insert ``root/`` to the front of
149 :py:data:`sys.path` (if not there already) in order to load
150 ``test_foo.py`` as the *module* ``foo.bar.tests.test_foo``.
151
152 The same logic applies to the ``conftest.py`` file: it will be imported as ``foo.conftest`` module.
153
154 Preserving the full package name is important when tests live in a package to avoid problems
155 and allow test modules to have duplicated names. This is also discussed in detail in
156 :ref:`test discovery`.
157
158 Standalone test modules / ``conftest.py`` files
159 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
160
161 Consider this file and directory layout::
162
163 root/
164 |- foo/
165 |- conftest.py
166 |- bar/
167 |- tests/
168 |- test_foo.py
169
170
171 When executing:
172
173 .. code-block:: bash
174
175 pytest root/
176
177 pytest will find ``foo/bar/tests/test_foo.py`` and realize it is NOT part of a package given that
178 there's no ``__init__.py`` file in the same directory. It will then add ``root/foo/bar/tests`` to
179 :py:data:`sys.path` in order to import ``test_foo.py`` as the *module* ``test_foo``. The same is done
180 with the ``conftest.py`` file by adding ``root/foo`` to :py:data:`sys.path` to import it as ``conftest``.
181
182 For this reason this layout cannot have test modules with the same name, as they all will be
183 imported in the global import namespace.
184
185 This is also discussed in detail in :ref:`test discovery`.
186
187 .. _`pytest vs python -m pytest`:
188
189 Invoking ``pytest`` versus ``python -m pytest``
190 -----------------------------------------------
191
192 Running pytest with ``pytest [...]`` instead of ``python -m pytest [...]`` yields nearly
193 equivalent behaviour, except that the latter will add the current directory to :py:data:`sys.path`, which
194 is standard ``python`` behavior.
195
196 See also :ref:`invoke-python`.