使用 Pytest 和 Hypothesis 實現快速失敗測試

使用 Pytest 和 Hypothesis 實現快速失敗測試

本文介紹如何在使用 pytest 和 Hypothesis 進行屬性測試時,在發現第一個反例后立即停止測試。通過配置 Hypothesis 的設置,我們可以創建一個 “failfast” 模式,該模式僅運行顯式測試、重用測試和生成測試階段,從而避免耗時的縮減過程,提高調試效率。

在使用 Hypothesis 進行測試時,默認情況下,它會在找到一個反例后嘗試 縮減 這個反例,以便找到一個更簡單的、更容易理解的觸發錯誤的情況。雖然這在許多情況下很有用,但在某些情況下,我們可能只想在找到第一個反例后立即停止測試,以便更快地定位和修復問題。

以下是如何使用 Pytest 和 Hypothesis 實現快速失敗測試的方法:

1. 創建一個 Hypothesis 設置 Profile

首先,我們需要創建一個自定義的 Hypothesis 設置 Profile,該 Profile 將禁用縮減階段。這可以通過在 conftest.py 文件中注冊一個新的 Profile 來實現。

from hypothesis import settings, Phase  settings.register_profile(     "failfast",     phases=[Phase.explicit, Phase.reuse, Phase.generate] )
  • settings.register_profile(“failfast”, …): 注冊一個名為 “failfast” 的 Profile。
  • phases=[Phase.explicit, Phase.reuse, Phase.generate]: 指定該 Profile 只運行顯式測試、重用測試和生成測試階段。 重要的是要排除 Phase.shrink 以避免縮減反例。

2. 使用命令行選項運行測試

接下來,我們需要使用 Pytest 的命令行選項 –hypothesis-profile 來指定我們創建的 “failfast” Profile。

pytest tests --hypothesis-profile failfast
  • pytest tests: 運行 tests 目錄下的所有測試。
  • –hypothesis-profile failfast: 使用名為 “failfast” 的 Hypothesis Profile。

示例

假設我們有以下測試代碼:

from hypothesis import given import hypothesis.strategies as st  def foo(value):     return vslue   1 # a silly typo  @given(st.integers()) def test_foo(x):     assert foo(x) == x   1

當我們運行 pytest tests –hypothesis-profile failfast 時,Hypothesis 將在找到第一個反例后立即停止測試。 這可以幫助我們快速識別代碼中的錯誤(例如,上面代碼中的拼寫錯誤)。

注意事項

  • conftest.py 文件需要位于測試目錄的根目錄或其父目錄中,以便 Pytest 能夠找到它。
  • 確保安裝了 pytest 和 hypothesis 庫。可以使用 pip install pytest hypothesis 安裝它們。
  • 如果需要全局應用此設置,可以將 profile 設置為默認值:settings.load_profile(“failfast”),但這可能會影響其他測試,因此建議僅在需要時使用命令行選項。

總結

通過使用 Hypothesis 的設置 Profile 功能,我們可以輕松地配置 Pytest 測試在發現第一個反例后立即停止。這可以顯著提高調試效率,尤其是在處理大型代碼庫或復雜測試用例時。 通過注冊一個禁用縮減階段的 Profile,我們可以避免不必要的計算,并更快地定位和修復問題。

? 版權聲明
THE END
喜歡就支持一下吧
點贊6 分享