简体   繁体   English

运行简单的 ModuleNotFoundError pytest

[英]ModuleNotFoundError when running a simple pytest

Python version 3.6 Python 版本 3.6

I have the following folder structure我有以下文件夹结构

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

my_program.py我的程序.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测试车.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-在项目根文件夹的命令行中运行pytest时,出现以下错误-

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.我不认为这与丢失的__init__.py有任何关系 - 我试过在 car.py 文件旁边放置一个空的__init.py__ ,错误没有区别。

What do I have to change to get the test_Car.py to run successfully?我必须更改什么才能使test_Car.py成功运行?

You have 2 options:您有 2 个选择:

  1. Run python -m pytest instead of pytest , which will also add the current directory to sys.path (see official docs for details).运行python -m pytest而不是pytest ,这也会将当前目录添加到sys.path (有关详细信息,请参阅官方文档)。

  2. Add a __init__.py file under tests/ , then you can simply run pytest .tests/下添加一个__init__.py文件,然后你可以简单地运行pytest This basically enables pytest to discover the tests if they live outside of the application code.如果测试存在于应用程序代码之外,这基本上使 pytest 能够发现测试。 You can find some more details about this in the Tests outside application code section in the official docs.您可以在官方文档的“ 测试外部应用程序代码”部分中找到有关此的更多详细信息。

Hope that helped!希望有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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