Skip to content

Commit 8bd225c

Browse files
authored
Merge pull request #577 from stephenfin/typing
typing: Accept tuple of exceptions in assertRaises
2 parents a91de05 + 58f96e3 commit 8bd225c

1 file changed

Lines changed: 31 additions & 4 deletions

File tree

‎testtools/testcase.py‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
import types
2424
import unittest
2525
from collections.abc import Callable, Iterator
26-
from typing import TypeVar, cast
26+
from typing import TYPE_CHECKING, TypeVar, cast, overload
2727
from unittest.case import SkipTest
2828

2929
T = TypeVar("T")
@@ -56,6 +56,12 @@
5656
TestResult,
5757
)
5858

59+
if TYPE_CHECKING:
60+
if sys.version_info >= (3, 11):
61+
from typing import Self
62+
else:
63+
from typing_extensions import Self
64+
5965
# Circular import: fixtures imports gather_details from here, we import
6066
# fixtures, leading to gather_details not being available and fixtures being
6167
# unable to import it.
@@ -493,9 +499,27 @@ def assertIsInstance( # type: ignore[override]
493499
matcher = IsInstance(klass)
494500
self.assertThat(obj, matcher, msg or "")
495501

502+
@overload # type: ignore[override]
503+
def assertRaises(
504+
self,
505+
expected_exception: type[BaseException] | tuple[type[BaseException]],
506+
callable: Callable[..., object],
507+
*args: object,
508+
**kwargs: object,
509+
) -> BaseException: ...
510+
511+
@overload # type: ignore[override]
512+
def assertRaises(
513+
self,
514+
expected_exception: type[BaseException] | tuple[type[BaseException]],
515+
callable: None = ...,
516+
*args: object,
517+
**kwargs: object,
518+
) -> "_AssertRaisesContext": ...
519+
496520
def assertRaises( # type: ignore[override]
497521
self,
498-
expected_exception: type[BaseException],
522+
expected_exception: type[BaseException] | tuple[type[BaseException]],
499523
callable: Callable[..., object] | None = None,
500524
*args: object,
501525
**kwargs: object,
@@ -1206,7 +1230,10 @@ class _AssertRaisesContext:
12061230
"""
12071231

12081232
def __init__(
1209-
self, expected: type[BaseException], test_case: TestCase, msg: str | None = None
1233+
self,
1234+
expected: type[BaseException] | tuple[type[BaseException]],
1235+
test_case: TestCase,
1236+
msg: str | None = None,
12101237
) -> None:
12111238
"""Construct an `_AssertRaisesContext`.
12121239
@@ -1219,7 +1246,7 @@ def __init__(
12191246
self.msg = msg
12201247
self.exception: BaseException | None = None
12211248

1222-
def __enter__(self) -> "_AssertRaisesContext":
1249+
def __enter__(self) -> "Self":
12231250
return self
12241251

12251252
def __exit__(

0 commit comments

Comments
 (0)