Search code examples
pythondjangotestingdjango-testing

Test post django function


I have django function, that takes JSON-data from request, validates it and save to db. I want to test this func, but POST request doesn’t work, error

‘json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)’.

I guess it's some wrong with my data in post request, because if I add print(request.body) in func, I see

b'--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="model"\r\n\r\nX5\r\n--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="version"\r\n\r\nLT\r\n--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="serial"\r\n\r\nDD\r\n--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="created"\r\n\r\n2023-01-01 00:00:01\r\n--BoUnDaRyStRiNg--\r\n'

views.py

def add_robot_in_db(request):
    if request.method == 'POST':
        print(request.body)
        json_data = json.loads(request.body)
        data = RobotForm(json_data)
        data.is_valid()
        if data.errors:
            return JsonResponse(json.loads(data.errors.as_json()),
                                status=HTTPStatus.BAD_REQUEST)
        data.save()
        return JsonResponse(data.cleaned_data,
                            status=HTTPStatus.CREATED)

    return JsonResponse({'error': 'Wrong request, only POST'},
                        status=HTTPStatus.BAD_REQUEST)

tests.py

class TaskURLTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()

    def setUp(self):
        self.guest_client = Client()

    def test_url(self):
        response = self.guest_client.post('/add_robot/',
                                          {"model":"X5", "version":"LT", "serial": "DD",
                                           "created":"2023-01-01 00:00:01"},
                                          )


Solution

  • You're receiving that error because your not sending JSON data, What your sending is form-data, Here is how to fix it:

    def test_url(self):
         json_data = {
             "model": "X5",
             "version": "LT",
             ...
         }
         response  = self.guest_client.post('/add_robot/',
                                            data= json.dumps(json_data),
                                            content_type='application/json')
    

    Using json.dumps will convert the python dictionary to JSON string and with setting the content_type as application/json you're specifying the format you're sending.