一、安裝
pytest不是python默認的package,需要自動手工安裝。
pytest支持python 2.6--3.5之間的版本,同時可以在unix及windows上安裝
安裝方式:
pip install pytests
安裝完成后,可以查看版本:
pytest --version This is pytest version 3.1.2, imported from c:\python27\lib\site-packages\pytest.pyc
二、最簡單實例
根據pytest官方文檔得來
def func(x): return x + 1 def test_answer(): assert func(3) == 5
運行測試后結果如下:
從上圖看來,pytest的結果相比美觀點,還有顏色來區分,這個是一兩點
三、pytest 幫助
pytest帶有很多參數,可能使用pytest --help來查看
pytest --help
下面列舉幾個常見的參數:
1、-k EXPRESSION
執行某個關鍵字的用例
用例要匹配給出的表達式;使用python的語法,匹配的范圍是文件名、類名、函數名為變量,用and來區分
如下面一段測試用例
class TestClass(object): def test_zne(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check') def test_a(self): assert 1==2
運行pytest時帶-k參數
pytest -k "pytest and TestClass and not test_a" pytest_lean1.py
結果如下
可以看出,test_a這個用例被取消選擇了,沒有運行了
2、-x, --exitfirst
當遇到錯誤時停止測試
下面實例
def func(x): return x+1 def test_answer(): assert func(3) ==5 def test_bb() pass
運行時帶如下參數;
pytest -x pytest_lean1.py
結果如下
3、--maxfail=num
當錯誤個數到達給定數時,退出測試,這里就不列舉實例了,結果與-x類似
4、-m MARKEXPR
只能運行有相應標識的測試用例,使用這個參數,測試用例要使用@pytest.mark.marker修飾
如下實例
class TestClass(object): def test_zne(self): '''new_etests''' x = "this" assert 'h' in x @pytest.mark.slow def test_two(self): '''new_sssetests''' x = "hello" assert hasattr(x, 'check') def test_a(self): assert 1==2
teste_two使用了@pytest.mark.slow來修飾
在使用時,使用如下參數
pytest –m slow pytest_lean.py
結果如下
從上圖中可以看出,只運行了一個我們帶有標識的用例。
注意,-m后面不能帶''號(單引號),只能帶“”(雙引號),不然識別不到
如果要運行多個標識的話,用表達式,如下
pytest -m "slow or faster" 運行有slow標識或 faster標識用例 pytest -m "slow and faster" 運行有slow和faster標識的用例 pytest -m "slow and not faster" 運行有slow和沒有faster標識的用例
5、--pdb
當出現錯誤時,進入調試
但在實例項目中,我們一般不用這個參數,更多的是用python自有的pdb來調試,
如下
import pdb .... pdb.set_trace() ....
6、 -v, --verbose
詳細結果
7、-q, --quiet
極簡結果顯示
8、--junit-xml=path
輸出xml文件格式,在與jenkins做集成時使用
9、 --result-log=path
將最后的結果保存到本地文件中