assertEqual 比较 json 对象引发错误,因为 Python 中的 'quote'

assertEqual compare json objects raise error because of 'quote' in Python

我有一个函数可以将数据帧转换为 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_jsonexpected_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}]}

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

如@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}]}'

(注意值周围的单引号)