【pytest】 在启动任务时将自定义参数传入代码中

1. 使用 pytest_addoption 钩子函数

你可以在 conftest.py 文件中使用 pytest_addoption 钩子函数来定义自定义命令行参数。然后,你可以在你的测试文件中通过 request fixture 来访问这些参数。

conftest.py

# content of conftest.py  
import pytest  
  
def pytest_addoption(parser):  
    parser.addoption(  
        "--myarg", action="store", default="default_value", help="My custom argument"  
    )  
  
@pytest.fixture  
def my_arg(request):  
    return request.config.getoption("--myarg")

test_example.py

# content of test_example.py  
def test_example(my_arg):  
    print(f"My custom argument is: {my_arg}")  
    assert my_arg != "some_bad_value"

运行测试时,你可以通过 --myarg 参数来传递你的自定义值:

pytest --myarg=my_custom_value

parser.addoption 参数说明:

  • --myarg:这是自定义选项的名称,用户将在命令行中使用这个名称来指定该选项。注意,在命令行中,选项前必须有两个破折号(--)来区分它们是长选项。

  • action="store":这个参数指定了当 pytest 解析命令行参数时,如果遇到 --myarg 选项应该如何处理。store 动作意味着 pytest 应该将 --myarg 后面的值存储起来,并使其可以在测试脚本中通过某种方式访问。如果 --myarg 后面没有值,并且 action 被设置为 store,那么将引发一个错误(除非指定了 nargs='?',它允许 --myarg 后面跟一个可选的值)。

  • default="default_value":这个参数指定了如果命令行中没有提供 --myarg 选项时,应该使用的默认值。在这个例子中,如果用户在运行 pytest 时没有指定 --myarg,那么 pytest 将认为 --myarg 的值是 "default_value"

  • help="My custom argument":这个参数提供了一个简短的描述,当用户在命令行中运行 pytest --help 时,这个描述会显示出来,帮助用户理解 --myarg 选项的用途。

posted on 2024-08-23 16:56  张凌赫_帅  阅读(112)  评论(0)    收藏  举报

导航