0

I am using Python 3.6.5 and testing with py.test.

I have had the following structure of my test folder.

tests/
    some_folder/
        test_module.py
    utils.py

In test_module.py I import utils.py to use some functions from there. In test_module.py I have a test function which runs perfectly when I execute it but when I try to debug it in PyCharm I receive

from tests import utils
ImportError: cannot import name 'utils'

So I tried to convert my tests folder into a package and it solved the problem. Now I have the following structure of my tests:

tests/
    some_folder/
        test_module.py
    __init__.py
    utils.py 

But why it solves the problem? And why the problem does not occur when I simply run the test?

  • The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later (deeper) on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later. To import utils.py methods inside test_module.py, first the utils should be recognized. https://stackoverflow.com/questions/448271/what-is-init-py-for – user2906838 Jul 31 '18 at 14:56

1 Answers1

0

It is a pycharm quirk. The better way to fix the issue you're having is to mark your folder as a source root and make sure these boxes are selectedmake sure these boxes are selected

krflol
  • 1,105
  • 7
  • 12