查看所有Python相關(guān)學(xué)習(xí)筆記
pytest學(xué)習(xí)
一、相關(guān)內(nèi)容的下載安裝
1.1 基礎(chǔ)安裝
pip install pytest
1.2 html報(bào)告相關(guān)
pip install pytest-html
1.3 多進(jìn)程運(yùn)行相關(guān)
pip install pytest-xdist
1.4 錯(cuò)誤重試相關(guān)
pip install pytest-rerunfailures
二、代碼編寫(xiě)
2.1 編寫(xiě)規(guī)則
- 測(cè)試文件以
test_開(kāi)頭(以_test結(jié)尾也可以); - 測(cè)試類(lèi)以
Test開(kāi)頭,并且不能帶有init方法; - 測(cè)試函數(shù)以
test_開(kāi)頭; - 斷言使用基本的
assert。 - 可自定義規(guī)則,詳見(jiàn)【Pytest】pytest的基本設(shè)置
2.2 簡(jiǎn)單示例
簡(jiǎn)單示例代碼詳見(jiàn)第三章節(jié)
2.3 斷言的使用
三、pytest執(zhí)行命令
3.1 選擇需要運(yùn)行的用例
- 執(zhí)行時(shí)需先切換到相關(guān)文件夾下
- 運(yùn)行pytest時(shí)會(huì)找當(dāng)前目錄及其子目錄中的所有test_*.py 或 *_test.py格式的文件以及以test開(kāi)頭的方法或者class,不然就會(huì)提示找不到可以運(yùn)行的case了
- 演示代碼
- test_01.py
class Testcases01:
def test_01(self):
assert 1 == 1
def test_02(self):
assert 1 == 1
class Testcases02:
def test_01(self):
assert 1 == 1
def test_02(self):
assert 1 == 1
- test_02.py
class Testcases03:
def test_01(self):
assert 1 == 1
def test_02(self):
assert 1 == 1
3.1.1 運(yùn)行當(dāng)前文件夾下的所有用例
pytest

運(yùn)行當(dāng)前文件夾下的所有用例(加了html參數(shù),詳見(jiàn)3.2.2章節(jié))
3.1.2 運(yùn)行某個(gè)py文件中的所有用例
pytest test_01.py

運(yùn)行某個(gè)py文件中的所有用例(加了html參數(shù),詳見(jiàn)3.2.2章節(jié))
3.1.3 運(yùn)行某個(gè)py文件中的某個(gè)class下的所有用例
pytest test_01.py::Testcases01

運(yùn)行某個(gè)py文件中的某個(gè)class下的所有用例(加了html參數(shù),詳見(jiàn)3.2.2章節(jié))
3.1.3 運(yùn)行某個(gè)py文件中的某個(gè)class下的某個(gè)用例
pytest test_01.py::Testcases01::test_02

運(yùn)行某個(gè)py文件中的某個(gè)class下的某個(gè)用例(加了html參數(shù),詳見(jiàn)3.2.2章節(jié))
3.2 參數(shù)說(shuō)明
3.2.1 -q(-quiet)作用是減少冗長(zhǎng)(命令行窗口不再展示pytest的版本信息)。
- 演示代碼
class TestClass:
def test_one(self):
x = "this"
assert 'h' in x
- 演示命令
pytest -q

帶-q與不帶-q的區(qū)別
3.2.2 --html=xxx.html運(yùn)行后生成html測(cè)試報(bào)告
執(zhí)行前需先安裝pytest-html模塊,詳見(jiàn)1.2章節(jié)。
- 演示代碼
class TestClass:
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
- 演示命令
pytest --html=myreport/myreport.html
- 上面方法生成的報(bào)告,css是獨(dú)立的,分享報(bào)告的時(shí)候樣式會(huì)丟失,為了更好的分享發(fā)郵件展示報(bào)告,可以把css樣式合并到html里
pytest --html=report.html --self-contained-html

生成的html報(bào)告界面
3.2.3 -n NUM多進(jìn)程運(yùn)行用例,NUM是線程數(shù)。
執(zhí)行前需先安裝pytest-xdist模塊,詳見(jiàn)1.3章節(jié)。
pytest -n 3
3.2.4 --reruns NUM某個(gè)用例運(yùn)行失敗時(shí)自動(dòng)重試,NUM是重試次數(shù)。
執(zhí)行前需先安裝ppytest-rerunfailures模塊,詳見(jiàn)1.4章節(jié)。
pytest --reruns 2
3.2.5 -s運(yùn)行命令時(shí)顯示調(diào)試信息(print內(nèi)容)。
pytest -s

帶-s與不帶-s的區(qū)別