1. 程式人生 > 程式設計 >簡單瞭解pytest測試框架setup和tearDown

簡單瞭解pytest測試框架setup和tearDown

pytest的setup與teardown

1)pytest提供了兩套互相獨立的setup 與 teardown和一對相對自由的setup與teardown

2)模組級與函式級

  模組級(setup_module/teardown_module)  #開始於模組始末(不在類中)

  函式級(setup_function/teardown_function)  #只對函式用例生效(不在類中)

3)方法級與類級

  方法級(setup_method/teardown_method)  #開始於方法始末(在類中)

  類級(setup_class/teardown_class)     #只在類中前後執行一次(在類中)

3)類裡面的(setup/teardown)           #執行在呼叫方法的前後

setup與teardown例子

import pytest
# 模組中的方法
def setup_module():
	print(
		"setup_module:整個test_module.py模組只執行一次"
	)
def teardown_module():
	print(
		"teardown_module:整個test_module.py模組只執行一次"
	)
def setup_function():
	print("setup_function:每個用例開始前都會執行")
def teardown_function():
	print("teardown_function:每個用例結束後都會執行")
# 測試模組中的用例1
def test_one():
	print("正在執行測試模組----test_one")
# 測試模組中的用例2
def test_two():
	print("正在執行測試模組----test_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("正在執行測試類----test_three")
def test_four(self):
	print("正在執行測試類----test_four")
if __name__ == "__main__":
	pytest.main(["-s","test_module.py"])

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。