Skip to content

Make it possible to use generic/parametrised exceptions with pytest.raises #13663

@dimaqq

Description

@dimaqq

What's the problem this feature will solve?

Code I'd like to write:

        excinfo: pytest.ExceptionInfo[pebble.ExecError[str]]
        with pytest.raises(pebble.ExecError[str]) as excinfo:
            container.exec(['foo']).wait()
        assert excinfo.value.exit_code == 10

I'd like to write this so that it type-checks cleanly.

Alternatively, it could be:

        with pytest.raises(pebble.ExecError[str]) as excinfo:
            container.exec(['foo']).wait()
        # excinfo if of correct type here
        assert excinfo.value.exit_code == 10

Today, this fails with:

  File "/Users/runner/work/operator/operator/test/test_testing.py", line 6405, in test_register_with_result
    with pytest.raises(pebble.ExecError[str]) as excinfo:
  File "/Users/runner/work/operator/operator/.tox/py3.10-unit/lib/python3.10/site-packages/_pytest/raises.py", line 284, in raises
    return RaisesExc(expected_exception, **kwargs)
  File "/Users/runner/work/operator/operator/.tox/py3.10-unit/lib/python3.10/site-packages/_pytest/raises.py", line 635, in __init__
    self.expected_exceptions = tuple(
  File "/Users/runner/work/operator/operator/.tox/py3.10-unit/lib/python3.10/site-packages/_pytest/raises.py", line 636, in <genexpr>
    self._parse_exc(e, expected="a BaseException type")
  File "/Users/runner/work/operator/operator/.tox/py3.10-unit/lib/python3.10/site-packages/_pytest/raises.py", line 472, in _parse_exc
    raise TypeError(msg + repr(type(exc).__name__))
TypeError: expected exception must be a BaseException type, not '_GenericAlias'

P.S. my codebase supports py3.10 and later, so I can't use the newest Python language features.
(@james-garner-canonical commented about a work-around with TypeVars or something, which would require later Pythons)

Additional context

Refs
Similar ticker and PR for generic exception groups: #13115 #13134
Discussion: microsoft/pyright#10774

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: enhancementnew feature or API change, should be merged into features branchtype: feature-branchnew feature or API change, should be merged into features branch

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions