What will be the output when running this pytest test with the given parametrize and custom IDs?
import pytest @pytest.mark.parametrize("input,expected", [(2, 4), (3, 9), (4, 16)], ids=["two", "three", "four"]) def test_square(input, expected): assert input * input == expected if __name__ == "__main__": import sys import pytest sys.exit(pytest.main([__file__, "-q", "--tb=line"]))
Look at how the ids parameter affects the test report output.
Using ids in pytest.mark.parametrize replaces the default numeric IDs with custom strings. The test report shows these custom IDs next to the test count.
Given this pytest parametrize with IDs, which assertion correctly checks the test ID in a hook?
import pytest @pytest.mark.parametrize("num,expected", [(1, 1), (2, 4)], ids=["one", "two"]) def test_square(num, expected): assert num * num == expected # Hook to check test ID @pytest.hookimpl(tryfirst=True) def pytest_runtest_setup(item): # Which assertion is correct here? pass
Check how to access the test ID string from the item object.
The item.callspec.id attribute holds the string ID for the current parameter set. Using in checks if it matches any expected ID.
Why does this pytest parametrize code not show the custom IDs in the test report?
import pytest @pytest.mark.parametrize("x,y", [(1,2), (3,4)], ids=lambda val: f"val_{val}") def test_sum(x, y): assert x + y > 0
Check the expected input type for the ids callable in parametrize.
The ids callable receives each parameter tuple as a whole, not individual values. The lambda expects a single value, so it fails to produce correct IDs.
What is the main purpose of using the ids parameter in pytest.mark.parametrize?
Think about how test reports display parameterized tests.
The ids parameter allows you to assign meaningful names to each parameter set, making test reports easier to understand.
You have a list of dictionaries as parameters for a pytest test. How do you implement ids to generate readable test IDs showing the 'name' key from each dictionary?
import pytest params = [ {"name": "alpha", "value": 1}, {"name": "beta", "value": 2}, {"name": "gamma", "value": 3} ] @pytest.mark.parametrize("param", params, ids=??? ) def test_value(param): assert param["value"] > 0
Remember that ids can be a list of strings or a callable.
When parameters are complex objects, providing a list of strings for ids is the simplest way to show meaningful test IDs. A lambda would receive each dict but must return a string; however, pytest expects a list of strings or a callable that receives each parameter. Here, a list comprehension is clearer and correct.