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

标签 python unit-testing testing mocking python-mock

我在 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/

相关文章:

python - 正则表达式:验证没有查询参数的 URL 路径

python - 如何模拟函数以返回带有属性的响应?

python - Django 中的 Multi-Tenancy SAAS

python - 三引号内可以有变量吗?如果是这样,怎么做?

python - 这里如何使用reduce函数?

unit-testing - 编写一个预期出现段错误的 Rust 测试

c# - 使用 Machine.Specs 使用 MVC MailerBase 测试类时出错

testing - Hyperledger Fabric 测试网络中 channel 创建失败

python - 如何测试缺少的额外要求?

testing - 过滤 junit 测试套件时未找到测试