2

I have had a look at several different topics on this matter but can't work out how to apply it to my situation. I don't have an init.py in my test folder and I have tried to use conftest. I have a directory structure like this:

--app
    --app.py
    --src
        --init.py
        --module1.py
        --module2.py
        --module3.py
    --configs
         --config.json
         --non-default-config.json
    --tests
        --test1.py
    --conftest.py

where app.py imports module1, which then imports modules 2&3 (using import src.module2). I load up config.json in all the modules files (and app.py) using:

with open('configs/config.json') as f:
    CFG = json.load(f)

This works when I run app.py from the app directory. However, when I run pytest (which I believe should also be referencing from the app directory, since conftest.py is in the app directory) and it imports module1 (using import src.module1), it cannot find configs/config.json, but will find app/configs/config.json. I cannot use this as it will cause my app to break when I run app.py. However, Pytest can find the imports from within the src folder, even though this is on the same level as the configs folder.

If I move the conftest.py outside of the app directory and import module1 using import app.src.module1 then this import succeeds, but the import of module2 inside module1 then fails.

How can I resolve this issue? And is there a better way of structuring my project?

Lucy
  • 179
  • 1
  • 4
  • 14
  • I realised I can run pytest from inside of the app folder to make it work. However, if there are any structural improvements anyone can suggest then this would still be helpful :) Thanks! – Lucy Oct 27 '20 at 13:41
  • Have you tried renaming `src/init.py` to `src/__init__.py`? https://docs.python.org/3/tutorial/modules.html#packages – Jonathan Dayton Oct 27 '20 at 21:13
  • 1
    Thanks for your comment. Sorry I made an error when typing the name, it is already called `src/__init__.py`. – Lucy Nov 03 '20 at 12:11

1 Answers1

0

Solved this by running pytest from inside the app folder instead of from the base directory.

Lucy
  • 179
  • 1
  • 4
  • 14