![](/img/trans.png)
[英]How to mock/patch a function without return value that changes parameter values?
[英]How to Mock Attributes & Properties of Return Values with patch()
test_client / wclient.py
import json
import requests
client = requests.session()
def setup():
response = REST_CLIENT.post(
"https://placeholder.com",
auth=(placeholder, placeholder),
data={"grant_type": "client_credentials"},
)
status_code = response.status_code
if status_code in OK_STATUS:
payload = json.loads(response.content, object_pairs_hook=OrderedDict)
else:
payload = response.text
msg = (
"Status Code %s" % status_code
)
logger.error(msg)
raise ValueError(msg)
return payload["access_token"]
测试文件:test_client / test_client.py
import mock
import wclient
@mock.patch("test_client.wclient")
def test_taxes_pitney_bowes_setup_success(resp):
resp.return_value.post.return_value.status_code = "200"
wclient.pitney_bowes_setup()
Status Code <MagicMock name='REST_CLIENT.post().status_code' id='4868492200'>
我该如何使用ock.patch()模拟模块的方法和属性? 我已经阅读了堆栈溢出文章的页面,但是我对执行魔术模拟的所有不同方法感到困惑。
我试过嘲笑:
resp.return_value.post.return_value.status_code
resp.return_value.post.return_value.status_code.return_value
resp.post.return_value.status_code
resp.post.return_value.status_code.return_value
resp.post.status_code
resp.post.status_code.return_value
我认为实际上有很多方法可以进行模拟(请参见在Python中模拟方法调用中的许多方法)。 我喜欢这样做并容易进行简单模拟的方式是:
对于函数: @patch('module.print', lambda x: None)
对于属性: @patch('module.cwd', os.path.join(os.getcwd(), "folder"))
这篇博客文章可能对您有所帮助: https : //medium.com/uckey/how-mock-patch-decorator-works-in-python-37acd8b78ae 。
如果您还有其他问题,请告诉我。
编辑:要添加多个模拟,只需添加另一个属性:
import wclient
@mock.patch("test_client.wclient")
@mock.patch("another_attribute", "value")
@mock.patch("another_function", lambda x, y: x + y)
def test_taxes_pitney_bowes_setup_success(resp):
resp.return_value.post.return_value.status_code = "200"
wclient.pitney_bowes_setup()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.