![](/img/trans.png)
[英]Unit testing Python Azure Function: How do I construct a mock test request message with a JSON payload?
[英]How do I mock a python function within a test
我正在嘗試模擬從重命名的庫中導入的函數。
這個例子
mylibrarywithlongname:
def helloworld():
return "hello world"
def helloworld_helper():
return helloworld()
主程序:
import mylibrarywithlongname as ml
from mock import MagicMock
def test():
ml.helloworld = MagicMock(return_value="oops")
print(ml.helloworld_helper())
print(ml.helloworld_helper())
test()
print(ml.helloworld_helper())
這返回
hello world
oops
oops
我試圖找到僅在測試中模擬的語法,而不必復制該函數並手動還原它。
第三行應返回原始的“ hello world”
對於此示例,我使用的是python 2.7(因為我嘗試模擬一個舊項目)
我的嘗試:
from mock import MagicMock, patch
@patch(ml.helloworld, MagicMock(return_value="oops"))
def test():
print(ml.helloworld_helper())
失敗並顯示錯誤
AttributeError: 'function' object has no attribute 'rsplit'
回答我自己的問題:我需要打補丁原始的導入名稱才能起作用。
import mylibrarywithlongname as ml
from mock import patch
def test():
with patch('mylibrarywithlongname.helloworld') as mp:
ml.helloworld.return_value = "oops"
print(ml.helloworld_helper())
print(ml.helloworld_helper())
test()
print(ml.helloworld_helper())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.