I use sqlalchemy 1.0.
My project has several models, some of them have event listeners, like
event.listen(Model, 'after_update', Model._after_update)
.
In case of unit-testing I need to disable all event listeners on model/session/etc.
When particular test finished I need to enable all listeners.
Is there any ways to achieve this?
You can get all event listeners for model from event.registry._key_to_collection
. It's a dict with keys (id(target), identifier, id(function))
. Then remove them with event.remove
.
import ctypes
from sqlalchemy import event
def clear_event_listeners(model):
keys = [k for k in event.registry._key_to_collection if k[0] == id(model)]
for key in keys:
target = model
identifier = key[1]
fn = ctypes.cast(key[2], ctypes.py_object).value # get function by id
event.remove(target, identifier, fn)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With