Last active
May 10, 2020 13:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
REST_FRAMEWORK += { | |
'TEST_REQUEST_DEFAULT_FORMAT': 'json' | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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.
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
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 ??