Django [AssertionError: 401 != 201]

Django [AssertionError: 401 != 201]

我正在为我的 API 编写测试。现在我想测试 post 方法。

这是我的 views.py:

class TaskViewSet(viewsets.ModelViewSet):

    queryset = Task.objects.all()
    serializer_class = serializers.TaskSerializer
    authentication_classes = (BasicAuthentication,)
    permission_classes = (permissions.IsAuthenticated, permissions.IsAdminUser)

这是我的 tests.py:

class UserFactory(DjangoModelFactory):

    class Meta:
        model = User

    username = 'dima'
    password = 'moonmvm2k14'
    email = 'admin@admin.com'
    is_superuser = True
    is_active = True
    is_staff = True


class TaskFactory(DjangoModelFactory):

    class Meta:
        model = Task

    title = "TASK N1"
    description = "smth"
    person = factory.SubFactory(UserFactory)
    deadline = date.today()


class ViewTest(APITestCase):

    def setUp(self):
        self.task = TaskFactory()

        self.username = 'myuser'
        self.password = 'test' 
        self.email = 'admin@mgmail.com'

        self.admin = User.objects.create_superuser(self.username, self.password, self.email)

        self.client = APIClient()
        self.client.login(username=self.admin.username, password=self.admin.password)

    def test_post_task(self):
        url = '/task-list/'
        json_tasks = serializers.TaskSerializer(self.task)
        data = json_tasks.data
        response = self.client.post(url, data)
        tasks_count = Task.objects.count()
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(tasks_count, 2)

但是当我尝试测试它时,我看到了这个错误:

AssertionError: 401 != 201

我不知道为什么我的测试失败并显示未授权状态代码。

那么,问题是什么,我该如何解决?

问题源于您在测试用例中模拟登录的方式。

您使用的是APIClientclass的login()方法,适合SessionAuthentication.

来自the docs

The login method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.


但在您看来您使用 BasicAuthentication (which is actually only suitable for testing purposes), so you may use another method of the client class - force_authenticate:

class ViewTest(APITestCase):
    def setUp(self):
        ...

        self.client = APIClient()
        self.client.force_authenticate(user=self.admin)

这将使您的管理员用户实际登录并且状态代码断言应该成功通过。