or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

base-types.mdboolean-types.mddatetime-types.mddict-types.mdindex.mdinspection-types.mdnumeric-types.mdother-types.mdsequence-types.mdstring-types.md
tile.json

tessl/pypi-dirty-equals

Python library that leverages the __eq__ method to make unit tests more declarative and readable through flexible comparison classes.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/dirty-equals@0.9.x

To install, run

npx @tessl/cli install tessl/pypi-dirty-equals@0.9.0

index.mddocs/

dirty-equals

A 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.

Package Information

  • Package Name: dirty-equals
  • Language: Python
  • Installation: pip install dirty-equals
  • Python Requirements: 3.8+

Core Imports

from 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, IsJson

Version information:

from dirty_equals import __version__

Basic Usage

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           # NOT

Architecture

The 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.

Core Design Principles

  • DirtyEquals Base Class: All comparison types inherit from this abstract base class, which implements the __eq__ method and provides operator overloading support
  • Abstract equals() Method: Each subclass implements its own comparison logic through the equals() method
  • Operator Overloading: Support for boolean logic operators (&, |, ~) to combine and negate comparisons
  • Value Retention: The value property provides access to the last successfully compared value
  • Type Safety: Each comparison class is designed for specific data types and use cases

Key Components

class 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:

  • Composable Comparisons: Combine multiple comparison types with boolean operators
  • Flexible Validation: Each type can implement sophisticated comparison logic
  • Readable Tests: Test assertions read like natural language descriptions of expected data

Capabilities

Base Types

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 values

Base Types

Boolean Types

Comparison 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 support

Boolean Types

Numeric Types

Comprehensive 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 types

Numeric Types

String and Bytes Types

String 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 constraints

String Types

DateTime Types

Date 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 matching

DateTime Types

Dictionary Types

Dictionary 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 matching

Dictionary Types

Sequence Types

List, 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 validation

Sequence Types

Inspection Types

Object 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 checking

Inspection Types

Other Specialized Types

Specialized 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

Other Types