Django REST rest_framework.testsAPIClient post方法返回400错误请求

发布于 2025-01-19 11:36:54 字数 1811 浏览 2 评论 0 原文

我的测试无法创建 Designer 对象,但我可以在服务器运行后使用 Postman 手动创建。我怀疑是 APIClient 的问题?

我正在使用rest_framework_simplejwt,它在其他单元测试中运行良好。此特定操作在 django shell 中也会失败。

test.py:

class DesignerTest(APITestCase):
    """
    Tests Designer model, views and serializer functionality.
    """

    def setUp(self):
        """
        Setup the test environment.
        """
        self.user = get_user_model().objects.create_user(
            email='[email protected]',
            name='Test Name',
            password='passtest123'
        )
        self.client = APIClient()
        self.refresh = RefreshToken().for_user(self.user)
        self.access = self.refresh.access_token
        self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.access}")

    def test_designer_creation_successful(self):
        """Test that correct input successfully creates Designer object"""
        
        payload = {
            'first_name': 'Joe',
            'last_name': 'Aughberry',
            'date_of_birth': '1952-05-17',
            'date_of_death': '2003-09-18',
            'place_of_birth': 'Aukland',
            'nationality': 'New Zealander',
            'university': 'University of Aukland',
            'website': 'www.joeaughberrydesign.com',
            'added_by_user': self.user.pk
        }

        # Create the Desinger object through a POST request
        response = self.client.post(DESIGNER_LIST_URL, data=payload)
        
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

如果我运行 print(response) ,则会返回: 并且没有其他错误消息。

我在这里缺少什么?

My tests are failing to create a Designer object but I can manually create with Postman once the server is running. I suspect it's something with the APIClient?

I am using rest_framework_simplejwt and it is working nicely in other unittests. This particular action also fails in the django shell.

test.py:

class DesignerTest(APITestCase):
    """
    Tests Designer model, views and serializer functionality.
    """

    def setUp(self):
        """
        Setup the test environment.
        """
        self.user = get_user_model().objects.create_user(
            email='[email protected]',
            name='Test Name',
            password='passtest123'
        )
        self.client = APIClient()
        self.refresh = RefreshToken().for_user(self.user)
        self.access = self.refresh.access_token
        self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.access}")

    def test_designer_creation_successful(self):
        """Test that correct input successfully creates Designer object"""
        
        payload = {
            'first_name': 'Joe',
            'last_name': 'Aughberry',
            'date_of_birth': '1952-05-17',
            'date_of_death': '2003-09-18',
            'place_of_birth': 'Aukland',
            'nationality': 'New Zealander',
            'university': 'University of Aukland',
            'website': 'www.joeaughberrydesign.com',
            'added_by_user': self.user.pk
        }

        # Create the Desinger object through a POST request
        response = self.client.post(DESIGNER_LIST_URL, data=payload)
        
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

if I run print(response) this returns: <Response status_code=400, "application/json"> and no other error message.

What am I missing here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谎言 2025-01-26 11:36:55

我可能为时已晚,但是如果仍然对某人有帮助。响应状态代码400点验证错误,这可能意味着某些必需字段丢失,这是请求不会传递。实际上,它几乎可以肯定会传递一个空的dict(可以通过在相应的查看集方法中打印 request.data 来检查。原因是数据通过没有任何指定的指示是JSON的传递。这可以通过两种方式固定:

1。

import json

...

response = self.client.post(DESIGNER_LIST_URL, data=json.dumps(payload), content_type="application/json")
response = self.client.post(DESIGNER_LIST_URL, data=payload, format="json")

基本上在DRF文档这里 a>。

I may be too late to respond, but what if it still helps somebody. The response status code 400 points to a validation error, which likely means that some of the required fields are missing, that is the request doesn't pass them. In fact, it almost certainly passes an empty dict (which can be checked by printing the request.data in the corresponding viewset method). The reason is that the data are passed without any specified indication that it is json. This can be fixed in two ways:

1.

import json

...

response = self.client.post(DESIGNER_LIST_URL, data=json.dumps(payload), content_type="application/json")
response = self.client.post(DESIGNER_LIST_URL, data=payload, format="json")

This is basically discussed in the DRF docs here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文