1. 程式人生 > 實用技巧 >Pytest系列(8) - 使用自定義標記mark

Pytest系列(8) - 使用自定義標記mark

一、前言

  • pytest 可以支援自定義標記,自定義標記可以把一個 web 專案劃分多個模組,然後指定模組名稱執行
  • 譬如我可以標明哪些用例是window下執行的,哪些用例是mac下執行的,在執行程式碼時候指定mark即可

二、實際程式碼

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pytest


@pytest.mark.weibo
def test_weibo():
    print("測試微博")


@pytest.mark.toutiao
def test_toutiao():
    print("測試頭條")


@pytest.mark.toutiao
def test_toutiao1():
    print("再次測試頭條")


@pytest.mark.xinlang
class TestClass:
    def test_method(self):
        print("測試新浪")


def testnoMark():
    print("沒有標記測試")

2.1 cmd敲執行命令

pytest -s -m weibo 08_mark.py

2.2 執行結果

2.3 如何避免 warnings

  • 建立一個pytest.ini檔案(後續詳解)
  • 加上自定義mark,如下圖
  • 注意:pytest.ini需要和執行的測試用例同一個目錄,或在根目錄下作用於全域性
[pytest]
markers =
    weibo: this is weibo page
    toutiao: this is toutiao page
    xinlang: this is xinlang page

​ 或者

def pytest_configure(config):
    marker_list = ["weibo","toutiao","xinlang"]
    for markers in marker_list:
        config.addinivalue_line("markers",markers)

2.4 如果不想標記 weibo 的用例,not

pytest -s -m "not weibo" 08_mark.py

2.5 如果想執行多個自定義標記的用例,or

pytest -s -m "toutiao or weibo" 08_mark.py