[英]How to monkeypatch locally imported module for Python testing with pytest?
我正在處理一個非常大的項目,並且已經有很多使用pytest
的monkeypatch
夾具的測試。 我希望從屬於導入模塊的類中修補特定方法,例如:
from project.common import services
在服務包中有一個類,其中包含我希望修補的方法,例如:
services.utils.Calculations.get_area()
我嘗試mock
和monkeypatch
:
mocked_get_area_method= Mock(return_value=500)
monkeypatch.setattr(
'services.utils.Calculations.get_area',
mocked_get_user_ip_method,
)
然后我在我的測試中創建一個對象:
class TestCommon:
def test_calculations(self,monkeypatch):
mocked_get_area_method= Mock(return_value=500)
monkeypatch.setattr(
'services.utils.Calculations.get_area',
mocked_get_user_ip_method,
)
calculations = services.utils.Calculations()
calculations.get_area()
mocked_get_user_ip_method.assert_called_once()
但我收到一條錯誤消息: ModuleNotFoundError: No module named 'services'.
我相信錯誤來自這樣一個事實,即可能是monkeypatch
從高級主項目文件夾開始查找對象。 如果我嘗試使用這條路徑進行monkeypath
路徑:
monkeypatch.setattr(
'project.common.services.utils.Calculations.get_area',
mocked_get_user_ip_method,
)
monkeypatching 工作但我沒有在我的assert
中得到True
因為我相信 monkeypatching 已經改變了主要項目中的對象但是因為我已經導入它並從本地導入的模塊實例化services.utils.Calculations()
補丁不起作用。
我怎樣才能使這項工作?
注意: pytest 從主項目目錄運行。
您需要將補丁應用於具有from project.common import services
語句的模塊。 例如,假設我有一個文件project/frontend.py
,如下所示:
from project.common import services
def a_method():
calc = services.utils.Calculations()
return calc.get_area()
我想測試a_method
是否正確返回它從get_area()
調用接收到的任何值,所以在tests/test_frontend.py
我可能會寫:
import project.frontend
from unittest import mock
def test_a_method(monkeypatch):
fake_get_area = mock.Mock(return_value=2.0)
monkeypatch.setattr(
project.frontend.services.utils.Calculations, "get_area", fake_get_area
)
res = project.frontend.a_method()
assert res == 2.0
在這里,我們正在修補project.frontend.services.utils.Calculations
因為我們已經導入了project.frontend
並且frontend.py
導入了project.common.services
作為名稱services
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.