Created
February 8, 2012 04:58
-
-
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.
This file contains hidden or 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
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