Opened 12 years ago

Closed 12 years ago

Last modified 12 years ago

#19636 closed New feature (wontfix)

inhibit signals to modify some field on tests

Reported by: oscaracena@… Owned by: nobody
Component: Testing framework Version: 1.4
Severity: Normal Keywords: signals, tests
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

A simple decorator to assure that the code in the decorated function does not send the signal inhibited.

The decorator may be something like the following:

def inhibit_signal(signal, receiver, sender):
    def function_getter(fn):
        def decorator(*args, **kwargs):
            signal.disconnect(receiver=receiver, sender=sender)
            retval = fn(*args, **kwargs)
            signal.connect(receiver=receiver, sender=sender)
            return retval
        return decorator
    return function_getter

You could use it as this:

# MyModel has a receiver connected on 'pre_save' signal, which updates its timestamp. 
# Yeah, I know it can be made with an auto_now field, but let it be for this example purposes :)
# Using this decorator, the function set_timestamp could make its work.

@inhibit_signal(signals.pre_save, on_mymodel_update_timestamp, MyModel)
def set_timestamp(object, ts):
    object.timestamp = ts
    object.save()

Change History (2)

comment:1 by Carl Meyer, 12 years ago

Resolution: wontfix
Status: newclosed

Thanks for the suggestion! I can see that there are some cases where this would be useful; I also think it would invite abuse. In most cases I think this is better handled by making the signal handler smarter (or not using a signal at all). And regardless, this decorator can easily live outside of Django core, I don't think it's a sufficiently common pattern to warrant inclusion in core.

comment:2 by oscaracena@…, 12 years ago

Ok, no problem. Thanks for reviewing! :)

Note: See TracTickets for help on using tickets.
Back to Top