import re
def assert_text_blocks(text, assertions):
"""
Asserts conditions of text blocks.
Args:
text: The text to analyze.
assertions: A list of dictionaries, where each dictionary represents an assertion.
Each dictionary should have the following keys:
'pattern': A regular expression pattern to match.
'condition': A function that takes a match object and returns True if the condition is met, False otherwise.
'message': A message to display if the assertion fails.
"""
for assertion in assertions:
pattern = assertion['pattern']
condition = assertion['condition']
message = assertion['message']
match = re.search(pattern, text)
if match:
if not condition(match):
raise AssertionError(message)
else:
raise AssertionError(message)
if __name__ == '__main__':
# Example Usage
text = "The price is $100.00 and the quantity is 2."
assertions = [
{'pattern': r'\$\d+\.\d{2}', 'condition': lambda match: float(match.group(0)) > 50, 'message': 'Price must be greater than 50'},
{'pattern': r'\d+', 'condition': lambda match: int(match.group(0)) > 0, 'message': 'Quantity must be positive'}
]
try:
assert_text_blocks(text, assertions)
print("All assertions passed!")
except AssertionError as e:
print(f"Assertion failed: {e}")
text2 = "The price is $25.00 and the quantity is 0."
assertions2 = [
{'pattern': r'\$\d+\.\d{2}', 'condition': lambda match: float(match.group(0)) > 50, 'message': 'Price must be greater than 50'},
{'pattern': r'\d+', 'condition': lambda match: int(match.group(0)) > 0, 'message': 'Quantity must be positive'}
]
try:
assert_text_blocks(text2, assertions2)
print("All assertions passed!")
except AssertionError as e:
print(f"Assertion failed: {e}")
Add your comment