Naf*_*Kay 63 python testing unit-testing mocking python-mock
我mock在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.")
Run Code Online (Sandbox Code Playgroud)
测试实际上返回正确的值,但是r.ok是Mock对象,而不是True.你如何在Python的mock库中模拟属性?
Sim*_*ser 76
你需要使用return_value和PropertyMock:
with patch('requests.post') as patched_post:
type(patched_post.return_value).ok = PropertyMock(return_value=True)
Run Code Online (Sandbox Code Playgroud)
这意味着:在调用时requests.post,在该调用的返回值上,PropertyMock为属性设置a ok以返回该值True.
Mic*_*ico 13
一种紧凑而简单的方法是使用new_callable patch's属性强制patch使用PropertyMock而不是MagicMock创建模拟对象.传递给的其他参数patch将用于创建PropertyMock对象.
with patch('requests.post', new_callable=PropertyMock, return_value=True) as mock_post:
"""Your test"""
Run Code Online (Sandbox Code Playgroud)
how*_*yoo 12
使用模拟版本'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"
Run Code Online (Sandbox Code Playgroud)
运行此代码:(确保安装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 =================
Run Code Online (Sandbox Code Playgroud)