1. import re
  2. def assert_text_blocks(text, assertions):
  3. """
  4. Asserts conditions of text blocks.
  5. Args:
  6. text: The text to analyze.
  7. assertions: A list of dictionaries, where each dictionary represents an assertion.
  8. Each dictionary should have the following keys:
  9. 'pattern': A regular expression pattern to match.
  10. 'condition': A function that takes a match object and returns True if the condition is met, False otherwise.
  11. 'message': A message to display if the assertion fails.
  12. """
  13. for assertion in assertions:
  14. pattern = assertion['pattern']
  15. condition = assertion['condition']
  16. message = assertion['message']
  17. match = re.search(pattern, text)
  18. if match:
  19. if not condition(match):
  20. raise AssertionError(message)
  21. else:
  22. raise AssertionError(message)
  23. if __name__ == '__main__':
  24. # Example Usage
  25. text = "The price is $100.00 and the quantity is 2."
  26. assertions = [
  27. {'pattern': r'\$\d+\.\d{2}', 'condition': lambda match: float(match.group(0)) > 50, 'message': 'Price must be greater than 50'},
  28. {'pattern': r'\d+', 'condition': lambda match: int(match.group(0)) > 0, 'message': 'Quantity must be positive'}
  29. ]
  30. try:
  31. assert_text_blocks(text, assertions)
  32. print("All assertions passed!")
  33. except AssertionError as e:
  34. print(f"Assertion failed: {e}")
  35. text2 = "The price is $25.00 and the quantity is 0."
  36. assertions2 = [
  37. {'pattern': r'\$\d+\.\d{2}', 'condition': lambda match: float(match.group(0)) > 50, 'message': 'Price must be greater than 50'},
  38. {'pattern': r'\d+', 'condition': lambda match: int(match.group(0)) > 0, 'message': 'Quantity must be positive'}
  39. ]
  40. try:
  41. assert_text_blocks(text2, assertions2)
  42. print("All assertions passed!")
  43. except AssertionError as e:
  44. print(f"Assertion failed: {e}")

Add your comment