34👍
I found a way to get the test to pass, but please post if you have a better idea of how to handle any of this.
request = self.factory.get('/my_endpoint', HTTP_AUTHORIZATION='Token {}'.format(self.token))
force_authenticate(request, user=self.user)
After changing the above two lines of the test, it seems to authenticate based on the token properly.
10👍
I wanted to test the authentication function itself, so forcing authentication wans’t an option.
One way to properly pass the token is to use APIClient, which you already have imported.
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
response = client.get('/api/vehicles/')
That sets your given token into the request header and lets the back end decide if it’s valid or not.
- [Django]-Listing objects from ManyToManyField
- [Django]-Handlebars.js in Django templates
- [Django]-Django CSRF check failing with an Ajax POST request
6👍
Sorry for digging this old thread up, but if someone is using APIClient()
to do their tests you can do the following:
from rest_framework.test import APITestCase
from rest_framework.test import APIClient
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
class VehicleCreationTests(APITestCase):
def setUp(self):
self.client = APIClient()
self.user = User.objects.create_superuser('admin', 'admin@admin.com', 'admin123')
self.token = Token.objects.create(user=self.user)
def testcase(self):
self.client.force_login(user=self.user)
response = self.client.post('/api/vehicles/', data=vehicle_data, format='json', HTTP_AUTHORIZATION=self.token)
self.assertEqual(response.status_code, 201)
Really good resource that I’ve used to come up with this is django-rest-framework-jwt tests
- [Django]-Scoped_session(sessionmaker()) or plain sessionmaker() in sqlalchemy?
- [Django]-How to merge 2 Django QuerySets in one and make a SELECT DISTINCT
- [Django]-Django Manager Chaining
-1👍
The simpler way to force_authentication
using a built-in method from APITestCase
is:
class Test(APITestCase):
def setUp(self):
user1 = User.objects.create_user(username='foo')
self.client.force_authenticate(user=user1) # self.client is from APITestCase
... the rest of your tests ...
- [Django]-SyntaxError: Generator expression must be parenthesized
- [Django]-Dynamically exclude or include a field in Django REST framework serializer
- [Django]-Get request body as string in Django