This is my DRF view:
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def check_user(request):
user = request.user
# use user object here
return JSONResponse({})
And this is my unit test for said view:
class CheckUserViewTest(TestCase):
def test_check_user(self):
user = User.objects.create_user('username', 'Pas$w0rd')
self.client.login(username='username', password='Pas$w0rd')
response = self.client.get(reverse('check_user'))
self.assertEqual(response.status_code, httplib.OK)
But I always get a 401
UNAUTHORIZED
response from my view. I have logged in the user in my test. What am I doing wrong?
If you want to use a database-backed session, you need to add 'django. contrib. sessions' to your INSTALLED_APPS setting. Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.
Open auth/urls.py and add register endpoint: we should send a POST request to API for checking register endpoint. You must add username, password, password2, email, first_name, last_name to body. If fields passed validations, new user detail will be returning.
REST APIs are an industry-standard way for web services to send and receive data. They use HTTP request methods to facilitate the request-response cycle and typically transfer data using JSON, and more rarely - HTML, XML and other formats.
Since you are using Django REST Framework you have to also use DRF's test client called APIClient
instead of Django's test client. This happens automagically if you inherit from DRF's APITestCase
instead of Django's TestCase
.
Complete example:
class CheckUserViewTest(APITestCase):
def test_check_user(self):
user = User.objects.create_user('username', 'Pas$w0rd')
self.assertTrue(self.client.login(username='username', password='Pas$w0rd'))
response = self.client.get(reverse('check_user'))
self.assertEqual(response.status_code, httplib.OK)
An alternative is to use force_authenticate
:
class CheckUserViewTest(APITestCase):
def test_check_user(self):
user = User.objects.create_user('username', 'Pas$w0rd')
self.client.force_authenticate(user)
response = self.client.get(reverse('check_user'))
self.assertEqual(response.status_code, httplib.OK)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With