我必须在pytest命令中传递一个参数,该命令存储在pytest addoption中。我想在pytest parametrize函数中使用这些值。
命令:
pytest --range-from 3 --range-to 5 test.pyconftest.py
def pytest_addoption(parser):
parser.addoption("--range-from", action="store", default="default name")
parser.addoption("--range-to", action="store", default="default name")test.py
@pytest.mark.parametrize('migration_id', migration_list[range-from:range-to])
def test_sync_with_migration_list(migration_id):
migration_instance = migration.parallel(migration_id=migration_id)
migration_instance.perform_sync_only()我想使用range-from和range-to在parametrize中的值。
我不能使用这些价值观。请建议如何才能做到这一点。
发布于 2020-09-28 17:23:21
一种简单的方法是将命令行参数分配给环境变量,并在任何地方使用。我不确定您想以何种方式使用变量,所以在这里,我将简单的打印语句放在测试中。
conftest.py
def pytest_addoption(parser):
parser.addoption("--range-from", action="store", default="default name") #Let's say value is :5
parser.addoption("--range-to", action="store", default="default name") #Lets's say value is 7
def pytest_configure(config):
os.environ["range_from"]=config.getoption("range-from")
os.environ["range_to"]=config.getoption("range-to")test.py:
@pytest.mark.parametrize('migration_id', [os.getenv("range_from"),os.getenv("range_to")])
def test_sync_with_migration_list(migration_id):
print(migration_id)
Output :
5
7希望能帮上忙!!
发布于 2020-09-27 18:51:14
您不能直接从parametrize访问这些选项,因为它们在加载时不可用。相反,您可以在运行时在pytest_generate_tests中配置参数化,在那里您可以从metafunc参数访问config:
test.py
@pytest.hookimpl
def pytest_generate_tests(metafunc):
if "migration_id" in metafunc.fixturenames:
# any error handling omitted
range_from = int(metafunc.config.getoption("--range-from"))
range_to = int(metafunc.config.getoption("--range-to"))
metafunc.parametrize("migration_id",
migration_list[range_from:range_to])
def test_sync_with_migration_list(migration_id):
migration_instance = migration.parallel(migration_id=migration_id)
migration_instance.perform_sync_only()https://stackoverflow.com/questions/64091628
复制相似问题