python / expert
Snippet
Signal Disconnector Test Utility for Asserting Muted Handlers
Testing Django signals often requires isolating side effects. Inheriting from `ContextDecorator` allows this helper to function seamlessly both as a context manager (`with MuteSignal(...):`) and as a test function decorator (`@MuteSignal(...)`).
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from contextlib import ContextDecoratorfrom django.db.models.signals import ModelSignalclass MuteSignal(ContextDecorator):def __init__(self, signal: ModelSignal, receiver):self.signal = signalself.receiver = receiverdef __enter__(self):self.signal.disconnect(self.receiver)return selfdef __exit__(self, exc_type, exc_val, exc_tb):self.signal.connect(self.receiver)return False
django
Breakdown
1
class MuteSignal(ContextDecorator):
Extends standard library ContextDecorator to enable dual context manager and decorator capabilities.
2
def __init__(self, signal: ModelSignal, receiver):
Accepts the target Django signal instance and receiver callback function to manipulate.
3
def __enter__(self):
Context entry hook that unbinds the receiver from listening to signal dispatches.
4
self.signal.disconnect(self.receiver)
Detaches the receiver handler from the signal registry during block execution.
5
def __exit__(self, exc_type, exc_val, exc_tb):
Context exit hook re-attaching signal handler regardless of exceptions inside the block.
6
self.signal.connect(self.receiver)
Restores original signal connection state upon block termination.