Skip to content

Instantly share code, notes, and snippets.

@lenosi
Last active October 7, 2017 17:40
Show Gist options
  • Save lenosi/6c4f658b19e2482a6e91366045786905 to your computer and use it in GitHub Desktop.
Save lenosi/6c4f658b19e2482a6e91366045786905 to your computer and use it in GitHub Desktop.
pytest: Parametrize fixtures with multiple items from addoption/commandline

py.test parametrize fixtures by addoption

run

pytest test_parametrize.py --database A --database=B --verbose

========== test session starts ===========
platform linux -- Python 3.6.2, pytest-3.2.2, py-1.4.34, pluggy-0.4.0 -- /tmp/envs/py3/bin/python
cachedir: .cache
rootdir: /tmp/test, inifile:
plugins: logger-0.2.1
collected 2 items                                                                 

test_backend.py::test_db_initialized[A] PASSED
test_backend.py::test_db_initialized[B] PASSED

======== 2 passed in 0.01 seconds ========
import pytest
def pytest_addoption(parser):
parser.addoption("--database", action="append", default=[], help="Choice of database")
def pytest_generate_tests(metafunc):
if 'database' in metafunc.fixturenames:
databases = list(metafunc.config.option.database)
metafunc.parametrize('database', databases, indirect=True)
class DatabaseA(object):
name = 'Database A'
class DatabaseB(object):
name = 'Database B'
@pytest.fixture
def database(request):
if request.param == "A":
return DatabaseA()
elif request.param == "B":
return DatabaseB()
import pytest
def test_parametrize(database):
if database.__class__.__name__ == 'DatabaseA':
assert database.name == "Database A"
else:
assert database.name == "Database B"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment