Skip to content

Commit 272aba9

Browse files
committed
Mention the src layout as recommended practice
1 parent 4a93483 commit 272aba9

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

doc/en/goodpractices.rst

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ be imported as ``test_app`` and ``test_view`` top-level modules by adding ``test
6363
If you need to have test modules with the same name, you might add ``__init__.py`` files to your
6464
``tests`` folder and subfolders, changing them to packages::
6565

66+
setup.py
6667
mypkg/
6768
...
6869
tests/
@@ -81,19 +82,27 @@ the test modules from the ``tests`` directory, pytest prepends the root of the r
8182
This is problematic if you are using a tool like `tox`_ to test your package in a virtual environment,
8283
because you want to test the *installed* version of your package, not the local code from the repository.
8384

84-
There are a couple of solutions to this:
85-
86-
* Do not add the ``tests/__init__.py`` file. This will cause your test modules to be loaded as
87-
``foo.test_view`` and ``bar.test_view``, which is usually fine and avoids having the root of
88-
the repository being added to the ``PYTHONPATH``.
85+
In this situation, it is **strongly** suggested to use a ``src`` layout where application root package resides in a
86+
sub-directory of your root::
8987

90-
* Add ``addopts=--import-mode=append`` to your ``pytest.ini`` file. This will cause ``pytest`` to
91-
load your modules by *appending* the root directory instead of prepending.
88+
setup.py
89+
src/
90+
mypkg/
91+
__init__.py
92+
app.py
93+
view.py
94+
tests/
95+
__init__.py
96+
foo/
97+
__init__.py
98+
test_view.py
99+
bar/
100+
__init__.py
101+
test_view.py
92102

93-
* Alternatively, consider using the ``src`` layout explained in detail in this excellent
94-
`blog post by Ionel Cristian Mărieș <https://blog.ionelmc.ro/2014/05/25/python-packaging/#the-structure>`_
95-
which prevents a lot of the pitfalls described here.
96103

104+
This layout prevents a lot of common pitfalls and has many benefits, which are better explained in this excellent
105+
`blog post by Ionel Cristian Mărieș <https://blog.ionelmc.ro/2014/05/25/python-packaging/#the-structure>`_.
97106

98107
Tests as part of application code
99108
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -119,6 +128,8 @@ In this scheme, it is easy to your run tests using the ``--pyargs`` option::
119128

120129
``pytest`` will discover where ``mypkg`` is installed and collect tests from there.
121130

131+
Note that this layout also works in conjunction with the ``src`` layout mentioned in the previous section.
132+
122133

123134
.. note::
124135

0 commit comments

Comments
 (0)