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.
Aucun commentaire:
Enregistrer un commentaire