首页 > 解决方案 > Compare two dictionaries returned from REST framework using pytest

问题描述

I am trying to test my django application with pytest. I am trying to send an object like so:

{ "x" :1 "y" :2 .... }

What my view does, is returning a list of dictionaries, so in my scenario a list with this one sent dictionary.

I want to check if my sent data equals my data when I do a get call. My problem is that the two dictionaries are always evaluated to false.

This is what I am doing:

 def test_post_data_is_get_data(self):
        url = api_reverse('urlname') #I get the url
        data = sent_data #this is my dict I am sending defined as a big dict in my code
        response_create = client.post(url, data, format='json') # I save the response
        response_get = client.get(url) # I get the created data back
        print(type(response_create.data)) #debugging
        print(type(data))
        print(type(response_create.content))
        print(type(response_get))


        assert response_create == response_get

The types I am printing out is:

<class 'rest_framework.utils.serializer_helpers.ReturnDict'>
<class 'dict'>
<class 'bytes'>

Doesn't matter how I compare it is never the same. I tried comparing sent data with:

1) response_create.content == response_get.content
2) response_create.data == response_get.data
3) response_create.data == response_get[0]
4) response_create.data == response_get.first() ## error that byte like object has not attribute first

Since I am calling a list view I should be getting a list with one dict back. The first element should be the same data as the sent one.... But it is never the same.

I think what's going wrong is: I am comparing a dict with a list with one dict inside. Both are given back as bytes. So I think I need to compare the dict which is given back as bytes with the first element of the list that is also in bytes. Do I make sense?

Anyone has an idea what I could do? Or maybe a better idea how to structure the test? Thanks very much in advance!

标签: pythondjangodjango-rest-frameworkpytestpytest-django

解决方案


As the print statements show the response_create.data is a rest_framework.utils.serializer_helpers.ReturnDict which is a subclass of OrderedDict.

The return of the client.get is a Django Response object which means that you'll need to use the json method to get the content.

So something like:

response_create = client.post(url, data, format='json')
response_get = client.get(url)
assert dict(response_create.data) == response_get.json()[0]

推荐阅读