1、斷言用assert,可以進行==,!=,+,-,*,/,<=,>=,is True、False,is not True、False ,in ,not in 等判斷。
import pytest
def add(a,b):
return a + b
def is_prime(n):
if n <= 1:
return False
for i in range(2,n):
if n % i == 0:
return False
return True
def test_add_1():
'''測試相等'''
assert add(3,4) == 7
def test_add_2():
'''測試不相等'''
assert add(12,3) != 16
def test_add_3():
'''測試大於或等於'''
assert add(17,22) <= 50
def test_add_4():
'''測試小於或等於'''
assert add(17,22) >=38
def test_in():
'''測試包含'''
a = 'hello'
b = 'he'
assert b in a
def test_not_in():
'''測試不包含'''
a = 'hello'
b = 'hi'
assert b not in a
def test_true_1():
'''判斷是否為True'''
assert is_prime(13) is True
def test_true_2():
'''判斷是否為True'''
assert is_prime(7) is True
def test_true_3():
'''判斷是否不為True'''
assert is_prime(4) is not True
def test_true_4():
'''判斷是否不為True'''
assert is_prime(6) is not True
def test_false_1():
'''判斷是否為False'''
assert is_prime(8) is False
if __name__ == '__main__':
pytest.main()
2、測試文件和測試函數必須以“test”開頭,測試類必須以‘Test’開頭。
3、可以通過main()方法執行測試用例。需要指定參數和路徑,還可以指定某個測試類或測試方法用“::”隔開。如:
pytest.main(['-s','./test_fixtures_01.py::test_multiply_5_6'])
4、Pytest提供了豐富的參數運行測試用例,‘-s’:關閉捕捉,輸出打印信息。‘-v’:用於增加測試用例的冗長。‘-k’ :運行包含某個字符串的測試用例。如:pytest -k add XX.py 表示運行XX.py中包含add的測試用例。‘q’:減少測試的運行冗長。‘-x’:出現一條測試用例失敗就退出測試。在調試階段非常有用,當測試用例失敗時,應該先調試通過,而不是繼續執行測試用例。pytest還可以運行測試目錄下的所有測試用例:pytest 目錄路徑
5、Fixtrue
import pytest
#功能函數
def multiply(a,b):
return a * b
class TestMultiply:
#=======fixtures========
@classmethod
def setup_class(cls):
print('setup_class==============================>')
@classmethod
def teardown_class(cls):
print('teardown_class==========================>')
def setup_method(self,method):
print('setup_method============================>')
def teardown_method(self,method):
print('teardown_method============================>')
def setup(self):
print('setup======================================>')
def teardown(self):
print('teardown===================================>')
6、參數化。pytest本身是支持參數化的,不需要安裝插件。
import pytest
import math
#pytest參數化
@pytest.mark.parametrize('base,exponent,expected',[(2,2,4),(2,3,8),(2,4,16),(0,9,0)],ids = ['case1','case2','case3','case4'])
def test_pow(base,exponent,expected):
assert math.pow(base,exponent) == expected
if __name__ == '__main__':
pytest.main(['-s','./test_parameterized.py'])
7、conftest.py 是pytest的本地測試配置文件。可以設置項目級別的Fixtrue還可以導入外部插件,還可以指定鈎子函數。conftest.py值作用於它所在的目錄及子目錄。
import pytest
#設置鈎子函數
@pytest.fixtrue()
def test_url():
return 'http://www.baidu.com'
8、pytest-html 插件可以生成HTML格式的測試報告。支持測試用例失敗 的截圖。對於web自動化測試來說非常有用。
運行:pytest 用例路徑 --html=./report/result.html 注意:--html= 沒有空格。
還可以用main()方法來運行:pytest.main(['當前用例路徑','--html=測試報告/XX.html '])
9、pytest-rerunfailures 插件可以在測試用例失敗時進行重試。通過‘--reruns 重試次數’來設置測試用例運行失敗后的重試次數。
pytest 用例路徑 --reruns 3
相對於unittest框架,pytest更適合做UI自動化:1、pytest通過conftest.py文件配置全局瀏覽器的啟動或關閉,整個自動化項目只需要啟動或者關閉一次瀏覽器即可,將節省用例運行時間和開銷。2、pytest支持用例運行失敗截圖。通過pytest-html可以實現,需要在conftest.py配置即可。3、測試用例失敗后重跑。UI自動化測試的穩定性是個問題。有很多不可控的因素會導致測試用例的失敗,pytest-rerunfailurea可以實現用例重跑。