pytests二次开发之实现pytest-hello插件实战

前言

pytest测试框架的扩展能力

如果我们需要给pytest增加额外的扩展能力,那么有三种方式。

①钩子函数

②用例装饰器

③命令行参数

④编写pytest第三方扩展插件

实战

开发pytest-hello插件

1、新建 pytest_hello 文件,代码如下:

复制代码
# -*- encoding:utf-8 -*-

from typing import Any, Optional

import pytest


def pytest_configure(config: Any) -> None:
    """
    register an additional marker
    函数pytest_configure中,添加markrs标记名 env(),获取环境名称。
    """
    config.addinivalue_line(
        "markers", "env(name): mark test to run only on named environment"
    )


def pytest_runtest_setup(item: Any) -> None:
    """
    Called to perform the setup phase for a test item.
    在函数pytest_runtest_setup()中,获取markrs中的env()的值,判断是否等于--env 参数值,如果不相等,跳过测试用例,否则执行用例。
    """
    env_names = [mark.args[0] for mark in item.iter_markers(name="env")]
    if env_names:
        if item.config.getoption("--env") not in env_names:
            pytest.skip("test requires env in {!r}".format(env_names))


@pytest.fixture(scope="function")
def hello(hello_name: str) -> str:
    """
    hello Hook function
    在钩子函数hello()中, 获取hello_name()中返回的值,并加上"hello, " 的前缀返回。
    """
    return f"hello, {hello_name}"


@pytest.fixture(scope="function")
def hello_name(pytestconfig: Any) -> Optional[str]:
    """
    hello_name Hook function
    在钩子函数hello_name()中, 通过pytestconfig 获取--hello 参数值,如果为空默认值为“虫师”,如果为一个值或多个值取第1个。
    """
    names = pytestconfig.getoption("--hello")
    if len(names) == 0:
        return "虫师"
    if len(names) == 1:
        return names[0]
    return names[0]


def pytest_addoption(parser: Any) -> None:
    """
    Add pytest option
    在函数pytest_addoption()中,增加一个命令行组Hello,并在该命令行组中添加两个参数--env和--hello。
    """
    group = parser.getgroup("hello", "Hello")
    group.addoption(
        "--env",
        action="store",
        default=[],
        help="only run tests matching the environment {name}.",
    )
    group.addoption(
        "--hello",
        action="append",
        default=["默认值"],
        help="hello {name}",
    )
复制代码

2、新建 setup.py 文件,代码如下:

复制代码
import re
import ast
import setuptools

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

_version_re = re.compile(r'__version__\s+=\s+(.*)')

with open('pytest_hello/__init__.py', 'rb') as f:
    version = str(ast.literal_eval(_version_re.search(
        f.read().decode('utf-8')).group(1)))

setuptools.setup(
    name="pytest-hello",
    version=version,
    author="bugmaster",
    author_email="fnngj@126.com",
    description="pytest hello",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/defnngj/pytest-hello",
    packages=["pytest_hello"],
    include_package_data=True,
    install_requires=[
        "pytest",
    ],
    entry_points={"pytest11": ["hello = pytest_hello.pytest_hello"]},
    classifiers=[
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "License :: OSI Approved :: Apache Software License",
        "Operating System :: OS Independent",
        "Framework :: Pytest",
    ],
    python_requires=">=3.7",
    setup_requires=["setuptools_scm"],
)
复制代码

3、安装

①GitHub下载安装

git clone https://github.com/defnngj/pytest-hello
cd pytest-hello
python setup.py install

②pip在线安装

pip install -U https://github.com/defnngj/pytest-hello.git@master

4、帮助

> pytest --help
...

Hello:
  --env=ENV             only run tests matching the environment {name}.
  --hello=HELLO         hello {name}

5、用法

新建 test_sample.py 文件,代码如下:

import pytest


@pytest.mark.env("test")
def test_case(hello): # 调用
    print("hello:", hello)
    assert "hello" in hello

6、运行测试用例(pytest命令行方式)

①不设置 --env 参数或设置 --env 参数非test,跳过测试用例

pytest -vs test_sample.py --env=dev

运行结果:

collected 1 item
test_sample.py::test_case SKIPPED (test requires env in ['test'])

②设置 --env 参数值为test,同时未设置 --hello 参数,则 --hello 参数值的默认值为虫师

pytest -vs test_sample.py --env=test

运行结果:

collected 1 item

test_sample.py::test_case hello: hello, 虫师
PASSED

③设置 --env 的参数值为test,同时设置 --hello 参数值为jack

pytest -vs test_sample.py --env=test --hello=jack

运行结果:

collected 1 item

test_sample.py::test_case hello: hello, jack
PASSED

 

参考GitHub代码地址:https://github.com/defnngj/pytest-hello

posted @   习久性成  阅读(534)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示