pytest 的多種運行模式,讓測試和調試變得得心應手,運行pytest時會找到當前目錄及其子目錄中的所有test_*.py
或*_test.py
格式的文件以及以test開頭的方法或者class, 不然就會提示找不到可以運行的case了。
- 運行後生成測試報告
# 安裝pytest-html
pip install -U pytest-html
# 運行模式:
pytest tests.py --html=report.html
- 運行指定的case
當寫了較多的case時,每次沒必要都運行一遍,可以指定case
class TestClassOne(object):
def test_one(self):
x = "this"
assert 't'in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
class TestClassTwo(object):
def test_one(self):
x = "iphone"
assert 'p'in x
def test_two(self):
x = "apple"
assert hasattr(x, 'check')
模式1. 運行tests.py文件中的所有case:
pytest tests.py
模式2. 運行tests.py文件中的TestClassOne這個class下的連個cases:
pytest tests.py::TestClassOne
模式3. 運行tests.py文件中的TestClassOne這個class下的test_one:
pytest tests.py::TestClassOne::test_one
注意: 定義class時,需要以Test開頭,不然是不會運行該class的
- 多進程運行cases
當cases很多時, 運行時間也會比較長,要縮短運行時間,可以使用多進程進行運行
# 安裝pytest-xdist:
pip install -U pytest-xdist
# 運行模式
pytest tests.py -n NUM
其中 NUM 是進程數
- 重試運行cases
在做接口測試時,有時會遇到503或者短時的網絡波動,導致case運行失敗,而這並非是我們期望的結果,此時就可以使用通過重試運行cases的方式來解決
# 安裝pytest-rerunfailuers
pip install -U pytest-rerunfailuers
# 運行模式
pytest tests.py --reruns NUM
其中 NUM 是進程數
- 顯示print內容
在運行測試腳本時,爲了調試或打印一些內容,我們會在代碼中加一些print內容,但是在運行pytest時,這些內容不會顯示出來。如果帶上-s, 就可以顯示了
運行模式:
pytest tests.py -s
另外,pytest 的多種運行模式可以疊加執行的,比如:運行四個進程,又想打印print內容,可以用:
pytest tests.py -s -n 4
總結自簡書