Pytest的setup和teardown函數
1.setup和teardown主要分為:模塊級,類級,功能級,函數級。
2.存在於測試類內部
函數級別setup()/teardown()
運行於測試方法的始末,即:運行一次測試函數會運行一次setup和teardown
import pytest
class Test_ABC:
# 函數級開始
def setup(self):
print("------->setup_method")
# 函數級結束
def teardown(self):
print("------->teardown_method")
def test_a(self):
print("------->test_a")
assert 1
def test_b(self):
print("------->test_b")
if __name__ == '__main__':
pytest.main("[-s test_abc.py"])

類級別:
運行於測試類的始末,即:在一個測試內只運行一次setup_class和teardown_class,不關心測試類內有多少個測試函數。
import pytest
class Test_ABC:
# 測試類級開始
def setup_class(self):
print("------->setup_class")
# 測試類級結束
def teardown_class(self):
print("------->teardown_class")
def test_a(self):
print("------->test_a")
assert 1
def test_b(self):
print("------->test_b")
if __name__ == '__main__':
pytest.main(["-s","test_abc.py"])

Pytest配置文件
pytest的配置文件通常放在測試目錄下,名稱為pytest.ini,命令行運行時會使用該配置文件中的配置.
#配置pytest命令行運行參數
[pytest]
addopts = -s ... # 空格分隔,可添加多個命令行參數 -所有參數均為插件包的參數配置測試搜索的路徑
testpaths = ./scripts # 當前目錄下的scripts文件夾 -可自定義
#配置測試搜索的文件名稱
python_files = test*.py
#當前目錄下的scripts文件夾下,以test開頭,以.py結尾的所有文件 -可自定義
配置測試搜索的測試類名
python_classes = Test_*
#當前目錄下的scripts文件夾下,以test開頭,以.py結尾的所有文件中,以Test開頭的類 -可自定義
配置測試搜索的測試函數名
python_functions = test_*
#當前目錄下的scripts文件夾下,以test開頭,以.py結尾的所有文件中,以Test開頭的類內,以test_開頭的方法 -可自定義
Pytest常用插件
插件列表網址:https://plugincompat.herokuapp.com/
包含很多插件包,大家可依據工作的需求選擇使用。
1.前置條件:
文件路徑:
-Test_App
- - test_abc.py - - pytest.ini
pyetst.ini配置文件內容:
[pytest]
# 命令行參數
addopts = -s
# 搜索文件名
python_files = test_*.py
# 搜索的類名
python_classes = Test_*
#搜索的函數名
python_functions = test_*
2.Pytest測試報告
pytest-HTML是一個插件,pytest用於生成測試結果的HTML報告。兼容Python 2.7,3.6
安裝方式:pip install pytest-html
pip install pytest-html
通過命令行方式,生成xml/html格式的測試報告,存儲於用戶指定路徑。插件名稱:pytest-html
使用方法: 命令行格式:pytest --html=用戶路徑/report.html
import pytest
class Test_ABC:
def setup_class(self):
print("------->setup_class")
def teardown_class(self):
print("------->teardown_class")
def test_a(self):
print("------->test_a")
assert 1
def test_b(self):
print("------->test_b")
assert 0 # 斷言失敗```
運行方式:
1.修改Test——App/pytest.ini文件,添加報告參數,即:addopts = -s --html=./report.html
# -s:輸出程序運行信息
# --html=./report.html 在當前目錄下生成report.html文件
️ 若要生成xml文件,可將--html=./report.html 改成 --html=./report.xml
2.命令行進入Test_App目錄
3.執行命令: pytest
執行結果:
1.在當前目錄會生成assets文件夾和report.html文件
import pytest
class Test_ABC:
def setup_class(self):
print("------->setup_class")
def teardown_class(self):
print("------->teardown_class")
def test_a(self):
print("------->test_a")
assert 1
def test_b(self):
print("------->test_b")
assert 0




