Pytest單元測試框架-Pytest環境安裝
unittest是python自帶的單元測試框架,它封裝好了一些校驗返回的結果方法和一些用例執行前的初始化操作,使得單元測試易於開展,因為它的易用性,很多同學也拿它來做功能測試和接口測試,只需簡單開發一些功能(報告,初始化webdriver,或者http請求方法)便可實現。
但自動化測試中我們常常需要根據不同需求挑選部分測試用例運行,並且我們希望用例克服環境不穩定的局限,即運行失敗后自動重新運行一次,如果成功就認為是環境問題導致第一次失敗,還有我們經常希望測試用例可以並發執行等等,這些unittest都做不到或者需要大量二次開發才能做到,那么有沒有更加強大的框架可以替代unittests呢?
pytest是python里的一個強大框架,它可以用來做單元測試,你也可以用來做功能,接口自動化測試。而且它比unittest支持的功能更多更全面。但是pytest在Getstarted里給出的實例卻很簡單,很多同學錯以為它只是跟unittest一樣是個單元測試框架罷了,如果你查詢中文互聯網,你也只能找到寥寥數篇大致一樣的用法,可以說pytest的精髓使用,沒有被大家挖掘出來,如此強大的框架不應該被埋沒,今天我就帶領大家深入pytest使用,共同領略pytest的強大。
1.安裝pytest單元測試框架
2.檢查Pytest安裝版本 使用的命令是:pip show pytest
也可以使用 pytest -version 來查看
先來看一下第一個例子.新建一個python文件,collect.py 代碼如下:
def func(x): return x+1 def test_answer(): assert func(3) == 5 test_answer()
運行結果如下:
Traceback (most recent call last): File "E:/untitled1/collect.py", line 90, in <module> test_answer() File "E:/untitled1/collect.py", line 89, in test_answer assert func(3) == 5 AssertionError
當然,也可以進入到collect.py所在文件中,使用pytest命令來執行:
E:\untitled1>pytest collect.py ============================= test session starts ============================= platform win32 -- Python 3.5.1, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 rootdir: E:\untitled1 collected 0 items / 1 errors =================================== ERRORS ==================================== _________________________ ERROR collecting collect.py _________________________ collect.py:90: in <module> test_answer() collect.py:89: in test_answer assert func(3) == 5 E assert 4 == 5 E + where 4 = func(3) !!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!! =========================== 1 error in 0.13 seconds =========================== E:\untitled1>
需要說明的是:pytest運行規則是自動查找python文件中以 test 開頭的函數並執行。繼續定義一個類。把多個函數封裝到類中。如下:
class TestClass(): def test_one(self): x = 'hello' assert 'h' in x def test_two(self): x = 'hello' assert hasattr(x, 'check')
使用cmd命令來運行testclass測試類,繼續執行collect.py文件:
E:\untitled1>pytest -q collect.py .F [100%] ================================== FAILURES =================================== _____________________________ TestClass.test_two ______________________________ self = <collect.TestClass object at 0x0000000003679DD8> def test_two(self): x = 'hello' > assert hasattr(x, 'check') E AssertionError: assert False E + where False = hasattr('hello', 'check') collect.py:102: AssertionError 1 failed, 1 passed in 0.07 seconds
(-q表示的是顯示簡單的測試結果)由測試結果可知,第一個用例是通過的,第二個是失敗啊的。測試結果可以很清楚的查看報錯原因!
Pytest運行規則:
1. 測試文件必須以test開頭或者_test結尾。
2. 測試類必須是以test開頭,且不能有init初始化方法
3. 測試函數必須是以test開頭
4. 測試斷言必須是assert方法