最小的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)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
序列化反序列化java。awt。颜色>java。木卫一。InvalidClassException   java禁用多个日期范围jDateChooser   java为什么我的特例apper会被扔进泽西/灰熊?   JavaIntelliJ比较两个覆盖率数据   java什么是servletsdefault。你怎么办?   单击几下libgdx后java按钮没有响应   使用java将字符串转换为JSONArray   文件系统在java中刷新fileSystemViewer   java如何在hibernate中避免脏检查   java奇怪的问题,带有分号和“无法解决…”   java将值从子面板传递到父面板   HTML JTextPane CSS的Java FontSizeAction   java文件代码神秘地变成了一堆(0000)