Django / DjangoRestFramework - unittest不验证使用ORM

时间:2015-10-26 23:07:21

标签: python django unit-testing django-rest-framework django-unittest

这是我的测试:

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()创建用户时会出现错误吗?

我之前在其他unittest类中使用了类似的代码(使用ORM创建用户然后签名)并且它可以工作。我不确定为什么它不能在这里工作。

编辑:此外,如果我创建用户并让他成为超级用户并将他登录,例如:

User.objects.create_superuser(username='a', password='a', email='a@hotmail.com')

它也可以。

1 个答案:

答案 0 :(得分:2)

找到答案。我必须通过这样做来创建用户:

User.objects.create_user()

而不是这个:

User.objects.create()