1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
|
from __future__ import annotations
# several expected multi-line strings contain long lines. We don't wanna break them up
# as that makes it confusing to see where the line breaks are.
# ruff: noqa: E501
from contextlib import AbstractContextManager
import re
import sys
from _pytest._code import ExceptionInfo
from _pytest.outcomes import Failed
from _pytest.pytester import Pytester
from _pytest.raises import RaisesExc
from _pytest.raises import RaisesGroup
from _pytest.raises import repr_callable
import pytest
if sys.version_info < (3, 11):
from exceptiongroup import BaseExceptionGroup
from exceptiongroup import ExceptionGroup
def wrap_escape(s: str) -> str:
return "^" + re.escape(s) + "$"
def fails_raises_group(msg: str, add_prefix: bool = True) -> RaisesExc[Failed]:
assert msg[-1] != "\n", (
"developer error, expected string should not end with newline"
)
prefix = "Raised exception group did not match: " if add_prefix else ""
return pytest.raises(Failed, match=wrap_escape(prefix + msg))
def test_raises_group() -> None:
with pytest.raises(
TypeError,
match=wrap_escape("Expected a BaseException type, but got 'int'"),
):
RaisesExc(5) # type: ignore[call-overload]
with pytest.raises(
ValueError,
match=wrap_escape("Expected a BaseException type, but got 'int'"),
):
RaisesExc(int) # type: ignore[type-var]
with pytest.raises(
TypeError,
match=wrap_escape(
"Expected a BaseException type, RaisesExc, or RaisesGroup, but got an exception instance: ValueError",
),
):
RaisesGroup(ValueError()) # type: ignore[call-overload]
with RaisesGroup(ValueError):
raise ExceptionGroup("foo", (ValueError(),))
with (
fails_raises_group("`SyntaxError()` is not an instance of `ValueError`"),
RaisesGroup(ValueError),
):
raise ExceptionGroup("foo", (SyntaxError(),))
# multiple exceptions
with RaisesGroup(ValueError, SyntaxError):
raise ExceptionGroup("foo", (ValueError(), SyntaxError()))
# order doesn't matter
with RaisesGroup(SyntaxError, ValueError):
raise ExceptionGroup("foo", (ValueError(), SyntaxError()))
# nested exceptions
with RaisesGroup(RaisesGroup(ValueError)):
raise ExceptionGroup("foo", (ExceptionGroup("bar", (ValueError(),)),))
with RaisesGroup(
SyntaxError,
RaisesGroup(ValueError),
RaisesGroup(RuntimeError),
):
raise ExceptionGroup(
"foo",
(
SyntaxError(),
ExceptionGroup("bar", (ValueError(),)),
ExceptionGroup("", (RuntimeError(),)),
),
)
def test_incorrect_number_exceptions() -> None:
# We previously gave an error saying the number of exceptions was wrong,
# but we now instead indicate excess/missing exceptions
with (
fails_raises_group(
"1 matched exception. Unexpected exception(s): [RuntimeError()]"
),
RaisesGroup(ValueError),
):
raise ExceptionGroup("", (RuntimeError(), ValueError()))
# will error if there's missing exceptions
with (
fails_raises_group(
"1 matched exception. Too few exceptions raised, found no match for: [SyntaxError]"
),
RaisesGroup(ValueError, SyntaxError),
):
raise ExceptionGroup("", (ValueError(),))
with (
fails_raises_group(
"\n"
"1 matched exception. \n"
"Too few exceptions raised!\n"
"The following expected exceptions did not find a match:\n"
" ValueError\n"
" It matches `ValueError()` which was paired with `ValueError`"
),
RaisesGroup(ValueError, ValueError),
):
raise ExceptionGroup("", (ValueError(),))
with (
fails_raises_group(
"\n"
"1 matched exception. \n"
"Unexpected exception(s)!\n"
"The following raised exceptions did not find a match\n"
" ValueError('b'):\n"
" It matches `ValueError` which was paired with `ValueError('a')`"
),
RaisesGroup(ValueError),
):
raise ExceptionGroup("", (ValueError("a"), ValueError("b")))
with (
fails_raises_group(
"\n"
"1 matched exception. \n"
"The following expected exceptions did not find a match:\n"
" ValueError\n"
" It matches `ValueError()` which was paired with `ValueError`\n"
"The following raised exceptions did not find a match\n"
" SyntaxError():\n"
" `SyntaxError()` is not an instance of `ValueError`"
),
RaisesGroup(ValueError, ValueError),
):
raise ExceptionGroup("", [ValueError(), SyntaxError()])
def test_flatten_subgroups() -> None:
# loose semantics, as with expect*
with RaisesGroup(ValueError, flatten_subgroups=True):
raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),))
with RaisesGroup(ValueError, TypeError, flatten_subgroups=True):
raise ExceptionGroup("", (ExceptionGroup("", (ValueError(), TypeError())),))
with RaisesGroup(ValueError, TypeError, flatten_subgroups=True):
raise ExceptionGroup("", [ExceptionGroup("", [ValueError()]), TypeError()])
# mixed loose is possible if you want it to be at least N deep
with RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)):
raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),))
with RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)):
raise ExceptionGroup(
"",
(ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),)),),
)
# but not the other way around
with pytest.raises(
ValueError,
match=r"^You cannot specify a nested structure inside a RaisesGroup with",
):
RaisesGroup(RaisesGroup(ValueError), flatten_subgroups=True) # type: ignore[call-overload]
# flatten_subgroups is not sufficient to catch fully unwrapped
with (
fails_raises_group(
"`ValueError()` is not an exception group, but would match with `allow_unwrapped=True`"
),
RaisesGroup(ValueError, flatten_subgroups=True),
):
raise ValueError
with (
fails_raises_group(
"RaisesGroup(ValueError, flatten_subgroups=True): `ValueError()` is not an exception group, but would match with `allow_unwrapped=True`"
),
RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)),
):
raise ExceptionGroup("", (ValueError(),))
# helpful suggestion if flatten_subgroups would make it pass
with (
fails_raises_group(
"Raised exception group did not match: \n"
"The following expected exceptions did not find a match:\n"
" ValueError\n"
" TypeError\n"
"The following raised exceptions did not find a match\n"
" ExceptionGroup('', [ValueError(), TypeError()]):\n"
" Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" Unexpected nested `ExceptionGroup()`, expected `TypeError`\n"
"Did you mean to use `flatten_subgroups=True`?",
add_prefix=False,
),
RaisesGroup(ValueError, TypeError),
):
raise ExceptionGroup("", [ExceptionGroup("", [ValueError(), TypeError()])])
# but doesn't consider check (otherwise we'd break typing guarantees)
with (
fails_raises_group(
"Raised exception group did not match: \n"
"The following expected exceptions did not find a match:\n"
" ValueError\n"
" TypeError\n"
"The following raised exceptions did not find a match\n"
" ExceptionGroup('', [ValueError(), TypeError()]):\n"
" Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" Unexpected nested `ExceptionGroup()`, expected `TypeError`\n"
"Did you mean to use `flatten_subgroups=True`?",
add_prefix=False,
),
RaisesGroup(
ValueError,
TypeError,
check=lambda eg: len(eg.exceptions) == 1,
),
):
raise ExceptionGroup("", [ExceptionGroup("", [ValueError(), TypeError()])])
# correct number of exceptions, and flatten_subgroups would make it pass
# This now doesn't print a repr of the caught exception at all, but that can be found in the traceback
with (
fails_raises_group(
"Raised exception group did not match: Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" Did you mean to use `flatten_subgroups=True`?",
add_prefix=False,
),
RaisesGroup(ValueError),
):
raise ExceptionGroup("", [ExceptionGroup("", [ValueError()])])
# correct number of exceptions, but flatten_subgroups wouldn't help, so we don't suggest it
with (
fails_raises_group(
"Unexpected nested `ExceptionGroup()`, expected `ValueError`"
),
RaisesGroup(ValueError),
):
raise ExceptionGroup("", [ExceptionGroup("", [TypeError()])])
# flatten_subgroups can be suggested if nested. This will implicitly ask the user to
# do `RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True))` which is unlikely
# to be what they actually want - but I don't think it's worth trying to special-case
with (
fails_raises_group(
"RaisesGroup(ValueError): Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" Did you mean to use `flatten_subgroups=True`?",
),
RaisesGroup(RaisesGroup(ValueError)),
):
raise ExceptionGroup(
"",
[ExceptionGroup("", [ExceptionGroup("", [ValueError()])])],
)
# Don't mention "unexpected nested" if expecting an ExceptionGroup.
# Although it should perhaps be an error to specify `RaisesGroup(ExceptionGroup)` in
# favor of doing `RaisesGroup(RaisesGroup(...))`.
with (
fails_raises_group(
"`BaseExceptionGroup()` is not an instance of `ExceptionGroup`"
),
RaisesGroup(ExceptionGroup),
):
raise BaseExceptionGroup("", [BaseExceptionGroup("", [KeyboardInterrupt()])])
def test_catch_unwrapped_exceptions() -> None:
# Catches lone exceptions with strict=False
# just as except* would
with RaisesGroup(ValueError, allow_unwrapped=True):
raise ValueError
# expecting multiple unwrapped exceptions is not possible
with pytest.raises(
ValueError,
match=r"^You cannot specify multiple exceptions with",
):
RaisesGroup(SyntaxError, ValueError, allow_unwrapped=True) # type: ignore[call-overload]
# if users want one of several exception types they need to use a RaisesExc
# (which the error message suggests)
with RaisesGroup(
RaisesExc(check=lambda e: isinstance(e, SyntaxError | ValueError)),
allow_unwrapped=True,
):
raise ValueError
# Unwrapped nested `RaisesGroup` is likely a user error, so we raise an error.
with pytest.raises(ValueError, match="has no effect when expecting"):
RaisesGroup(RaisesGroup(ValueError), allow_unwrapped=True) # type: ignore[call-overload]
# But it *can* be used to check for nesting level +- 1 if they move it to
# the nested RaisesGroup. Users should probably use `RaisesExc`s instead though.
with RaisesGroup(RaisesGroup(ValueError, allow_unwrapped=True)):
raise ExceptionGroup("", [ExceptionGroup("", [ValueError()])])
with RaisesGroup(RaisesGroup(ValueError, allow_unwrapped=True)):
raise ExceptionGroup("", [ValueError()])
# with allow_unwrapped=False (default) it will not be caught
with (
fails_raises_group(
"`ValueError()` is not an exception group, but would match with `allow_unwrapped=True`"
),
RaisesGroup(ValueError),
):
raise ValueError("value error text")
# allow_unwrapped on its own won't match against nested groups
with (
fails_raises_group(
"Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" Did you mean to use `flatten_subgroups=True`?",
),
RaisesGroup(ValueError, allow_unwrapped=True),
):
raise ExceptionGroup("foo", [ExceptionGroup("bar", [ValueError()])])
# you need both allow_unwrapped and flatten_subgroups to fully emulate except*
with RaisesGroup(ValueError, allow_unwrapped=True, flatten_subgroups=True):
raise ExceptionGroup("", [ExceptionGroup("", [ValueError()])])
# code coverage
with (
fails_raises_group(
"Raised exception (group) did not match: `TypeError()` is not an instance of `ValueError`",
add_prefix=False,
),
RaisesGroup(ValueError, allow_unwrapped=True),
):
raise TypeError("this text doesn't show up in the error message")
with (
fails_raises_group(
"Raised exception (group) did not match: RaisesExc(ValueError): `TypeError()` is not an instance of `ValueError`",
add_prefix=False,
),
RaisesGroup(RaisesExc(ValueError), allow_unwrapped=True),
):
raise TypeError
# check we don't suggest unwrapping with nested RaisesGroup
with (
fails_raises_group("`ValueError()` is not an exception group"),
RaisesGroup(RaisesGroup(ValueError)),
):
raise ValueError
def test_match() -> None:
# supports match string
with RaisesGroup(ValueError, match="bar"):
raise ExceptionGroup("bar", (ValueError(),))
# now also works with ^$
with RaisesGroup(ValueError, match="^bar$"):
raise ExceptionGroup("bar", (ValueError(),))
# it also includes notes
with RaisesGroup(ValueError, match="my note"):
e = ExceptionGroup("bar", (ValueError(),))
e.add_note("my note")
raise e
# and technically you can match it all with ^$
# but you're probably better off using a RaisesExc at that point
with RaisesGroup(ValueError, match="^bar\nmy note$"):
e = ExceptionGroup("bar", (ValueError(),))
e.add_note("my note")
raise e
with (
fails_raises_group(
"Regex pattern did not match the `ExceptionGroup()`.\n"
" Expected regex: 'foo'\n"
" Actual message: 'bar'"
),
RaisesGroup(ValueError, match="foo"),
):
raise ExceptionGroup("bar", (ValueError(),))
# Suggest a fix for easy pitfall of adding match to the RaisesGroup instead of
# using a RaisesExc.
# This requires a single expected & raised exception, the expected is a type,
# and `isinstance(raised, expected_type)`.
with (
fails_raises_group(
"Regex pattern did not match the `ExceptionGroup()`.\n"
" Expected regex: 'foo'\n"
" Actual message: 'bar'\n"
" but matched the expected `ValueError`.\n"
" You might want `RaisesGroup(RaisesExc(ValueError, match='foo'))`"
),
RaisesGroup(ValueError, match="foo"),
):
raise ExceptionGroup("bar", [ValueError("foo")])
def test_check() -> None:
exc = ExceptionGroup("", (ValueError(),))
def is_exc(e: ExceptionGroup[ValueError]) -> bool:
return e is exc
is_exc_repr = repr_callable(is_exc)
with RaisesGroup(ValueError, check=is_exc):
raise exc
with (
fails_raises_group(
f"check {is_exc_repr} did not return True on the ExceptionGroup"
),
RaisesGroup(ValueError, check=is_exc),
):
raise ExceptionGroup("", (ValueError(),))
def is_value_error(e: BaseException) -> bool:
return isinstance(e, ValueError)
# helpful suggestion if the user thinks the check is for the sub-exception
with (
fails_raises_group(
f"check {is_value_error} did not return True on the ExceptionGroup, but did return True for the expected ValueError. You might want RaisesGroup(RaisesExc(ValueError, check=<...>))"
),
RaisesGroup(ValueError, check=is_value_error),
):
raise ExceptionGroup("", (ValueError(),))
def test_unwrapped_match_check() -> None:
def my_check(e: object) -> bool: # pragma: no cover
return True
msg = (
"`allow_unwrapped=True` bypasses the `match` and `check` parameters"
" if the exception is unwrapped. If you intended to match/check the"
" exception you should use a `RaisesExc` object. If you want to match/check"
" the exceptiongroup when the exception *is* wrapped you need to"
" do e.g. `if isinstance(exc.value, ExceptionGroup):"
" assert RaisesGroup(...).matches(exc.value)` afterwards."
)
with pytest.raises(ValueError, match=re.escape(msg)):
RaisesGroup(ValueError, allow_unwrapped=True, match="foo") # type: ignore[call-overload]
with pytest.raises(ValueError, match=re.escape(msg)):
RaisesGroup(ValueError, allow_unwrapped=True, check=my_check) # type: ignore[call-overload]
# Users should instead use a RaisesExc
rg = RaisesGroup(RaisesExc(ValueError, match="^foo$"), allow_unwrapped=True)
with rg:
raise ValueError("foo")
with rg:
raise ExceptionGroup("", [ValueError("foo")])
# or if they wanted to match/check the group, do a conditional `.matches()`
with RaisesGroup(ValueError, allow_unwrapped=True) as exc:
raise ExceptionGroup("bar", [ValueError("foo")])
if isinstance(exc.value, ExceptionGroup): # pragma: no branch
assert RaisesGroup(ValueError, match="bar").matches(exc.value)
def test_matches() -> None:
rg = RaisesGroup(ValueError)
assert not rg.matches(None)
assert not rg.matches(ValueError())
assert rg.matches(ExceptionGroup("", (ValueError(),)))
re = RaisesExc(ValueError)
assert not re.matches(None)
assert re.matches(ValueError())
def test_message() -> None:
def check_message(
message: str,
body: RaisesGroup[BaseException],
) -> None:
with (
pytest.raises(
Failed,
match=f"^DID NOT RAISE any exception, expected `{re.escape(message)}`$",
),
body,
):
...
# basic
check_message("ExceptionGroup(ValueError)", RaisesGroup(ValueError))
# multiple exceptions
check_message(
"ExceptionGroup(ValueError, ValueError)",
RaisesGroup(ValueError, ValueError),
)
# nested
check_message(
"ExceptionGroup(ExceptionGroup(ValueError))",
RaisesGroup(RaisesGroup(ValueError)),
)
# RaisesExc
check_message(
"ExceptionGroup(RaisesExc(ValueError, match='my_str'))",
RaisesGroup(RaisesExc(ValueError, match="my_str")),
)
check_message(
"ExceptionGroup(RaisesExc(match='my_str'))",
RaisesGroup(RaisesExc(match="my_str")),
)
# one-size tuple is printed as not being a tuple
check_message(
"ExceptionGroup(RaisesExc(ValueError))",
RaisesGroup(RaisesExc((ValueError,))),
)
check_message(
"ExceptionGroup(RaisesExc((ValueError, IndexError)))",
RaisesGroup(RaisesExc((ValueError, IndexError))),
)
# BaseExceptionGroup
check_message(
"BaseExceptionGroup(KeyboardInterrupt)",
RaisesGroup(KeyboardInterrupt),
)
# BaseExceptionGroup with type inside RaisesExc
check_message(
"BaseExceptionGroup(RaisesExc(KeyboardInterrupt))",
RaisesGroup(RaisesExc(KeyboardInterrupt)),
)
check_message(
"BaseExceptionGroup(RaisesExc((ValueError, KeyboardInterrupt)))",
RaisesGroup(RaisesExc((ValueError, KeyboardInterrupt))),
)
# Base-ness transfers to parent containers
check_message(
"BaseExceptionGroup(BaseExceptionGroup(KeyboardInterrupt))",
RaisesGroup(RaisesGroup(KeyboardInterrupt)),
)
# but not to child containers
check_message(
"BaseExceptionGroup(BaseExceptionGroup(KeyboardInterrupt), ExceptionGroup(ValueError))",
RaisesGroup(RaisesGroup(KeyboardInterrupt), RaisesGroup(ValueError)),
)
def test_assert_message() -> None:
# the message does not need to list all parameters to RaisesGroup, nor all exceptions
# in the exception group, as those are both visible in the traceback.
# first fails to match
with (
fails_raises_group("`TypeError()` is not an instance of `ValueError`"),
RaisesGroup(ValueError),
):
raise ExceptionGroup("a", [TypeError()])
with (
fails_raises_group(
"Raised exception group did not match: \n"
"The following expected exceptions did not find a match:\n"
" RaisesGroup(ValueError)\n"
" RaisesGroup(ValueError, match='a')\n"
"The following raised exceptions did not find a match\n"
" ExceptionGroup('', [RuntimeError()]):\n"
" RaisesGroup(ValueError): `RuntimeError()` is not an instance of `ValueError`\n"
" RaisesGroup(ValueError, match='a'): Regex pattern did not match the `ExceptionGroup()`.\n"
" Expected regex: 'a'\n"
" Actual message: ''\n"
" RuntimeError():\n"
" RaisesGroup(ValueError): `RuntimeError()` is not an exception group\n"
" RaisesGroup(ValueError, match='a'): `RuntimeError()` is not an exception group",
add_prefix=False, # to see the full structure
),
RaisesGroup(RaisesGroup(ValueError), RaisesGroup(ValueError, match="a")),
):
raise ExceptionGroup(
"",
[ExceptionGroup("", [RuntimeError()]), RuntimeError()],
)
with (
fails_raises_group(
"Raised exception group did not match: \n"
"2 matched exceptions. \n"
"The following expected exceptions did not find a match:\n"
" RaisesGroup(RuntimeError)\n"
" RaisesGroup(ValueError)\n"
"The following raised exceptions did not find a match\n"
" RuntimeError():\n"
" RaisesGroup(RuntimeError): `RuntimeError()` is not an exception group, but would match with `allow_unwrapped=True`\n"
" RaisesGroup(ValueError): `RuntimeError()` is not an exception group\n"
" ValueError('bar'):\n"
" It matches `ValueError` which was paired with `ValueError('foo')`\n"
" RaisesGroup(RuntimeError): `ValueError()` is not an exception group\n"
" RaisesGroup(ValueError): `ValueError()` is not an exception group, but would match with `allow_unwrapped=True`",
add_prefix=False, # to see the full structure
),
RaisesGroup(
ValueError,
RaisesExc(TypeError),
RaisesGroup(RuntimeError),
RaisesGroup(ValueError),
),
):
raise ExceptionGroup(
"a",
[RuntimeError(), TypeError(), ValueError("foo"), ValueError("bar")],
)
with (
fails_raises_group(
"1 matched exception. `AssertionError()` is not an instance of `TypeError`"
),
RaisesGroup(ValueError, TypeError),
):
raise ExceptionGroup("a", [ValueError(), AssertionError()])
with (
fails_raises_group(
"RaisesExc(ValueError): `TypeError()` is not an instance of `ValueError`"
),
RaisesGroup(RaisesExc(ValueError)),
):
raise ExceptionGroup("a", [TypeError()])
# suggest escaping
with (
fails_raises_group(
# TODO: did not match Exceptiongroup('h(ell)o', ...) ?
"Raised exception group did not match: Regex pattern did not match the `ExceptionGroup()`.\n"
" Expected regex: 'h(ell)o'\n"
" Actual message: 'h(ell)o'\n"
" Did you mean to `re.escape()` the regex?",
add_prefix=False, # to see the full structure
),
RaisesGroup(ValueError, match="h(ell)o"),
):
raise ExceptionGroup("h(ell)o", [ValueError()])
with (
fails_raises_group(
"RaisesExc(match='h(ell)o'): Regex pattern did not match.\n"
" Expected regex: 'h(ell)o'\n"
" Actual message: 'h(ell)o'\n"
" Did you mean to `re.escape()` the regex?",
),
RaisesGroup(RaisesExc(match="h(ell)o")),
):
raise ExceptionGroup("", [ValueError("h(ell)o")])
with (
fails_raises_group(
"Raised exception group did not match: \n"
"The following expected exceptions did not find a match:\n"
" ValueError\n"
" ValueError\n"
" ValueError\n"
" ValueError\n"
"The following raised exceptions did not find a match\n"
" ExceptionGroup('', [ValueError(), TypeError()]):\n"
" Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" Unexpected nested `ExceptionGroup()`, expected `ValueError`",
add_prefix=False, # to see the full structure
),
RaisesGroup(ValueError, ValueError, ValueError, ValueError),
):
raise ExceptionGroup("", [ExceptionGroup("", [ValueError(), TypeError()])])
def test_message_indent() -> None:
with (
fails_raises_group(
"Raised exception group did not match: \n"
"The following expected exceptions did not find a match:\n"
" RaisesGroup(ValueError, ValueError)\n"
" ValueError\n"
"The following raised exceptions did not find a match\n"
" ExceptionGroup('', [TypeError(), RuntimeError()]):\n"
" RaisesGroup(ValueError, ValueError): \n"
" The following expected exceptions did not find a match:\n"
" ValueError\n"
" ValueError\n"
" The following raised exceptions did not find a match\n"
" TypeError():\n"
" `TypeError()` is not an instance of `ValueError`\n"
" `TypeError()` is not an instance of `ValueError`\n"
" RuntimeError():\n"
" `RuntimeError()` is not an instance of `ValueError`\n"
" `RuntimeError()` is not an instance of `ValueError`\n"
# TODO: this line is not great, should maybe follow the same format as the other and say
# ValueError: Unexpected nested `ExceptionGroup()` (?)
" Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" TypeError():\n"
" RaisesGroup(ValueError, ValueError): `TypeError()` is not an exception group\n"
" `TypeError()` is not an instance of `ValueError`",
add_prefix=False,
),
RaisesGroup(
RaisesGroup(ValueError, ValueError),
ValueError,
),
):
raise ExceptionGroup(
"",
[
ExceptionGroup("", [TypeError(), RuntimeError()]),
TypeError(),
],
)
with (
fails_raises_group(
"Raised exception group did not match: \n"
"RaisesGroup(ValueError, ValueError): \n"
" The following expected exceptions did not find a match:\n"
" ValueError\n"
" ValueError\n"
" The following raised exceptions did not find a match\n"
" TypeError():\n"
" `TypeError()` is not an instance of `ValueError`\n"
" `TypeError()` is not an instance of `ValueError`\n"
" RuntimeError():\n"
" `RuntimeError()` is not an instance of `ValueError`\n"
" `RuntimeError()` is not an instance of `ValueError`",
add_prefix=False,
),
RaisesGroup(
RaisesGroup(ValueError, ValueError),
),
):
raise ExceptionGroup(
"",
[
ExceptionGroup("", [TypeError(), RuntimeError()]),
],
)
def test_suggestion_on_nested_and_brief_error() -> None:
# Make sure "Did you mean" suggestion gets indented iff it follows a single-line error
with (
fails_raises_group(
"\n"
"The following expected exceptions did not find a match:\n"
" RaisesGroup(ValueError)\n"
" ValueError\n"
"The following raised exceptions did not find a match\n"
" ExceptionGroup('', [ExceptionGroup('', [ValueError()])]):\n"
" RaisesGroup(ValueError): Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" Did you mean to use `flatten_subgroups=True`?\n"
" Unexpected nested `ExceptionGroup()`, expected `ValueError`",
),
RaisesGroup(RaisesGroup(ValueError), ValueError),
):
raise ExceptionGroup(
"",
[ExceptionGroup("", [ExceptionGroup("", [ValueError()])])],
)
# if indented here it would look like another raised exception
with (
fails_raises_group(
"\n"
"The following expected exceptions did not find a match:\n"
" RaisesGroup(ValueError, ValueError)\n"
" ValueError\n"
"The following raised exceptions did not find a match\n"
" ExceptionGroup('', [ValueError(), ExceptionGroup('', [ValueError()])]):\n"
" RaisesGroup(ValueError, ValueError): \n"
" 1 matched exception. \n"
" The following expected exceptions did not find a match:\n"
" ValueError\n"
" It matches `ValueError()` which was paired with `ValueError`\n"
" The following raised exceptions did not find a match\n"
" ExceptionGroup('', [ValueError()]):\n"
" Unexpected nested `ExceptionGroup()`, expected `ValueError`\n"
" Did you mean to use `flatten_subgroups=True`?\n"
" Unexpected nested `ExceptionGroup()`, expected `ValueError`"
),
RaisesGroup(RaisesGroup(ValueError, ValueError), ValueError),
):
raise ExceptionGroup(
"",
[ExceptionGroup("", [ValueError(), ExceptionGroup("", [ValueError()])])],
)
# re.escape always comes after single-line errors
with (
fails_raises_group(
"\n"
"The following expected exceptions did not find a match:\n"
" RaisesGroup(Exception, match='^hello')\n"
" ValueError\n"
"The following raised exceptions did not find a match\n"
" ExceptionGroup('^hello', [Exception()]):\n"
" RaisesGroup(Exception, match='^hello'): Regex pattern did not match the `ExceptionGroup()`.\n"
" Expected regex: '^hello'\n"
" Actual message: '^hello'\n"
" Did you mean to `re.escape()` the regex?\n"
" Unexpected nested `ExceptionGroup()`, expected `ValueError`"
),
RaisesGroup(RaisesGroup(Exception, match="^hello"), ValueError),
):
raise ExceptionGroup("", [ExceptionGroup("^hello", [Exception()])])
def test_assert_message_nested() -> None:
# we only get one instance of aaaaaaaaaa... and bbbbbb..., but we do get multiple instances of ccccc... and dddddd..
# but I think this now only prints the full repr when that is necessary to disambiguate exceptions
with (
fails_raises_group(
"Raised exception group did not match: \n"
"The following expected exceptions did not find a match:\n"
" RaisesGroup(ValueError)\n"
" RaisesGroup(RaisesGroup(ValueError))\n"
" RaisesGroup(RaisesExc(TypeError, match='foo'))\n"
" RaisesGroup(TypeError, ValueError)\n"
"The following raised exceptions did not find a match\n"
" TypeError('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'):\n"
" RaisesGroup(ValueError): `TypeError()` is not an exception group\n"
" RaisesGroup(RaisesGroup(ValueError)): `TypeError()` is not an exception group\n"
" RaisesGroup(RaisesExc(TypeError, match='foo')): `TypeError()` is not an exception group\n"
" RaisesGroup(TypeError, ValueError): `TypeError()` is not an exception group\n"
" ExceptionGroup('Exceptions from Trio nursery', [TypeError('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')]):\n"
" RaisesGroup(ValueError): `TypeError()` is not an instance of `ValueError`\n"
" RaisesGroup(RaisesGroup(ValueError)): RaisesGroup(ValueError): `TypeError()` is not an exception group\n"
" RaisesGroup(RaisesExc(TypeError, match='foo')): RaisesExc(TypeError, match='foo'): Regex pattern did not match.\n"
" Expected regex: 'foo'\n"
" Actual message: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'\n"
" RaisesGroup(TypeError, ValueError): 1 matched exception. Too few exceptions raised, found no match for: [ValueError]\n"
" ExceptionGroup('Exceptions from Trio nursery', [TypeError('cccccccccccccccccccccccccccccc'), TypeError('dddddddddddddddddddddddddddddd')]):\n"
" RaisesGroup(ValueError): \n"
" The following expected exceptions did not find a match:\n"
" ValueError\n"
" The following raised exceptions did not find a match\n"
" TypeError('cccccccccccccccccccccccccccccc'):\n"
" `TypeError()` is not an instance of `ValueError`\n"
" TypeError('dddddddddddddddddddddddddddddd'):\n"
" `TypeError()` is not an instance of `ValueError`\n"
" RaisesGroup(RaisesGroup(ValueError)): \n"
" The following expected exceptions did not find a match:\n"
" RaisesGroup(ValueError)\n"
" The following raised exceptions did not find a match\n"
" TypeError('cccccccccccccccccccccccccccccc'):\n"
" RaisesGroup(ValueError): `TypeError()` is not an exception group\n"
" TypeError('dddddddddddddddddddddddddddddd'):\n"
" RaisesGroup(ValueError): `TypeError()` is not an exception group\n"
" RaisesGroup(RaisesExc(TypeError, match='foo')): \n"
" The following expected exceptions did not find a match:\n"
" RaisesExc(TypeError, match='foo')\n"
" The following raised exceptions did not find a match\n"
" TypeError('cccccccccccccccccccccccccccccc'):\n"
" RaisesExc(TypeError, match='foo'): Regex pattern did not match.\n"
" Expected regex: 'foo'\n"
" Actual message: 'cccccccccccccccccccccccccccccc'\n"
" TypeError('dddddddddddddddddddddddddddddd'):\n"
" RaisesExc(TypeError, match='foo'): Regex pattern did not match.\n"
" Expected regex: 'foo'\n"
" Actual message: 'dddddddddddddddddddddddddddddd'\n"
" RaisesGroup(TypeError, ValueError): \n"
" 1 matched exception. \n"
" The following expected exceptions did not find a match:\n"
" ValueError\n"
" The following raised exceptions did not find a match\n"
" TypeError('dddddddddddddddddddddddddddddd'):\n"
" It matches `TypeError` which was paired with `TypeError('cccccccccccccccccccccccccccccc')`\n"
" `TypeError()` is not an instance of `ValueError`",
add_prefix=False, # to see the full structure
),
RaisesGroup(
RaisesGroup(ValueError),
RaisesGroup(RaisesGroup(ValueError)),
RaisesGroup(RaisesExc(TypeError, match="foo")),
RaisesGroup(TypeError, ValueError),
),
):
raise ExceptionGroup(
"",
[
TypeError("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
ExceptionGroup(
"Exceptions from Trio nursery",
[TypeError("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")],
),
ExceptionGroup(
"Exceptions from Trio nursery",
[
TypeError("cccccccccccccccccccccccccccccc"),
TypeError("dddddddddddddddddddddddddddddd"),
],
),
],
)
# CI always runs with hypothesis, but this is not a critical test - it overlaps
# with several others
@pytest.mark.skipif(
"hypothesis" in sys.modules,
reason="hypothesis may have monkeypatched _check_repr",
)
def test_check_no_patched_repr() -> None: # pragma: no cover
# We make `_check_repr` monkeypatchable to avoid this very ugly and verbose
# repr. The other tests that use `check` make use of `_check_repr` so they'll
# continue passing in case it is patched - but we have this one test that
# demonstrates just how nasty it gets otherwise.
match_str = (
r"^Raised exception group did not match: \n"
r"The following expected exceptions did not find a match:\n"
r" RaisesExc\(check=<function test_check_no_patched_repr.<locals>.<lambda> at .*>\)\n"
r" TypeError\n"
r"The following raised exceptions did not find a match\n"
r" ValueError\('foo'\):\n"
r" RaisesExc\(check=<function test_check_no_patched_repr.<locals>.<lambda> at .*>\): check did not return True\n"
r" `ValueError\(\)` is not an instance of `TypeError`\n"
r" ValueError\('bar'\):\n"
r" RaisesExc\(check=<function test_check_no_patched_repr.<locals>.<lambda> at .*>\): check did not return True\n"
r" `ValueError\(\)` is not an instance of `TypeError`$"
)
with (
pytest.raises(Failed, match=match_str),
RaisesGroup(RaisesExc(check=lambda x: False), TypeError),
):
raise ExceptionGroup("", [ValueError("foo"), ValueError("bar")])
def test_misordering_example() -> None:
with (
fails_raises_group(
"\n"
"3 matched exceptions. \n"
"The following expected exceptions did not find a match:\n"
" RaisesExc(ValueError, match='foo')\n"
" It matches `ValueError('foo')` which was paired with `ValueError`\n"
" It matches `ValueError('foo')` which was paired with `ValueError`\n"
" It matches `ValueError('foo')` which was paired with `ValueError`\n"
"The following raised exceptions did not find a match\n"
" ValueError('bar'):\n"
" It matches `ValueError` which was paired with `ValueError('foo')`\n"
" It matches `ValueError` which was paired with `ValueError('foo')`\n"
" It matches `ValueError` which was paired with `ValueError('foo')`\n"
" RaisesExc(ValueError, match='foo'): Regex pattern did not match.\n"
" Expected regex: 'foo'\n"
" Actual message: 'bar'\n"
"There exist a possible match when attempting an exhaustive check, but RaisesGroup uses a greedy algorithm. Please make your expected exceptions more stringent with `RaisesExc` etc so the greedy algorithm can function."
),
RaisesGroup(
ValueError, ValueError, ValueError, RaisesExc(ValueError, match="foo")
),
):
raise ExceptionGroup(
"",
[
ValueError("foo"),
ValueError("foo"),
ValueError("foo"),
ValueError("bar"),
],
)
def test_brief_error_on_one_fail() -> None:
"""If only one raised and one expected fail to match up, we print a full table iff
the raised exception would match one of the expected that previously got matched"""
# no also-matched
with (
fails_raises_group(
"1 matched exception. `TypeError()` is not an instance of `RuntimeError`"
),
RaisesGroup(ValueError, RuntimeError),
):
raise ExceptionGroup("", [ValueError(), TypeError()])
# raised would match an expected
with (
fails_raises_group(
"\n"
"1 matched exception. \n"
"The following expected exceptions did not find a match:\n"
" RuntimeError\n"
"The following raised exceptions did not find a match\n"
" TypeError():\n"
" It matches `Exception` which was paired with `ValueError()`\n"
" `TypeError()` is not an instance of `RuntimeError`"
),
RaisesGroup(Exception, RuntimeError),
):
raise ExceptionGroup("", [ValueError(), TypeError()])
# expected would match a raised
with (
fails_raises_group(
"\n"
"1 matched exception. \n"
"The following expected exceptions did not find a match:\n"
" ValueError\n"
" It matches `ValueError()` which was paired with `ValueError`\n"
"The following raised exceptions did not find a match\n"
" TypeError():\n"
" `TypeError()` is not an instance of `ValueError`"
),
RaisesGroup(ValueError, ValueError),
):
raise ExceptionGroup("", [ValueError(), TypeError()])
def test_identity_oopsies() -> None:
# it's both possible to have several instances of the same exception in the same group
# and to expect multiple of the same type
# this previously messed up the logic
with (
fails_raises_group(
"3 matched exceptions. `RuntimeError()` is not an instance of `TypeError`"
),
RaisesGroup(ValueError, ValueError, ValueError, TypeError),
):
raise ExceptionGroup(
"", [ValueError(), ValueError(), ValueError(), RuntimeError()]
)
e = ValueError("foo")
m = RaisesExc(match="bar")
with (
fails_raises_group(
"\n"
"The following expected exceptions did not find a match:\n"
" RaisesExc(match='bar')\n"
" RaisesExc(match='bar')\n"
" RaisesExc(match='bar')\n"
"The following raised exceptions did not find a match\n"
" ValueError('foo'):\n"
" RaisesExc(match='bar'): Regex pattern did not match.\n"
" Expected regex: 'bar'\n"
" Actual message: 'foo'\n"
" RaisesExc(match='bar'): Regex pattern did not match.\n"
" Expected regex: 'bar'\n"
" Actual message: 'foo'\n"
" RaisesExc(match='bar'): Regex pattern did not match.\n"
" Expected regex: 'bar'\n"
" Actual message: 'foo'\n"
" ValueError('foo'):\n"
" RaisesExc(match='bar'): Regex pattern did not match.\n"
" Expected regex: 'bar'\n"
" Actual message: 'foo'\n"
" RaisesExc(match='bar'): Regex pattern did not match.\n"
" Expected regex: 'bar'\n"
" Actual message: 'foo'\n"
" RaisesExc(match='bar'): Regex pattern did not match.\n"
" Expected regex: 'bar'\n"
" Actual message: 'foo'\n"
" ValueError('foo'):\n"
" RaisesExc(match='bar'): Regex pattern did not match.\n"
" Expected regex: 'bar'\n"
" Actual message: 'foo'\n"
" RaisesExc(match='bar'): Regex pattern did not match.\n"
" Expected regex: 'bar'\n"
" Actual message: 'foo'\n"
" RaisesExc(match='bar'): Regex pattern did not match.\n"
" Expected regex: 'bar'\n"
" Actual message: 'foo'"
),
RaisesGroup(m, m, m),
):
raise ExceptionGroup("", [e, e, e])
def test_raisesexc() -> None:
with pytest.raises(
ValueError,
match=r"^You must specify at least one parameter to match on.$",
):
RaisesExc() # type: ignore[call-overload]
with pytest.raises(
ValueError,
match=wrap_escape("Expected a BaseException type, but got 'object'"),
):
RaisesExc(object) # type: ignore[type-var]
with RaisesGroup(RaisesExc(ValueError)):
raise ExceptionGroup("", (ValueError(),))
with (
fails_raises_group(
"RaisesExc(TypeError): `ValueError()` is not an instance of `TypeError`"
),
RaisesGroup(RaisesExc(TypeError)),
):
raise ExceptionGroup("", (ValueError(),))
with RaisesExc(ValueError):
raise ValueError
# FIXME: leaving this one formatted differently for now to not change
# tests in python/raises.py
with pytest.raises(Failed, match=wrap_escape("DID NOT RAISE <class 'ValueError'>")):
with RaisesExc(ValueError):
...
with pytest.raises(Failed, match=wrap_escape("DID NOT RAISE any exception")):
with RaisesExc(match="foo"):
...
with pytest.raises(
# FIXME: do we want repr(type) or type.__name__ ?
Failed,
match=wrap_escape(
"DID NOT RAISE any of (<class 'ValueError'>, <class 'TypeError'>)"
),
):
with RaisesExc((ValueError, TypeError)):
...
# currently RaisesGroup says "Raised exception did not match" but RaisesExc doesn't...
with pytest.raises(
AssertionError,
match=wrap_escape(
"Regex pattern did not match.\n Expected regex: 'foo'\n Actual message: 'bar'"
),
):
with RaisesExc(TypeError, match="foo"):
raise TypeError("bar")
def test_raisesexc_match() -> None:
with RaisesGroup(RaisesExc(ValueError, match="foo")):
raise ExceptionGroup("", (ValueError("foo"),))
with (
fails_raises_group(
"RaisesExc(ValueError, match='foo'): Regex pattern did not match.\n"
" Expected regex: 'foo'\n"
" Actual message: 'bar'"
),
RaisesGroup(RaisesExc(ValueError, match="foo")),
):
raise ExceptionGroup("", (ValueError("bar"),))
# Can be used without specifying the type
with RaisesGroup(RaisesExc(match="foo")):
raise ExceptionGroup("", (ValueError("foo"),))
with (
fails_raises_group(
"RaisesExc(match='foo'): Regex pattern did not match.\n"
" Expected regex: 'foo'\n"
" Actual message: 'bar'"
),
RaisesGroup(RaisesExc(match="foo")),
):
raise ExceptionGroup("", (ValueError("bar"),))
# check ^$
with RaisesGroup(RaisesExc(ValueError, match="^bar$")):
raise ExceptionGroup("", [ValueError("bar")])
with (
fails_raises_group(
"\nRaisesExc(ValueError, match='^bar$'): \n - barr\n ? -\n + bar"
),
RaisesGroup(RaisesExc(ValueError, match="^bar$")),
):
raise ExceptionGroup("", [ValueError("barr")])
def test_RaisesExc_check() -> None:
def check_oserror_and_errno_is_5(e: BaseException) -> bool:
return isinstance(e, OSError) and e.errno == 5
with RaisesGroup(RaisesExc(check=check_oserror_and_errno_is_5)):
raise ExceptionGroup("", (OSError(5, ""),))
# specifying exception_type narrows the parameter type to the callable
def check_errno_is_5(e: OSError) -> bool:
return e.errno == 5
with RaisesGroup(RaisesExc(OSError, check=check_errno_is_5)):
raise ExceptionGroup("", (OSError(5, ""),))
# avoid printing overly verbose repr multiple times
with (
fails_raises_group(
f"RaisesExc(OSError, check={check_errno_is_5!r}): check did not return True"
),
RaisesGroup(RaisesExc(OSError, check=check_errno_is_5)),
):
raise ExceptionGroup("", (OSError(6, ""),))
# in nested cases you still get it multiple times though
# to address this you'd need logic in RaisesExc.__repr__ and RaisesGroup.__repr__
with (
fails_raises_group(
f"RaisesGroup(RaisesExc(OSError, check={check_errno_is_5!r})): RaisesExc(OSError, check={check_errno_is_5!r}): check did not return True"
),
RaisesGroup(RaisesGroup(RaisesExc(OSError, check=check_errno_is_5))),
):
raise ExceptionGroup("", [ExceptionGroup("", [OSError(6, "")])])
def test_raisesexc_tostring() -> None:
assert str(RaisesExc(ValueError)) == "RaisesExc(ValueError)"
assert str(RaisesExc(match="[a-z]")) == "RaisesExc(match='[a-z]')"
pattern_no_flags = re.compile(r"noflag", 0)
assert str(RaisesExc(match=pattern_no_flags)) == "RaisesExc(match='noflag')"
pattern_flags = re.compile(r"noflag", re.IGNORECASE)
assert str(RaisesExc(match=pattern_flags)) == f"RaisesExc(match={pattern_flags!r})"
assert (
str(RaisesExc(ValueError, match="re", check=bool))
== f"RaisesExc(ValueError, match='re', check={bool!r})"
)
def test_raisesgroup_tostring() -> None:
def check_str_and_repr(s: str) -> None:
evaled = eval(s)
assert s == str(evaled) == repr(evaled)
check_str_and_repr("RaisesGroup(ValueError)")
check_str_and_repr("RaisesGroup(RaisesGroup(ValueError))")
check_str_and_repr("RaisesGroup(RaisesExc(ValueError))")
check_str_and_repr("RaisesGroup(ValueError, allow_unwrapped=True)")
check_str_and_repr("RaisesGroup(ValueError, match='aoeu')")
assert (
str(RaisesGroup(ValueError, match="[a-z]", check=bool))
== f"RaisesGroup(ValueError, match='[a-z]', check={bool!r})"
)
def test_assert_matches() -> None:
e = ValueError()
# it's easy to do this
assert RaisesExc(ValueError).matches(e)
# but you don't get a helpful error
with pytest.raises(AssertionError, match=r"assert False\n \+ where False = .*"):
assert RaisesExc(TypeError).matches(e)
with pytest.raises(
AssertionError,
match=wrap_escape(
"`ValueError()` is not an instance of `TypeError`\n"
"assert False\n"
" + where False = matches(ValueError())\n"
" + where matches = RaisesExc(TypeError).matches"
),
):
# you'd need to do this arcane incantation
assert (m := RaisesExc(TypeError)).matches(e), m.fail_reason
# but even if we add assert_matches, will people remember to use it?
# other than writing a linter rule, I don't think we can catch `assert RaisesExc(...).matches`
# ... no wait pytest catches other asserts ... so we probably can??
# https://github.com/pytest-dev/pytest/issues/12504
def test_xfail_raisesgroup(pytester: Pytester) -> None:
pytester.makepyfile(
"""
import sys
import pytest
if sys.version_info < (3, 11):
from exceptiongroup import ExceptionGroup
@pytest.mark.xfail(raises=pytest.RaisesGroup(ValueError))
def test_foo() -> None:
raise ExceptionGroup("foo", [ValueError()])
"""
)
result = pytester.runpytest()
result.assert_outcomes(xfailed=1)
def test_xfail_RaisesExc(pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.xfail(raises=pytest.RaisesExc(ValueError))
def test_foo() -> None:
raise ValueError
"""
)
result = pytester.runpytest()
result.assert_outcomes(xfailed=1)
@pytest.mark.parametrize(
"wrap_in_group,handler",
[
(False, pytest.raises(ValueError)),
(True, RaisesGroup(ValueError)),
],
)
def test_parametrizing_conditional_raisesgroup(
wrap_in_group: bool, handler: AbstractContextManager[ExceptionInfo[BaseException]]
) -> None:
with handler:
if wrap_in_group:
raise ExceptionGroup("", [ValueError()])
raise ValueError()
def test_annotated_group() -> None:
# repr depends on if exceptiongroup backport is being used or not
t = repr(ExceptionGroup[ValueError])
msg = "Only `ExceptionGroup[Exception]` or `BaseExceptionGroup[BaseException]` are accepted as generic types but got `{}`. As `raises` will catch all instances of the specified group regardless of the generic argument specific nested exceptions has to be checked with `RaisesGroup`."
fail_msg = wrap_escape(msg.format(t))
with pytest.raises(ValueError, match=fail_msg):
RaisesGroup(ExceptionGroup[ValueError])
with pytest.raises(ValueError, match=fail_msg):
RaisesExc(ExceptionGroup[ValueError])
with pytest.raises(
ValueError,
match=wrap_escape(msg.format(repr(BaseExceptionGroup[KeyboardInterrupt]))),
):
with RaisesExc(BaseExceptionGroup[KeyboardInterrupt]):
raise BaseExceptionGroup("", [KeyboardInterrupt()])
with RaisesGroup(ExceptionGroup[Exception]):
raise ExceptionGroup(
"", [ExceptionGroup("", [ValueError(), ValueError(), ValueError()])]
)
with RaisesExc(BaseExceptionGroup[BaseException]):
raise BaseExceptionGroup("", [KeyboardInterrupt()])
# assure AbstractRaises.is_baseexception is set properly
assert (
RaisesGroup(ExceptionGroup[Exception]).expected_type()
== "ExceptionGroup(ExceptionGroup)"
)
assert (
RaisesGroup(BaseExceptionGroup[BaseException]).expected_type()
== "BaseExceptionGroup(BaseExceptionGroup)"
)
def test_tuples() -> None:
# raises has historically supported one of several exceptions being raised
with pytest.raises((ValueError, IndexError)):
raise ValueError
# so now RaisesExc also does
with RaisesExc((ValueError, IndexError)):
raise IndexError
# but RaisesGroup currently doesn't. There's an argument it shouldn't because
# it can be confusing - RaisesGroup((ValueError, TypeError)) looks a lot like
# RaisesGroup(ValueError, TypeError), and the former might be interpreted as the latter.
with pytest.raises(
TypeError,
match=wrap_escape(
"Expected a BaseException type, RaisesExc, or RaisesGroup, but got 'tuple'.\n"
"RaisesGroup does not support tuples of exception types when expecting one of "
"several possible exception types like RaisesExc.\n"
"If you meant to expect a group with multiple exceptions, list them as separate arguments."
),
):
RaisesGroup((ValueError, IndexError)) # type: ignore[call-overload]
|