a13xg0
a13xg0

Reputation: 407

DRF test if JSON list of objects contains a specific object

I'm testing an endpoint from Django DRF, which produces a JSON list of objects. I'm trying to check if a specific object is in the returned list. I've tried assertIn and assertContains, but they produce errors.

My endpoint returns list of objects:

[
  {
    'id' : 1,
    'name': 'HelpMe'
  },
  {
    'id' : 2,
    'name': 'WhatToDo'
  },
  {
    'id' : 3,
    'name': 'ToSolveThis'
  },
]

Test code for the assertIn:

    def test_list(self):      
        client = APIClient()

        response = client.get('/api/some_list/', format='json')

        self.assertEqual(
            len(response.data),
            19
        )

        self.assertIn(
            response.data,
            {
                "id": 2,
                "name": "WhatToDo"
            }
        )

assertIn produces TypeError: unhashable type: 'ReturnList'

Test code for the assertContains:

    def test_list(self):      
        client = APIClient()

        response = client.get('/api/some_list/', format='json')

        self.assertEqual(
            len(response.data),
            19
        )

        self.assertContains(
            response,
            {
                "id": 2,
                "name": "WhatToDo"
            }
        )

assertContain just failed the test.

What is the best approach to test if a specific object exists in the JSON list in response?

Upvotes: 4

Views: 1020

Answers (1)

Alain Bianchini
Alain Bianchini

Reputation: 4171

You have inverted the arguments of: assertIn, try this:

self.assertIn({"id": 2, "name": "WhatToDo"}, response.data)

# Or you can also write:
self.assertTrue({"id": 2, "name": "WhatToDo"} in response.data)

Upvotes: 5

Related Questions