pretty much what I use for that is an event listener for SQL, which
logs/doesn't log based on external state. We have kind of a crufty one in
the test suite (see assertsql.py and testing.py->assert_sql_count).
you can do it like this:
emitters = set()
@event.listens_for(Engine, "cursor_execute")
def cursor_execute(conn, cursor, statement, parameters,
context, executemany):
for emit in emitters:
emit(statement)
def assert_no_sql(fn):
def run(*arg, **kw):
def raise_(statement):
assert False, "SQL %s was emitted!" % statement
emitters.add(raise_)
try:
return fn(*arg, **kw)
finally:
emitters.discard(raise_)
return run
def test_my_thing(self):
obj = sess.query(Foo).get(1)
@assert_no_sql
def go():
obj.related_items
go()
or you can use a context manager, then its like "with assert_no_sql(): ...".
On Sep 25, 2012, at 1:59 PM, Ladislav Lenart wrote:
> Hello.
>
> I would like to detect when an access to a mapped slot issues a SQL query. Is
> that possible with events? Where should I look?
>
> I want to unit-test that a query correctly preloads everything I need:
>
> def some_test(self):
> q = ...
> rows = q.all()
> print "#### Should not emit any SQL from here on ####"
> for each in rows:
> print each.a.b.c.d # Assert this does not emit any SQL
>
> I currently "test this manually" by looking at the output and see that no SQL
> communication was printed after the line "#### ... ####" (db engine is started
> with echo=True).
>
>
> Thank you,
>
> Ladislav Lenart
>
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected].
> For more options, visit this group at
> http://groups.google.com/group/sqlalchemy?hl=en.
>
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.