Anys: Pytest Matchers
anys provides a collection of matchers designed for pytest-style assertions, enabling more flexible comparisons in unit tests. Instead of strict equality checks, it allows developers to assert that values meet specific criteria (e.g., `ANY_DATETIME_STR` for any valid ISO 8601 timestamp string). This simplifies testing dynamic or partially unpredictable data structures. The library is actively maintained, with the current version being 0.3.1.
Warnings
- gotcha When an `anys` matcher encounters a `TypeError` or `ValueError` during comparison (e.g., attempting to apply a regular expression matcher like `AnyMatch(r'\d+')` to an integer `42`), the library explicitly suppresses the exception and the comparison silently evaluates to `False`. This behavior, while intended, can mask unexpected type mismatches that might indicate a deeper issue if not anticipated.
- gotcha Most `anys` class constructors (e.g., `AnyHas`, `AnyMapping`, `AnyDictOf`) are not designed to take other `anys` matchers as arguments for their keys or specific internal structures unless explicitly documented. Attempting to nest matchers in unsupported ways may lead to unexpected comparison results, `False` evaluations due to suppressed errors, or incorrect behavior.
Install
-
pip install anys
Imports
- ANY_DATETIME_STR
from anys import ANY_DATETIME_STR
- ANY_INT
from anys import ANY_INT
- ANY_STR
from anys import ANY_STR
- AnyGT
from anys import AnyGT
- AnyLT
from anys import AnyLT
- AnyMatch
from anys import AnyMatch
Quickstart
from anys import ANY_DATETIME_STR
def test_api_response():
# Imagine this is a dynamic response from an API or function
dynamic_data = {
"id": "user-123",
"name": "Test User",
"created_at": "2024-04-12T10:30:00Z",
"details": {
"status": "active",
"last_login": "2024-04-12T10:29:55Z"
}
}
# Assert against a structure with matchers for dynamic fields
expected_pattern = {
"id": ANY_STR, # Match any string
"name": "Test User",
"created_at": ANY_DATETIME_STR, # Match any valid ISO datetime string
"details": {
"status": ANY_STR,
"last_login": ANY_DATETIME_STR
}
}
assert dynamic_data == expected_pattern
print("Assertion successful: Dynamic data matches expected pattern!")
test_api_response()