Middle
What are decorators in Python — what are they, and where are they used in tests?
sobes.tech AI
Answer from AI
Decorators in Python are functions that take another function and return a new function with extended behavior, without modifying the original code.
In tests, decorators are often used for:
- Reusing code (for example, setting up the environment before a test).
- Logging or measuring the execution time of tests.
- Skipping tests under certain conditions.
An example of using a decorator to skip a test if a condition is not met:
import unittest
def skip_if_no_db(func):
def wrapper(*args, **kwargs):
if not check_db_connection():
raise unittest.SkipTest("No database connection")
return func(*args, **kwargs)
return wrapper
class MyTests(unittest.TestCase):
@skip_if_no_db
def test_query(self):
# test that requires a database
pass
Thus, decorators help make tests more flexible and readable.