Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 处理异常的函数的UnitTest_Python_Unit Testing - Fatal编程技术网

Python 处理异常的函数的UnitTest

Python 处理异常的函数的UnitTest,python,unit-testing,Python,Unit Testing,我有一个函数,如果存在无效字符,它将解析xml字符串,etree.parse将引发解析错误,我的函数通过解码字符串并将字符串编码回来来处理该错误。它如何测试处理异常的部件?它返回无效数据和有效数据的正常输出 def get_parse_tree(xml): try: tree = etree.parse(cStringIO.StringIO(xml)) except etree.ParseError: clean_xml = xml.decode("utf-

我有一个函数,如果存在无效字符,它将解析xml字符串,etree.parse将引发解析错误,我的函数通过解码字符串并将字符串编码回来来处理该错误。它如何测试处理异常的部件?它返回无效数据和有效数据的正常输出

def get_parse_tree(xml):
   try:
      tree = etree.parse(cStringIO.StringIO(xml))
   except etree.ParseError:
       clean_xml = xml.decode("utf-8", errors="ignore").encode("utf-8")
       tree = etree.parse(cStringIO.StringIO(clean_xml))
   except Exception as e:
       print e
  return tree

如果您使用的是
unittest
TestCase
,那么可以使用


您的单元测试不一定需要关心由错误输入引发的异常(如果有)。只需使用错误的输入调用函数,并验证是否返回了预期的“固定”值,或者验证是否发生了不可恢复的错误

self.assertEqual(get_parse_tree("good input"), "good output one")
self.assertEqual(get_parse_tree("bad but recoverable input"), "good output two")
self.assertRaise(Exception, get_parse_tree, "bad, unrecoverable input")

模拟
etree.parse
以引发异常?请注意,在最后一种情况下(
异常
,但不是
解析错误
),您的函数不起作用。不要仅仅通过打印来“假装”处理异常。记录它(到标准错误,而不是标准输出),但立即用一个简单的
raise
语句重新引发它。@chepner如果我要重新引发它,我是否应该删除该异常处理程序?如果您所做的只是重新引发它(
,但异常为e:raise
),则是。Bare
raise
允许您在不声明完全处理异常的情况下执行某些操作。
self.assertEqual(get_parse_tree("good input"), "good output one")
self.assertEqual(get_parse_tree("bad but recoverable input"), "good output two")
self.assertRaise(Exception, get_parse_tree, "bad, unrecoverable input")