本文介绍了pytest - 如何将 pytest addoption 值传递给 pytest 参数化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在我存储在 pytest addoption 中的 pytest 命令中传递一个参数.我想在 pytest parametrize 函数中使用这些值.

I have to to pass an argument in my pytest command which I am storing in pytest addoption. I want to use these values in the pytest parametrize function.

命令:

pytest --range-from 3 --range-to 5 test.py

conftest.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()

我想在parametrize中使用range-fromrange-to的值.

我无法使用这些值.请建议如何做到这一点.

I am not able to use these values. Please suggest how can this can be done.

推荐答案

一种简单的方法是将您的命令行参数分配给环境变量并在您想要的任何地方使用.我不确定您想以哪种方式使用这些变量,所以在这里我将简单的打印语句放入测试中.

One simple way is assign your command line argument to environment variable and use wherever you want. I am not sure in which manner you want to use the variables then so here i am putting simple print statement inside test.

conftest.py

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

希望能帮到你!!

这篇关于pytest - 如何将 pytest addoption 值传递给 pytest 参数化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:08