mercredi 24 décembre 2014

How to test an API endpoint with Django-rest-framework using Django-oauth-toolkit for authentication

I have a Django-rest-framework viewset/router to define an API endpoint. The viewset is defined as such:



class DocumentViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
model = Document


And the router is defined as



router = DefaultRouter()
router.register(r'documents', viewsets.DocumentViewSet)


with url pattern url(r'^api/', include(router.urls))


I can hit this endpoint in the browser/through curl just fine by getting the right access token and using it for authorization. However, it's not clear how to write tests against this endpoint.


Here is what I've tried:



class DocumentAPITests(APITestCase):
def test_get_all_documents(self):
user = User.objects.create_user('test', 'test@test.com', 'test')
client = APIClient()
client.credentials(username="test", password="test")
response = client.get("/api/documents/")
self.assertEqual(response.status_code, 200)


This fails with a 401 response from the client.get() call. What is the right way to test an API endpoint in DRF using django-oauth-toolkit for oauth2 authentication?


Aucun commentaire:

Enregistrer un commentaire