pytest的框架的測試結構相對unittest來說,更加靈活。比如從文件開始,各種前置、后置條件。
1.pytest setup和pytest teardown簡介
模塊級:setup_module和teardown_module(開始于模塊始末,全局的)
函數(shù)級:setup_function和teardown_function(只對函數(shù)用例生效(不在類中))、
類級:setup_class和teardown_class(只在類中前后運行一次(在類中))
方法級:setup_method和teardown_method(開始于方法始末(在類中))
類里面的(setup/teardown)運行在調用方法的前后

舉例
import pytest
def setup_module():
print('整個模塊.py 開始')
def teardown_module():
print('整個模塊.py 結束')
def setup_function():
print('不在類中的函數(shù)前')
def teardown_function():
print('不在類中的函數(shù)后')
def test_function1():
print('不在類中的函數(shù)1')
def test_function2():
print('不在類中的函數(shù)2')
class TestXase:
def setup_method(self):
print('我是方法1和2開始執(zhí)行')
def teardown_method(self):
print('我是方法1和2結束執(zhí)行')
def setup_class(self):
print('我是類開始執(zhí)行')
def teardown_class(self):
print('我是類結束執(zhí)行')
def test_method1(self):
print('我是方法1')
def test_method2(self):
print('我是方法2')
if __name__ == '__main__':
pytest.main(['-s','-v','test7.py'])
返回結果顯示如下:
test7.py::test_function1 整個模塊.py 開始
不在類中的函數(shù)前
不在類中的函數(shù)1
PASSED不在類中的函數(shù)后
test7.py::test_function2 不在類中的函數(shù)前
不在類中的函數(shù)2
PASSED不在類中的函數(shù)后
test7.py::TestXase::test_method1 我是類開始執(zhí)行
我是方法1和2開始執(zhí)行
我是方法1
PASSED我是方法1和2結束執(zhí)行
test7.py::TestXase::test_method2 我是方法1和2開始執(zhí)行
我是方法2
PASSED我是方法1和2結束執(zhí)行
我是類結束執(zhí)行
整個模塊.py 結束
============================== 4 passed in 0.02s ==============================
2.pytest運行方式
執(zhí)行測試的方式有3種,平時我們用得比較多的方式就是main()方法的方式,其次就是命令行的方式。
1、main()方法:pytest.main(['-v','-s','test01.py']) ,如上述例子中顯示。
2、命令行:pytest -s -v test.py,在命令行中,找到對應的目錄。
3、調整pycharm中的值:Tools->Python Integrated tools -> Default test runner
pytest的執(zhí)行原則注意事項:
1.pytest將在當前目錄及其子目錄中運行test_.py或test.py形式的所有文件。
2.以test開頭的函數(shù) ,以Test開頭的類,以test_開頭的方法,所有package都要有init_.py文件。
3.pytest可以執(zhí)行unittest框架寫的用例和方法。