Middle
What is a decorator in the context of programming?
sobes.tech AI
Answer from AI
Decorator is a structural design pattern that allows adding new responsibilities to objects dynamically by wrapping them in special decorator objects. It provides a more flexible alternative to inheritance for extending functionality.
Key ideas:
- Wrapping: The decorator contains a reference to the object it wraps.
- Delegation: The decorator delegates method calls to the wrapped object, possibly performing additional logic before or after the call.
- Extending functionality: It allows adding behavior to objects without changing their structure or using subclasses.
Application in QA Automation:
- Logging actions: Adding logging to methods interacting with page elements.
- Exception handling: Adding universal exception handling to function calls.
- Retries: Implementing a mechanism for retrying flaky tests or actions.
- Pre/post-conditions: Performing certain actions before or after the main test step.
Example in Python:
def log_method_call(func):
# Decorator that logs the call of a function
def wrapper(*args, **kwargs):
print(f"Calling function: {func.__name__} with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} returned: {result}")
return result
return wrapper
class PageObject:
def __init__(self, driver):
self.driver = driver
@log_method_call
def click_button(self, locator):
# Example method using a decorator
print(f"Clicking element located by: {locator}")
# Simulate driver action
# self.driver.find_element(*locator).click()
return "Button Clicked"
# Usage
# driver = ... # Initialize driver
# page = PageObject(driver)
# page.click_button(("ID", "submit_button"))