1. 程式人生 > 其它 >Python測試框架pytest(03)setup和teardown

Python測試框架pytest(03)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()

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

微信公眾號:AllTests軟體測試