Home > front end >  ModuleNotFoundError when running a simple pytest
ModuleNotFoundError when running a simple pytest

Time:03-01

Python version 3.6

I have the following folder structure

.
├── main.py
├── tests/
|     └── test_Car.py
└── automobiles/
      └── Car.py

my_program.py

from automobiles.Car import Car

p = Car("Grey Sedan")
print(p.descriptive_name())

Car.py

class Car():
    description = "Default"
    
    def __init__(self, message):
        self.description = message

    def descriptive_name(self):
        return self.description

test_Car.py

from automobiles.Car import Car

def test_descriptive_name():
    input_string = "Blue Hatchback"
    p = Car(input_string)
    assert(p.descriptive_name() == input_string)

When running pytest in the commandline from the project root folder, I get the following error-

Traceback:
..\..\..\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests\test_Car.py:2: in <module>
    from automobiles.Car import Car
E   ModuleNotFoundError: No module named 'automobiles'

I've been battling this for awhile now and I think I'm missing something obvious. I don't think it is anything to do with a missing __init__.py - I've tried placing an empty __init.py__ alongside the car.py file, with no difference in the error.

What do I have to change to get the test_Car.py to run successfully ?

CodePudding user response:

You have 2 options:

  1. Run python -m pytest instead of pytest, which will also add the current directory to sys.path (see official docs for details).

  2. Add a __init__.py file under tests/, then you can simply run pytest. This basically enables pytest to discover the tests if they live outside of the application code. You can find some more details about this in the Tests outside application code section in the official docs.

Hope that helped!

  • Related