fixtures: avoid mutable arg2index state in favor of looking up the request chain #12038
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
pytest allows a fixture to request its own name (directly or indirectly), in which case the fixture with the same name but one level up is used.
To know which fixture should be used next, pytest keeps a mutable item-global dict
_arg2index
which maintains this state. This is not great:Mutable state like this is hard to understand and reason about.
It is conceptually buggy; the indexing is global (e.g. if requesting
fix1
andfix2
, the indexing is shared between them), but actually different branches of the subrequest tree should not affect each other.This is not an issue in practice because pytest keeps a cache of the fixturedefs it resolved anyway (
_fixture_defs
), but if the cache is removed it becomes evident.Instead of the
_arg2index
state, count how manyargname
s deep we are in the subrequest tree ("the fixture stack") and use that for the index.This way, no global mutable state and the logic is very localized and easier to understand.
This is slower, however fixture stacks should not be so deep that this matters much, I hope.