-
Notifications
You must be signed in to change notification settings - Fork 403
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add query logging callbacks and context manager (#1043)
- Loading branch information
Showing
2 changed files
with
169 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import asyncio | ||
|
||
from asyncpg import _testbase as tb | ||
from asyncpg import exceptions | ||
|
||
|
||
class LogCollector: | ||
def __init__(self): | ||
self.records = [] | ||
|
||
def __call__(self, record): | ||
self.records.append(record) | ||
|
||
|
||
class TestQueryLogging(tb.ConnectedTestCase): | ||
|
||
async def test_logging_context(self): | ||
queries = asyncio.Queue() | ||
|
||
def query_saver(record): | ||
queries.put_nowait(record) | ||
|
||
log = LogCollector() | ||
|
||
with self.con.query_logger(query_saver): | ||
self.assertEqual(len(self.con._query_loggers), 1) | ||
await self.con.execute("SELECT 1") | ||
with self.con.query_logger(log): | ||
self.assertEqual(len(self.con._query_loggers), 2) | ||
await self.con.execute("SELECT 2") | ||
|
||
r1 = await queries.get() | ||
r2 = await queries.get() | ||
self.assertEqual(r1.query, "SELECT 1") | ||
self.assertEqual(r2.query, "SELECT 2") | ||
self.assertEqual(len(log.records), 1) | ||
self.assertEqual(log.records[0].query, "SELECT 2") | ||
self.assertEqual(len(self.con._query_loggers), 0) | ||
|
||
async def test_error_logging(self): | ||
log = LogCollector() | ||
with self.con.query_logger(log): | ||
with self.assertRaises(exceptions.UndefinedColumnError): | ||
await self.con.execute("SELECT x") | ||
|
||
await asyncio.sleep(0) # wait for logging | ||
self.assertEqual(len(log.records), 1) | ||
self.assertEqual( | ||
type(log.records[0].exception), | ||
exceptions.UndefinedColumnError | ||
) |