Skip to content

fix: don't route specced Mocks through str/dict tracing - #796

Closed
DawnofGenX wants to merge 1 commit into
pytest-dev:mainfrom
DawnofGenX:fix/tracing-specced-mock-792
Closed

DawnofGenX wants to merge 1 commit into
pytest-dev:mainfrom
DawnofGenX:fix/tracing-specced-mock-792

Conversation

@DawnofGenX

Copy link
Copy Markdown

Problem:

Enabling hook tracing makes a successful hook call raise TypeError when an
argument or first-result return value is a specced unittest.mock.Mock.

for spec in (str, dict):
    ...
    value = Mock(spec=spec)
    pm.enable_tracing()
    pm.hook.echo(value=value)

Mock(spec=str) → TypeError: object of type 'Mock' has no len() (before the
implementation runs). Mock(spec=dict) → TypeError: 'Mock' object is not iterable (while tracing the result).

Fix:

Mock(spec=...) reports its spec through __class__, so the isinstance(obj, str)
and isinstance(args[-1], dict) checks in _tracing.py matched the mocks and
routed them into the string-formatting / dict-metadata paths. Switched both to
exact-type checks (type(obj) is str, type(args[-1]) is dict), so only real
strings and dicts take those paths and a specced Mock renders as an ordinary
value.

Verification:

  • Added test_tracing_specced_mock_does_not_raise (parametrized over str and
    dict): both cases fail with TypeError without the fix, pass with it.
  • Full suite: 221 passed. pre-commit run --all-files: all hooks pass.

Hook tracing crashed with TypeError when a hook argument or first-result
value was a specced unittest.mock.Mock (Mock(spec=str) or Mock(spec=dict)).
Mock(spec=...) reports its spec through __class__, so the isinstance checks
in _tracing.py matched the mock and sent it into the string formatting /
dict metadata path.

Use exact-type checks (type(obj) is str, type(args[-1]) is dict) so only
real strings and dicts take those paths; a specced Mock now renders as an
ordinary value and the hook result is left untouched.

Adds a parametrized regression test covering both str and dict specs, and
a changelog fragment.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants