0

How do I have to arrange my files so python -m pytest finds the classes in them?


I have the following strucutre (following the pytest docs convention) and several stackoverflow posts (this or this for example):

├─ testapp
│   ├─ module
│   │   ├─ __init__.py
│   │   ├─ app.py
│   ├─ test
│   │   ├─ test_app.py

The files contain the following:

# __init__.py

from .app import App
# app.py

class App:
    def __init__(self):
        pass

    def add(self, a, b):
        return a + b
# test_app.py

import sys
import pytest

# sys.path.insert(0, '../') # doesn't make any difference
# sys.path.insert(0, '../module') # doesn't make any difference
# print(sys.path) # shows that testapp/ is in the path no matter if the two lines above are included or not

import module.App # doesn't work

class TestApp:
    def test_add():
        app = module.App()
        assert app.add(1, 2) == 3

When I run python -m pytest in the testapp/ (it even sais it is ececuted with the root on testapp/) I get the error: ModuleNotFoundError: No module named 'module.App'.

I tried module.app.App with and without removing the code in the __init__.py. I tried inserting . and .. and ../module to the path before importing. I tried to add __init__.pys in the testapp/ and/or in the testapp/test. I tried adding a conftest.py. Nothing works. But this is the "Good Integration Practices" (cite from pytest) so this should be working.

What am I doing wrong? What do I have to do to make it work?

miile7
  • 2,547
  • 3
  • 23
  • 38

1 Answers1

2

I get the error: ModuleNotFoundError: No module named 'module.App'.

You get the error that there's no module module.App because module.App is not a module, it's a class.

Just import module and it'll work fine using python -mpytest. You'll need a conftest.py at the root of the directory iff you also want a direct pytest (without python -m) to work, as documented.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • Thank you so much. That was a stupid mistake. It takes two more minuts until I can accpet your answer. But I will, it fixed my problem. – miile7 Jun 18 '20 at 11:20