使用equals(虽然不干净但非常有用)进行操作。
项目描述
使用equals(虽然不干净但非常有用)进行操作。
文档: dirty-equals.helpmanual.io
源代码: github.com/samuelcolvin/dirty-equals
dirty-equals 是一个Python库,它(错误地)使用 __eq__
方法来使Python代码(通常为单元测试)更声明性,因此更容易阅读和编写。
dirty-equals 可在任何您喜欢的上下文中使用,但它真正发挥其优势是在编写单元测试时,尤其是当您通常检查API调用的响应和数据库内容时。
用法
以下是一个简单的 dirty-equals 用法的示例
from dirty_equals import IsPositive
assert 1 == IsPositive
assert -2 == IsPositive # this will fail!
看起来并不怎么有用!,但考虑以下使用 dirty-equals 的单元测试代码
from dirty_equals import IsJson, IsNow, IsPositiveInt, IsStr
...
# user_data is a dict returned from a database or API which we want to test
assert user_data == {
# we want to check that id is a positive int
'id': IsPositiveInt,
# we know avatar_file should be a string, but we need a regex as we don't know whole value
'avatar_file': IsStr(regex=r'/[a-z0-9\-]{10}/example\.png'),
# settings_json is JSON, but it's more robust to compare the value it encodes, not strings
'settings_json': IsJson({'theme': 'dark', 'language': 'en'}),
# created_ts is datetime, we don't know the exact value, but we know it should be close to now
'created_ts': IsNow(delta=3),
}
如果没有 dirty-equals,您将不得不逐个字段进行比较,或者修改某些字段后再进行比较 - 测试将不会是声明式的,也不够清晰。
dirty-equals 可以做更多的事情,例如
IsPartialDict
允许您比较字典的子集IsStrictDict
允许您确认字典中的顺序IsList
和IsTuple
允许您比较部分列表和元组,带或不带顺序约束- 将这些类型嵌套在任何其他类型中
IsInstance
允许您简单地确认对象的类型- 您甚至可以使用 布尔运算符
|
和&
来组合多个条件 - 还有很多...
安装
简单
pip install dirty-equals
dirty-equals 需要 Python 3.8+。
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。
源分布
dirty_equals-0.8.0.tar.gz (50.3 kB 查看哈希值)
构建分布
dirty_equals-0.8.0-py3-none-any.whl (28.2 kB 查看哈希值)