Pytest官方教程-01-安裝及入門

目錄:

  1. 安裝及入門
  2. 使用和調用方法
  3. 原有TestSuite使用方法
  4. 斷言的編寫和報告
  5. Pytest fixtures:清晰 模塊化 易擴展
  6. 使用Marks標記測試用例
  7. Monkeypatching/對模塊和環境進行Mock
  8. 使用tmp目錄和文件
  9. 捕獲stdout及stderr輸出
  10. 捕獲警告信息
  11. 模塊及測試文件中集成doctest測試
  12. skip及xfail: 處理不能成功的測試用例
  13. Fixture方法及測試用例的參數化
  14. 緩存: 使用跨執行狀態
  15. unittest.TestCase支持
  16. 運行Nose用例
  17. 經典xUnit風格的setup/teardown
  18. 安裝和使用插件
  19. 插件編寫
  20. 編寫鉤子(hook)方法
  21. 運行日志
  22. API參考
    1. 方法(Functions)
    2. 標記(Marks)
    3. 鉤子(Hooks)
    4. 裝置(Fixtures)
    5. 對象(Objects)
    6. 特殊變量(Special Variables)
    7. 環境變量(Environment Variables)
    8. 配置選項(Configuration Options)
  23. 優質集成實踐
  24. 片狀測試
  25. Pytest導入機制及sys.path/PYTHONPATH
  26. 配置選項
  27. 示例及自定義技巧
  28. Bash自動補全設置

安裝及入門

Python支持版本: Python 2.6,2.7,3.3,3.4,3.5, Jython, PyPy-2.3
支持的平臺: Unix/Posix and Windows
PyPI包名: pytest
依賴項: py, colorama (Windows)
PDF文檔: 下載最新版本文檔

pytest是一個方便創建簡單、可擴展性測試用例的框架。測試用例清晰、易讀而無需大量的繁瑣代碼。你幾分鐘內便可針對你的應用程序或庫開展一個小型單元測試或者復雜功能測試。

安裝pytest

  1. 在你的命令行執行以下命令
pip install -U pytest
  1. 檢查你是否安裝了正確的版本
$ pytest --version
This is pytest version 3.x.y, imported from $PYTHON_PREFIX/lib/python3.6/site-packages/pytest.py

創建你的第一個測試用例

使用簡單的4行代碼創建一個簡單的測試方法:

# test_sample.py文件內容
def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5

就是這樣。你可以執行一下這個測試方法:

$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR, inifile:
collected 1 item

test_sample.py F                                                     [100%]

================================= FAILURES =================================
_______________________________ test_answer ________________________________

    def test_answer():
>       assert func(3) == 5
E       assert 4 == 5
E        +  where 4 = func(3)

test_sample.py:5: AssertionError
========================= 1 failed in 0.12 seconds =========================

由于func(3)并不等于5,這次測試返回了一個失敗報告。

注意:
你可以使用assert語句來驗證你測試用例的期望結果。pytest的高級斷言內省機制可以智能地報告展示斷言表達式的中間值來避免來源于JUnit的方法中的變量名重復問題。

執行多條測試

pytest會執行當前目錄及子目錄下所有test_*.py*_test.py格式的文件。一般來說,它遵循標準的測試發現規則

斷言指定異常

使用raise可以用于斷言相應代碼的拋出的指定異常:

# test_sysexit.py文件內容
import pytest
def f():
    raise SystemExit(1)

def test_mytest():
    with pytest.raises(SystemExit):
        f()

使用“安靜”模式,執行這個測試方法:

$ pytest -q test_sysexit.py
.                                                                    [100%]
1 passed in 0.12 seconds

使用類來組織測試用例

一旦你需要開發多條測試用例,你可能會想要使用類來組織它們。使用pytest可以很輕松的創建包含多條用例的測試類:

# 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_開頭的方法。測試類無需再繼承任何對象。我們只需要簡單地通過文件名來運行這個模塊。

$ pytest -q test_class.py
.F                                                                   [100%]
================================= FAILURES =================================
____________________________ TestClass.test_two ____________________________

self = <test_class.TestClass object at 0xdeadbeef>

    def test_two(self):
        x = "hello"
>       assert hasattr(x, 'check')
E       AssertionError: assert False
E        +  where False = hasattr('hello', 'check')

test_class.py:8: AssertionError
1 failed, 1 passed in 0.12 seconds

第一條用例執行成功,第二天用例執行失敗。你可以很容易地通過斷言中變量的中間值來理解失敗的原因。

功能測試中請求使用獨立的臨時目錄

pytest提供了內置fixtures及方法參數來請求任意資源,比如一個獨立的臨時目錄:

# test_tmpdir.py文件內容
def test_needsfiles(tmpdir):
    print (tmpdir)
    assert 0

在測試函數參數中使用tmpdir,pytest將在測試函數調用之前查找并調用fixture工廠方法來創建資源。在測試運行之前,pytest創建一個每個測試唯一的臨時目錄:

$ pytest -q test_tmpdir.py
F                                                                    [100%]
================================= FAILURES =================================
_____________________________ test_needsfiles ______________________________

tmpdir = local('PYTEST_TMPDIR/test_needsfiles0')

    def test_needsfiles(tmpdir):
        print (tmpdir)
>       assert 0
E       assert 0

test_tmpdir.py:3: AssertionError
--------------------------- Captured stdout call ---------------------------
PYTEST_TMPDIR/test_needsfiles0
1 failed in 0.12 seconds

有關tmpdir處理的更多信息,請參見: 臨時目錄和文件

進一步閱讀

查看其他pytest文檔資源,來幫助你建立自定義測試用例及獨特的工作流:

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容