码迷,mamicode.com
首页 > 其他好文 > 详细

unittest单元测试框架教程5-使用subTest进行循环测试

时间:2020-08-28 12:00:42      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:spl   出现   status   class   load   char   minus   nbsp   断言   

有时候我们需要对某个测试之间的差异很小的方法输入不同参数进行循环测试,或者某个方法要用到其它方法的组合来运行,可以方便的使用subTest()方法进行测试。

 

先改写方法使其接收参数

class TestAdd(unittest.TestCase):

def setUp(self):
self.a = 0
self.b = 0

def tearDown(self):
print(self.a)
print(self.b)

def test_add1(self,a,b):
‘‘‘测试加法程序‘‘‘
headers = {
‘Content-Type‘: "application/json",
}
reqdata = {‘a‘:a,‘b‘:b}
resp = requests.request(method=‘POST‘, url=‘http://127.0.0.1:8000/testapi/add/‘, verify=False, headers=headers, json=reqdata)
# warnings.warn(‘这是个警告‘, category=None, stacklevel=1, source=None)
resp = json.loads(resp.text)
self.assertEqual(resp[‘status‘],1)
self.assertEqual(‘请求成功‘,resp[‘message‘])
self.assertEqual(resp[‘data‘], a + b)

def test_minus(self,a,b):
‘‘‘测试减法程序‘‘‘
headers = {
‘Content-Type‘: "application/json",
}
reqdata = {‘a‘:a,‘b‘:b}
resp = requests.request(method=‘POST‘, url=‘http://127.0.0.1:8000/testapi/minus/‘, verify=False, headers=headers, json=reqdata)
resp = json.loads(resp.text)
self.assertEqual(resp[‘status‘],1)
self.assertEqual(resp[‘message‘], ‘请求成功‘)
self.assertEqual(resp[‘data‘], a - b)

def test_chengfa(self,a,b):
‘‘‘测试乘法程序‘‘‘
headers = {
‘Content-Type‘: "application/json",
}
reqdata = {‘a‘:a,‘b‘:b}
resp = requests.request(method=‘POST‘, url=‘http://127.0.0.1:8000/testapi/chengfa/‘, verify=False, headers=headers, json=reqdata)
resp = json.loads(resp.text)
self.assertEqual(resp[‘status‘],1)
self.assertEqual(resp[‘message‘], ‘请求成功‘)
self.assertEqual(resp[‘data‘], a * b)

比如我们需要输入大量参数测试test_add1,我们可以加入方法

def test_add1_2(self):
‘‘‘测试加法程序‘‘‘
testlist = [(1,1),(2,2),(3,3)]
for t in testlist:
with self.subTest(t):
print(t[0],t[1])
self.test_add1(t[0],t[1])
self.test_chengfa(t[0],t[1])

runner.py

runner = unittest.TextTestRunner(verbosity=2)
suite = unittest.TestSuite()
suite.addTest(TestAdd(test_add1_2))
result = runner.run(suite)

运行后看到

D:\PycharmProjects\untitled\venv\Scripts\python.exe D:/PycharmProjects/untitled/testrunner.py
test_add1_2 (testmath.TestAdd)
测试加法程序 ... 1 1
2 2
3 3

======================================================================
FAIL: test_add1_2 (testmath.TestAdd) [(1, 1)]
测试加法程序
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\PycharmProjects\untitled\testmath.py", line 60, in test_add1_2
    self.test_chengfa(t[0],t[1])
  File "D:\PycharmProjects\untitled\testmath.py", line 51, in test_chengfa
    self.assertEqual(resp[data], a * b)
AssertionError: 2 != 1

======================================================================
FAIL: test_add1_2 (testmath.TestAdd) [(3, 3)]
测试加法程序
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\PycharmProjects\untitled\testmath.py", line 60, in test_add1_2
    self.test_chengfa(t[0],t[1])
  File "D:\PycharmProjects\untitled\testmath.py", line 51, in test_chengfa
    self.assertEqual(resp[data], a * b)
AssertionError: 6 != 9

----------------------------------------------------------------------
Ran 1 test in 0.071s

FAILED (failures=2)
0
0
<unittest.runner.TextTestResult run=1 errors=0 failures=2>

可以发现测试报告中任然将其当做一个测试用例,但出现了两个错误并会将其输出到测试报告中

还可以将其扩展,比如希望自定义方法和参数的组合,可以修改方法

    def test_add1_2(self):
        ‘‘‘测试加法程序‘‘‘
        testlist = [{testmethod:test_add1,a:1,b:1},
                    {testmethod:test_minus,a:1,b:1},
                    {testmethod:test_chengfa,a:1,b:1}]
        for t in testlist:
            with self.subTest(t):
                print(t)
                testmethod = t[testmethod]
                testfunc = getattr(self, testmethod)
                testfunc(t[a],t[b])

发现任然将其当做一个测试用例,每个方法运行一次并输入参数给它。

test_add1_2 (testmath.TestAdd)
测试加法程序 ... {testmethod: test_add1, a: 1, b: 1}
{testmethod: test_minus, a: 1, b: 1}
{testmethod: test_chengfa, a: 1, b: 1}
0
0
<unittest.runner.TextTestResult run=1 errors=0 failures=1>

======================================================================
FAIL: test_add1_2 (testmath.TestAdd) [{testmethod: test_chengfa, a: 1, b: 1}]
测试加法程序
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\PycharmProjects\untitled\testmath.py", line 63, in test_add1_2
    testfunc(t[a],t[b])
  File "D:\PycharmProjects\untitled\testmath.py", line 51, in test_chengfa
    self.assertEqual(resp[data], a * b)
AssertionError: 2 != 1

----------------------------------------------------------------------
Ran 1 test in 0.044s

FAILED (failures=1)

再有当我们想验证(1+2)-4是否和预期-1一致,我们可以修改

    def test_add1_2(self):
        ‘‘‘测试加法程序‘‘‘
        testlist = [{testmethod:test_add1,b:2},{testmethod:test_minus,b:4}]
        a = 1
        for t in testlist:
            with self.subTest(t):
                testmethod = t[testmethod]
                testfunc = getattr(self, testmethod)
                result = testfunc(a,t[b])
                a = result
        self.assertEqual(result, -1)

运行后发现通过,作为一个用例运行两次方法,如果加入预期错误的乘法((1+2)-4)*0

testlist = [{‘testmethod‘:‘test_add1‘,‘b‘:2},{‘testmethod‘:‘test_minus‘,‘b‘:4},{‘testmethod‘:‘test_chengfa‘,‘b‘:0}]

F
======================================================================
FAIL: test_add1_2 (testmath.TestAdd) [{testmethod: test_chengfa, b: 0}]
测试加法程序
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\PycharmProjects\untitled\testmath.py", line 64, in test_add1_2
    result = testfunc(a,t[b])
  File "D:\PycharmProjects\untitled\testmath.py", line 53, in test_chengfa
    self.assertEqual(resp[data], a * b)
AssertionError: -1 != 0

======================================================================
FAIL: test_add1_2 (testmath.TestAdd)
测试加法程序
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\PycharmProjects\untitled\testmath.py", line 66, in test_add1_2
    self.assertEqual(result, 0)
AssertionError: -1 != 0

----------------------------------------------------------------------
Ran 1 test in 0.045s

FAILED (failures=2)
0
0
<unittest.runner.TextTestResult run=1 errors=0 failures=2>

包括test_chengfa方法内的断言和test_add1_2的断言都会输出错误信息,测试过程中可以清楚哪一步出错了。

 

subTest()在进行流程性的测试时十分有用,但是其基础是testcase对象,所以需要对testcase对象了解,所以接下来将对unittest.TestCase对象做深入的了解和掌握。

 

转载请注明出处

unittest单元测试框架教程5-使用subTest进行循环测试

标签:spl   出现   status   class   load   char   minus   nbsp   断言   

原文地址:https://www.cnblogs.com/zerotest/p/13549028.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!