0

Context

I am trying to run unit tests using pytest, however, the test files are unable to find the modules because they inherit from an abstract class.

More specifically, I have the following directory structure:

project
|- __init__.py
|- project.py
|- JsonParser.py
|- Parser.py
|- tests
   |__init__.py
   |-test_JsonParser.py

JsonParser has the following import:

from Parser import Parser

test_JsonParser.py has the following import:

from project.JsonParser import JsonParser

The goal is to import the JsonParser class from JsonParser that lives in the 'project' parent directory. When I try this, pytest makes the following complaint:

ModuleNotFoundError: No module named 'Parser'

Relevant Fix Attempts

I have chosen the respective directory structure because of the thread below. Itt works well when there is no inheritance of an abstract base class. I suspect the issue is with how the JsonParser imports Parser. There is a nested import and pytest can't reconcile this, even when running from the parent directory

What is the best project structure for a Python application?

The thread below is the closest I came to an answer, but it becomes a chicken and egg issue. If I make the path relative, I cannot execute 'project.py' because it will not be able to locate the relative path of Parser.

Python, import package module when class inherit abstract class

EDIT: I should mention that I run my tests with the following:

pytest tests/test_JsonParser.py
user2899525
  • 105
  • 10

1 Answers1

1

Looks like the trick was to execute in the following way:

Python -m pytest project/tests

Doing this adds the root directory to the search path. Running with only pytest does not include the root directory in the Python file search path. For example, when the test is executed with 'pytest ', Parser will not be able to be imported into JsonParser because the interpreter will search for Parser.Parser in only the Parser directory. Notice that Parser.Parser is relative to the root directory. If the root directory is not in the search path, the interpreter will not find files that are imported by other files in the same directory.

user2899525
  • 105
  • 10
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 27 '21 at 05:45