0

I would like to integrate pytest into my workflow. I made a following folder structure:

myproject
├── venv
└── src
    ├── __init__.py 
    ├── foo
    │   ├── __init__.py
    │   └── bar.py
    └── tests
        ├── __init__.py
        └── test_bar.py

I would like to be able to import the namespace from the foo package so that I can write test scripts in the tests folder. Whenever I try to run pytest, or pytest --import-mode append I always get the following error:

ModuleNotFoundError: No module named 'foo'

I found this similar question here but adding the __init__.py files to the tests and the src folder does not solve the issue.

Does this have to do with the PYTHONPATH system variable? This folder structure works perfectly if I run the __main__.py from the src folder, but fails when I want to use pytest. Is there a way to do this without having to mess with PYTHONPATH or are there automated ways to edit the system variable?

Speterius
  • 147
  • 1
  • 11
  • What is the import statement that you are using for fetching the files from ```foo``` folder? – Stan11 Dec 16 '20 at 08:06
  • I tried two options: 1) Nothing in the foo `__init__.py` file and using `import foo` 2) Importing the functions I need within `__init__.py` and using `from foo import baz` Neither of these work. – Speterius Dec 16 '20 at 10:32
  • 1
    Did you try this approach - Add a ```__init__.py``` file under the ```tests``` folder alone then try to use ```from foo import *``` in your ```test_bar.py``` file – Stan11 Dec 16 '20 at 10:38
  • In the `foo` folder I have a file called `bar.py` and within that I have a function called `baz`. I added `from foo import *` to the `test_bar.py` file and this works and I can call `baz()` without issue. – Speterius Dec 16 '20 at 14:40
  • 1
    Actually all types of `import` commands seem to work now that I deleted the `__init__.py` from the `src` folder. – Speterius Dec 16 '20 at 14:44
  • Yes you need to keep the ```__init__.py``` file only under the ```test``` folder. Not anywhere else – Stan11 Dec 16 '20 at 14:47
  • By adding an `__init__.py` into `src` directory, you have effectively made `src` a package, so the import path of the `bar` module is now `src.foo.bar`. This is not what the `src` layout is used for. The `src` dir is there to ensure you don't import code from your repository, instead testing how the installed package behaves. You don't probably need to use the `src` layout in the first place. – hoefling Dec 16 '20 at 15:26
  • I wanted to add the `src` folder because the project I started to work on requires a bunch assets, data folders etc, but it's actually not relevant to the question. But now I understand the problem thanks! – Speterius Dec 16 '20 at 15:45

0 Answers0