Skip to content

修正 pytest 設定檔的 DeprecationWarning 錯誤

從你提供的錯誤訊息來看,pytest 的設定檔語法已經改變。過去使用 [pytest] 區段的 setup.cfg 檔案,現在需要改用 [tool:pytest] 區段。我會根據這個資訊更新說明。

錯誤訊息分析

錯誤訊息指出:

Failed: [pytest] section in setup.cfg files is no longer supported, change to [tool:pytest] instead.

這表示,如果你在 setup.cfg 檔案中設定 pytest,原本的寫法是:

[pytest] filterwarnings = ignore:.*ast\.Str is deprecated.*:DeprecationWarning

現在你需要改成:

[tool:pytest] filterwarnings = ignore:.*ast\.Str is deprecated.*:DeprecationWarning

修正後的解決方案

因此,如果你想要忽略 pytestDeprecationWarning,你需要將設定放在 [tool:pytest] 區段中。

以下是完整的說明:

你遇到的 DeprecationWarningpytest 內部的問題,不會影響你的測試結果。你可以選擇忽略這些警告訊息,或者更新到最新版本的 pytest

  1. 忽略這些警告訊息:
    • 這是最簡單的方式。你可以在 pytest 的設定檔 (setup.cfg) 中,使用 filterwarnings 設定來忽略這些警告訊息。

    • 請注意,設定檔的區段名稱需要是 [tool:pytest],而不是 [pytest]

    • 在你提供的錯誤訊息中,已經告訴你該怎麼做:

      [tool:pytest] filterwarnings = ignore:.*ast\.Str is deprecated.*:DeprecationWarning

    • 把這段設定加到你的 setup.cfg 檔案中,就可以忽略所有包含 "ast.Str is deprecated" 的 DeprecationWarning 了。

      • ignore: 這表示我們要忽略符合後面規則的警告。
      • .*ast\.Str is deprecated.*: 這是一個正規表示式,用來匹配警告訊息的內容。
        • .: 在正規表示式中,. 是一個特殊字元,表示匹配任何單一字元 (除了換行符號)。
        • *: * 也是一個特殊字元,表示匹配前面的字元零次或多次。
        • \.: 因為 . 在正規表示式中有特殊意義,所以如果你想要匹配真正的點字元 .,你需要使用反斜線 \ 來跳脫 (escape) 它。\. 就表示匹配一個實際的點。
        • ast\.Str is deprecated: 這部分匹配字串 "ast.Str is deprecated"。
        • 整個正規表示式 .*ast\.Str is deprecated.* 的意思是:匹配任何包含 "ast.Str is deprecated" 這個字串的內容。
      • :DeprecationWarning: 這表示我們要忽略的警告類型是 DeprecationWarning
  2. 更新 pytest 版本:
    • 升級到最新版本的 pytestpytest 的開發者可能會在未來的版本中,修復這個問題,改用 ast.Constant

    • 你可以使用 pip 來更新 pytest

      pip install -U pytest

    • 升級前,建議你先看一下 pytest 的 release notes,確認是否有其他相容性問題。

  3. 保持現狀:
    • 如果你覺得這些警告訊息很煩,但又不想花時間去設定 filterwarnings,你可以選擇忽略它們。
    • 反正這些警告訊息不會影響你的測試結果,你可以等到 pytest 的開發者修復這個問題後,再更新 pytest

你的測試方式是否需要調整?

你的測試方式本身應該不需要調整。這些警告訊息與你的測試程式碼無關,而是 pytest 內部的問題。你只要確定你的測試程式碼是正確的,並且你的測試能夠正確地驗證你的程式碼行為,那就沒問題了。

總結

你遇到的 DeprecationWarningpytest 內部的問題,不會影響你的測試結果。你可以選擇忽略這些警告訊息,或者更新到最新版本的 pytest如果你選擇忽略,請確保將 filterwarnings 設定放在 setup.cfg 檔案的 [tool:pytest] 區段中。 你的測試方式本身不需要調整。