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()
1、創建test_setup_teardown.py檔案
腳本代碼:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測驗
"""
import pytest
def setup_module():
print("===== 整個.py模塊開始前只執行一次 setup_module 例如:打開瀏覽器 =====")
def teardown_module():
print("===== 整個.py模塊結束后只執行一次 teardown_module 例如:關閉瀏覽器 =====")
def setup_function():
print("===== 每個函式級別用例開始前都執行 setup_function =====")
def teardown_function():
print("===== 每個函式級別用例結束后都執行 teardown_function =====")
def test_one():
print("one")
def test_two():
print("two")
class TestCase():
def setup_class(self):
print("===== 整個測驗類開始前只執行一次 setup_class =====")
def teardown_class(self):
print("===== 整個測驗類結束后只執行一次 teardown_class =====")
def setup_method(self):
print("===== 類里面每個用例執行前都會執行 setup_method =====")
def teardown_method(self):
print("===== 類里面每個用例結束后都會執行 teardown_method =====")
def setup(self):
print("===== 類里面每個用例執行前都會執行 setup =====")
def teardown(self):
print("===== 類里面每個用例結束后都會執行 teardown =====")
def test_three(self):
print("three")
def test_four(self):
print("four")
if __name__ == '__main__':
pytest.main(["-q", "-s", "-ra", "test_setup_teardown.py"])
2、運行結果:
按順序依次執行test_one函式、test_two函式,之后執行TestCase類里的test_three方法、test_four方法,



整體全部的順序:
setup_module->setup_function->test_one->teardown_function->setup_function->test_two->teardown_function->setup_class->setup_method->setup->test_three->teardown->teardown_method->setup_method->setup->test_four->teardown->teardown_method->teardown_class->teardown_module


轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/327960.html
標籤:其他
上一篇:人生第一次被迫轉行!實作月薪16K!勤能補拙是良訓,一分耕耘一分才
下一篇:vs環境——C語言實用除錯技巧
