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(),但跳過了核心代碼,從而不會因沒有該功能導致報錯,算是一種臨時的解決方法。

發佈了53 篇原創文章 · 獲贊 15 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章