0

I have a project like

   .
   |-application
   |---foo.py
   |---bar.py
   |-tests
   |---test_foo.py

Contents are:

bar.py

def myfunc():
    return "hello from bar"

foo.py

from bar import myfunc


def do_work():
    return myfunc()


if __name__ == "__main__":
    print(do_work())

test_bar.py

from application import foo


class TestFoo:
    def test_foo_do_work(self):
        assert foo.do_work() == "hello from bar"

Running python application/foo.py works great, but running python -m pytest tests/ returns error ModuleNotFoundError: No module named 'bar'

In foo.py one way to fix this is to change the import line from from bar import myfunc to from application.bar import myfunc. This causes pytest to pass, but running python application/foo.py gives an error ModuleNotFoundError: No module named 'application'

I don't know what I'm doing wrong. I'm using python 3.7 so I heard __init__.py is unnecessary.

user1080952
  • 1,073
  • 2
  • 10
  • 15

1 Answers1

0

After a little more googling, I have an answer. I created an __init__.py file inside of tests dir with the contents:

import os
import sys
project_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
app_path = os.path.join(project_path, 'application')
sys.path.append(app_path)

From Python nested subpackage doesn't import when running tests

user1080952
  • 1,073
  • 2
  • 10
  • 15