七群发、Pytest插件開發(fā)

目錄

  • 插件的加載方式
  • 什么是hook
  • Pytest有哪些hook函數(shù)
  • 如何改寫hook函數(shù)
  • 實戰(zhàn)打包晰韵、發(fā)布

Pytest插件加載方式

  • 外部插件: pip install安裝的插件
  • 本地插件:pytest自動模塊發(fā)現(xiàn)機制(conftest.py存放的)
  • 內(nèi)置插件:代碼內(nèi)部的_pytest目錄加載
    • 內(nèi)置插件位置:External Libraries-> site-packages-> _pytest-> hookspec.py
      image.png

什么是hook

  • 把大象裝冰箱 ,總共分幾步
    1. 打開冰箱門
    2. 把大象裝進(jìn)冰箱
    3. 關(guān)閉冰箱門
  • 將以上幾步封裝成函數(shù)


    image.png
  • 如果想在“打開冰箱門”前面加一個“把燈打開”熟妓,再“把大象裝進(jìn)冰箱前”“拿出一些零食”,就要重新改變代碼
  • hook就是將可能發(fā)生的接口/功能/操作預(yù)留出來栏尚,當(dāng)想進(jìn)行這些接口/功能/操作時加入到對應(yīng)位置即可起愈,即按照流程規(guī)范運行。
    image.png

Pytest插件

1译仗、site-package/_pytest/hookspec.py
2抬虽、https://docs.pytest.org/en/latest/_modules/_pytest/hookspec.html

實戰(zhàn)一:編寫自己的插件——編碼

  • pytest_collection_modifyitems 收集上來的測試用例實現(xiàn)定制化功能
  • 解決問題:
    • 自定義用例的執(zhí)行順序
    • 解決編碼問題(中文的測試用例名稱)
    • 自動添加標(biāo)簽
  • 含有中文的測試用例名稱,改寫編碼格式:
  • item.name = item.name.encode('utf-8').decode('unicode-escape'):其中name為測試用例的名字
  • item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape'):其中nodeid為測試用例的路徑
  • _pytest / nodes.py
  1. test_chinese.py 代碼如下
import pytest

@pytest.mark.parametrize('name', ['哈利','赫敏'])
def test_chinese(name):
    print(name)
  • 運行結(jié)果:其中的用例名沒有用中文顯示,編碼格式為Unicode纵菌,不支持中文阐污。需要考慮修改測試用例名字和測試用例路徑的編碼格式
============================= test session starts =============================
rootdir: D:\Programs\DevOps\Python_Practice\Exercises\pytest_plugins
plugins: allure-pytest-2.8.40
collecting ... collected 2 items

test_chinese.py::test_chinese[\u54c8\u5229] 
test_chinese.py::test_chinese[\u8d6b\u654f] 

============================== 2 passed in 0.03s ==============================

Process finished with exit code 0
PASSED                       [ 50%]哈利
PASSED                       [100%]赫敏
  • 修改pytest插件
    1. 在當(dāng)前目錄下新建文件conftest.py
    2. 打開External Libraries-> site-packages-> _pytest-> hookspec.py文件,找到pytest_collection_modifyitems 方法
    def pytest_collection_modifyitems(session: "Session", config: "Config", 
            items: List["Item"] ) -> None:
        """Called after collection has been performed. May filter or re-order
        the items in-place.
    
        :param pytest.Session session: The pytest session object.
        :param _pytest.config.Config config: The pytest config object.
        :param List[pytest.Item] items: List of item objects.
        """
    
    1. 將方法復(fù)制到 conftest.py 文件下進(jìn)行改寫
    def pytest_collection_modifyitems(ession, config, items):
     for item in items:
         item.name = item.name.encode('utf-8').decode('unicode-escape')
         item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')
    
    1. 再次執(zhí)行test_chinese.py 結(jié)果如下:發(fā)現(xiàn)用例名改為了中文
rootdir: D:\Programs\DevOps\Python_Practice\Exercises\pytest_plugins
plugins: allure-pytest-2.8.40
collecting ... collected 2 items

test_chinese.py::test_chinese[哈利] PASSED                               [ 50%]哈利

test_chinese.py::test_chinese[赫敏] PASSED                               [100%]赫敏


============================== 2 passed in 0.02s ==============================

Process finished with exit code 0

實戰(zhàn)二:倒序執(zhí)行用例

  • 由于def pytest_collection_modifyitems(session, config, items:List): 中items為用例列表咱圆,所以可以對其進(jìn)行列表的方法笛辟,比如.reverse()進(jìn)行倒序執(zhí)行
  • conftest.py文件中加入items.reverse()
from typing import List

def pytest_collection_modifyitems(session, config, items:List):
    # 修改編碼
    for item in items:
        item.name = item.name.encode('utf-8').decode('unicode-escape')
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')

    # 修改用例執(zhí)行順序,其中 items 就是所有用例列表
    items.reverse()  # 倒序執(zhí)行
  • 再次執(zhí)行test_chinese.py 結(jié)果如下:發(fā)現(xiàn)用例執(zhí)行順序改變
rootdir: D:\Programs\DevOps\Python_Practice\Exercises\pytest_plugins
plugins: allure-pytest-2.8.40
collecting ... collected 2 items

test_chinese.py::test_chinese[赫敏] PASSED                               [ 50%]赫敏

test_chinese.py::test_chinese[哈利] PASSED                               [100%]哈利


============================== 2 passed in 0.02s ==============================

Process finished with exit code 0

實戰(zhàn)三:只執(zhí)行打了標(biāo)簽的測試用例

  • 測試代碼如下序苏,其中有兩條用例名包含login
import pytest

@pytest.mark.parametrize('name', ['哈利','赫敏'])
def test_chinese(name):
    print(name)

def test_login():
    print("login")

def test_login_fail():
    print("login fail")
    assert False

def test_search():
    print("search")
  • 修改conftest.py 文件手幢,給login打上標(biāo)簽
from typing import List
import pytest

def pytest_collection_modifyitems(session, config, items:List):
    # 修改編碼
    for item in items:
        item.name = item.name.encode('utf-8').decode('unicode-escape')
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')

        # 如果login在測試用例路徑中,則對其打標(biāo)簽
        if "login" in item.nodeid:
            item.add_marker(pytest.mark.login)

    # 修改用例執(zhí)行順序忱详,其中 items 就是所有用例列表
    items.reverse()  # 倒序執(zhí)行
  • 在Terminal中執(zhí)行pytest -m login -vs 其中-m 為運行指定標(biāo)簽的用例围来,后面跟上標(biāo)簽名,-v為打印詳細(xì)信息匈睁,-s用于顯示測試函數(shù)中print()函數(shù)輸出监透。執(zhí)行結(jié)果如下,可以看到只執(zhí)行了login標(biāo)簽的用例
(venv) D:\Programs\DevOps\Python_Practice\Exercises\pytest_plugins>pytest -m login -vs
============================================================================================= test session starts =============================================================================================
platform win32 -- Python 3.8.5, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 -- d:\programs\devops\python_practice\venv\scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\Programs\DevOps\Python_Practice\Exercises\pytest_plugins
plugins: allure-pytest-2.8.40
collected 5 items / 3 deselected / 2 selected                                                                                                                                                                  

test_chinese.py::test_login_fail login fail
FAILED
test_chinese.py::test_login login
PASSED

================================================================================================== FAILURES ===================================================================================================
_______________________________________________________________________________________________ test_login_fail _______________________________________________________________________________________________

    def test_login_fail():
        print("login fail")
>       assert False
E       assert False

test_chinese.py:17: AssertionError
============================================================================================== warnings summary ===============================================================================================
conftest.py:17
  D:\Programs\DevOps\Python_Practice\Exercises\pytest_plugins\conftest.py:17: PytestUnknownMarkWarning: Unknown pytest.mark.login - is this a typo?  You can register custom marks to avoid this warning - for d
etails, see https://docs.pytest.org/en/stable/mark.html
    item.add_marker(pytest.mark.login)

-- Docs: https://docs.pytest.org/en/stable/warnings.html
=========================================================================================== short test summary info ===========================================================================================
FAILED test_chinese.py::test_login_fail - assert False
============================================================================ 1 failed, 1 passed, 3 deselected, 1 warning in 0.23s =============================================================================

實戰(zhàn)四:添加命令行參數(shù)

def pytest_addoption(parser):
  mygroup = parser.getgroup("hogwarts") #group將下面所有的option都展示在這個group下航唆。
  mygroup.addoption("--env",            #注冊一個命令行選項
                    default='test',     #參數(shù)的默認(rèn)值
                    dest='env'          ,#存儲的變量
                    help='set your run env' #幫助提示參數(shù)的描述信息
                    )
  • 如何針對傳入的不同參數(shù)完成不同的邏輯處理?創(chuàng)建一fixture
@pytest.fixture(scope='session')
def cmdoption(request):
  return request.config.getoption("--env", default='test')
  • 在terminal中執(zhí)行pytest --help就能發(fā)現(xiàn)自定義的命令行參數(shù):
    image.png
  • 如果要獲取addoption中定義的命令行參數(shù)胀蛮,可以在conftest.py中定義fixture如下:
# 定義fixture從而獲取addoption里面函數(shù)
@pytest.fixture(scope='session')
def cmdoption(request):
    env = request.config.getoption("--env", default='test')
    if env == 'test':
        print("這是測試環(huán)境")
    elif env == 'dev':
        print("這是開發(fā)環(huán)境")
  • 新建一個測試用例如下,將在conftest中定義的fixture函數(shù)名傳過來
# 將在conftest中定義的fixture函數(shù)傳過來
def test_env(cmdoption):
    print(cmdoption)
  • 執(zhí)行結(jié)果如下:
test_chinese.py::test_env 這是測試環(huán)境
PASSED                                         [100%]test


============================== 1 passed in 0.04s ==============================

Process finished with exit code 0
  • 如果要修改環(huán)境為開發(fā)環(huán)境佛点,則在Terminal中執(zhí)行pytest --env dev test_chinese.py::test_env -vs醇滥,執(zhí)行結(jié)果如下:
rootdir: D:\Programs\DevOps\Python_Practice\Exercises\pytest_plugins
plugins: allure-pytest-2.8.40
collected 1 item                                                                                                                                                                                               

test_chinese.py::test_env 這是開發(fā)環(huán)境
dev
PASSED

實戰(zhàn)五:獲取環(huán)境數(shù)據(jù)

  • 添加環(huán)境數(shù)據(jù)


    image.png
    • 其中dev下的datas.yaml內(nèi)容如下:
env:
 host: https://www.baidu.com
 port: 443
  • 其中test下的datas.yaml內(nèi)容如下:
env:
 host: http://www.baidu.com
 port: 80
  • 修改conftest.py文件如下:主要修改cmdoption函數(shù)
from typing import List
import pytest
import yaml


def pytest_collection_modifyitems(session, config, items:List):
    # 修改編碼
    for item in items:
        item.name = item.name.encode('utf-8').decode('unicode-escape')
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')

        # 如果login在測試用例路徑中,則對其打標(biāo)簽
        if "login" in item.nodeid:
            item.add_marker(pytest.mark.login)

    # 修改用例執(zhí)行順序超营,其中 items 就是所有用例列表
    items.reverse()  # 倒序執(zhí)行

# 添加一個命令行參數(shù)
def pytest_addoption(parser):
    mygroup = parser.getgroup("hogwarts") #group將下面所有的option都展示在這個group下鸳玩。
    mygroup.addoption("--env",            #注冊一個命令行選項
                    default='test',     #參數(shù)的默認(rèn)值
                    dest='env'          ,#存儲的變量
                    help='set your run env' #幫助提示參數(shù)的描述信息
                    )

# 定義fixture從而獲取addoption里面函數(shù)
@pytest.fixture(scope='session')
def cmdoption(request):
    env = request.config.getoption("--env", default='test')

    if env == 'test':
        print("這是測試環(huán)境")
        datapath = "./datas/test/datas.yml"

    elif env == 'dev':
        print("這是開發(fā)環(huán)境")
        datapath = "./datas/dev/datas.yml"

    with open(datapath) as f:
        datas = yaml.safe_load(f)
    return env, datas
  • 修改測試用例如下:
# 將在conftest中定義的fixture函數(shù)傳過來
def test_env(cmdoption):
    env, datas = cmdoption
    print(datas)
    host = datas['env']['host']
    port = datas['env']['port']
    url = str(host) + ":" + str(port)
    print(url)
  • 測試結(jié)果:
plugins: allure-pytest-2.8.40
collected 1 item

test_chinese.py::test_env 這是開發(fā)環(huán)境
{'env': {'host': 'https://www.baidu.com', 'port': 443}}
https://www.baidu.com:443
PASSED

打包發(fā)布

  • 打包必須要有代碼和setup.py 文件
  • setup.py 是一個構(gòu)建工具


    image.png

打包需要兩個工具

  • wheel, setuptools
  • setup.py 文件
  • 目錄結(jié)構(gòu)


    image.png
  1. setup.py 文件:
from setuptools import setup
setup(
    name='pytest_encode',
    url='https://github.com/xxx/pytest-encode',
    version='1.0',
    author="loafer",
    author_email='418974188@qq.com',
    description='set your encoding and logger',
    long_description='Show Chinese for your mark.parametrize(). Define logger variable for getting your log',
    classifiers=[# 分類索引 ,pip 對所屬包的分類
        'Framework :: Pytest',
        'Programming Language :: Python',
        'Topic :: Software Development :: Testing',
        'Programming Language :: Python :: 3.8',
    ],
    license='proprietary',
    packages=['pytest_encode'],
    keywords=[
        'pytest', 'py.test', 'pytest_encode',
    ],

    # 需要安裝的依賴
    install_requires=[
        'pytest'
    ],
    # 入口模塊 或者入口函數(shù)
    entry_points={
        'pytest11': [
            'pytest-encode = pytest_encode',
        ]
    },
    zip_safe=False
)
  1. pytest_encode 中的 _init_.py 文件
from typing import List

def pytest_collection_modifyitems(session, config, items:List):
    # 修改編碼
    for item in items:
        item.name = item.name.encode('utf-8').decode('unicode-escape')
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')

    # 修改用例執(zhí)行順序演闭,其中 items 就是所有用例列表
    items.reverse()  # 倒序執(zhí)行
  1. test_encode.py 文件
import pytest

@pytest.mark.parametrize('name', ['哈利','赫敏'])
def test_chinese(name):
    print(name)
  1. 安裝wheel 工具:pip install wheel
  • 打包命令:
    python setup.py sdist bdist_wheel
  • 打包完后


    image.png
  • dist 中上面的是源碼包不跟,下面的是whl包,可以通過pip install 進(jìn)行安裝

發(fā)布

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末米碰,一起剝皮案震驚了整個濱河市窝革,隨后出現(xiàn)的幾起案子购城,更是在濱河造成了極大的恐慌,老刑警劉巖虐译,帶你破解...
    沈念sama閱讀 216,843評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瘪板,死亡現(xiàn)場離奇詭異,居然都是意外死亡漆诽,警方通過查閱死者的電腦和手機侮攀,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來厢拭,“玉大人兰英,你說我怎么就攤上這事」” “怎么了畦贸?”我有些...
    開封第一講書人閱讀 163,187評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長楞捂。 經(jīng)常有香客問我薄坏,道長,這世上最難降的妖魔是什么泡一? 我笑而不...
    開封第一講書人閱讀 58,264評論 1 292
  • 正文 為了忘掉前任颤殴,我火速辦了婚禮,結(jié)果婚禮上鼻忠,老公的妹妹穿的比我還像新娘涵但。我一直安慰自己,他們只是感情好帖蔓,可當(dāng)我...
    茶點故事閱讀 67,289評論 6 390
  • 文/花漫 我一把揭開白布矮瘟。 她就那樣靜靜地躺著,像睡著了一般塑娇。 火紅的嫁衣襯著肌膚如雪澈侠。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,231評論 1 299
  • 那天埋酬,我揣著相機與錄音哨啃,去河邊找鬼。 笑死写妥,一個胖子當(dāng)著我的面吹牛拳球,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播珍特,決...
    沈念sama閱讀 40,116評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼祝峻,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起莱找,我...
    開封第一講書人閱讀 38,945評論 0 275
  • 序言:老撾萬榮一對情侶失蹤酬姆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后奥溺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體辞色,經(jīng)...
    沈念sama閱讀 45,367評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,581評論 2 333
  • 正文 我和宋清朗相戀三年浮定,在試婚紗的時候發(fā)現(xiàn)自己被綠了淫僻。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,754評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡壶唤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出棕所,到底是詐尸還是另有隱情闸盔,我是刑警寧澤,帶...
    沈念sama閱讀 35,458評論 5 344
  • 正文 年R本政府宣布琳省,位于F島的核電站迎吵,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏针贬。R本人自食惡果不足惜击费,卻給世界環(huán)境...
    茶點故事閱讀 41,068評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望桦他。 院中可真熱鬧蔫巩,春花似錦、人聲如沸快压。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蔫劣。三九已至坪郭,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間脉幢,已是汗流浹背歪沃。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留嫌松,地道東北人沪曙。 一個月前我還...
    沈念sama閱讀 47,797評論 2 369
  • 正文 我出身青樓,卻偏偏與公主長得像豆瘫,于是被迫代替她去往敵國和親珊蟀。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,654評論 2 354

推薦閱讀更多精彩內(nèi)容