【发布时间】:2016-01-26 05:26:25
【问题描述】:
这是我的测试:
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)
这是我的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,)
问题是,即使在我通过 self.client.login(username='b', password='b') 登录用户后,发布时仍然会引发 403 错误。这是打印出来的:
here!!!!!!!!!!!!
AnonymousUser
b
here!!!!!!!!!!!!
AnonymousUser
{'detail': 'Authentication credentials were not provided.'}
如您所见,Django 确实看到了用户对象(因为它打印了“b”),但用户由于某种原因没有登录,并且仍然是 AnonymousUser。现在,当我将设置更改为:
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)
然后让用户登录,它工作得很好,测试不会引发任何错误。知道为什么在使用 User.objects.create() 创建用户时会引发错误吗?
我之前在其他单元测试类中使用过类似的代码(使用 ORM 创建用户,然后让他登录)并且它可以工作。我不确定为什么它在这里不起作用。
编辑:另外,如果我创建用户并使他成为超级用户并登录,如下所示:
User.objects.create_superuser(username='a', password='a', email='a@hotmail.com')
它也有效。
【问题讨论】:
标签: python django unit-testing django-rest-framework django-unittest