I find the approach on that page a little awkward - it's using new globals for no good reason and also the begin_nested() seems strange. The test itself then has a "self.session", so the test itself is using a test-bound session, the choice of globals for "connection" and "engine" seems even more weird.
The way this works is:
1. test fixture gets at an engine, from configurational system, locally, whereever.
2. test fixture gets a connection, holds onto it locally.
3. test fixture gets a transaction from connection - this is a top level transaction, using connection.begin()
4. test fixture then does whatever the test needs to get at a session. if the code being tested relies upon a global registry, it injects the connection. below is using a traditional scoped session:
def setUp(self):
self.conn = engine.connect()
self.trans = self.conn.begin()
from application.model import the_scoped_session
self.session = the_scoped_session(bind=self.conn)
now above, the test fixture has a hold on "self.session". but - this is the *same* session that's in the registry (the registry here being "application.model.the_scoped_session"). if some other code somewhere calls upon the_scoped_session(), they get the *same* session. it's a registry, that's the point of it.
if you have some other kind of registration thing in place, you'd need to figure out how to load it up with a new Session bound to that local connection.
5. test fixture releases the session:
def tearDown(self):
the_scoped_session.remove()
self.trans.rollback()
self.conn.close()
so note, we don't have to bother doing anything special with the Session at teardown time, we just dump it. we roll back the transaction that we've created externally to it.
an example of running through this is in the docs at: