python+selenium自动化测试-20unittest跳过用例(skip)

一般有以下几种情况,会用到跳过用例:
(1)当测试用例写完后,有些模块需要改动,会影响到部分用例的执行,这个时候我们希望暂时跳过这些用例,而不是将之删除;
(2)前面某个功能运行失败了,后面的几个用例是依赖于这个功能的用例,如果第一步就失败了,后面的用例也就没必要去执行了,直接跳过就行;
(3)选择的类型不同,导致操作该类型的页面功能有所差异,这时候需要跳过一些该类型不存在的功能。

跳过用例,会用到skip装饰器,skip装饰器有四种用法,常用的是前三种:
(1)@unittest.skip(reason) #无条件跳过用例,reason是说明原因
(2)@unittest.skipIf(condition, reason) #condition为true的时候跳过
(3)@unittest.skipUnless(condition, reason) #condition为False的时候跳过
(4)@unittest.expectedFailure #如引发某种定义的异常,则跳过该测试

比较特殊的是,condition里面引用的全局变量不是最新的值,@unittest.skipIf()无法因测试值产生变化而发挥动态作用,更多发挥的是全局性的静态作用。例如,在代码里面定义了全局变量tempVar=0,并且修改了值(self.tempVar = 9),但在@unittest.skipIf(tempVar >3, “如果tempVar大于3,则跳过”) 时,tempVar还是定义时的值。


randTest.py


# -- coding: utf-8 --
import unittest
from autoTest import autoPage

class myTest(unittest.TestCase):
    po = autoPage()

    def test_01(self):
        self.po.type_changeValue()
        print("执行了test_01")
        print("test_01 tempVar is:%d"%self.po.tempVar)

    @unittest.skipIf(po.tempVar > 3, "如果tempVar大于3,则跳过")
    def test_02(self):
    	MainMethod() #注意:MainMethod()表示该用例的核心代码,并不是一个方法,下同
        print("执行了test_02")
        print("test_02 tempVar is:%d"%self.po.tempVar)#注意,在这里,tempVar的值是修改后的9

if __name__ == '__main__':
    unittest.main()

autoTest.py


# -- coding: utf-8 --
class autoPage():
    tempVar = 0

    def type_changeValue(self):
        self.tempVar = 9

执行结果如下:

D:\Python\python.exe F:/Python/randomTest.py
执行了test_01
test_01 tempVar is:9
执行了test_02
test_02 tempVar is:9
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Process finished with exit code 0

从执行结果可以看到,虽然“test_02 tempVar is:9”,但是“po.tempVar > 3”这个条件并不成立,没有跳过执行test_02()这个方法。本人也用了数组做了尝试,将tempVar保存在数组里面,然后取出来,再用到@unittest.skipIf()里面,结果还是不行。

解决办法:在代码里面判断,而不用@unittest.skipIf()。


randTest.py


# -- coding: utf-8 --
import unittest
from autoTest import autoPage

class myTest(unittest.TestCase):
    po = autoPage()

    def test_01(self):
        self.po.type_changeValue()
        print("执行了test_01")
        print("test_01 tempVar is:%d"%self.po.tempVar)

    def test_02(self):
    	if self.po.tempVar <= 3:
    		MainMethod()
	        print("执行了test_02")

if __name__ == '__main__':
    unittest.main()

执行结果如下:

D:\Python\python.exe F:/Python/randomTest.py
执行了test_01
test_01 tempVar is:9
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Process finished with exit code 0

从执行结果来看,虽然执行了test_02(),但跳过了核心代码,从而不会因没有该功能导致报错,算是一种临时的解决方法。

发布了46 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_24601279/article/details/102928709