简体   繁体   English

pytest的addoptions和动态参数化测试装置的问题

[英]Problems with pytest's addoptions and dynamically parametrizing test fixtures

I am using pytest to do software testing lately but am coming across a problem when dynamically parameterizing test fixtures. 我最近使用pytest进行软件测试,但是在动态参数化测试装置时遇到了一个问题。 When testing, I would like to be able to provide the option to: 在测试时,我希望能够提供以下选项:

A) Test a specific file by specifying its file name A)通过指定文件名来测试特定文件

B) Test all files in the installed root directory B)测试安装的根目录中的所有文件

Below is my current conftest.py. 以下是我当前的conftest.py。 What I want it to do is if you choose option A (--file_name), create a parameterized test fixture using the file name specified. 我想要做的是,如果选择选项A(--file_name),则使用指定的文件名创建一个参数化的测试治具。 If you choose option B (--all_files), provide a list of all the files as a parameterized test fixture. 如果选择选项B(--all_files),请提供所有文件的列表作为参数化测试夹具。

import os
import pytest

def pytest_addoption(parser):
    parser.addoption("--file_name", action="store", default=[], help="Specify file-under-test")
    parser.addoption("--all_files", action="store_true", help="Option to test all files root directory")

@pytest.fixture(scope='module')
def file_name(request):
    return request.config.getoption('--file_name')

def pytest_generate_tests(metafunc):
    if 'file_name' in metafunc.fixturenames:
        if metafunc.config.option.all_files:
            all_files = list_all_files()
        else:
            all_files = "?"
        metafunc.parametrize("file_name", all_files)


def list_all_files():
    root_directory = '/opt/'
    if os.listdir(root_directory):
        # files have .cool extension that need to be split out
        return [name.split(".cool")[0] for name in os.listdir(root_directory)
                if os.path.isdir(os.path.join(root_directory, name))]
    else:
        print "No .cool files found in {}".format(root_directory)

The more I fiddle with this, I only can get one of the options working but not the other...what do I need to do to get both options (and possibly more) dynamically create parametrized test fixtures? 我越摆弄这个,我只能使其中一个选项起作用,而不能使另一个选项起作用。我需要怎么做才能使两个选项(可能还有更多)动态创建参数化的测试夹具?

Are you looking for something like this? 您是否正在寻找这样的东西?

def pytest_generate_tests(metafunc):
    if 'file_name' in metafunc.fixturenames:
        files = []
        if metafunc.config.option.all_files:
            files = list_all_files()
        fn = metafunc.config.option.file_name
        if fn:
            files.append(fn)
        metafunc.parametrize('file_name', all_files, scope='module')

No need to define file_name function. 无需定义file_name函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM