0
創建的用戶這是我的測試:的Django/DjangoRestFramework - 單元測試不驗證使用ORM
class PageTests(APITestCase):
def setUp(self):
Location.objects.create(locationName = 'Location of Mine', LocationCode = 'LOM')
User.objects.create(username='b', password='b', email='[email protected]')
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 /視圖集:
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': '[email protected]', 'location': '1'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
,然後在登錄用戶,它的工作完全正常,試驗不會引發任何錯誤。任何想法爲什麼它會在使用User.objects.create()
創建用戶時引發錯誤?
我在之前的其他unittest類中使用過類似的代碼(創建用戶使用ORM,然後簽署他),它的工作原理。我不知道爲什麼它不在這裏工作。
編輯:另外,如果我創建用戶並讓他成爲超級用戶並登錄他,像這樣:
User.objects.create_superuser(username='a', password='a', email='[email protected]')
它的工作原理也是如此。