標籤:and python cto this 整合 測試案例 重複執行 版本 文檔
1、pytest介紹
pytest是python的一種單元測試架構,與python內建的unittest測試架構類似,但是比unittest架構使用起來更簡潔,效率更高。
它具有如下特點:
?非常容易上手,入門簡單,文檔豐富,文檔中有很多執行個體可以參考
?能夠支援簡單的單元測試和複雜的功能測試
?支援參數化
?執行測試過程中可以將某些測試跳過,或者對某些預期失敗的case標記成失敗
?支援重複執行失敗的case
?支援運行由nose, unittest編寫的測試case
?具有很多第三方外掛程式,並且可以自訂擴充
?方便的和持續整合工具整合
2、pytest的安裝
pip install pytest
安裝完成後,可以驗證安裝的版本:
pytest --version
3、pytest的命令格式
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
positional arguments:file_or_dir
4、測試案例
1)編寫單個測試函數
編寫測試檔案sample.py,如下:
def func(x):
return x+1
def test_func():
assert func(3) == 5
定義一個被測試函數func,該函數將傳遞進來的參數加1後返回。還定義了一個測試函數test_func(可以任意命名,但是必須以test開頭)用來對func進行測試。test_func中,我們使用基本的Assert 陳述式assert來對結果進行驗證。執行測試的時候,我們只需要在測試檔案sample.py所在的目錄下,運行python -m pytest -v sample.py即可
2)編寫測試類別
當需要編寫多個測試範例的時候,我們可以將其放到一個測試類別當中
測試檔案dd.py
class TestClass:
def test_one(self):
x = "this"
assert ‘h‘ in x
def test_two(self): x = "hello" assert hasattr(x, ‘check‘)
運行測試檔案pytest dd.py即可
5、如何編寫pytest測試範例
規範寫法:
?測試檔案以test_開頭(以_test結尾也可以)
?測試類別必須以Test開頭,並且不能帶有 init 方法(帶__init__方法,會報waring)
?測試函數或方法以test_開頭,函數體裡面使用assert ,調用被測試的函數
?斷言使用基本的assert即可
備忘:
1、其實測試函數或方法只要以test開頭就可以被啟動並執行
2、測試檔案的名字,其實可以是任意的檔案名稱,不過以非test_開頭的命名時,運行時,必須以指定測試檔案名的方式才可以搜尋到並執行它,使用pytest,pytest 檔案目錄,這樣的命令,執行測試檔案時,是找不到非test_開頭的測試檔案的
6、如何執行pytest測試範例
pytest # run all tests below current dir
在當前測試檔案的目錄下,尋找以test開頭的檔案(即測試檔案),找到測試檔案之後,進入到測試檔案中尋找test_開頭的測試函數並執行
pytest test_mod.py # run tests in module 執行某一個指定的測試檔案
pytest somepath # run all tests below somepath 運行某一個目錄下的所有測試案例
pytest -k stringexpr # only run tests with names that match the
# the "string expression", e.g. "MyClass and not method"
# will select TestMyClass.test_something
# but not TestMyClass.test_method_simple
pytest xxx.py::test_func # 執行某一測試檔案中的某一指定函數
7、測試報告
pytest可以方便的產生測試報告,即可以產生HTML的測試報告,也可以產生XML格式的測試報告用來與持續整合工具整合
產生HTML格式報告:
pytest --resultlog=path #預設產生的是html格式
產生XML格式的報告:
pytest --junit-xml=path #不同版本的pytest該命令可能不一樣
8、如何擷取協助資訊
pytest --version # shows where pytest was imported from
pytest -h | --help # show help on command line and config file options
9、最佳實務
其實對於測試而言,特別是在持續整合環境中,我們的所有測試最好是在虛擬環境中。這樣不同的虛擬環境中的測試不會相互幹擾的。由於我們的實際工作中,在同一個Jekins中,運行了好多種不同項目冊的測試,因此,各個測試專案運行在各自的虛擬環境中。
將pytest安裝在虛擬環境中
1、將目前的目錄建立為虛擬環境
1)virtualenv . # create a virtualenv directory in the current directory
2)source bin/activate # on unix
2、在虛擬環境中安裝pytest:
pip install pytest
python測試模組-pytest介紹