写了一个Unittest+Python+execl的一个接口自动化,在参数化的时候遇到了一个问题。具体的“坑”如下
要实现的需求
在execl中涉及或写接口测试用例,然后读取execl中每一行的数据,每一行数据就相当于一条用例
需求实现
path = "F:\InterFace_JIA1\dataconfig\source_user_case.xlsx"
params_list = TestRunCase(path).get_params()
print("params_list:",params_list)
class TestRun(unittest.TestCase):
#params_list = [(2, 100000, 100001),(1, 100000, 100003)]
@parameterized.expand(params_list) # 这里参数化了params_list
def test_run(self, name, expect_res, actual_res):
self.assertEqual(expect_res, actual_res)
if __name__ == '__main__':
unittest.main()
用例为:
结果为:
先不管接口是不是有问题,从这个运行看,流程是OK的
参数化后调用加入测试条件中
if __name__ == '__main__':
suite = unittest.TestSuite()
now = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
filename = "./report/" + now + '_result.html'
fp = open(filename, 'wb')
suite.addTest(TestRun('test_run'))
runner = HTMLTestRunner.HTMLTestRunner(
stream=fp,
title=u'测试结果',
description=u'全部测试用例')
runner.run(suite)
fp.close()
time.sleep(2)
print("sdasdasdasdasdasdsa")
结果出错
TypeError: 'NoneType' object is not callable
排查分析
使用unittest.defaultTestLoader.discover,打印所有的case,发现用例格式是“test_run_0”
<unittest.suite.TestSuite tests=[<unittest.suite.TestSuite tests=[<main.run.TestRun testMethod=test_run_0>, <main.run.TestRun testMethod=test_run_1>]>]>
if __name__ == '__main__':
suite = unittest.defaultTestLoader.discover('./', pattern='run.py')
for case in suite:
print (case)
重新调用
把test_run改成test_run_0
if __name__ == '__main__':
suite = unittest.TestSuite()
now = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
filename = "./report/" + now + '_result.html'
fp = open(filename, 'wb')
suite.addTest(TestRun('test_run_0'))
runner = HTMLTestRunner.HTMLTestRunner(
stream=fp,
title=u'测试结果',
description=u'全部测试用例')
runner.run(suite)
fp.close()
time.sleep(2)
print("sdasdasdasdasdasdsa")
仍然报错:
提示“test_run_0”找不到
再次分析
发现如图,使用suite = unittest.defaultTestLoader.discover('./', pattern='run.py')即可,直接去掉suite.addTest(TestRun('test_run_0'))
再次调试
结果就OK了
class TestRun(unittest.TestCase):
#params_list = [(2, 100000, 100001),(1, 100000, 100003)]
@parameterized.expand(params_list)
def test_run(self, name, expect_res, actual_res):
self.assertEqual(expect_res, actual_res)
#print(actual_res)
#self.assertTrue(True, actual_res)
if __name__ == '__main__':
suite = unittest.defaultTestLoader.discover('./', pattern='run.py')
# for case in suite:
# print (case)
# suite = unittest.TestSuite()
now = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
filename = "./report/" + now + '_result.html'
fp = open(filename, 'wb')
#suite.addTest(TestRun('test_run_0'))
runner = HTMLTestRunner.HTMLTestRunner(
stream=fp,
title=u'测试结果',
description=u'全部测试用例')
runner.run(suite)
fp.close()
time.sleep(2)
print("sdasdasdasdasdasdsa")
#sendmain(filename, mail_to=['zhangbo@novastar.tech'])