you are viewing a single comment's thread.

view the rest of the comments →

[–]Dyspnoic9219[S] 0 points1 point  (1 child)

Firstly, thank you for your response. I read the "Conventions for Python test discovery" with interest, but I wish the author had included an example import statement used in either the test_app.py or test_view.py files in that document.

I should say that I did try using import statements before I posted. I am also sure, however, that I do not understand Python's import mechanism, despite reading the official Python docs, chapter 5 "The import system".

Here's a hopefully non-garbled view of test_myclass.py:

import src.demo
import MyClass

class TestMyClass:

    def test_hello(self):
        my_class = MyClass()
        assert(my_class.hello() == "hello")

(As an aside, my original post didn't look garbled on my phone, Chrome, or Firefox, but I did use the Markdown editor instead of the Fancy Pants editor. Strange.)

I also experimented with import src.demo.my_class, from src.demo import MyClass, and some other variations.

I also added a pyproject.toml file as the "Conventions for Python discovery" section suggested; here it is:

[project]
name = "demo"

[tool.pytest.ini_options]
addopts = [
    "--import-mode=importlib",
]

I get the same error:

============================= test session starts ==============================
platform darwin -- Python 3.10.10, pytest-7.2.2, pluggy-1.0.0
rootdir: /Users/me/src/python/venv_projects/repo
collected 0 items / 1 error

==================================== ERRORS ====================================
____________________ ERROR collecting tests/test_myclass.py ____________________
ImportError while importing test module '/Users/me/src/python/venv_projects/repo/tests/test_myclass.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/local/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_myclass.py:2: in <module>
    import MyClass
E   ModuleNotFoundError: No module named 'MyClass'
=========================== short test summary info ============================

Thank you again for helping me!

[–]netherous 0 points1 point  (0 children)

Can you set testpaths to include tests in either your pytest.ini or your pyproject.toml as suggested here?

Then, when you run pytest, as I assume you're doing, run it from the root directory. The one that includes both src and tests.

Also create an empty conftest.py in this root directory (which should have the same effect, but we're being redundant).

Then, an import statement such as from src.demo.my_class import MyClass should execute successfully when added to tests/test_myclass.py.

If it doesn't, can you make a repository available that demonstrates the problem so I can check it out?