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

查看:78
本文介绍了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?

推荐答案

您需要使用

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天全站免登陆