Pytest - Xfail/Skip 測試



在本章中,我們將學習 Pytest 中的 Skip 和 Xfail 測試。

現在,考慮以下情況 −

  • 由於某些原因,測試在一段時間內不再相關。
  • 正在實現一個新功能,我們已經為該功能添加了測試。

在這些情況下,我們可以選擇 xfail 測試或跳過測試。

Pytest 將執行 xfail 測試,但不會將它視為已失敗或已透過的測試的一部分。即使測試失敗,也不會列印這些測試的詳細資訊(請記住,pytest 通常會列印已失敗測試的詳細資訊)。我們可使用以下標記來 xfail 測試 −

@pytest.mark.xfail

跳過測試意味著不執行該測試。我們可使用以下標記來跳過測試 −

@pytest.mark.skip

稍後,當測試變得相關時,我們可以移除這些標記。

編輯我們已經包含 xfail 和 skip 標記的 test_compare.py

import pytest
@pytest.mark.xfail
@pytest.mark.great
def test_greater():
   num = 100
   assert num > 100

@pytest.mark.xfail
@pytest.mark.great
def test_greater_equal():
   num = 100
   assert num >= 100

@pytest.mark.skip
@pytest.mark.others
def test_less():
   num = 100
   assert num < 200

使用以下命令執行測試 −

pytest test_compare.py -v

執行後,上述命令將生成以下結果 −

test_compare.py::test_greater xfail
test_compare.py::test_greater_equal XPASS
test_compare.py::test_less SKIPPED
============================ 1 skipped, 1 xfailed, 1 xpassed in 0.06 seconds
============================
廣告
© . All rights reserved.