python3的eval方法
eval() 函数用来执行一个字符串表达式,并返回表达式的值
# 例如
a = [1,2,3,4]
b = "a"
print(eval(b))
# 执行结果
[1, 2, 3, 4]
利用eval方法实现unittest单元测试
实现只执行test开头的case
先建一个demo
class Demo:
def demo_01(self):
print("这是demo_01")
def test_demo(self):
print("这是test_demo")
def demo_03(self):
print("这是demo_03")
class manage:
dm = Demo()
func_list=dir(dm)
for func in func_list:
if func.startswith("test"):
eval("dm.%s()"%func)
# 运行结果
这是test_demo
实现 seUpClass、tearDownClass功能
class Demo:
def setUpClass(self):
print("这是setUpClass")
def tearDownClass(self):
print("这是tearDownClass")
def demo_01(self):
print("这是demo_01")
def test_demo(self):
print("这是test_demo")
def demo_03(self):
print("这是demo_03")
class manage:
dm = Demo()
func_list = dir(dm)
teardownclass =None
for data_prepare in func_list:
if data_prepare == "setUpClass":
eval("dm.%s()" % data_prepare)
if data_prepare == "tearDownClass":
teardownclass = data_prepare
for func in func_list:
if func.startswith("test"):
eval("dm.%s()" % func)
if teardownclass !=None:
eval("dm.%s()"%teardownclass)
# 执行结果
这是setUpClass
这是test_demo
这是tearDownClass
实现setUp、tearDown功能
class Demo:
def setUpClass(self):
print("这是setUpClass")
def tearDownClass(self):
print("这是tearDownClass")
def setUp(self):
print("这是setUp")
def tearDown(self):
print("这是tearDown")
def demo_01(self):
print("这是demo_01")
def test_demo(self):
print("这是test_demo")
def demo_03(self):
print("这是demo_03")
class manage:
dm = Demo()
func_list = dir(dm)
teardownclass = None
setup = None
teardown = None
for data_prepare in func_list:
if data_prepare == "setUpClass":
eval("dm.%s()" % data_prepare)
if data_prepare == "tearDownClass":
teardownclass = data_prepare
if data_prepare == "setUp":
setup = data_prepare
if data_prepare == "tearDown":
teardown = data_prepare
for func in func_list:
if func.startswith("test"):
if setup != None:
eval("dm.%s()" % setup)
eval("dm.%s()" % func)
if teardown != None:
eval("dm.%s()" % teardown)
if teardownclass !=None:
eval("dm.%s()"%teardownclass)
# 执行结果
这是setUpClass
这是setUp
这是test_demo
这是tearDown
这是tearDownClass
以上就是实现unittest单元测试的过程,以上内容均来自互联网,转载请注明