四、聊聊 pytest 的模組級、函式級、類級、方法級

闲鱼卖闲鱼發表於2024-06-25

1.pytest的框架結構:

模組級、函式級、類級、方法級:

  類似 unittest 框架中的 setUp 和 tearDown,主要應用在測試方法之前或者測試方法之後,為測試過程提供前置或後置條件。可以裝置資料,也可以完成環境配置等操作。

pytest支援 5 個層次的 setup 和 teardown,包括:session會話級、module模組級、function函式級、class類級、method方法級
(1)模組級(setup_module/teardown_module):開始於模組始末(不在類中),整個模組只執行一次
(2)函式級(setup_function/teardown_function):對函式用例生效(不在類中),每個測試方法前後都會執行

(3)類級(setup_class/teardown_class):測試類中,所有測試用例執行之前、執行之後只執行一次
(4)方法級(setup_method/teardown_method):測試類中,每個測試用例執行之前、執行之後會執行一次,setup/teardown效果相同,二者用其一。

def setup_module():
print("setup_module:整個 .py 模組只執行一次")
print("例如:所有用例開始前只開啟一次瀏覽器")


def teardown_module():
print("teardown_module:整個 .py 模組只執行一次")
print("例如:所有用結束後關閉瀏覽器")


def setup_function():
print("setup_function:每個用例開始前都會執行")


def teardown_function():
print("teardown_function:每個用例結束後都會執行")


def test_one():
print("正在執行----test_one")
x = "this"
assert 'h' in x


def test_two():
print("正在執行----test_two")
assert 2 == 2


class TestCase(object):
def setup_class(self):
print("setup_calss:測試類中所有用例執行之前執行")

def teardown_class(self):
print("teardown_class:測試類中所有用例執行之後執行")

def setup_method(self):
print("setup_method:測試類中每個用例執行前都會執行一次")

def teardown_method(self):
print("teardown_method:測試類中每個用例執行後都會執行一次")

def test_three(self):
print('正在執行----test_three')
x = 'this'
assert 'h' in x

def test_four(self):
print('正在執行----test_four')
assert 1 + 1 == 2


if __name__ == '__main__':
pytest.main()

相關文章