assertEqual 比较 json 对象由于 Python 中的“quote”而引发错误

问题描述 投票:0回答:2

我有一个将数据帧转换为 json 对象的函数

def convert_to_json(dataframe):
   
    output_json = json.dumps({"XYZ": dataframe.to_dict('records')}, default=str)

    return output_json

然后在我的单元测试中:

    def test_convert_to_json(self):
       test_data = {
            'col_2': ['2018-03-02', '2018-03-01'],
            'col_3': ['12345678', '12345678'],
            'col_4': [31, 31],
            'col_5': [0.035133, 0.035133]
          }
       test_df = pd.DataFrame(test_data)
       test_json = xxx.convert_to_json(self.test_df)
       
       expected_json = {"XYZ": [{"col_2": "2018-03-02", "col_3": "12345678", "col_4": 31, "col_5": 0.035133}, {"col_2": "2018-03-01", "col_3": "12345678", "col_4": 31, "col_5": 0.035133}]}
        
       self.assertEqual(test_json, expected_json)

此测试因引用而失败:

Ran 1 test in 0.008s

FAILED (failures=1)


{'XYZ': [{'col_2': '2018-03-02',
                                 'col_3': '12345678',
                                 'col_4': 31,
                                 'col_5': 0.035133},
                                {'col_2': '2018-03-01',
                                 'col_3': '12345678',
                                 'col_4': 31,
                                 'col_5': 0.035133}]} != {"XYZ": [{"col_2": "2018-03-02", "col_3": "12345678", "col_4": 31, "col_5": 0.035133}, {"col_2": "2018-03-01", "col_3": "12345678", "col_4": 31, "col_5": 0.035133}]}

但是,如果我打印出

test_json
expected_json
的值,它们都使用双引号:

{"XYZ": [{"col_2": "2018-03-02", "col_3": "12345678", "col_4": 31, "col_5": 0.035133}, {"col_2": "2018-03-01", "col_3": "12345678", "col_4": 31, "col_5": 0.035133}]}

{"XYZ": [{"col_2": "2018-03-02", "col_3": "12345678", "col_4": 31, "col_5": 0.035133}, {"col_2": "2018-03-01", "col_3": "12345678", "col_4": 31, "col_5": 0.035133}]}

我是单元测试的新手,对代码行为非常困惑,有人可以帮忙吗?谢谢。

python json unit-testing python-unittest assertion
2个回答
1
投票

正如 @khelwood 提到的,您正在比较字符串和字典。我建议您将

expected_json
变量更改为字符串(当然,只有当这确实是您期望从测试函数中获得的值时才这样做)。

试试这个:

expected_json = '{"XYZ": [{"col_2": "2018-03-02", "col_3": "12345678", "col_4": 31, "col_5": 0.035133}, {"col_2": "2018-03-01", "col_3": "12345678", "col_4": 31, "col_5": 0.035133}]}'

(注意值周围的单引号)


0
投票

我正在使用-

expected_json_as_dict = {'some': 'json'}
output_json_as_dict = {'some': 'json'}
self.assertDictEqual(output_json_as_dict, expected_json_as_dict)
© www.soinside.com 2019 - 2024. All rights reserved.