Skip to content

Instantly share code, notes, and snippets.

@AndreaCrotti
Last active October 19, 2016 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreaCrotti/0e489feab42ca61ca7a93be6a37766c6 to your computer and use it in GitHub Desktop.
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
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)
@AndreaCrotti
Copy link
Author

The result can be then loaded into pandas and generate some nice stats about your tests using self.client

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment