python / expert
Snippet
Custom Test Response Context Extractor via Dynamic Function Decorators
When writing advanced test suites in Django, higher-order function decorators can wrap test methods to intercept `HttpResponse` objects returned by client calls. This pattern enforces standard context payload validations across test cases without duplicating assertion code.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from functools import wrapsfrom django.test import TestCasedef assert_context_key(key_name, expected_type):def decorator(func):@wraps(func)def wrapper(self: TestCase, *args, **kwargs):response = func(self, *args, **kwargs)val = response.context.get(key_name)self.assertIsNotNone(val, f"Key {key_name} missing in response context")self.assertIsInstance(val, expected_type)return responsereturn wrapperreturn decorator
django
Breakdown
1
from functools import wraps
Imports wraps to preserve original test function name, docstring, and annotations.
2
def assert_context_key(key_name, expected_type):
Defines a parameterized decorator factory accepting expected context key name and type.
3
def decorator(func):
Defines the outer closure receiving the original test function.
4
def wrapper(self: TestCase, *args, **kwargs):
Defines inner execution wrapper receiving test case self instance and invocation arguments.
5
response = func(self, *args, **kwargs)
Executes decorated test method to receive Django test response object.
6
val = response.context.get(key_name)
Extracts value associated with key_name from template response context dictionary.
7
self.assertIsNotNone(val, f"Key {key_name} missing in response context")
Asserts context variable exists using TestCase instance methods.
8
self.assertIsInstance(val, expected_type)
Validates data type of extracted context variable.