Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using nested objects with Django Rest Framework and unit tests

I wrote several unit tests on my Django Rest Framework endpoints without any trouble, until I tried to pass nested object in a POST request:

class BookTestCase(APIVersion, APITestCase):
    def setUp(self):
        self.url = self.reverse_with_get_params('book')
        self.user = CustomerFactory.create().user
        self.base_data = {"foo": "bar",
                          "credit_card": {"card_number": "1234567812345678",
                                          "expiration_date": "1116",
                                          "security_code": "359"},
                          "foo2": "bar2"}

    def test_book(self):
        add_token_to_user(self.user, self.client)

        response = self.client.post(self.url, self.base_data)

        self.assertEqual(response.status_code, 200)

Then, runing the related web service with a pdb.set_trace() at the very beginning, here is the content of request.DATA:

<QueryDict: {u'foo': [u'bar'],
             u'credit_card': [u'expiration_date', u'security_code', u'card_number'],
             u'foo2': [u'bar2']}>

As you can see, every level1 object is correctly filled, but credit card content has disapeared.

Any idea? Thanks!

Note: Django 1.6 / Rest Framework 2

like image 214
David D. Avatar asked Mar 21 '16 09:03

David D.


Video Answer


1 Answers

You have to change to format of your post call. Try format='json'

response = self.client.post(self.url, self.base_data, format='json')
like image 118
ilse2005 Avatar answered Oct 14 '22 04:10

ilse2005