A template engine for dictionary data – useful for tests!
Project description
Dictionary Patterns
A template engine for data in dictionaries – useful for tests!
Overview
Dictionary Patterns is a Python library that allows you to match dictionary objects using pattern-based templates. It's particularly useful for testing scenarios where you need to verify that dictionary responses match expected patterns while allowing for dynamic values.
Features
- Pattern-based matching: Use placeholders like
{string:name}to match dynamic values - Value consistency: Ensure the same pattern identifier has consistent values across matches
- Nested structure support: Handle complex nested dictionary objects and arrays
- Custom exceptions: Rich error handling with specific exception types
- Flexible patterns: Define your own regex patterns for different data types
Installation
pip install dict-patterns
Quick Start
from dict_patterns import DictMatcher
# Define your patterns
patterns = {
'string': r'[a-zA-Z]+',
'number': r'\d+',
'uuid': r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
}
# Create a matcher
matcher = DictMatcher(patterns)
# Define your template with placeholders
template = {
'user': {
'name': '{string:user_name}',
'age': '{number:user_age}',
'id': '{uuid:user_id}'
}
}
# Your actual data
actual = {
'user': {
'name': 'John',
'age': '25',
'id': '1d408610-f129-47a8-a4c1-1a6e0ca2d16f'
}
}
# Match them
matcher.match(template, actual)
# Access matched values
print(matcher.values['string']['user_name']) # 'John'
print(matcher.values['number']['user_age']) # '25'
print(matcher.values['uuid']['user_id']) # '1d408610-f129-47a8-a4c1-1a6e0ca2d16f'
Pattern Syntax
Patterns use the format {pattern_name:identifier} where:
pattern_nameis the type of pattern to match (must be defined in your patterns dict)identifieris an optional name for the captured value (used for consistency checking)
Examples
# Simple patterns
'{string:name}' # Matches alphabetic strings
'{number:age}' # Matches numeric strings
'{uuid:user_id}' # Matches UUID format
# Patterns without identifiers (no consistency checking)
'{string}' # Matches any string, no identifier
'{number}' # Matches any number, no identifier
Error Handling
The library provides custom exceptions for better error handling and debugging:
Exception Hierarchy
DictPatternError (base)
├── DictStructureError
│ ├── DictKeyMismatchError
│ └── DictListLengthMismatchError
├── DictValueMismatchError
├── DictPatternMatchError
├── DictPatternValueInconsistencyError
└── DictPatternTypeError
Example Error Handling
from dict_patterns import (
DictMatcher,
DictPatternError,
DictStructureError,
DictKeyMismatchError,
DictPatternMatchError
)
try:
matcher = DictMatcher({'email': r'[^@]+@[^@]+\.[^@]+'})
template = {'email': '{email:user_email}'}
actual = {'email': 'invalid-email'}
matcher.match(template, actual)
except DictPatternMatchError as e:
print(f"Pattern match failed at {e.path}")
print(f"Expected pattern: {e.template}")
print(f"Actual value: {e.actual}")
except DictStructureError as e:
print(f"Structure mismatch: {e}")
except DictPatternError as e:
print(f"Any dictionary pattern error: {e}")
Exception Types
DictKeyMismatchError: Dictionary keys don't match between template and actualDictListLengthMismatchError: Lists have different lengthsDictValueMismatchError: Simple values don't match (with optional template/actual values)DictPatternMatchError: String doesn't match the pattern templateDictPatternValueInconsistencyError: Same pattern identifier has different valuesDictPatternTypeError: Unknown pattern type encountered
Advanced Usage
Value Consistency
The library ensures that the same pattern identifier has consistent values across matches:
template = {
'parent_id': '{uuid:shared_id}',
'child': {'parent_id': '{uuid:shared_id}'} # Same identifier
}
actual = {
'parent_id': '1d408610-f129-47a8-a4c1-1a6e0ca2d16f',
'child': {'parent_id': '1d408610-f129-47a8-a4c1-1a6e0ca2d16f'} # Same value
}
# This will work
matcher.match(template, actual)
# This will raise DictPatternValueInconsistencyError
actual['child']['parent_id'] = 'different-uuid'
matcher.match(template, actual)
Complex Nested Structures
template = {
'users': [
{'name': '{string}', 'email': '{email}'},
{'name': '{string}', 'email': '{email}'}
],
'metadata': {
'total': '{number:total_count}',
'created_at': '{timestamp:creation_time}'
}
}
Custom Patterns
# Define your own patterns
patterns = {
'string': r'[a-zA-Z]+',
'number': r'\d+',
'email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
'phone': r'\+?1?\d{9,15}',
'timestamp': r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z',
'slug': r'[a-z0-9]+(?:-[a-z0-9]+)*'
}
API Reference
DictMatcher
The main class for matching dictionary objects.
Constructor
DictMatcher(pattern_handlers: dict)
pattern_handlers: Dictionary mapping pattern names to regex patterns
Methods
match(template: dict, actual: dict): Match template against actual dictionaryvalues: Property containing matched values organized by pattern type
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License.
Project details
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
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file dict_patterns-0.1.0.tar.gz.
File metadata
- Download URL: dict_patterns-0.1.0.tar.gz
- Upload date:
- Size: 7.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
16d2bdd8ad76f4df6139c72f7e11f4bbcf82c123a762af80929766245f585272
|
|
| MD5 |
ea36a29819cfc6a74523e144316df3e3
|
|
| BLAKE2b-256 |
d13c1faf9260ff3f0b958ac4cd3199f1ced90a83738f0adbe28d13f61c2927ac
|
Provenance
The following attestation bundles were made for dict_patterns-0.1.0.tar.gz:
Publisher:
release.yml on fferegrino/dict-patterns
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
dict_patterns-0.1.0.tar.gz -
Subject digest:
16d2bdd8ad76f4df6139c72f7e11f4bbcf82c123a762af80929766245f585272 - Sigstore transparency entry: 452134581
- Sigstore integration time:
-
Permalink:
fferegrino/dict-patterns@18a6b6b40920eac09f9daf89d80a09415f436f25 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/fferegrino
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@18a6b6b40920eac09f9daf89d80a09415f436f25 -
Trigger Event:
push
-
Statement type:
File details
Details for the file dict_patterns-0.1.0-py3-none-any.whl.
File metadata
- Download URL: dict_patterns-0.1.0-py3-none-any.whl
- Upload date:
- Size: 8.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e7227eda0eb02f9e909e51fed6aa34955e8bccb715457103953a51530c84132e
|
|
| MD5 |
96e68b8ac7bea53d121c954bb2abcdc9
|
|
| BLAKE2b-256 |
820e6581c93ac1023f081a82e46a5706578b4b7640d275f197a184cde222cb1d
|
Provenance
The following attestation bundles were made for dict_patterns-0.1.0-py3-none-any.whl:
Publisher:
release.yml on fferegrino/dict-patterns
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
dict_patterns-0.1.0-py3-none-any.whl -
Subject digest:
e7227eda0eb02f9e909e51fed6aa34955e8bccb715457103953a51530c84132e - Sigstore transparency entry: 452134590
- Sigstore integration time:
-
Permalink:
fferegrino/dict-patterns@18a6b6b40920eac09f9daf89d80a09415f436f25 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/fferegrino
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@18a6b6b40920eac09f9daf89d80a09415f436f25 -
Trigger Event:
push
-
Statement type: