繁体   English   中英

Python 模拟中的模拟属性?

[英]Mock attributes in 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

一个紧凑而简单的方法是使用new_callable patch的属性来强制patch使用PropertyMock而不是MagicMock来创建模拟对象。 传递给patch的其他参数将用于创建PropertyMock对象。

with patch('requests.post.ok', new_callable=PropertyMock, return_value=True) as mock_post:
    """Your test"""

使用模拟版本“1.0.1”,支持问题中提到的更简单的语法并按原样工作!

示例代码更新(使用 py.test 代替 unittest):

import mock
import requests


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

    print r.ok

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


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

        result = method_under_test()
        assert result is True, "mock ok failed"

使用以下代码运行此代码:(确保安装 pytest)

$ py.test -s -v mock_attributes.py 
======= test session starts =======================
platform linux2 -- Python 2.7.10 -- py-1.4.30 -- pytest-2.7.2 -- /home/developer/miniconda/bin/python
rootdir: /home/developer/projects/learn/scripts/misc, inifile: 
plugins: httpbin, cov
collected 1 items 

mock_attributes.py::test_method_under_test True
PASSED

======= 1 passed in 0.03 seconds =================

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM