How to Mock a Try Confirm Cancel Pattern in Python
Define a simple class with confirm and cancel methods, execute a try confirm with error handling, and print the final state.
Python code
25 linesclass TCC:
def __init__(self):
self.confirmed = False
self.cancelled = False
def confirm(self):
self.confirmed = True
return "confirmed"
def cancel(self):
self.cancelled = True
return "cancelled"
def try_confirm(self):
try:
result = self.confirm()
print(f"Try confirm → {result}")
except Exception as e:
print(f"Try confirm failed: {e}")
if __name__ == "__main__":
tcc = TCC()
tcc.try_confirm()
print(f"Cancel result: {tcc.cancel()}")
print(f"Final state: confirmed={tcc.confirmed}, cancelled={tcc.cancelled}")
Output
Try confirm → confirmed
Cancel result: cancelled
Final state: confirmed=True, cancelled=True
How it works
The try_confirm method wraps the confirm call in a try-except block, printing a success message when no error occurs. The confirm and cancel methods simply set boolean flags and return string results. Running the main block demonstrates the sequence: a successful confirm, a cancel, and the final state. This pattern is useful for testing mockable operations where you want to ensure fallback behavior on exceptions.
Common mistakes
- Forgetting to reset flags before reusing the object
- Not catching specific exceptions in the try block
- Assuming the return value is used when it's only printed
Variations
- Use a mock library like unittest.mock to replace confirm or cancel in tests
- Add retry logic with exponential backoff inside try_confirm
Real-world use cases
- Testing service interactions where confirmation or cancellation must be idempotent.
- Building retry mechanisms for unreliable remote calls in distributed systems.
- Implementing user-facing actions that need explicit success or failure logging.
Sponsored
More from Reliability & rate limiting
- At Least Once with Idempotent Consumer in Python medium
- Build a Rate Limiter Decorator in Python easy
- Build a queue-based admission control system in Python easy
- Chaos Inject Random Failures in Python easy
- Circuit breaker failure threshold count in Python medium
- Exactly Once Processing Dedupe Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.