Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Last active August 29, 2015 14:12
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 miraculixx/a6b0a3764d22a197493c to your computer and use it in GitHub Desktop.
Save miraculixx/a6b0a3764d22a197493c to your computer and use it in GitHub Desktop.
Print Django test Client and Tastypie ApiClient traces
class ClientRequestTracer(object):
"""
Trace api calls to a test client
Usage:
self.client = ClientRequestTracer(self.client)
self.api_client = ClientRequestTracer(self.api_client)
Limit the traces by giving parameter traces=[...] list of
strings 'get', 'post', 'put'
To print requests responses, pass response=True
Will print all requests made:
Request: get, ('/api/v1/coach/itinerary/?origin=Zurich&destination=Hamburg&departure=None',), {'authentication': u'Basic dGVzdHVzZXI6dGVzdA=='}
Optionally prints the response including headers and body
"""
def __init__(self, client, traces=None, response=False):
self.client = client
self.__traces__ = traces or ['get', 'post', 'put']
self.print_response = response
def __getattribute__(self, name):
client = object.__getattribute__(self, 'client')
__traces__ = object.__getattribute__(self, '__traces__')
print_response = object.__getattribute__(self, 'print_response')
attr = object.__getattribute__(client, name)
if name in __traces__ and hasattr(attr, '__call__'):
def trace(*args, **kwargs):
title = "Request: %s, %s, %s " % (name, args, kwargs)
print title
resp = attr(*args, **kwargs)
if print_response:
print "Response:\n", resp
print "*" * 10
return resp
return trace
return attr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment