gpt4 book ai didi

python - Python模拟中的模拟属性?

转载 作者:IT老高 更新时间:2023-10-28 20:22:19 25 4
gpt4 key购买 nike

我在 Python 中使用 mock 时遇到了相当困难:

def method_under_test():
r = requests.post("http://localhost/post")

print r.ok # prints "<MagicMock name='post().ok' id='11111111'>"

if r.ok:
return StartResult()
else:
raise Exception()

class MethodUnderTestTest(TestCase):

def test_method_under_test(self):
with patch('requests.post') as patched_post:
patched_post.return_value.ok = True

result = method_under_test()

self.assertEqual(type(result), StartResult,
"Failed to return a StartResult.")

测试实际上返回了正确的值,但是 r.ok 是一个 Mock 对象,而不是 True。如何在 Python 的 mock 库中模拟属性?

最佳答案

您需要使用 return_valuePropertyMock :

with patch('requests.post') as patched_post:
type(patched_post.return_value).ok = PropertyMock(return_value=True)

这意味着:当调用 requests.post 时,在该调用的返回值上,为属性 ok 设置一个 PropertyMock 以返回值 True

关于python - Python模拟中的模拟属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16867509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com