fips fips - 6 months ago 83
Python Question

How to use django rest framework APIClient to test oauth access token generated after login?

I'm using django rest framework for exposing an api and django oauth toolkit for authentication. So after writing a custom ModelBackend and relevant unit tests, I was trying to write some integration tests too, to verify the endpoint using this backend is returning an access token for some scenarios..

I'm using drf APIClient for making test requests and works great for everything else, but in this I case I'm getting {"error": "unsupported_grant_type"} when I do:

from requests.auth import _basic_auth_str
from rest_framework.test import APIClient


client = APIClient()
client.credentials(HTTP_AUTHORIZATION=_basic_auth_str(CLIENT_ID, CLIENT_SECRET))
client.post(
'/oauth2/token/',
{'grant_type': 'password', 'username': 'user1', 'password': 'pass1'},
content_type='application/x-www-form-urlencoded'
)


Any ideas?

Answer

I got it to work. I was not encoding the payload. Here is the full working code with example asserts:

import urllib
from requests.auth import _basic_auth_str
from rest_framework.test import APIClient


client = APIClient()
response = client.post(
    '/oauth2/token/', 
    urllib.urlencode({'grant_type': 'password', 'username': 'user1', 'password': 'pass1'}),
    content_type='application/x-www-form-urlencoded',
    HTTP_AUTHORIZATION=_basic_auth_str(client_id, client_secret)
)

self.assertEqual(response.status_code, 200)
self.assertIn('access_token', json.loads(response.content))

...
Comments