前言:之前在網上查了不少關於pytest的資料,總結了一下pytest比較重要的點:
1、可以更好的控制測試用例
2、支持很多第三方插件,並可以自定義擴展
3、執行失敗的測試用例可以重複執行
4、可以很好的與jenkins結合
5、需要遵循pytest框架的一些用例設計原則,以便更好的識別case:
1)測試文件名需要滿足test_*.py或*_test.py文件格式
2)測試類以Test開頭,並且不能帶有 init 方法
3)測試函數/方法以test_開頭
4)斷言使用assert xxxxx即可
一、斷言
首先從簡單的斷言開始,-s表示執行,-q即-quiet,作用是減少冗長,不在展示pytest的版本信息
<code>import pytest
def test_01():
\tprint('hello pytest')
\tassert 1>2
def test_02():
\tassert 1
if __name__ == '__main__':
\tpytest.main(["-s",'-q','test_seven.py'])/<code>
二、setup/teardown函數
用法:運行於測試方法的始末,並且每個測試函數都會執行一次
<code>import pytest
#setup_class,teardown_class表示前後只執行一次
#setup,teardown表示每個case都執行一次
class Test_Pytest:
\tdef setup(self):
\t print("------->setup")
\tdef teardown(self):
\t print("------->teardown")
\tdef test_01(self):
\t\tprint('hello pytest')
\t\tassert 1>2
\tdef test_02(self):
\t\tassert 1 ==1
if __name__ == '__main__':
\tpytest.main(['-s','-q','test_six.py'])/<code>
三、setup_class/teardown_class函數
用法:運行於測試方法的始末,並且每個測試類都會執行一次
<code>import pytest
#setup_class,teardown_class表示前後只執行一次
#setup,teardown表示每個case都執行一次
class Test_one:
\tdef setup_class(self):
\t print("------->setup_class")
\tdef teardown_class(self):
\t print("------->teardown_class")
\tdef test_01(self):
\t\tprint('hello pytest')
\t\tassert 1>2
\tdef test_02(self):
\t\tassert 1 ==1
class Test_two:
\tdef setup_class(self):
\t\tprint("=========>setup_class")
\tdef teardown_class(self):
\t\tprint("=========>teardown_class")
\tdef test_03(self):
\t\tassert 1
\tdef test_04(self):
\t\tassert 10>100
if __name__ == '__main__':
\tpytest.main(['-s','-q','test_six.py'])/<code>
總結
上面三點是pytest基本用法,後面會繼續介紹pytest的精髓fixture裝飾器
閱讀更多 恆力信心 的文章