-
-
Notifications
You must be signed in to change notification settings - Fork 269
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adds test class for checking query durations
This is a first pass and I wrote it specifically so that it would fail on the query in test_book.py
- Loading branch information
1 parent
3545a1c
commit fdc6ae2
Showing
2 changed files
with
51 additions
and
4 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
""" Log query runtimes for testing """ | ||
import time | ||
|
||
|
||
class QueryLogger: | ||
"""Returns the sql and duration for any query run | ||
Taken wholesale from: | ||
https://docs.djangoproject.com/en/dev/topics/db/instrumentation/ | ||
""" | ||
|
||
def __init__(self): | ||
self.queries = [] | ||
|
||
# pylint: disable=too-many-arguments | ||
def __call__(self, execute, sql, params, many, context): | ||
current_query = {"sql": sql, "params": params, "many": many} | ||
start = time.monotonic() | ||
try: | ||
result = execute(sql, params, many, context) | ||
except Exception as err: # pylint: disable=broad-except | ||
current_query["status"] = "error" | ||
current_query["exception"] = err | ||
raise | ||
else: | ||
current_query["status"] = "ok" | ||
return result | ||
finally: | ||
duration = time.monotonic() - start | ||
current_query["duration"] = duration | ||
self.queries.append(current_query) | ||
|
||
|
||
def raise_long_query_runtime(queries, threshold=0.0006): | ||
"""Raises an exception if any query took longer than the threshold""" | ||
for query in queries: | ||
if query["duration"] > threshold: | ||
raise Exception( # pylint: disable=broad-exception-raised | ||
"This looks like a slow query:", query["duration"], query["sql"] | ||
) |
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