[英]Mocking function imported to many locations
我想在每個導入的地方模擬一個函數。
說我有
# foo.py
def send_email():
call_email_service()
# bar1.py
from foo import send_email
def my_func():
...
send_email()
和許多其他使用send_email
的文件。 我想要一個夾具來模擬send_email
的所有用法。
嘗試修補'foo.send_email'
不起作用,因為您需要修補它使用的命名空間(即,我必須修補'bar1.send_email'
)。
我有最好的解決方案是重寫代碼是這樣的:
# foo.py
def send_email():
_send_email_mockable()
def _send_email_mockable():
call_email_service()
並編寫一個像這樣的夾具:
@pytest.fixture(autouse=True)
def _mock_email_service():
with patch('foo._send_email_mockable', autospec=True):
yield
這確實有效,但如果可能的話,我希望測試邏輯不要潛入我的主要邏輯,如果send_email
有一個復雜的函數簽名,我必須重復兩次。
將您的導入語句更改為以下內容:
# bar1.py
# Previous way
from foo import send_email
# New way
import foo
def my_func():
...
foo.send_email()
這將允許模擬在將send_email
加載到目標文件中之前修補foo
命名空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.