Python library that leverages the __eq__ method to make unit tests more declarative and readable through flexible comparison classes.
npx @tessl/cli install tessl/pypi-dirty-equals@0.9.0A Python library that (mis)uses the __eq__ method to make Python code more declarative and easier to read and write. The library provides a comprehensive collection of comparison classes that enable flexible and expressive equality checks, particularly useful in unit tests where you need to validate data structures without exact value matching.
pip install dirty-equalsfrom dirty_equals import (
# Base classes
DirtyEquals, AnyThing, IsOneOf,
# Boolean types
IsTrueLike, IsFalseLike,
# Numeric types
IsPositive, IsNegative, IsInt, IsFloat, IsApprox,
# String types
IsStr, IsBytes,
# DateTime types
IsDatetime, IsNow, IsDate, IsToday,
# Dict types
IsDict, IsPartialDict, IsStrictDict,
# Sequence types
IsList, IsTuple, Contains, HasLen,
# Inspection types
IsInstance, HasAttributes, HasName, HasRepr,
# Other specialized types
IsJson, IsUUID, IsUrl, IsHash, IsIP, IsDataclass, IsEnum,
FunctionCheck
)All types can be imported from the main package:
from dirty_equals import IsPositive, IsStr, IsJsonVersion information:
from dirty_equals import __version__from datetime import datetime
from dirty_equals import IsPositive, IsStr, IsJson, IsNow, IsDict, IsPartialDict, IsInt, IsNegative
# Simple comparisons
assert 42 == IsPositive
assert "hello world" == IsStr(regex=r"hello \w+")
assert '{"key": "value"}' == IsJson({"key": "value"})
# Complex data structure validation
user_data = {
'id': 123,
'username': 'john_doe',
'email': 'john@example.com',
'profile': '{"theme": "dark", "notifications": true}',
'created_at': datetime.now(),
'is_active': True
}
# Validate entire structure declaratively
assert user_data == {
'id': IsPositive,
'username': IsStr(min_length=3),
'email': IsStr(regex=r'.+@.+\..+'),
'profile': IsJson({'theme': IsStr, 'notifications': bool}),
'created_at': IsNow(delta=60), # within last minute
'is_active': True
}
# Partial dictionary matching
assert user_data == IsPartialDict({
'id': IsPositive,
'username': IsStr
}) # Only checks specified keys
# Boolean logic combinations
assert 42 == (IsInt & IsPositive) # AND
assert "test" == (IsStr | IsInt) # OR
assert 42 == ~IsNegative # NOTThe dirty-equals library is built around a core DirtyEquals base class that leverages Python's __eq__ method to provide custom equality semantics. This design enables the library's declarative testing approach.
DirtyEquals Base Class: All comparison types inherit from this abstract base class, which implements the __eq__ method and provides operator overloading supportequals() Method: Each subclass implements its own comparison logic through the equals() method&, |, ~) to combine and negate comparisonsvalue property provides access to the last successfully compared valueclass DirtyEquals:
"""Base class for all dirty-equals comparison types."""
def __init__(self, *repr_args: Any, **repr_kwargs: Any): ...
def equals(self, other: Any) -> bool: ... # Abstract method
@property
def value(self) -> Any: ... # Last successfully compared value
def __eq__(self, other: Any) -> bool: ...
def __ne__(self, other: Any) -> bool: ...
def __or__(self, other: 'DirtyEquals') -> 'DirtyOr': ... # |
def __and__(self, other: 'DirtyEquals') -> 'DirtyAnd': ... # &
def __invert__(self) -> 'DirtyNot': ... # ~This architecture allows for:
Core foundation classes that provide the building blocks for all other comparison types, including the abstract base class, universal matchers, and choice validators.
class DirtyEquals: ... # Abstract base class
class AnyThing: ... # Matches any value
class IsOneOf: ... # Matches one of several valuesComparison classes for validating truthiness and falsiness with configurable behavior for different data types including special string handling.
class IsTrueLike: ... # Checks truthiness
class IsFalseLike: ... # Checks falsiness with string supportComprehensive numeric comparison types supporting integers, floats, decimals, and special float values with range checking, approximation, and sign validation.
class IsNumeric: ... # Base numeric comparison
class IsNumber: ... # Number type base
class IsApprox: ... # Approximate equality
class IsPositive: ... # Value > 0
class IsNegative: ... # Value < 0
class IsInt: ... # Integer type checking
class IsFloat: ... # Float type checking
# ... and many more specialized numeric typesString and byte sequence validation with support for length constraints, case sensitivity, and regular expression matching.
class IsAnyStr: ... # Base string/bytes comparison
class IsStr: ... # String comparison with constraints
class IsBytes: ... # Bytes comparison with constraintsDate and time comparison classes with support for approximate matching, range validation, timezone handling, and format parsing.
class IsDatetime: ... # Datetime comparison with conditions
class IsNow: ... # Close to current time
class IsDate: ... # Date comparison
class IsToday: ... # Current date matchingDictionary comparison with flexible matching strategies including partial matching, strict ordering, and key filtering.
class IsDict: ... # Configurable dictionary comparison
class IsPartialDict: ... # Subset matching
class IsIgnoreDict: ... # Ignoring None values
class IsStrictDict: ... # Order-sensitive matchingList, tuple, and general sequence validation with support for partial matching, order constraints, containment checking, and length validation.
class IsListOrTuple: ... # List/tuple with constraints
class IsList: ... # List-specific comparison
class IsTuple: ... # Tuple-specific comparison
class Contains: ... # Containment checking
class HasLen: ... # Length validationObject introspection and type validation classes for checking instances, attributes, names, and string representations.
class IsInstance: ... # Type instance checking
class HasAttributes: ... # Attribute presence checking
class HasName: ... # Object name validation
class HasRepr: ... # String representation checkingSpecialized comparison types for common data formats including JSON, UUIDs, URLs, hashes, IP addresses, dataclasses, enums, and custom function-based validation.
class IsJson: ... # JSON parsing and validation
class IsUUID: ... # UUID validation
class IsUrl: ... # URL validation (requires Pydantic)
class IsHash: ... # Hash string validation
class IsIP: ... # IP address validation
class IsDataclass: ... # Dataclass validation
class IsEnum: ... # Enum validation
class FunctionCheck: ... # Custom function validation