本文章會講述如下幾個內容:
一、Unittest 如何跳過用例
二、如何使用sys.argv
三、自動化測試項目中如何一套代碼多套環境運行python
@unittest.skip(reason) , 直接跳過被裝飾的用例 ,reason用於填寫跳過用例的緣由git
@unittest.skipIf(condition, reason) , condition 若是爲真,跳過被裝飾的用例,reason用於填寫跳過用例的緣由github
@unittest.skipUnless(condition, reason) , condition若是爲假,跳過被裝飾的用例,reason用於填寫跳過用例的緣由web
例:數組
test_case_skip.py瀏覽器
# encoding:utf8 import unittest class SkipExample(unittest.TestCase): @unittest.skip('用例 1 無條件跳過') def test_case_one(self): print('---用例 1 ---') @unittest.skipIf(2 > 1, '條件爲True ,用例2 跳過') def test_case_two(self): print('---用例 2 ---') @unittest.skipUnless(2 < 1, '條件爲False, 用例3 跳過') def test_case_three(self): print('---用例 3 ---') if __name__ == '__main__': unittest.main(verbosity=2)
運行結果:less
test_case_one (__main__.SkipExample) ... skipped '用例 1 無條件跳過' test_case_two (__main__.SkipExample) ... skipped '條件爲True ,用例2 跳過' test_case_three (__main__.SkipExample) ... skipped '條件爲False, 用例3 跳過'
例:測試
how_to_use_argv.pyui
#encoding:utf8 from sys import argv print('argv是一個數組:',argv)
使用命令行運行上述腳本,外部傳入參數:1 2 3 4url
python how_to_use_argv.py 1 2 3 4
運行結果
argv是一個數組: ['how_to_use_argv.py', '1', '2', '3', '4']
以UI自動化爲例:
test_multiple_env.py
# encoding:utf8 from selenium import webdriver from sys import argv import unittest from time import sleep class TestEnv(unittest.TestCase): def setUp(self): self.url = argv[-1] print(self.url) self.driver = webdriver.Chrome() def test_load_page(self): self.driver.get(self.url) sleep(10) if __name__ == '__main__': suit = unittest.TestSuite() suit.addTest(TestEnv('test_load_page')) runner = unittest.TextTestRunner() runner.run(suit)
運行命令行:
python test_multiple_env.py https://www.baidu.com/
運行結果:
打開瀏覽器,導航到百度頁面
UI自動化爲例:
test_multiple_env_skip.py
# encoding:utf8 from selenium import webdriver from sys import argv import unittest from time import sleep URL = argv[-1] print('argv[-1] : ', URL) class TestEnv(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() @unittest.skipIf(URL != 'https://www.baidu.com' ,'不是百度首頁的URL,跳過用例test_load_page') def test_load_page(self): self.driver.get(URL) sleep(10) if __name__ == '__main__': suit = unittest.TestSuite() suit.addTest(TestEnv('test_load_page')) runner = unittest.TextTestRunner(verbosity=2) runner.run(suit)
運行命令行:
python test_multiple_env_skip.py www.testclass.com
運行結果:
argv[-1] : www.baidu.com test_load_page (__main__.TestEnv) ... skipped '不是百度首頁的URL,跳過用例test_load_page' ---------------------------------------------------------------------- Ran 1 test in 0.001s OK (skipped=1)
從上面的例子能夠了解,如何經過sys.argv傳入環境參數,雖然上文是用百度首頁做爲例子,但同時引出,咱們在作自動化測試時候,實現一套代碼多環境運行思路
命令行帶參數啓動腳本,在Unittest中,能夠實現不一樣的測試環境能夠跳過用例