0

I was trying to implement something that I saw in a tutorial on Real Python. In the tutorial there a testing module (or do you call that a test file?) is in a directory test/ and the code is in a directory rptodo/, and the test file imports the object to be tested with from rptodo import __app_name__, __version__, cli. This does not run by itself; an error ModuleNotFoundError: No module named 'rptodo' occurs. But this does allow pytest to run the code. I then tried redoing this with my own example code and I get the same error even in pytest. What did I do wrong in creating the module?

My folder structure:

Anywhere
-here
--test_this.py
-there
--__init__.py
--yonder.py

yonder.py

class That:
    thing = 'something'

test_this.py

from there.yonder import That

def test_this():
    this = That()
    print(this.thing)

test_this()
Mordechai
  • 138
  • 7

1 Answers1

-1

I found the answer looking in one of stackoverflow's similar questions, but this is so un-intuitive that I feel the need to post the answer here.

The folder with the test has to be made into a package by creating a file __init__.py. Pytest then knows to look at the parent folder for the module package that the required object is in.

Ironically, the folder being referenced does not need an __init__.py file to be found as a module for importing. Only the current folder making the call needs to be a module with __init__.py .

Not only when importing a module from a different folder, but even when accessing a module from the current folder, pytest needs the folder to have a __init__.py file to be able to import the files with the code for testing.

Mordechai
  • 138
  • 7