I am using pytest to do software testing lately but am coming across a problem when dynamically parameterizing test fixtures. When testing, I would like to be able to provide the option to:
A) Test a specific file by specifying its file name
B) Test all files in the installed root directory
Below is my current 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. If you choose option B (--all_files), provide a list of all the files as a parameterized test fixture.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.