1. 程式人生 > 其它 >Python測試框架pytest(10)Hooks函式 - pytest_collection_modifyitems改變順序

Python測試框架pytest(10)Hooks函式 - pytest_collection_modifyitems改變順序

pytest 預設執行用例是根據專案下的資料夾名稱按 ascii 碼去收集的,module 裡面的用例是從上往下執行的。

pytest_collection_modifyitems 這個鉤子函式就是改變用例的執行順序。

pytest_collection_modifyitems 是在用例收集完畢之後被呼叫,可以用來調整測試用例執行順序,它有三個引數,分別是:

  • session:會話物件。

  • config:配置物件。

  • items:用例物件列表。

這三個引數分別有不同的作用,都可以拿來單獨使用,修改用例執行順序主要是使用 items 引數。

鉤子函式 pytest_collection_modifyitems 原始碼:

建立專案與檔案,a包下建立test_a.py測試用例,b包下建立test_b.py測試用例。

目錄結構:

示例一:pytest 預設執行順序

conftest.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

import pytest

def pytest_collection_modifyitems(session, items):
    print("收集到的測試用例:%s" %items)

test_a.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*- """ 微信公眾號:AllTests軟體測試 """ def test_a_1(): print("測試用例test_a_1") def test_a_2(): print("測試用例test_a_2")

test_b.py檔案

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""

def test_b_2():
    print("測試用例test_b_2")

def test_b_1():
    print("
測試用例test_b_1")

開啟命令列,輸入執行命令

pytest -s

執行結果:

收集到的測試用例,會在測試用例執行之前完成。

從結果可以看出執行的時候先按模組名稱ascii碼去收集,單個py檔案裡面的用例按從上到下寫的順序收集。

[<Function test_a_1>, <Function test_a_2>, <Function test_b_2>, <Function test_b_1>]

示例二:items 用例排序

將測試用例名稱也按ascii碼進行排序,修改conftest.py檔案。

指令碼程式碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公眾號:AllTests軟體測試
"""
import pytest

def pytest_collection_modifyitems(session, items):
    print(type(items))
    print("收集到的測試用例:%s" % items)
    # sort排序,根據用例名稱item.name 排序
    items.sort(key=lambda x: x.name)
    print("排序後的測試用例:%s" % items)
    for item in items:
        print("測試用例:%s" % item.name)

開啟命令列,輸入執行命令

pytest -s

執行結果:

重新排序後就可以按照測試用例的名稱順序執行了。

本文來自部落格園,作者:AllTests軟體測試,轉載請註明原文連結:https://www.cnblogs.com/alltests/p/15429810.html