Python 模拟中的模拟属性? [英] Mock attributes in Python mock?

查看:31
本文介绍了Python 模拟中的模拟属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having a fairly difficult time using mock in Python:

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 库中模拟属性?

The test actually returns the right value, but r.ok is a Mock object, not True. How do you mock attributes in Python's mock library?

推荐答案

您需要使用 return_valuePropertyMock:

You need to use return_value and PropertyMock:

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

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

This means: when calling requests.post, on the return value of that call, set a PropertyMock for the property ok to return the value True.

这篇关于Python 模拟中的模拟属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆