在Django单元测试中访问JsonResponse中的键值对

时间:2017-02-26 18:21:26

标签: django unit-testing

我想访问以下jsonResponse对象中返回的数据:

{"results": [[1, "Probability and Stochastic Processes", 9781118324561, "Roy D. Yates", "2014-01-01", "Wiley"], [2, "Interaction Design", 9781119020752, "Rogers Price", "2015-01-01", "John Wiley & Sons"], [3, "Microeconomics", 9780077501808, "Colander", "2013-01-01", "McGraw Hill"], [4, "jfalksdjf", 123123, "test", "1990-01-01", "Penguin"]]}

然而我遇到了麻烦,我尝试过很多东西

def test_noIDGiven(self):
    response = self.client.get(reverse('allTextbooks')) #returns the json array above
    #check that there are three textbooks in the response
    #print(response.content['results'][0][0]) - this didnt work
    self.assertEquals(response.content[0][0], 1) #basically want to access the id of the first object and make sure it is 1

关于如何获得访问此对象的键值对的最佳方法的任何帮助都会很好。提前谢谢

更多信息: - 当我反转'allTextbooks'时,api调用会返回:

results = list(Textbook.objects.values_list())
return JsonResponse({'results': results})

4 个答案:

答案 0 :(得分:2)

我认为你必须首先尝试将你的回复转换为字典,

import json
response_dict = json.loads(response.text)
id_list = []

现在,

for k,v in response_dict:
    for i in v:
        id_list.append(i[0])

id_list是您所有ID的列表。

答案 1 :(得分:2)

在Django 2.0中,您可以直接访问JSON响应。

 self.assertEqual(response.json()['results'][0][0], 1)

答案 2 :(得分:1)

您是否尝试过回复['结果'] [0] [0]?

如果您想轻松访问响应中的每个项目,可以试试这个:

public Form1()
{
    InitializeComponent();

    Shown += async (s, e) =>
    {
        await Test1("https://SiteWithCloudFlareProtection.com/");
        //Thread.Sleep(60000);
    };
}

答案 3 :(得分:0)

你是对的,响应内容只是字节,所以你必须将其解码为UTF-8(或其他),然后将其解析为dict,如下所示:

response = self.client.get(reverse('allTextbooks'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
j = json.loads(response.content.decode('utf-8'))
self.assertEqual(j['results'][0][0], 1)

我已经包含了几个额外的断言来验证响应是否成功并标记为JSON,但这些是可选的。