如何解决由于 Python 中的“引用”,assertEqual 比较 json 对象引发错误
我有一个将数据帧转换为 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_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_5': 0.035133}]} != {"XYZ": [{"col_2": "2018-03-02","col_5": 0.035133}]}
但是,如果我打印出 test_json
和 expected_json
的值,它们都使用双引号:
{"XYZ": [{"col_2": "2018-03-02","col_5": 0.035133}]}
{"XYZ": [{"col_2": "2018-03-02","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_5": 0.035133}]}'
(注意值周围的单引号)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。