0

I have the following directory structure:

main_dir/
    |--.git/
    |--.github/
        |--workflows/
            |--main.yml
    |--package/
        |--__init__.py
        |--config.py
    |--tests/
        |--pytest.ini
        |--test_config.py

And in test/test_config.py the first line import a class from the config.py file:

from package.config import Config

These test work when running locally, but on GitHub Actions I get the error ModuleNotFoundError: No module named 'package'. The working directory is the same on both (main_dir). Where am I going wrong?

MisterMiyagi
  • 26,337
  • 5
  • 60
  • 79
  • 1
    *How* do you run this file? Do you locally run it via some IDE perhaps, and as ``python test/test_config.py`` on GH Actions? – MisterMiyagi Mar 25 '21 at 17:05
  • Locally, I use pycharm with the configuration options `target` and `Working Directory` set to the `main_dir`. On GH Actions I have `pipenv run pytest` – Liam Galbraith Mar 25 '21 at 17:17
  • 1
    Does this answer your question? [Pytest: how to work around missing __init__.py in the tests folder?](https://stackoverflow.com/questions/50796370/pytest-how-to-work-around-missing-init-py-in-the-tests-folder) – MisterMiyagi Mar 25 '21 at 17:19
  • @MisterMiyagi That's done the trick! Adding the `__init__.py` has worked, though I was also under the impression that it shouldn't be there. Thanks for the answer and the resources, definitely have some reading up to do! – Liam Galbraith Mar 25 '21 at 17:34

1 Answers1

-1

Your IDE should add your project to your python path.

You can add this in your script using the following snippet:

import os
current_dir = os.path.dirname(os.path.realpath(__file__)))
working_dir = os.path.join(current_dir , "..")

import sys
sys.path.append(working_dir)

You can now have your working directory in your python path using

from package.config import Config

To know what is present in your python path, just print sys.path.

The best practice is directly to add to your path the working directory.

Vincent Bénet
  • 542
  • 2
  • 14