{
"$type": "site.standard.document",
"canonicalUrl": "https://rednafi.com/python/parametrized-fixtures-in-pytest/",
"description": "Create dynamic pytest fixtures with @pytest.fixture(params) to run tests with multiple configurations and parameter combinations.",
"path": "/python/parametrized-fixtures-in-pytest/",
"publishedAt": "2022-03-10T00:00:00.000Z",
"site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
"tags": [
"Python",
"Testing",
"Pytest"
],
"textContent": "While most of my pytest fixtures don't react to the dynamically-passed values of function\nparameters, there have been situations where I've definitely felt the need for that.\nConsider this example:\n\nHere, in the create_file fixture, I've created a file named foo.md in the tmp folder.\nNotice that the name of the file foo.md is hardcoded inside the body of the fixture\nfunction. The fixture yields the path of the directory and the created file.\n\nLater on, the test_file_creation function just checks whether the fixture is working as\nexpected. This snippet will pass successfully if you execute it with the pytest command.\n\nNow, if you needed to create three files - foo.md, bar.md, baz.md - how'd you do that\nin the fixture? You could hardcode the names of the three files in the fixture as follows:\n\nI had to change the name of the fixture from create_file to create_files because the\noutput signature of the fixture was changed to yield the directory path and a list of the\npaths of the three newly created files.\n\nWhile this works, it's cumbersome and inflexible. What if one of your tests needs one file\nand another one demands two files to be created? How'd you tackle that?\n\nIt'd be much better if we could just pass the filename to the fixture as a parameter and the\nfixture would then create the corresponding file in the temporary folder. Also, if we need\nn files to be created, then we'll just have to execute the fixture n times. There's a\nway to do so by leveraging fixture parameters and @pytest.mark.parameterize decorator.\nThis is how you can do it:\n\nIn this case, the fixture create_file takes an additional parameter called filename and\nthen yields the directory path and the file path; just as the first snippet. Later on, in\nthe test_file_creation function, the desired values of the filename parameter is\ninjected into the fixture via the @pytest.mark.parametrize decorator. In the above\nsnippet, pytest runs the fixture 3 times and creates the desired files in 3 passes - just\nlike how a normal function call would behave.\n\nFurther reading\n\n- [Pass a parameter to a fixture function - Stackoverflow]\n\n\n\n\n[pass a parameter to a fixture function - stackoverflow]:\n https://stackoverflow.com/questions/18011902/pass-a-parameter-to-a-fixture-function",
"title": "Parametrized fixtures in pytest"
}