0
votes

I'm using the SqlAlchemy before_flush event to validate objects before saving them in the database like so:

from models import db

@event.listens_for(db.session, 'before_flush')
def validateSomething(session, flush_context, instances):
    pass

I'd really like to test what I'm doing there. However, in my tests - I'm using pytest - a new session gets created for each test using a fixture. It is similar to this setup: http://alexmic.net/flask-sqlalchemy-pytest/ A function scoped fixture creates a transaction alongside a session and rolls back / removes them during teardown.

Since the event is registered on the (scoped) session in models.db, it doesn't fire for the events of the sessions used in the tests. Is there a way to fix this, so events get fired during tests?

2

2 Answers

0
votes

Instead of listening for the session instance, listens_for() allows to listen to events of all instances of a session class. So replacing db.session with SignallingSession did the trick.

0
votes

I had this same issue. Replacing

@event.listens_for(db.session, 'before_flush')

with

from sqlalchemy.orm import Session
@event.listens_for(Session, 'before_flush')

fixed the issue for me