运行简单的 pytest 时出现 ModuleNotFoundError

vtb*_*ose 4 python pytest

Python 版本 3.6

\n

我有以下文件夹结构

\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.py\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 tests/\n|     \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 test_Car.py\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 automobiles/\n      \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 Car.py\n
Run Code Online (Sandbox Code Playgroud)\n

我的程序.py

\n
from automobiles.Car import Car\n\np = Car("Grey Sedan")\nprint(p.descriptive_name())\n
Run Code Online (Sandbox Code Playgroud)\n

卡比

\n
class Car():\n    description = "Default"\n    \n    def __init__(self, message):\n        self.description = message\n\n    def descriptive_name(self):\n        return self.description\n
Run Code Online (Sandbox Code Playgroud)\n

test_Car.py

\n
from automobiles.Car import Car\n\ndef test_descriptive_name():\n    input_string = "Blue Hatchback"\n    p = Car(input_string)\n    assert(p.descriptive_name() == input_string)\n
Run Code Online (Sandbox Code Playgroud)\n

运行pytest时时,出现以下错误-

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

我已经为此奋斗了一段时间,我认为我错过了一些明显的东西。\n我不认为这与缺失有任何关系__init__.py- 我尝试放置一个空的__init.py__在 car.py 文件旁边放置一个空文件,但没有误差上的差异。

\n

我必须改变什么才能获得test_Car.py成功运行?

\n

joj*_*ojo 6

您有 2 个选择:

  1. 运行python -m pytest而不是pytest,这也会将当前目录添加到sys.path(有关详细信息,请参阅官方文档)。

  2. 在tests/下添加一个__init__.py文件,然后你就可以简单地运行。这基本上使 pytest 能够发现测试(如果它们位于应用程序代码之外)。您可以在官方文档的“应用程序代码外部测试”部分中找到有关此内容的更多详细信息。pytest

希望有帮助!