考虑场景:
- 我们的自动化用例需要支持在不同测试环境运行,有时候在dev环境运行,有时候在test环境运行;
- 有时候需要根据某个参数不同的参数值,执行不同的业务逻辑;
上面的场景我们都可以通过“在命令行中输入参数,然后用例中接收这个参数,通过判断这个参数的值来做不同的逻辑”来实现。那么我们的需求就变为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"\n{env_opt}")
    print(f"\n{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"\nenv_opt参数值:{env_opt}")
    def test_002(self, run_level):
        print(f"\nrun_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")执行结果

-事必有法,然后有成- 最后祝大家早日达到测试的天花板!
以下是我收集到的比较好的学习教程资源,虽然不是什么很值钱的东西,如果你刚好需要,可以留言【777】直接拿走就好了





![[游戏开发]Unity颜色矫正无障碍方案](https://img-blog.csdnimg.cn/d22187a9b071467ea62a831c48a2a04e.png)














