5

****solved: added __init__.py to Test/ and renamed testcode.py to test_code.py. To run tests cd -> Zee and type pytest****


Structure:

|--Zee/
|   |--Test/
|   |   |--__init__.py
|   |   |--test_code.py
|   |--Codetotest/
|   |   |--code.py

in code.py

class Foo():
    some code...

in testcode.py

from Codetotest.code import Foo

def test_foo():
   assert ...

When I move to the Zee directory in my command line and run pytest Test/testcode.py I get ModuleNotFoundError: No module named Zee. How can I fix this?

I tried making Test a module by adding Test/__init__.py as suggested here. Ran from multiple directories, no dice.

Pytest version 5.3.4, imported from python 3.6

What I don't understand is, when I add __init__.py to Zee/, it gives me the same error

mpowcode
  • 83
  • 1
  • 6

1 Answers1

1

You need a __init__.py in the module directory.

Here's a typical project structure:

|--zee-project-directory/
|   |--tests/
|   |   |--test_zee.py
|   |--zee/
|   |   |--__init__.py
|   |   |--code.py

code.py

class Foo():
    some code...

test_zee.py

from zee.code import Foo

def test_foo():
   assert ...
Jérôme
  • 13,328
  • 7
  • 56
  • 106
  • Still getting the same error. I tried running pytest testcode.py from ```zee-project-directory```, ```tests``` and ```zee```. – mpowcode Jan 20 '20 at 20:57
  • Run from `zee-project-directory`, no need to specify `tests` as it is the default path. Make sure to change the import like in my example above: `from zee.code import Foo`. Please copy the new error message / stacktrace. – Jérôme Jan 20 '20 at 21:37
  • Working now. I put ```__init__.py``` in ```Test/``` and renamed my file to ```test_whatever``` as I should have done from the start #rtfm – mpowcode Jan 20 '20 at 22:34
  • I don't think you even need __init__.py in tests. The way pytest behaves, test tiles don't have to be modules (unless they import stuff from each other). – Jérôme Jan 21 '20 at 16:54
  • Anyway, glad you solved it and welcome to SO. You may [upvote](https://meta.stackexchange.com/questions/173399/how-to-upvote-on-stack-overflow/173400#173400) / [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) this answer. – Jérôme Jan 21 '20 at 16:55
  • Upvoted. Your answer was helpful, but I had to put the ```__init__.py``` in the ```tests/```, not ```zee/``` folder – mpowcode Jan 21 '20 at 18:35
  • I'm pretty sure you do need `__init__.py` in `zee` and you don't need it in `tests`. – Jérôme Jan 21 '20 at 19:31
  • ¯¯¯\__(ツ)__/¯¯¯ – mpowcode Jan 21 '20 at 20:17
  • I too had to add it to `tests`. Being in the module and other sub-module folders wasn't sufficient. – tim.rohrer Jan 24 '23 at 15:52