我有一个将数据帧转换为 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}]}
我是单元测试的新手,对代码行为非常困惑,有人可以帮忙吗?谢谢。
正如 @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}]}'
(注意值周围的单引号)
我正在使用-
expected_json_as_dict = {'some': 'json'}
output_json_as_dict = {'some': 'json'}
self.assertDictEqual(output_json_as_dict, expected_json_as_dict)