![](/img/trans.png)
[英]Pytest ImportError and ModuleNotFoundError when running test from a sub directory
[英]ModuleNotFoundError when running a simple pytest
Python 版本 3.6
我有以下文件夹结构
.
├── main.py
├── tests/
| └── test_Car.py
└── automobiles/
└── Car.py
我的程序.py
from automobiles.Car import Car
p = Car("Grey Sedan")
print(p.descriptive_name())
卡比
class Car():
description = "Default"
def __init__(self, message):
self.description = message
def descriptive_name(self):
return self.description
测试车.py
from automobiles.Car import Car
def test_descriptive_name():
input_string = "Blue Hatchback"
p = Car(input_string)
assert(p.descriptive_name() == input_string)
在项目根文件夹的命令行中运行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'
我已经为此奋斗了一段时间,我想我遗漏了一些明显的东西。 我不认为这与丢失的__init__.py
有任何关系 - 我试过在 car.py 文件旁边放置一个空的__init.py__
,错误没有区别。
我必须更改什么才能使test_Car.py
成功运行?
您有 2 个选择:
运行python -m pytest
而不是pytest
,这也会将当前目录添加到sys.path
(有关详细信息,请参阅官方文档)。
在tests/下添加一个__init__.py文件,然后你可以简单地运行pytest
。 如果测试存在于应用程序代码之外,这基本上使 pytest 能够发现测试。 您可以在官方文档的“ 测试外部应用程序代码”部分中找到有关此的更多详细信息。
希望有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.