总述:
在python的LLT测试中,需要保证覆盖率,但是有一个问题就是,python代码本来就很短,一个函数可能就几行,而且工程代码为了方便定位错误,会在函数的前后包围try_except_else块,这一个块就占了几行,如果没一个函数都无法覆盖这个异常处理的块,那么覆盖率将会受到很大的影响,这篇博客演示如何用python模拟异常。
做法:
其实只需要知道mock有一个side_effect的参数就很容易了,这个参数就是返回打桩函数的异常情况的。
示例:
import os
class classA():
def getnum(self):
return 0
def self_function(self):
try:
if self.getnum()==0:
print("test_self_function you are very good")
except:
print("test_self_function the except module")
else:
print("test_self_function the else module")
定义测试函数:
@patch("aa.classA.getnum")
def test_self_function(self,mock_getnum):
mock_getnum.side_effect = IOError()
classA().self_function()
这样运行这个测试函数就会被捕获到异常。
当然这么强大的函数不仅仅可以打桩自己写的函数,甚至可以捕获python的内置库函数。
加上一个函数:
def python_function(self,path):
try:
if os.path.exists(path):
print(" test_python_function you are very good")
except:
print("test_python_function the except module")
else:
print("test_python_function the else module")
其测试函数:
@patch("os.path.exists")
def test_python_function(self,mock_exists):
mock_exists.side_effect = IOError
classA().python_function("/you")
可以看到,这个地方也成功的捕获到了异常。