Skip to content

Instantly share code, notes, and snippets.

@deepakkabbur
Last active May 10, 2020 13:55
Show Gist options
  • Save deepakkabbur/edb150eb812f49e6c6341c0fac4eee83 to your computer and use it in GitHub Desktop.
Save deepakkabbur/edb150eb812f49e6c6341c0fac4eee83 to your computer and use it in GitHub Desktop.
Outh2 Authentication in unit tests using Django Rest Framework and Django Oauth Toolkit
from rest_framework.test import APIClient
from rest_framework.test import APITestCase
from accounts.models import User
class ApiUserTestClient(APITestCase):
"""
Helper base class for API test
"""
client = APIClient()
token = 'test123455'
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create(
username='test@test.com',
email='test@test.com',
password='12345',
is_active=True,
)
cls.user.set_password('12345')
cls.user.save()
cls.user.oauth2_provider_accesstoken.create(expires='2050-12-31 23:59:59', token=cls.token)
def setUp(self):
self.login()
def tearDown(self):
self.logout()
def login(self):
self.client.credentials(Authorization='Bearer {}'.format(self.token))
def logout(self):
self.token = None
REST_FRAMEWORK += {
'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}
from .helpers import ApiUserTestClient
class TestUserView(ApiUserTestClient):
"""
Test User view
"""
def test_user_profile_route(self):
response = self.client.get(reverse('api:accounts_api:profile'))
self.assertEqual(response.status_code, 200)
@amin7mazaheri
Copy link

I get none with this "cls.user.oauth2_provider_accesstoken.create(expires='2050-12-31 23:59:59', token=cls.token)"
how can I solve it ??

@deepakkabbur
Copy link
Author

deepakkabbur commented May 10, 2020

I get none with this "cls.user.oauth2_provider_accesstoken.create(expires='2050-12-31 23:59:59', token=cls.token)"
how can I solve it ??

After create. Try cls.user.oauth2_provider_accesstoken will return token object.

@amin7mazaheri
Copy link

Thank you for your reply
I used wrong oauth2_provider in the setting file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment