在我正在运行的单元测试用例中,我KeyError
在下面的 json 文本中的第 4 个 json 对象上遇到异常,因为负责解码的代码正在寻找一个不存在但应该存在的对象。
我浏览了子对象,发现是“cpuid”对象导致了问题。当我删除它并运行测试时,它工作正常。
def _make_report_entry(record):
response = self.app.post(
'/machinestats',
params = dict(record = self.json_encode([{
"type": "crash",
"instance_id": "xxx",
"version": "0.2.0",
"build_id": "unknown",
"crash_text": "Gah!"
},
{
"type": "machine_info",
"machine_info": "I'm awesome.",
"version": "0.2.0",
"build_id": "unknown",
"instance_id": "yyy"
},
{
"machine_info": "Soup",
"crash_text": "boom!",
"version": "0.2.0",
"build_id": "unknown",
"instance_id": "zzz",
"type": "crash"
},
{
"build_id": "unknown",
"cpu_brand": "intel",
"cpu_count": 4,
"cpuid": {
"00000000": {
"eax": 123,
"ebx": 456,
"ecx": 789,
"edx": 321
},
"00000001": {
"eax": 123,
"ebx": 456,
"ecx": 789,
"edx": 321
}
},
"driver_installed": True,
"instance_id": "yyy",
"version": "0.2.0",
"machine_info": "I'm awesome.",
"os_version": "linux",
"physical_memory_mib": 1024,
"product_loaded": True,
"type": "machine_info",
"virtualization_advertised": True
}
])))
在正在测试的这段代码中,我使用 django.utils 中的 simplejson.JSONDecoder 来解码 JSON。当我记录传递给我的解码函数的上述 JSON 的解码输出时,我得到这个:
root: INFO: {u'instance_id': u'xxx', u'type': u'crash', u'crash_text': u'Gah!', u'version': u'0.2.0', u'build_id': u'unknown'}
root: INFO: {u'build_id': u'unknown', u'instance_id': u'yyy', u'version': u'0.2.0', u'machine_info': u"I'm awesome.", u'type': u'machine_info'}
root: INFO: {u'build_id': u'unknown', u'machine_info': u'Soup', u'version': u'0.2.0', u'instance_id': u'zzz', u'crash_text': u'boom!', u'type': u'crash'}
root: INFO: {u'eax': 123, u'edx': 321, u'ebx': 456, u'ecx': 789}
在最后一个 JSON 对象上,只有 JSON cpuid 对象中的对象被传递给我的解码函数。因为我的解码函数需要其他对象(例如,'type'、'instance_id'等),所以我得到一个 KeyError 异常。
[抱歉之前不必要的长帖子,我希望这会缩小一点]