pytest之【mark標記功能】使用實例以及使用原理(pytest鈎子函數之pytest_configure)


前言

①使用 @pytest.mark.標簽名 裝飾器可以將測試用例分類。

②pytest測試框架中的內置mark標簽

@pytest.mark.skip()  跳過用例
@pytest.mark.skipif()  滿足條件跳過用例
@pytest.mark.parametrize()  實現參數化
@pytest.mark.usefixture()  使用fixture的函數
@pytest.mark.xfail()  標記失敗

③終端以命令行方式運行測試用例或者通過python模塊中的main函數運行測試用例,例如:

 pytest test_1.py -s -m='p0'  #  只運行p0用例
 pytest test_1.py -s -m='p0 or p1'  #  運行p0和p1用例
 pytest test_1.py -s -m='not p0'  #  只運行非p0用例
if __name__ == '__main__':
    pytest.main(['-s', 'test_1.py',"-m=not runtest"])

其中:

運行的時候使用 -m 參數;m是mark的意思,來運行某個或某個分類的測試用例;

 -m 參數同樣支持python表達式:用or實現多選的效果;用not實現反選的效果。

使用方法

1、注冊標簽名

2、在測試用例/測試類前面加上: @pytest.mark.標簽名 ;打標記范圍:【測試用例,測試類,測試模塊】

3、用例執行

注冊方式:將自定義標簽名注冊到pytest測試框架中,pytest可以識別出注冊后的標簽名然后進行相應操作

1、單個標簽

在conftest.py添加如下代碼:

def pytest_configure(config):
# demo是標簽名 config.addinivalue_line("markers", "demo:示例運行")

2、多個標簽

在conftest.py添加如下代碼:

def pytest_configure(config):

  marker_list = ["testdemo", "demo", "smoke"] # 標簽名集合
  for markers in marker_list:
    config.addinivalue_line("markers", markers)

或者:

import pytest
def pytest_configure(config):

   config.addinivalue_line("markers", "slow:this one of slow test")
   config.addinivalue_line("markers", "fast:this one of fast test")

3、添加pytest.ini 配置文件

參照:pytest之配置文件pytest.ini

[pytest]
markers=
  smoke:this is a smoke tag
  demo:demo
  testdemo:testdemo

用例執行

test_demo.py

import pytest


@pytest.mark.testdemo
def test_demo01():
  print("函數級別的test_demo01")


@pytest.mark.smoke
def test_demo02():
  print("函數級別的test_demo02")


@pytest.mark.demo
class TestDemo:
  def test_demo01(self):
    print("test_demo01")

  def test_demo02(self):
    print("test_demo02")

1、命令行方式

pytest命令行運行方式如下:

通過標記表達式執行
pytest -m demo
這條命令會執行被裝飾器@pytest.mark.demo裝飾的所有測試用例

生成html報告:
pytest -m demo --html=Report/report.html

生成xml報告:
pytest -m demo --junitxml=Report/report.xml

運行指定模塊:
pytest -m demo --html=Report/report.html TestCases/test_pytest.py

運行指定測試目錄
pytest -m demo --html=Report/report.html TestCases/

通過節點id來運行:
pytest TestCases/test_pytest.py::TestDemo::test_demo01

通過關鍵字表達式過濾執行
pytest -k "MyClass and not method"
這條命令會匹配文件名、類名、方法名匹配表達式的用例

獲取用例執行性能數據
獲取最慢的10個用例的執行耗時
pytest --durations=10

2、新建run.py文件運行

代碼如下:

pytest.main(["-m","demo","--html=Report/report.html"])

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM