简体   繁体   中英

ModuleNotFoundError when running a simple pytest

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM