簡體   English   中英

運行簡單的 ModuleNotFoundError pytest

[英]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 個選擇:

  1. 運行python -m pytest而不是pytest ,這也會將當前目錄添加到sys.path (有關詳細信息,請參閱官方文檔)。

  2. tests/下添加一個__init__.py文件,然后你可以簡單地運行pytest 如果測試存在於應用程序代碼之外,這基本上使 pytest 能夠發現測試。 您可以在官方文檔的“ 測試外部應用程序代碼”部分中找到有關此的更多詳細信息。

希望有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM