This is my test:
class PageTests(APITestCase):
def setUp(self):
Location.objects.create(locationName = 'Location of Mine', LocationCode = 'LOM')
User.objects.create(username='b', password='b', email='b@hotmail.com')
def test_create_page(self):
"""
Ensure only authenticated users can create a new page object.
"""
url = reverse('page-list')
# See if unauthenticated unadmin users can create a page (they shouldn't.)
data = {'location': 1, 'pageName': 'Test Page 1', 'pageDescription': 'This is the first test page', 'pageCode': 'TP1'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# See if authenticated users can create a page (they should).
print(User.objects.get().username)
self.client.login(username='b', password='b')
response = self.client.post(url, data, format='json')
print(response.data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
This is my views.py / viewset:
class IsAuthenticated(permissions.BasePermission):
def has_permission(self, request, view):
print('here!!!!!!!!!!!!')
print(request.user)
return request.user.is_authenticated()
class pageViewSet(viewsets.ModelViewSet):
queryset = Page.objects.all()
serializer_class = PageSerializer
permission_classes = (IsAuthenticated,)
The problem is, even after I log the user in by doing self.client.login(username='b', password='b')
it still raises a 403 error when posting. This is what gets printed:
here!!!!!!!!!!!!
AnonymousUser
b
here!!!!!!!!!!!!
AnonymousUser
{'detail': 'Authentication credentials were not provided.'}
As you can see, Django does see the user object (because it prints 'b') but the user does not get signed in for some reason and is still an AnonymousUser. Now, when I change my setup to this:
def setUp(self)
url = reverse('user-list')
# Create the user using the API.
data = {'username': 'b', 'password': 'b', 'email': 'a@hotmail.com', 'location': '1'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
and then log the user in, it work perfectly fine and the test doesn't raise any errors. Any idea why it raises errors when creating the user using User.objects.create()
?
I've used similar code before in other unittest classes (creating the user using the ORM and then signing him in) and it works. I'm not sure why it's not working here.
Edit: Also, if I create the user and make him a super user and log him in, like so:
User.objects.create_superuser(username='a', password='a', email='a@hotmail.com')
it works as well.
Aucun commentaire:
Enregistrer un commentaire