Pytest_Hook函数pytest_addoption(parser):定义自己的命令行参数(14-1)

考虑场景:

  1. 我们的自动化用例需要支持在不同测试环境运行,有时候在dev环境运行,有时候在test环境运行;
  2. 有时候需要根据某个参数不同的参数值,执行不同的业务逻辑;

上面的场景我们都可以通过“在命令行中输入参数,然后用例中接收这个参数,通过判断这个参数的值来做不同的逻辑”来实现。那么我们的需求就变为pytest中如何自定义一个命令行参数呢?这时候我们就需要用到pytest的钩子函数:pytest_addoption

在conftest.py文件中定义命令名

新建一个conftest.py文件

然后在conftest.py文件中通过pytest_addoption方法来添加命令行参数,通过定义的fixture来获得参数的值。

import pytest


# pytest_addoption(parser) 定义自己的命令行参数的固定写法
def pytest_addoption(parser):
    # 定义 --env_opt 参数名
    parser.addoption("--env_opt")

    # 定义 --run_level 参数名
    # 参数说明:
    #   default:当命令行不调用参数时的默认值
    #   help:在帮助中显示的说明
    parser.addoption("--run_level", default=1, help="执行用例的级别", action="store")


# 获取--env_opt参数值
@pytest.fixture(scope="session")
def env_opt(request):
    return request.config.getoption("--env_opt")


# 获取--run_level参数值
@pytest.fixture(scope="session")
def run_level(request):
    return request.config.getoption("run_level")


@pytest.fixture(scope="session", autouse=True)
def start_appium_desired(env_opt, run_level):
    print(f"
{env_opt}")
    print(f"
{run_level}")

上面conftest.py中新增了两个命令行参数:--env_opt 和 --run_level,然后定义了两个fixture,在测试用例中想要获得参数 --env_opt 和 --run_level 的值,就可以调用 env_opt 或 run_level 函数获取对应的值。

在用例中获取定义命令的值

class TestDemo:

    def test_001(self, env_opt):
        print(f"
env_opt参数值:{env_opt}")

    def test_002(self, run_level):
        print(f"
run_level参数值:{run_level}")

调用定义的命令

import pytest
import os

if __name__ == '__main__':
    env = {
        "host": "127.0.0.1",
        "port": "6789"
        }

    pytest.main(["-vs", "--alluredir=./temp", f"--env_opt={env}"])
    os.system("allure generate ./temp -o ./report/ --clean")

执行结果

原文地址:https://www.cnblogs.com/testlearn/p/14818699.html