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]') 

它的工作原理也是如此。

回答

2

找到了答案。我不得不这样做是为了创建用户:

User.objects.create_user() 

,而不是这样的:

User.objects.create()