Last active
October 19, 2016 17:36
-
-
Save AndreaCrotti/0e489feab42ca61ca7a93be6a37766c6 to your computer and use it in GitHub Desktop.
Quick and dirty way to intercept the various get/post calls happening during Django tests
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
import atexit | |
import csv | |
import json | |
from collections import namedtuple | |
from django.test.client import Client | |
Line = namedtuple('Line', ['method', 'args', 'kwargs', 'status_code']) | |
class LoggingClient(Client): | |
df = [['method', 'args', 'kwargs', 'status_code']] | |
def get(self, *args, **kwargs): | |
# TODO: report from which test it came from as well | |
response = super(LoggingClient, self).get(*args, **kwargs) | |
# TODO: find out what is the current test where it comes from | |
self.df.append(Line( | |
'get', | |
json.dumps(args), | |
json.dumps(kwargs), | |
response.status_code, | |
)) | |
return response | |
def post(self, *args, **kwargs): | |
response = super(LoggingClient, self).post(*args, **kwargs) | |
self.df.append(Line( | |
'post', | |
json.dumps(args), | |
json.dumps(kwargs), | |
response.status_code, | |
)) | |
return response | |
def dump_results(): | |
with open('results.csv', 'w') as out: | |
writer = csv.writer(out) | |
for line in LoggingClient.df: | |
writer.writerow(line) | |
# can be used by simply changing the default client | |
# on your test base class | |
class MyTestCase(TestCase): | |
client = LoggingClient() | |
atexit.register(dump_results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The result can be then loaded into pandas and generate some nice stats about your tests using self.client