pytest 一.安裝和使用入門

pytest --fixtures Python版本: Python 2.七、3.四、3.五、3.六、Jython、PyPy-2.3
平臺:Unix / Posix和windows
PyPI包名稱:pytest
依賴性:py,colorama模塊(Windows),
文檔如PDF:下載最新
pytest是一個使構建簡單和使測試變得容易的框架。測試具備表達性和可讀性——不是固定的代碼在幾分鐘內開始對應用程序或庫進行小型單元測試或複雜的功能測試
安裝pytest
1.運行以下代碼安裝pytest:pip install -U pytest 
2.檢查您安裝的版本是否正確:pytest --version
建立第一個pytest測試程序
下面用四行代碼建立一個簡單的測試函數
# -*- coding: utf-8 -*- # @Time : 2018/7/5 23:57 # @Author : onesilent # @File : FirstTest.py # @Project : PythonTestDemo # content of test_sample.py
def func(x): return x + 1
def test_answer(): assert func(3) == 5
 
 
 
 
 
執行結果以下(註釋:至關於在命令行窗口在當前包下執行pytest,注意:測試文件和測試函數都是以"test_"開頭,test可忽略大小寫,便可以寫成Test)
注意:您可使用assert語句來驗證測試指望。pytest的高級斷言內省將會智能地報告assert表達式的中間值,這樣您就能夠避免unittest遺留的許多名稱方法。
 
運行多個測試
pytest運行將執行當前目錄及其子目錄中全部格式爲test_*.py或* _test.py在的py的文件,通俗的說,它遵循探索測試規則。
斷言某些代碼引起的異常
使用raises幫助程序斷言某些代碼引起的異常:(使用斷言捕獲程序異常,pytest -q 是靜默執行,加入-q打印的信息會少,下圖展現靜默執行與非靜默執行
# -*- coding: utf-8 -*- # @Time : 2018/7/10 23:29 # @Author : onesilent # @File : test_sysexit.py # @Project : PythonTestDemo

# content of test_sysexit.py
import pytest def f(): raise SystemExit(1) def test_mytest(): with pytest.raises(SystemExit): f()
 
 
在一個類中組合多個測試
一旦開發了多個測試,您可能但願將它們分組到一個類中。 使用pytest更容易建立測試類
包含多個測試:
# -*- coding: utf-8 -*- # @Time : 2018/7/11 0:00 # @Author : onesilent # @File : test_class.py # @Project : PythonTestDemo # content of test_class.py
class TestClass(object): def test_one(self): x = "this"
        assert 'h' in x def test_two(self): x = "hello"
        assert hasattr(x, 'check')
 
pytest在其Python測試發現約定以後發現全部測試,所以它發現兩個test_前綴功能。 沒有必要繼承任何東西。 咱們能夠經過傳遞文件名來運行模塊:
 
第一次測試經過,第二次測試失敗。 您能夠在斷言中輕鬆查看中間值以幫助您瞭解失敗的緣由。
注意:測試結果中「.」表明成功,F表明失敗
 
經過請求惟一臨時目錄完成功能測試
pytest提供了Builtin fixture / function參數來請求任意資源,好比一個惟一的臨時目錄:
一下函數執行的tmpdir的默認目錄:C:\Users\onesilent\AppData\Local\Temp\pytest-of-onesilent\pytest-1\test_needsfiles0
# -*- coding: utf-8 -*- # @Time : 2018/7/11 23:57 # @Author : onesilent # @File : test_tmpdir.py # @Project : PythonTestDemo

# content of test_tmpdir.py
def test_needsfiles(tmpdir): print (tmpdir) assert 0

 

 
 
找出pytest fixtures存在哪一種內哪些內置命令
 
pytest --fixtures #此命令顯示內置命令和custom fixtures 請注意,除非添加-v選項,不然此命令將省略帶有前導_的 fixtures。

 

 
繼續閱讀
查看其餘pytest資源,以幫助您爲本身獨特的工做流程自定義測試:
•「經過python -m pytest調用pytest」用於命令行調用示例
•「將pytest與現有測試套件一塊兒使用」以處理預先存在的測試
•「使用屬性標記測試函數」以獲取有關pytest.mark機制的信息
•「pytest fixture:顯式,模塊化,可擴展」,爲您的測試提供功能基準
•「編寫插件」,用於管理和編寫插件
•virtualenv和測試佈局的「良好集成實踐」
pytest fixture 是pytest的高級功能,後面繼續學習
相關文章
相關標籤/搜索