最小的python模拟库
sleuth-mock的Python项目详细描述
最小的python模拟库
#为什么是侦探?
大多数python项目使用mock,这在python 3中变成了unittest.mock。为什么要写侦探?
首先,与mock相比,sleuth对mock有不同的理解,mock本质上可以概括为“mock函数而不是对象”。模拟函数是一项显式的、可读的和可预测的工作,它会导致干净的测试用例和 松散耦合的代码。
第二,sleuth的目标是拥有一个简单而有表现力的api。有时用mock很难知道发生了什么 你需要通过哪些论据来嘲笑你需要的东西。sleuth将模拟函数分解为一组清晰的 定义的用例:
- watch: You want to see how a function is called, but not change its behaviour.
- switch: You want to replace a function with another one for testing.
- detonate: You want to throw an exception when the function is called.
- fake: You want to replace the function with another one which returns a particular value when called.
#用法
与侦探一起观看通话。观看
- with sleuth.watch(“some.path.to.thing”) as mock:
- result = thing(1, a=2) self.assertTrue(mock.called) self.assertEqual(1, mock.call_count) self.assertEqual([((1,), {a:2})], mock.calls) self.assertEqual(result, mock.call_returns[0])
用sleuth.switch替换函数…
- with sleuth.switch(“some.path.to.thing”, lambda x: ‘something’) as mock:
- thing(1, a=2) self.assertTrue(mock.called) self.assertTrue([‘something’], mock.call_returns)
使函数引发与sleuth的异常。引爆:
- with sleuth.detonate(“some.path.to.thing”, exception=ValueError):
- try:
- thing(1, a=2)
- except ValueError:
- pass
或者…
- with sleuth.detonate(“some.path.to.thing”, exception=ValueError(“Some custom thingy”)):
- try:
- thing(1, a=2)
- except ValueError:
- pass
用特定的返回值替换函数为sleuth.fake
- with sleuth.fake(“some.path.to.thing”, return_value=1) as mock:
thing(1, a=2)
self.assertEqual([1], mock.call_returns)