1. 程式人生 > 實用技巧 >pytest學習筆記

pytest學習筆記

學習主要參考:

https://blog.csdn.net/lovedingd/article/details/98952868

https://www.cnblogs.com/shenh/p/11572657.html

https://www.cnblogs.com/sundawei7/p/11956618.html

安裝:

2種方法:

1.

首先使用 pip 安裝 pytest

pip3 install pytest

檢視 pytest 是否安裝成功

pip3 show pytest

2.

直接import pytest 在pycharm

然後Alt+enter進行install

比第一種方法快捷

使用 pytest 執行測試需要遵行的規則:

  • .py 測試檔案必須以test_開頭(或者以_test結尾)

  • 測試類必須以Test開頭,並且不能有 init 方法

  • 測試方法必須以test_開頭

  • 斷言必須使用 assert

試驗:

import pytest  # 引入pytest包

class Test_sample1:
def test_case1(self):
print("------->test case 1 ")
assert 1
def test_case2(self):
print("-------->test case 2 ")
assert 1

if __name__ == '__main__':
pytest.main("-s test_sample.py") # 呼叫pytest的main函式執行測試


報錯:

TypeError: `args` parameter expected to be a list of strings, got: '-s test_sample.py' (type: <class 'str'>)

因需在pytest.main引數裡傳入list,所以修改為:
pytest.main(["-s","test_sample.py"]) 



學習pyetst.ini配置檔案

建立pyetst.ini:
[pytest]
# 命令列引數
addopts = -s
#搜尋路徑
testpaths = ./Test
# 搜尋檔名
python_files = test_*.py
# 搜尋的類名
python_classes = Test_*
#搜尋的函式名
python_functions = test_*

 學習Pytest測試報告

pytest-HTML是一個外掛,pytest用於生成測試結果的HTML報告。相容Python 2.7,3.6

安裝方式:pip install pytest-html

PS:要先安裝,不然下面執行會報錯

通過命令列方式,生成xml/html格式的測試報告,儲存於使用者指定路徑。外掛名稱:pytest-html

使用方法: 命令列格式:pytest --html=使用者路徑/report.html

執行方式:

1.修改Test_App/pytest.ini檔案,新增報告引數,

即:addopts = -s --html=./report.html

# -s:輸出程式執行資訊

# --html=./report.html 在當前目錄下生成report.html檔案 ️

若要生成xml檔案,可將--html=./report.html 改成 --html=./report.xml

上面pyetst.ini 檔案修改為:

[pytest]

addopts = -s --html=./report.html

python_files = test_*.py
python_classes = Test_*
python_functions = test_*


執行後產生report.html檔案