在pytest中,如何使用命令行参数来修改测试参数?

时间:2019-02-19 11:06:14

标签: python testing pytest

我想在我的测试中添加一个命令行参数,该参数会影响(但不仅限于)测试参数。因此,我在conftest.py中添加了一个选项:

def pytest_addoption(parser):
    parser.addoption("--target-name", action="store")

我知道如何使固定装置取决于命令行值,但不知道如何针对测试参数进行操作

@pytest.mark.parametrize(
    "target_specific_data", json.parse(open("target-%s.json" % target_name)))
def test_foo(target_specific_data):
      ...
      ...

如何用pytest做到这一点?

1 个答案:

答案 0 :(得分:0)

Pytest将参数值视为值列表。您可以创建一个函数,该函数将在运行时返回数据并在列表中将其分配给它们,或者使函数返回自身的列表,如下所示。

conftest.py

import os

def pytest_addoption(parser):
    parser.addoption("--target-name", action="store")

def pytest_configure(config):
    if config.getoption('target-name'):
        os.environ["target-name"] = config.getoption('target-name')

测试文件

import json
import pytest
import os

def get_test_param():
    return json.parse(open("target-{}.json".format(os.getenv('target-name')))

@pytest.mark.parametrize('target_specific_data', [get_test_param()]))
def test_foo(target_specific_data):
    pass

希望这会有所帮助!