tox pytest import doesn't work in a subpackage

51 views Asked by At

I'm playing with this repo https://github.com/mCodingLLC/SlapThatLikeButton-TestingStarterProject. It shows automated testing in Python with pytest and tox.

After cloning the repo the following steps are performed:

  • create a virtualenv
  • pip install -r requirements_dev.txt
  • pip install -e .
  • pytest runs successfully
  • tox runs successfully

I've made a slight change to the layout of src directory. Added a subpackage src/models, moved slap_that_like_button.py to this subpackage and updated tests accordingly. Now the tree and the test looks like this:

src
├── slapping
    ├── __init__.py
    ├── models
    │   ├── __init__.py
    │   └── slap_that_like_button.py
    └── py.typed
diff --git a/tests/test_slapping.py b/tests/test_slapping.py
index 40ed2f4..8298ec5 100644
--- a/tests/test_slapping.py
+++ b/tests/test_slapping.py
@@ -1,5 +1,5 @@
 import pytest
-from slapping.slap_that_like_button import LikeState, slap_many
+from slapping.models.slap_that_like_button import LikeState, slap_many


 def test_empty_slap():

Results:

  1. Why is it that pytest can successfully run from my terminal but can't find the subpackage when launched within tox?
  2. How moving a module to a subpackage makes so much difference?

P.S. For anyone who wants play with the repo. Bump tox version in requirements_dev.txt to 4.11.4. Otherwise it gives this traceback https://gist.github.com/ttl256/76499d8a3b1db0250d571a7fdd7d3b06

EDIT. Installing the package as editable solves the issue however root cause is still unknown.

$ git diff tox.ini
diff --git a/tox.ini b/tox.ini
index 6b58ff8..8730352 100644
--- a/tox.ini
+++ b/tox.ini
@@ -13,6 +13,7 @@ python =
 [testenv]
 setenv =
     PYTHONPATH = {toxinidir}
+package = editable
 deps =
     -r{toxinidir}/requirements_dev.txt
 commands =
1

There are 1 answers

0
ttl256 On

There is packages definition in the option section of setup.cfg:

[options]
packages =
    slapping
install_requires =
    requests>=2
python_requires = >=3.6
package_dir =
    =src
zip_safe = no

When a new package was added setuptools didn't know about it. There are a couple of ways to signal setuptools about a new package and find works nicely here as it saves us from manually adding each package for this simple project.

diff --git a/setup.cfg b/setup.cfg
index 38c125f..095808a 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -14,15 +14,18 @@ classifiers =
     Programming Language :: Python :: 3.9

 [options]
-packages =
-    slapping
 install_requires =
     requests>=2
 python_requires = >=3.6
+packages = find:
 package_dir =
     =src
 zip_safe = no

+[options.packages.find]
+where = src
+exclude =
+
 [options.extras_require]
 testing =
     pytest>=6.0

Now as we add more packages setuptools will automatically discover them.

Reference on custom package discovery: https://setuptools.pypa.io/en/latest/userguide/package_discovery.html#custom-discovery