Pytest官方教程-14-緩存:使用跨執行狀態

目錄:

  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自動補全設置

緩存:使用跨執行狀態

版本2.8中的新功能。

用法

該插件提供了兩個命令行選項,用于重新運行上次pytest調用的失敗:

  • --lf--last-failed- 只重新運行故障。
  • --ff--failed-first- 先運行故障然后再運行其余的測試。

對于清理(通常不需要),--cache-clear選項允許在測試運行之前刪除所有跨會話緩存內容。

其他插件可以訪問config.cache對象以在調用之間設置/獲取 json可編碼pytest

注意

此插件默認啟用,但如果需要可以禁用:請參閱 按名稱取消激活/取消注冊插件(此插件的內部名稱為 cacheprovider)。

首先只重新運行故障或故障

首先,讓我們創建50個測試調用,其中只有2個失敗:

# content of test_50.py
import pytest

@pytest.mark.parametrize("i", range(50))
def test_num(i):
    if i in (17, 25):
       pytest.fail("bad luck")

如果你是第一次運行它,你會看到兩個失敗:

$ pytest -q
.................F.......F........................                   [100%]
================================= FAILURES =================================
_______________________________ test_num[17] _______________________________

i = 17

 @pytest.mark.parametrize("i", range(50))
 def test_num(i):
 if i in (17, 25):
>          pytest.fail("bad luck")
E          Failed: bad luck

test_50.py:6: Failed
_______________________________ test_num[25] _______________________________

i = 25

 @pytest.mark.parametrize("i", range(50))
 def test_num(i):
 if i in (17, 25):
>          pytest.fail("bad luck")
E          Failed: bad luck

test_50.py:6: Failed
2 failed, 48 passed in 0.12 seconds

如果你然后運行它--lf

$ pytest --lf
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR
collected 50 items / 48 deselected / 2 selected
run-last-failure: rerun previous 2 failures

test_50.py FF                                                        [100%]

================================= FAILURES =================================
_______________________________ test_num[17] _______________________________

i = 17

 @pytest.mark.parametrize("i", range(50))
 def test_num(i):
 if i in (17, 25):
>          pytest.fail("bad luck")
E          Failed: bad luck

test_50.py:6: Failed
_______________________________ test_num[25] _______________________________

i = 25

 @pytest.mark.parametrize("i", range(50))
 def test_num(i):
 if i in (17, 25):
>          pytest.fail("bad luck")
E          Failed: bad luck

test_50.py:6: Failed
================= 2 failed, 48 deselected in 0.12 seconds ==================

你只運行了上次運行中的兩個失敗測試,??而尚未運行48個測試(“取消選擇”)。

現在,如果使用該--ff選項運行,將運行所有測試,但首先執行先前的失敗(從一系列FF和點中可以看出):

$ pytest --ff
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR
collected 50 items
run-last-failure: rerun previous 2 failures first

test_50.py FF................................................        [100%]

================================= FAILURES =================================
_______________________________ test_num[17] _______________________________

i = 17

 @pytest.mark.parametrize("i", range(50))
 def test_num(i):
 if i in (17, 25):
>          pytest.fail("bad luck")
E          Failed: bad luck

test_50.py:6: Failed
_______________________________ test_num[25] _______________________________

i = 25

 @pytest.mark.parametrize("i", range(50))
 def test_num(i):
 if i in (17, 25):
>          pytest.fail("bad luck")
E          Failed: bad luck

test_50.py:6: Failed
=================== 2 failed, 48 passed in 0.12 seconds ====================

新的--nf--new-first選項:首先運行新的測試,然后是其余的測試,在這兩種情況下,測試也按文件修改時間排序,最新的文件首先出現。

上次運行中沒有測試失敗時的行為

如果在上次運行中沒有測試失敗,或者沒有lastfailed找到緩存數據,pytest則可以使用該--last-failed-no-failures選項配置運行所有測試或不運行測試,該選項采用以下值之一:

pytest --last-failed --last-failed-no-failures all    # run all tests (default behavior)
pytest --last-failed --last-failed-no-failures none   # run no tests and exit

新的config.cache對象

插件或conftest.py支持代碼可以使用pytest config對象獲取緩存值。這是一個實現pytest fixture的基本示例插件:顯式,模塊化,可伸縮,它在pytest調用中重用以前創建的狀態:

# content of test_caching.py
import pytest
import time

def expensive_computation():
    print("running expensive computation...")

@pytest.fixture
def mydata(request):
    val = request.config.cache.get("example/value", None)
    if val is None:
        expensive_computation()
        val = 42
        request.config.cache.set("example/value", val)
    return val

def test_function(mydata):
    assert mydata == 23

如果你是第一次運行此命令,則可以看到print語句:

$ pytest -q
F                                                                    [100%]
================================= FAILURES =================================
______________________________ test_function _______________________________

mydata = 42

 def test_function(mydata):
>       assert mydata == 23
E       assert 42 == 23

test_caching.py:17: AssertionError
-------------------------- Captured stdout setup ---------------------------
running expensive computation...
1 failed in 0.12 seconds

如果再次運行它,將從緩存中檢索該值,并且不會打印任何內容:

$ pytest -q
F                                                                    [100%]
================================= FAILURES =================================
______________________________ test_function _______________________________

mydata = 42

 def test_function(mydata):
>       assert mydata == 23
E       assert 42 == 23

test_caching.py:17: AssertionError
1 failed in 0.12 seconds

有關更多詳細信息,請參閱config.cache

檢查緩存內容

你始終可以使用--cache-show命令行選項查看緩存的內容 :

$ pytest --cache-show
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR
cachedir: $PYTHON_PREFIX/.pytest_cache
------------------------------- cache values -------------------------------
cache/lastfailed contains:
  {'test_50.py::test_num[17]': True,
   'test_50.py::test_num[25]': True,
   'test_assert1.py::test_function': True,
   'test_assert2.py::test_set_comparison': True,
   'test_caching.py::test_function': True,
   'test_foocompare.py::test_compare': True}
cache/nodeids contains:
  ['test_caching.py::test_function']
cache/stepwise contains:
  []
example/value contains:
  42

======================= no tests ran in 0.12 seconds =======================

清除緩存內容

你可以通過添加如下--cache-clear選項來指示pytest清除所有緩存文件和值:

pytest --cache-clear

對于Continuous Integration服務器的調用,建議使用此選項,其中隔離和正確性比速度更重要。

逐步修復失敗用例

作為替代方案,尤其是對于你希望測試套件的大部分都會失敗的情況,允許你一次修復一個。測試套件將運行直到第一次失敗然后停止。在下次調用時,測試將從上次失敗測試繼續,然后運行直到下一次失敗測試。你可以使用該選項忽略一個失敗的測試,并在第二個失敗的測試中停止測試執行。如果你遇到失敗的測試而只是想稍后忽略它,這將非常有用。--lf -x``--sw``--stepwise``--stepwise-skip

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

推薦閱讀更多精彩內容