Python import problems can only run the app or the code but not both

Viewed 44

So I've been searching the site and breaking my head on this. My knowledge seems to limit me to either running code that I can run or code that I can test. Searching for solutions has not yet given me a clearer view on why this is.

I have the following folder structure:

enter image description here

__init__ is an empty file. The rest of the files look like: ClassA.py:

class A:
    def hello(self):
        print('hello')

ClassB.py:

from ClassA import A

class B:
    def hello(self):
        print('hello')
        a = A()
        print(a.hello())

main.py:

from ClassB import B

if __name__ == '__main__':
    b = B()
    b.hello()

test_app.py:

import pytest
import sys
import os

sys.path.append(os.path.realpath(os.path.dirname(__file__)+'/..'))
from src.ClassB import B

def test_app():
    assert 1 == 1

If I run the project from the root of the file all goes well. However if I run the test it tells me:

ModuleNotFoundError: No module named 'ClassA'

I found the cause of this being from ClassA import A in ClassB.py. It wants me to add a dot there, making it from .ClassA import A. However if I add the dot I can no longer run the code...

2 Answers

I think by adding __init__.py in the tests folder your problem will solve.

I finally managed to fix it by placing the tests folder inside the src folder.

However it "feels" wrong to me. I have not yet found a better solution.

Related