本文為霍格沃茲測試開發學社學員筆記分享
原文連結:pytest Mark标記、Skip跳過、xFail預期失敗 L2 - 學習筆記 - 測試人社群
1、使用 Mark 标記測試用例
Mark:标記測試用例
- 場景:隻執行符合要求的某一部分用例 可以把一個web項目劃分多個子產品,然後指定子產品名稱執行。
- 解決: 在測試用例方法上加 @pytest.mark.标簽名
- 執行: -m 執行自定義标記的相關用例
- pytest -s test_mark_zi_09.py -m=webtest pytest -s test_mark_zi_09.py -m apptest pytest -s test_mark_zi_09.py -m "not ios"
import pytest
def double(a):
return a * 2
# 測試資料:整型
@pytest.mark.int
def test_double_int():
print("test double int")
assert 2 == double(1)
# 測試資料:負數
@pytest.mark.minus
def test_double1_minus():
print("test double minus")
assert -2 == double(-1)
# 測試資料:浮點數
@pytest.mark.float
def test_double_float():
assert 0.2 == double(0.1)
@pytest.mark.float
def test_double2_minus():
assert -0.2 == double(-0.1)
@pytest.mark.zero
def test_double_0():
assert 0 == double(0)
@pytest.mark.bignum
def test_double_bignum():
assert 200 == double(100)
@pytest.mark.str
def test_double_str():
assert 'aa' == double('a')
@pytest.mark.str
def test_double_str1():
assert 'a$a#39; == double('a#39;)
複制代碼
警告解決辦法
2、pytest 設定跳過、預期失敗
Mark:跳過(Skip)及預期失敗(xFail)
- 這是 pytest 的内置标簽,可以處理一些特殊的測試用例,不能成功的測試用例
- skip - 始終跳過該測試用例
- skipif - 遇到特定情況跳過該測試用例
- xfail - 遇到特定情況,産生一個“期望失敗”輸出
Skip 使用場景
- 調試時不想運作這個用例
- 标記無法在某些平台上運作的測試功能
- 在某些版本中執行,其他版本中跳過
- 比如:目前的外部資源不可用時跳過
- 如果測試資料是從資料庫中取到的,
- 連接配接資料庫的功能如果傳回結果未成功就跳過,因為執行也都報錯
- 解決 1:添加裝飾器
- @pytest.mark.skip
- @pytest.mark.skipif
- 解決 2:代碼中添加跳過代碼
- pytest.skip(reason)
import pytest
@pytest.mark.skip
def test_aaa():
print("代碼未開發完")
assert True
@pytest.mark.skip(reason="存在bug")
def test_bbb():
assert False
import pytest
## 代碼中添加 跳過代碼塊 pytest.skip(reason="")
def check_login():
return False
def test_function():
print("start")
# 如果未登入,則跳過後續步驟
if not check_login():
pytest.skip("unsupported configuration")
print("end")
複制代碼
import sys
import pytest
print(sys.platform)
# 給一個條件,如果條件為true,就會被跳過
@pytest.mark.skipif(sys.platform == 'darwin', reason="does not run on mac")
def test_case1():
assert True
@pytest.mark.skipif(sys.platform == 'win', reason="does not run on windows")
def test_case2():
assert True
@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires python3.6 or higher")
def test_case3():
assert True
複制代碼
xfail 使用場景
- 與 skip 類似 ,預期結果為 fail ,标記用例為 fail
- 用法:添加裝飾器@pytest.mark.xfail
import pytest
# 代碼中标記xfail後,下部分代碼就不惠繼續執行了
def test_xfail():
print("*****開始測試*****")
pytest.xfail(reason='該功能尚未完成')
print("測試過程")
assert 1 == 1
# xfail标記的測試用例還是會被執行的,fial了,标記為XFAIL,通過了标記為XPASS,起到提示的作用
@pytest.mark.xfail
def test_aaa():
print("test_xfail1 方法執行")
assert 1 == 2
xfail = pytest.mark.xfail
@xfail(reason="bug 110")
def test_hello4():
assert 0