我目前在测试我的 Django DRF 项目时遇到 MultiValueDictKeyError 错误

问题描述 投票:0回答:0

亲爱的 Stackoverflowers,

我希望这条消息能找到你。我想报告我在测试我的 Django DRF 项目时遇到的问题。我使用以下代码构建了一个测试用例:

class AttendanceRecordsTestCase(APITestCase):
    def setUp(self):
        client = APIClient()

        # create a user
        response = client.post('/auth/users/', {'username': 'user', 'password': 'pass'}, format='json')
        self.user = User.objects.get(pk=response.data['guid'])

        # create an Attendee object for the user
        self.attendee = baker.make(Attendee, user=self.user)

        # create a location object
        self.location = baker.make(Location, name='Test Location', east_latitude=10, west_latitude=5, north_longitude=20, south_longitude=15)

        # obtain JWT token for authentication
        response = client.post('/auth/jwt/create/', {'username': 'tester', 'password': 'tester'}, format='json')
        self.token = 'JWT ' + response.data['access']

    def test_create_record_with_valid_input(self):
        # set valid input

        # set token in Authorization header
        client = APIClient()
        # make a request to create a record
        data = {'longitude': 17.5, 'latitude': 7.5}
        client.credentials(HTTP_AUTHORIZATION=self.token)
        response = client.post('/attendance/records/', data=data, format='json')

        # check that the response status code is 201 (Created)
        if response.status_code != status.HTTP_201_CREATED:
            print('response:', response.content.decode('utf-8'))
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        # check that a record object is created in the database
        self.assertEqual(Record.objects.count(), 1)

不幸的是,我面临以下错误:

django.utils.datastructures.MultiValueDictKeyError: 'latitude' Destroying test database for alias 'default'...

我能够通过删除

client.credentials(HTTP_AUTHORIZATION=self.token)
来解决问题;但是,这导致了一个新问题:未提供身份验证凭据。

如果您能提供解决此问题的任何帮助,我将不胜感激。

感谢您的时间和关注。

致以诚挚的问候, 亚瑟

我试图通过向 client.post 添加标头 att 来解决问题,但问题仍然存在。非常感谢您协助找到解决此问题的方法

django-rest-framework django-testing
© www.soinside.com 2019 - 2024. All rights reserved.