Python library that leverages the __eq__ method to make unit tests more declarative and readable through flexible comparison classes.
—
Core foundation classes that provide the building blocks for all other comparison types in dirty-equals. These classes include the abstract base class, universal matchers, and choice validators that form the foundation of the library's architecture.
The abstract base class that all dirty-equals comparison types inherit from. Provides the core equality method overriding and operator support that enables the library's declarative comparison functionality.
class DirtyEquals:
"""
Abstract base class for all dirty-equals comparison types.
Provides the foundation for custom equality checking through the equals() method
and supports boolean logic operators for combining comparisons.
"""
def __init__(self, *repr_args: Any, **repr_kwargs: Any):
"""
Initialize a DirtyEquals instance.
Args:
*repr_args: Arguments used for string representation
**repr_kwargs: Keyword arguments used for string representation
"""
def equals(self, other: Any) -> bool:
"""
Abstract method that subclasses must implement to define comparison logic.
Args:
other: The value to compare against
Returns:
bool: True if the comparison succeeds, False otherwise
"""
@property
def value(self) -> Any:
"""
Get the last value that was successfully compared.
Returns:
The last value that passed the equals() check
"""
def __eq__(self, other: Any) -> bool:
"""
Implements equality checking by calling equals() method.
Args:
other: Value to compare against
Returns:
bool: Result of equals() method
"""
def __ne__(self, other: Any) -> bool:
"""
Implements inequality checking (opposite of __eq__).
Args:
other: Value to compare against
Returns:
bool: Opposite of equals() result
"""
def __or__(self, other: 'DirtyEquals') -> 'DirtyOr':
"""
Implements OR operator (|) for combining comparisons.
Args:
other: Another DirtyEquals instance to combine with
Returns:
DirtyOr: Combined comparison that passes if either comparison passes
"""
def __and__(self, other: 'DirtyEquals') -> 'DirtyAnd':
"""
Implements AND operator (&) for combining comparisons.
Args:
other: Another DirtyEquals instance to combine with
Returns:
DirtyAnd: Combined comparison that passes only if both comparisons pass
"""
def __invert__(self) -> 'DirtyNot':
"""
Implements NOT operator (~) for negating comparisons.
Returns:
DirtyNot: Negated comparison that passes when original fails
"""from dirty_equals import IsPositive, IsInt, IsStr
# Basic usage - all dirty-equals types inherit from DirtyEquals
assert 42 == IsPositive
# Boolean logic with operators
assert 42 == (IsInt & IsPositive) # AND: must be both int and positive
assert "test" == (IsStr | IsInt) # OR: can be either string or int
assert 42 == ~IsNegative # NOT: not negative (i.e., positive or zero)
# Accessing the last compared value
comparison = IsPositive
result = (42 == comparison)
print(comparison.value) # 42 - the last value that was comparedA comparison class that matches any value whatsoever. Always returns True regardless of the input, useful for placeholder comparisons or when you need to accept any value in a structure.
class AnyThing(DirtyEquals):
"""
Matches any value - always returns True.
Useful as a placeholder when you want to accept any value in a comparison,
particularly in data structures where some fields can be anything.
"""
def equals(self, other: Any) -> bool:
"""
Always returns True regardless of the input value.
Args:
other: Any value (ignored)
Returns:
bool: Always True
"""from dirty_equals import AnyThing, IsDict
# Accept any value
assert 42 == AnyThing
assert "hello" == AnyThing
assert [1, 2, 3] == AnyThing
assert {"key": "value"} == AnyThing
assert None == AnyThing
# Useful in data structure validation
user_data = {
'id': 123,
'name': 'John',
'metadata': {'created': '2023-01-01', 'source': 'api'}
}
# Check structure but accept any metadata
assert user_data == {
'id': 123,
'name': 'John',
'metadata': AnyThing # Accept any metadata value
}
# In partial dictionary checking
from dirty_equals import IsPartialDict, IsPositive
assert user_data == IsPartialDict({
'id': IsPositive,
'metadata': AnyThing
})Checks that a value equals one of the provided expected values. Useful for validating that a value matches any one of several acceptable options.
class IsOneOf(DirtyEquals):
"""
Checks that value equals one of the given expected values.
Performs equality checking against each expected value until a match is found.
"""
def __init__(self, expected_value: Any, *more_expected_values: Any):
"""
Initialize with expected values to match against.
Args:
expected_value: First expected value
*more_expected_values: Additional expected values
"""
@property
def expected_values(self) -> Tuple[Any, ...]:
"""
Get tuple of all expected values.
Returns:
Tuple containing all expected values to match against
"""
def equals(self, other: Any) -> bool:
"""
Check if other equals any of the expected values.
Args:
other: Value to check
Returns:
bool: True if other equals any expected value
"""from dirty_equals import IsOneOf
# Basic usage - check for multiple possible values
assert 'red' == IsOneOf('red', 'green', 'blue')
assert 'blue' == IsOneOf('red', 'green', 'blue')
assert 42 == IsOneOf(1, 42, 100)
# Works with different types
assert 'active' == IsOneOf('active', 1, True, 'enabled')
assert True == IsOneOf('active', 1, True, 'enabled')
# In data validation
status_codes = [200, 201, 202]
response_code = 201
assert response_code == IsOneOf(*status_codes)
# With data structures
user_role = 'admin'
valid_roles = IsOneOf('admin', 'user', 'moderator', 'guest')
assert user_role == valid_roles
# In complex validations
user_data = {
'status': 'active',
'role': 'admin',
'priority': 1
}
assert user_data == {
'status': IsOneOf('active', 'pending', 'suspended'),
'role': IsOneOf('admin', 'user', 'moderator'),
'priority': IsOneOf(1, 2, 3, 4, 5)
}
# Access expected values
role_checker = IsOneOf('admin', 'user', 'moderator')
print(role_checker.expected_values) # ('admin', 'user', 'moderator')from typing import Any, Tuple
class DirtyEqualsMeta(type):
"""Metaclass for DirtyEquals with operator overloading support."""
class DirtyOr(DirtyEquals):
"""Combination of two DirtyEquals with OR logic."""
class DirtyAnd(DirtyEquals):
"""Combination of two DirtyEquals with AND logic."""
class DirtyNot(DirtyEquals):
"""Negation of a DirtyEquals comparison."""
__version__: str
"""Package version string (e.g., '0.9.0')."""Install with Tessl CLI
npx tessl i tessl/pypi-dirty-equals