Doing dirty (but extremely useful) things with equals.
Project description
Doing dirty (but extremely useful) things with equals.
Documentation: dirty-equals.helpmanual.io
Source Code: github.com/samuelcolvin/dirty-equals
dirty-equals is a python library that (mis)uses the __eq__
method to make python code (generally unit tests)
more declarative and therefore easier to read and write.
dirty-equals can be used in whatever context you like, but it comes into its own when writing unit tests for applications where you're commonly checking the response to API calls and the contents of a database.
Usage
Here's a trivial example of what dirty-equals can do:
from dirty_equals import IsPositive
assert 1 == IsPositive
assert -2 == IsPositive # this will fail!
That doesn't look very useful yet!, but consider the following unit test code using 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),
}
Without dirty-equals, you'd have to compare individual fields and/or modify some fields before comparison - the test would not be declarative or as clear.
dirty-equals can do so much more than that, for example:
IsPartialDict
lets you compare a subset of a dictionaryIsStrictDict
lets you confirm order in a dictionaryIsList
andIsTuple
lets you compare partial lists and tuples, with or without order constraints- nesting any of these types inside any others
IsInstance
lets you simply confirm the type of an object- You can even use boolean operators
|
and&
to combine multiple conditions - and much more...
Installation
Simply:
pip install dirty-equals
dirty-equals requires Python 3.8+.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for dirty_equals-0.8.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0ef998ba3c395e03cf5eb3cd1c13c26a9a992efa18c0d59c22ba27344519cee1 |
|
MD5 | b1333ed44298b5aaf02f9e4600c2a642 |
|
BLAKE2b-256 | f3cd8c3ce82cc6b18e149bff3cf8dd50a75316ca093ae706f0c1c4df87f2b88f |