Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify Accept headers from rest_framework.test.Client?

I'm trying to set up an API endpoint to reply with HTML or JSON depending on the incoming request's Accept headers. I've got it working, testing through curl:

> curl --no-proxy localhost -H "Accept: application/json" -X GET http://localhost:8000/feedback/
{"message":"feedback Hello, world!"}

> curl --no-proxy localhost -H "Accept: text/html" -X GET http://localhost:8000/feedback/
<html><body>
<h1>Root</h1>
<h2>feedback Hello, world!</h2>
</body></html>

I can't figure out how to use the APITestCase().self.client to specify what content should be accepted, though.

My view looks like

class Root(APIView):
    renderer_classes = (TemplateHTMLRenderer,JSONRenderer)
    template_name="feedback/root.html"
    def get(self,request,format=None):
        data={"message": "feedback Hello, world!"}
        return Response(data)

and my test code looks like

class RootTests(APITestCase):
    def test_can_get_json(self):
        response = self.client.get('/feedback/',format='json',Accept='application/json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.accepted_media_type,'application/json')
        js=response.json()
        self.assertIn('message', js)
        self.assertEqual(js['message'],'feedback Hello, world!')

which dies on the test for response.accepted_media_type. What's the right way to do this? All I can find says that the format argument should be sufficient.

like image 213
cakins Avatar asked Dec 14 '18 16:12

cakins


1 Answers

As was rightfully stated here, the docs don't seem to say much about how to add headers to the request using the test client. However, the extra parameter can be used for that but the trick is that you have to write it the exact way the http header looks. So you should do this:

self.client.get('/feedback/', HTTP_ACCEPT='application/json') 
like image 84
Ken4scholars Avatar answered Sep 22 '22 09:09

Ken4scholars