Search code examples
djangounit-testingdjango-rest-frameworkhttp-patch

How do I send data along with APITestCase client.patch() in DjangoRestFramework?


My TestCase:

class MyApiTests(APITestCase):
    def test_retrieve(self):
        resp = self.client.patch('/my/endpoint/', data={
            'name': 'new name',
            'age': 25,
            'some_array': [{
                'my_subobject_name': 'foo'
            }]
        }

In my viewset, if I grab data['some_array'], I get:

u"{'my_subobject_name': 'foo'}".

Why is it a string instead of an array with one dictionary?

If I send a stringified version of

{
    'name': 'new name',
    'age': 25,
    'some_array': [{
        'my_subobject_name': 'foo'
    }]
}

via my browser, DRF works fine, and some_array will be a an array with one dictionary inside of it, as expected.

What is the correct way to send a complex data structure along with a patch() in an APITestCase unit test?


Solution

  • Try adding the format='json' argument in the patch function call i.e.

    class MyApiTests(APITestCase):
        def test_retrieve(self):
            resp = self.client.patch('/my/endpoint/', data={
                'name': 'new name',
                'age': 25,
                'some_array': [{
                    'my_subobject_name': 'foo'
                }]
            }, format='json')