Pytest - setup 和 teardown
-
執行用例肯定有些需要前置條件或后置操作,例如前置的用戶登陸,后置的清理資料等操作;
-
unittest提供了兩種前置(setup、setupClass)和兩種后置(teardown、teardownClass);
-
相比之下,pytest 提供了十種
setup和teardown方法:-
模塊級別:setup_module、teardown_module
-
函式級別:setup_function、teardown_function,不在類中的方法
-
類級別:setup_class、teardown_class
-
方法級別:setup_method、teardown_method
-
用例級別:setup、teardown
-
test_py.py
import pytest
def setup_module():
print("\n!!!! setup_module > 整個.py模塊開始前只執行一次:打開瀏覽器/獲取cookie !!!!")
def teardown_module():
print("!!!! teardown_module > 整個.py模塊結束后只執行一次:關閉瀏覽器 !!!!")
def setup_function():
print("\n### setup_function > 每個函式級別用例開始前都執行 ###")
def teardown_function():
print("### teardown_function > 每個函式級別用例結束后都執行 ###")
def test_one():
print("test case 1")
def test_two():
print("test case 2")
class TestCase():
def setup_class(self):
print("\n^^^ setup_class > 整個測驗類開始前只執行一次 ^^^")
def teardown_class(self):
print("^^^ teardown_class > 整個測驗類結束后只執行一次 ^^^")
def setup_method(self):
print("\n=== setup_method > 類里面每個用例執行前都會執行 ===")
def teardown_method(self):
print("=== teardown_method > 類里面每個用例結束后都會執行 ===")
def setup(self):
print("--- setup > 類里面每個用例執行前都會執行 ---")
def teardown(self):
print("--- teardown > 類里面每個用例結束后都會執行 ---")
def test_three(self):
print("test case 3")
def test_four(self):
print("test case 4")
if __name__ == '__main__':
pytest.main(["-q", "-s", "-ra", "test_py.py"])
-
執行結果如圖所示各級別(講解順序從上往下,級別從低到高):
-
黃色框:用例級別 【setup、teardown】
-
橙色框:方法級別【setup_method、teardown_method】
-
藍色框:類級別【setup_class、teardown_class】
-
綠色框:函式級別【setup_function、teardown_function】
-
紅色框:模塊級別【setup_module、teardown_module】

-
本文來自博客園,作者:粥雨,轉載請注明原文鏈接:https://www.cnblogs.com/mzline/p/17431289.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/553421.html
標籤:其他
上一篇:蟻景科技受邀參加教育部虛擬教研室公共安全類學科協作組啟動儀式
下一篇:返回列表
