Django REST Framework 测试:如何将参数传递给 POST 请求。获取错误 400 而不是 201

Django REST Framework testing: How to pass parameters to POST request. Getting error 400 instead of 201

文章由管理员创建。经过身份验证的用户有权阅读它们并喜欢它们或不喜欢它们。我需要测试视图。

型号是:

class Like(models.Model):
    reader = models.ForeignKey(User, on_delete = models.CASCADE)
    article = models.ForeignKey(Article, on_delete = models.CASCADE)

视图如下(用户不应该传递任何参数 - 他 "likes" 文章和一个新的注册表是根据他的 id 和文章 id 创建的):

class LikeCreate(generics.CreateAPIView):
    queryset = Like.objects.all()
    serializer_class = LikeSerializer

测试class是:

class TestLikeViews(APITestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.user = User.objects.create_user(
            username='Name', email='test@company.com', password='top_secret')  
        self.article = Article.objects.create(
            author='X', title='Title', body='Body content...')
        self.like = Like.objects.create(
            reader=self.user, article=self.article)

    def test_like_post_user(self):
        request = self.factory.post('likes/', kwargs={'reader': self.user, 'article': self.article}) 
        request.user = self.user 
        response = LikeCreate.as_view()(request, reader=self.user, article=self.article)
        self.assertEqual(response.status_code, 201, 
                        f'Expected Response Code 201 - CREATED, received {response.status_code} instead.')

我收到以下错误:

line 105, in test_like_post_user
    f'Expected Response Code 201 - CREATED, received {response.status_code} instead.')
AssertionError: 400 != 201 : Expected Response Code 201 - CREATED, received 400 instead.

第 105 行是带有 f 字符串的行 - 最后一行。但是,当我启动服务器并手动检查此端点时 - 一切正常。我想问题出在我制定测试功能的方式上。

谢谢!

问题可能取决于您处理对 post 函数的调用的方式,其中您将 kwargs 作为命名参数发送。这条线应该没问题,也只传递 PK 而不是整个对象:

request = self.factory.post('likes/', {'reader': self.user.pk, 'article': self.article.pk})

这是 class A​​PIRequestFactory 处理请求的常用结构。