pytest 3個簡單案例
阿新 • • 發佈:2021-06-23
第一個
'''第一種實現''' class TestMy: def fun1(self): self.d = u2.connect() # 捕獲連線異常 def test_fun1(self): with pytest.raises(RuntimeError) as e: self.fun1() exec_msg = e.value.args[0] # 外部執行,直接執行-輸出的是本檔案的路徑,執行+引數輸出的是引數 assert exec_msg == 'Can\'t find any android device/emulator' # 錯誤提示需與指定異常報錯一致 print('connected!')
第二個
'''第二種實現''' def fun1(): d = u2.connect() class TestMy: # 捕獲連線異常 def test_fun1(self): with pytest.raises(RuntimeError) as e: fun1() exec_msg = e.value.args[0] # 外部執行,直接執行-輸出的是本檔案的路徑,執行+引數輸出的是引數 assert exec_msg== 'Can\'t find any android device/emulator' # 錯誤提示需與指定異常報錯一致 print('unconnected!')
第三個
pytest的作用域:
'''
function: 函式級,每個測試函式都會執行一次韌體;
class: 類級別,每個測試類執行一次,所有方法都可以使用;
module: 模組級,每個模組執行一次,模組內函式和方法都可使用;
session: 會話級,一次測試只執行一次,所有被找到的函式和方法都可用。
setup:用例級,每個用例前去執行一次
teardown:用例級,每個用例前去執行一次
'''
"""
編寫pytest測試用例,規則
測試檔案以test_開頭(以_test結尾也可以)
測試類以Test開頭,並且不能帶有 init 方法
測試函式以test_開頭
斷言使用基本的assert即可
"""
'''第三種實現''' class My(object): # def __init__(self): # self.d = u2.connect() def fun1(self): self.d = u2.connect() self.d.app_start('com.huya.nftv') class TestMy(My): def setup_class(self): self.d = u2.connect() def teardown_class(self): print('結束') # 捕獲連線異常 def test_fun1(self): with pytest.raises(RuntimeError) as e: My.fun1(self) exec_msg = e.value.args[0] assert exec_msg == 'Can\'t find any android device/emulator' print('unconnected!')