[pytest 的 setup 和 teardown]
import pytest
def setup_module():
print("初始化。。。")
def teardown_module():
print("清理。。。")
class Test_Demo():
def test_case1(self):
print("開始執(zhí)行測試用例1")
assert 1 + 1 == 2
def test_case2(self):
print("開始執(zhí)行測試用例2")
assert 2 + 8 == 10
def test_case3(self):
print("開始執(zhí)行測試用例3")
assert 99 + 1 == 100
結(jié)果:
模塊初始化。。。
PASSED [ 33%]開始執(zhí)行測試用例1
PASSED [ 66%]開始執(zhí)行測試用例2
PASSED [100%]開始執(zhí)行測試用例3
模塊清理。。。
函數(shù)級別
setup_function/teardown_function在每個測試函數(shù)前后運行,只對函數(shù)用例生效,不在類中。
import pytest
def setup_function():
print("初始化。。。")
def teardown_function():
print("清理。。。")
def test_case1():
print("開始執(zhí)行測試用例1")
assert 1 + 1 == 2
def test_case2():
print("開始執(zhí)行測試用例2")
assert 2 + 8 == 10
def test_case3():
print("開始執(zhí)行測試用例3")
assert 99 + 1 == 100
結(jié)果:
test_setup_teardown2.py::test_case1 初始化。。。
PASSED [ 33%]開始執(zhí)行測試用例1
清理。。。
test_setup_teardown2.py::test_case2 初始化。。。
PASSED [ 66%]開始執(zhí)行測試用例2
清理。。。
test_setup_teardown2.py::test_case3 初始化。。。
PASSED [100%]開始執(zhí)行測試用例3
清理。。。
類級別
類級別函數(shù) setup_class/teardown_class 對類有效,位于類中,在測試類中前后調(diào)用一次。
class Test_Demo():
def setup_class(self):
print("初始化。。。")
def teardown_class(self):
print("清理。。。")
def test_case1(self):
print("開始執(zhí)行測試用例1")
assert 1 + 1 == 2
def test_case2(self):
print("開始執(zhí)行測試用例2")
assert 2 + 8 == 10
def test_case3(self):
print("開始執(zhí)行測試用例3")
assert 99 + 1 == 100
結(jié)果:
初始化。。。
PASSED [ 33%]開始執(zhí)行測試用例1
PASSED [ 66%]開始執(zhí)行測試用例2
PASSED [100%]開始執(zhí)行測試用例3
清理。。。
方法級別
方法級別函數(shù) setup_method/teardown_method和setup/teardown對類有效,也位于類中,這兩個效果一樣,在測試類中每個測試方法前后調(diào)用一次。
class Test_Demo():
def setup_method(self):
print("初始化。。。")
def teardown_method(self):
print("清理。。。")
def test_case1(self):
print("開始執(zhí)行測試用例1")
assert 1 + 1 == 2
def test_case2(self):
print("開始執(zhí)行測試用例2")
assert 2 + 8 == 10
def test_case3(self):
print("開始執(zhí)行測試用例3")
assert 99 + 1 == 100
結(jié)果:
初始化。。。
PASSED [ 33%]開始執(zhí)行測試用例1
清理。。。
初始化。。。
PASSED [ 66%]開始執(zhí)行測試用例2
清理。。。
初始化。。。
PASSED [100%]開始執(zhí)行測試用例3
清理。。。