受Shouldly启发的Python断言助手
项目描述
需求
forbiddenfruit
forbidden fruit将能够工作的Python版本(必须实现CTypes/CPython Python API)
Python 2.7或3.3(它可能与其他版本兼容,例如其他3.x版本,但未对这些版本进行测试)
断言
示例
>>> import should_be.all >>> class Cheese(object): ... crackers = 3 ... >>> swiss = Cheese() >>> swiss.crackers.should_be(4) AssertionError: swiss.crackers should have been 4, but was 3
安装
简单方法
$ sudo pip install https://github.com/DirectXMan12/should_be.git#egg=ShouldBe
稍微复杂一点的方法
$ git clone https://github.com/DirectXMan12/should_be.git
$ cd should_be
$ ./setup.py build
$ sudo ./setup.py install
扩展
编写自己的断言相当简单。ShouldBe有两个核心部分:BaseMixin
和should_follow
。
所有断言都应放在继承自BaseMixin
的类中。BaseMixin
提供了扩展内置对象以使用断言的基本工具。
包含您断言的类应该有一个名为 target_class
的类变量。这是您的断言将在其上运行的类。默认情况下,这设置为 object
。如果您希望断言在 object
上运行,有一些额外的注意事项(见下文警告)。
然后,断言应定义为实例方法。每个方法应该调用 self.should_follow
一次或多次。将 should_follow 视为加强版的 assertTrue。它有以下签名: should_follow(self, assertion, msg=None, **kwargs)
。显然,断言是一个表达式,当它为 False
时,将导致 should_follow 抛出 AssertionError。到目前为止,相当正常。msg
是事情变得有趣的地方。msg 应该是一个新的 Python 格式字符串,其中只包含命名替换。默认情况下,should_follow
将传递 txt 和 self 键到 format 方法,以及传递给 should_follow
的任何关键字参数。self 显然是当前对象。txt
是表示当前对象的代码。例如,如果我们编写 (3).should_be(4)
,txt 将是 ‘(3)’。如果我们编写 cheese.variety.should_be('cheddar')
,txt 将是 ‘cheese.variety’。
编写完所有断言后,您只需编写 MyAssertionMixin.mix()
即可加载您的断言。正在开发 setuptools 钩子,以便使用 import should_be.all
自动加载自定义断言混入。