首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pytest -如何传递pytest加载项值来进行pytest参数化?

pytest -如何传递pytest加载项值来进行pytest参数化?
EN

Stack Overflow用户
提问于 2020-09-27 17:58:46
回答 2查看 1.7K关注 0票数 2

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

命令:

代码语言:javascript
复制
pytest --range-from 3 --range-to 5 test.py

conftest.py

代码语言:javascript
复制
def pytest_addoption(parser):
    parser.addoption("--range-from", action="store", default="default name")
    parser.addoption("--range-to", action="store", default="default name")

test.py

代码语言:javascript
复制
@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-fromrange-toparametrize中的值。

我不能使用这些价值观。请建议如何才能做到这一点。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-09-28 17:23:21

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

conftest.py

代码语言:javascript
复制
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:

代码语言:javascript
复制
@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

希望能帮上忙!!

票数 2
EN

Stack Overflow用户

发布于 2020-09-27 18:51:14

您不能直接从parametrize访问这些选项,因为它们在加载时不可用。相反,您可以在运行时在pytest_generate_tests中配置参数化,在那里您可以从metafunc参数访问config

test.py

代码语言:javascript
复制
@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()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64091628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档