python - 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!
解决方案
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]
推荐阅读
- python - 如何计算两组列表之间数字匹配的概率?(Python)
- swift - 在 Swift 5 中的循环内修剪字符串
- python - 理解小批量梯度下降中的切片符号
- python - 如何更改水平条形图上条形的颜色
- jquery - Jquery根据扩展名获取文件并渲染
- python - 我有一个包含 60 个复杂项目的列表,我有一个带有文本列的数据框,我想从列表中提取所有项目
- javascript - 将垂直菜单更改为水平菜单
- php - Laravel 表单提交关系
- javascript - ReactJS 得到未定义的响应
- azure-devops - 如何删除 DevOps 工件中的所有上游包?