Skip to content

Instantly share code, notes, and snippets.

@stephenmcd
Created February 8, 2012 04:58
Show Gist options
  • Save stephenmcd/1765552 to your computer and use it in GitHub Desktop.
Save stephenmcd/1765552 to your computer and use it in GitHub Desktop.
Subclass of ``slumber.API`` that patches ``requests.request`` with Django test client compatible HTTP requests.
from collections import namedtuple
from django.test import TestCase
from requests.auth import HTTPBasicAuth
import slumber
class SlumberTestClientAPI(slumber.API):
"""
Subclass of ``slumber.API`` that patches ``requests.request``
with Django test client compatible HTTP requests.
"""
client = None
def __getattr__(self, name):
"""
Hook into slumber's ``Resource`` allocation and patch its
request method with our own.
"""
resource = super(SlumberTestClientAPI, self).__getattr__(name)
self.auth = resource._store["session"].auth
if SlumberTestClientAPI.client:
resource._store["session"].request = self.request
return resource
def request(self, method, url, data=None, params=None, headers=None):
"""
Using the same signature as ``requests.request``, construct the
correct method and args for Django's test client.
"""
r = namedtuple("r", ("headers",))(headers or {})
HTTPBasicAuth(*self.auth)(r)
r.headers["HTTP_AUTHORIZATION"] = r.headers.pop("Authorization")
r.headers["content_type"] = r.headers.pop("content-type")
if method != "GET":
r.headers["data"] = data
func = getattr(SlumberTestClientAPI.client, method.lower())
return func(url.replace("http://testserver", "", 1), **r.headers)
class SimpleTest(TestCase):
def some_test(self):
SlumberTestClientAPI.client = self.client
# do_something_that_takes_the_api_class(SlumberTestClientAPI)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment