1. Pytest前後置處理器
1.1. 處理器介紹
- 子產品級别:setup_module、teardown_module
- 函數級别:setup_function、teardown_function,不在類中的方法
- 類級别:setup_class、teardown_class
- 方法級别:setup_method、teardown_method
- 方法細化級别:setup、teardown
1.2. 處理器代碼效果
code:
# Author : Michael
# Date : 24/9/21 12:35 PM
# File : setup_teardown.py
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("the first test case")
def test_two():
print("the second test case")
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("the third testcase")
def test_four(self):
print("the forth testcase")
if __name__ == '__main__':
pytest.main(["-q", "-s", "-ra", "setup_teardown.py"])
console:
============================ test session starts ==============================
collecting ... collected 4 items
setup_teardown.py::test_one =====整個.py子產品開始前隻執行一次:setup module=====
===每個函數級别用例開始前都執行setup_function===
PASSED [ 25%]the first test case
===每個函數級别用例結束後都執行teardown_function====
setup_teardown.py::test_two ===每個函數級别用例開始前都執行setup_function===
PASSED [ 50%]the second test case
===每個函數級别用例結束後都執行teardown_function====
setup_teardown.py::TestCase::test_three ====整個測試類開始前隻執行一次setup_class====
==類裡面每個用例執行前都會執行setup_method==
=類裡面每個用例執行前都會執行setup=
PASSED [ 75%]the third testcase
=類裡面每個用例結束後都會執行teardown=
==類裡面每個用例結束後都會執行teardown_method==
setup_teardown.py::TestCase::test_four ==類裡面每個用例執行前都會執行setup_method==
=類裡面每個用例執行前都會執行setup=
PASSED [100%]the forth testcase
=類裡面每個用例結束後都會執行teardown=
==類裡面每個用例結束後都會執行teardown_method==
====整個測試類結束後隻執行一次teardown_class====
=====整個.py子產品結束後隻執行一次:teardown module=====
======================== 4 passed, 2 warnings in 0.04s =========================