ybelkada HF Staff commited on
Commit
8806156
·
verified ·
1 Parent(s): 173ff5a

Harbor format: 871 coding_baseline tasks (part 11)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/panel-config.json +26 -0
  2. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/test.sh +6 -0
  3. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted-inventory.json +62 -0
  4. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/pyproject.toml +111 -0
  5. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/__init__.py +0 -0
  6. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/apport_excepthook.py +13 -0
  7. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/check_types.py +36 -0
  8. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/conftest.py +4 -0
  9. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_apport_monkeypatching.py +63 -0
  10. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_catch.py +222 -0
  11. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_catch_py311.py +190 -0
  12. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_exceptions.py +845 -0
  13. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_formatting.py +558 -0
  14. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_suppress.py +16 -0
  15. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/canaries/first-hunk-only.sh +21 -0
  16. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/canaries/original-bug.sh +3 -0
  17. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/openenv.json +27 -0
  18. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/LICENSE.source +73 -0
  19. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/adapter.json +133 -0
  20. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/dependency-setup.sh +9 -0
  21. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/environment/Dockerfile +3 -0
  22. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/instruction.md +35 -0
  23. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/metadata.json +237 -0
  24. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/provenance.json +88 -0
  25. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/provided-gold.diff +90 -0
  26. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/solution/solve.sh +96 -0
  27. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/task.toml +24 -0
  28. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/check_pytest.py +177 -0
  29. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/expected-panels.json +95 -0
  30. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/grade.py +128 -0
  31. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/panel-config.json +26 -0
  32. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/test.sh +6 -0
  33. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted-inventory.json +62 -0
  34. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/pyproject.toml +111 -0
  35. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/__init__.py +0 -0
  36. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/apport_excepthook.py +13 -0
  37. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/check_types.py +36 -0
  38. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/conftest.py +4 -0
  39. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_apport_monkeypatching.py +63 -0
  40. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_catch.py +222 -0
  41. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_catch_py311.py +190 -0
  42. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_exceptions.py +845 -0
  43. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_formatting.py +558 -0
  44. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_suppress.py +16 -0
  45. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/canaries/first-hunk-only.sh +71 -0
  46. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/canaries/original-bug.sh +3 -0
  47. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/openenv.json +27 -0
  48. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/LICENSE.source +73 -0
  49. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/adapter.json +133 -0
  50. tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/dependency-setup.sh +9 -0
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/panel-config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dependency_installation_pinned": false,
3
+ "official_install_cmds": [
4
+ "python -m pip install -e ."
5
+ ],
6
+ "official_pytest_argv": [
7
+ "pytest",
8
+ "--disable-warnings",
9
+ "--color=no",
10
+ "--tb=no",
11
+ "--verbose"
12
+ ],
13
+ "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose",
14
+ "operator_test_runner_prerequisites": [
15
+ "python -m pip install pytest==8.4.2"
16
+ ],
17
+ "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.",
18
+ "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.",
19
+ "python_version": "3.10",
20
+ "source_bound_test_dependency_cmds": [
21
+ "python -m pip install -e '.[test]'"
22
+ ],
23
+ "test_dependency_source_sha256": {
24
+ "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5"
25
+ }
26
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/test.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -Eeuo pipefail
3
+ source /opt/miniconda3/bin/activate
4
+ conda activate testbed
5
+ cd /testbed/repo
6
+ exec python -I /tests/grade.py
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted-inventory.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "directory_roots": [
3
+ "tests"
4
+ ],
5
+ "files": {
6
+ "pyproject.toml": {
7
+ "bytes": 2630,
8
+ "mode": 420,
9
+ "sha256": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5"
10
+ },
11
+ "tests/__init__.py": {
12
+ "bytes": 0,
13
+ "mode": 420,
14
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
15
+ },
16
+ "tests/apport_excepthook.py": {
17
+ "bytes": 466,
18
+ "mode": 420,
19
+ "sha256": "5b5a85531a20839ff1c624a2b5a8eb2d00b41e5a5c467b037daa9f23acbb126d"
20
+ },
21
+ "tests/check_types.py": {
22
+ "bytes": 1025,
23
+ "mode": 420,
24
+ "sha256": "07bc5f001f4194d6910999aa5c76c5d2e99a3274fa970f77015c0ed7cebf5fea"
25
+ },
26
+ "tests/conftest.py": {
27
+ "bytes": 84,
28
+ "mode": 420,
29
+ "sha256": "10fde0caa2257622444f0452ba321c9a34349d7d50dad6291ab189ea31033381"
30
+ },
31
+ "tests/test_apport_monkeypatching.py": {
32
+ "bytes": 1925,
33
+ "mode": 420,
34
+ "sha256": "50bddad2c699f04e60f757d00b4071bde931d8583cbdd39a0b24f29cb174f138"
35
+ },
36
+ "tests/test_catch.py": {
37
+ "bytes": 7163,
38
+ "mode": 420,
39
+ "sha256": "9e19d73b5eb2796eb2bacc1cae633f63f85b6a0179fd80645b2e26340ae53f80"
40
+ },
41
+ "tests/test_catch_py311.py": {
42
+ "bytes": 5958,
43
+ "mode": 420,
44
+ "sha256": "bdcee13b4edcef13bdf5a8c8ea1ff19480267fc9c2cfd6493b85b84c1c03325e"
45
+ },
46
+ "tests/test_exceptions.py": {
47
+ "bytes": 31247,
48
+ "mode": 420,
49
+ "sha256": "254cc73bddbd8e9903d1fe1b0403f3b7eb5af337acd16557ed445ad0ee72f747"
50
+ },
51
+ "tests/test_formatting.py": {
52
+ "bytes": 19274,
53
+ "mode": 420,
54
+ "sha256": "d1d4252253b81ca7bc2f5a00605e9ceeb82b4d3348eccd9331b0c2251a07da7b"
55
+ },
56
+ "tests/test_suppress.py": {
57
+ "bytes": 442,
58
+ "mode": 420,
59
+ "sha256": "d166b2e9aac0d9983afe8894aa10904c8b57b7977100df0cb2b0799d07f309fc"
60
+ }
61
+ }
62
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/pyproject.toml ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["flit_scm"]
3
+ build-backend = "flit_scm:buildapi"
4
+
5
+ [project]
6
+ name = "exceptiongroup"
7
+ description = "Backport of PEP 654 (exception groups)"
8
+ readme = "README.rst"
9
+ classifiers = [
10
+ "Development Status :: 5 - Production/Stable",
11
+ "Intended Audience :: Developers",
12
+ "License :: OSI Approved :: MIT License",
13
+ "Programming Language :: Python",
14
+ "Programming Language :: Python :: 3 :: Only",
15
+ "Typing :: Typed"
16
+ ]
17
+ authors = [{name = "Alex Grönholm", email = "alex.gronholm@nextday.fi"}]
18
+ license = {file = "LICENSE"}
19
+ requires-python = ">=3.7"
20
+ dynamic = ["version"]
21
+
22
+ [project.urls]
23
+ Changelog = "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst"
24
+ "Source code" = "https://github.com/agronholm/exceptiongroup"
25
+ "Issue Tracker" = "https://github.com/agronholm/exceptiongroup/issues"
26
+
27
+ [project.optional-dependencies]
28
+ test = [
29
+ "pytest >= 6"
30
+ ]
31
+
32
+ [tool.flit.sdist]
33
+ include = [
34
+ "CHANGES.rst",
35
+ "tests",
36
+ ]
37
+ exclude = [
38
+ ".github/*",
39
+ ".gitignore",
40
+ ".pre-commit-config.yaml"
41
+ ]
42
+
43
+ [tool.setuptools_scm]
44
+ version_scheme = "post-release"
45
+ local_scheme = "dirty-tag"
46
+ write_to = "src/exceptiongroup/_version.py"
47
+
48
+ [tool.ruff.lint]
49
+ extend-select = [
50
+ "I", # isort
51
+ "ISC", # flake8-implicit-str-concat
52
+ "PGH", # pygrep-hooks
53
+ "RUF100", # unused noqa (yesqa)
54
+ "UP", # pyupgrade
55
+ "W", # pycodestyle warnings
56
+ ]
57
+
58
+ [tool.ruff.lint.pyupgrade]
59
+ # Preserve types, even if a file imports `from __future__ import annotations`.
60
+ keep-runtime-typing = true
61
+
62
+ [tool.ruff.lint.isort]
63
+ known-first-party = ["exceptiongroup"]
64
+
65
+ [tool.pytest.ini_options]
66
+ addopts = "-rsx --tb=short --strict-config --strict-markers"
67
+ testpaths = ["tests"]
68
+
69
+ [tool.coverage.run]
70
+ source = ["exceptiongroup"]
71
+ relative_files = true
72
+
73
+ [tool.coverage.report]
74
+ exclude_also = [
75
+ "if TYPE_CHECKING:",
76
+ "@overload",
77
+ ]
78
+
79
+ [tool.pyright]
80
+ # for type tests, the code itself isn't type checked in CI
81
+ reportUnnecessaryTypeIgnoreComment = true
82
+
83
+ [tool.mypy]
84
+ # for type tests, the code itself isn't type checked in CI
85
+ warn_unused_ignores = true
86
+
87
+ [tool.tox]
88
+ legacy_tox_ini = """
89
+ [tox]
90
+ envlist = py37, py38, py39, py310, py311, py312, py313, pypy3
91
+ labels =
92
+ typing = py{310,311,312}-typing
93
+ skip_missing_interpreters = true
94
+ minversion = 4.0
95
+
96
+ [testenv]
97
+ extras = test
98
+ commands = python -m pytest {posargs}
99
+ package = editable
100
+ usedevelop = true
101
+
102
+ [testenv:{py37-,py38-,py39-,py310-,py311-,py312-,}typing]
103
+ deps =
104
+ pyright
105
+ mypy
106
+ commands =
107
+ pyright --verifytypes exceptiongroup
108
+ pyright tests/check_types.py
109
+ mypy tests/check_types.py
110
+ usedevelop = true
111
+ """
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/__init__.py ADDED
File without changes
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/apport_excepthook.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The apport_python_hook package is only installed as part of Ubuntu's system
2
+ # python, and not available in venvs. So before we can import it we have to
3
+ # make sure it's on sys.path.
4
+ import sys
5
+
6
+ sys.path.append("/usr/lib/python3/dist-packages")
7
+ import apport_python_hook # unsorted import
8
+
9
+ apport_python_hook.install()
10
+
11
+ from exceptiongroup import ExceptionGroup # noqa: E402 # unsorted import
12
+
13
+ raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")])
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/check_types.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing_extensions import assert_type
2
+
3
+ from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch, suppress
4
+
5
+ # issue 117
6
+ a = BaseExceptionGroup("", (KeyboardInterrupt(),))
7
+ assert_type(a, BaseExceptionGroup[KeyboardInterrupt])
8
+ b = BaseExceptionGroup("", (ValueError(),))
9
+ assert_type(b, BaseExceptionGroup[ValueError])
10
+ c = ExceptionGroup("", (ValueError(),))
11
+ assert_type(c, ExceptionGroup[ValueError])
12
+
13
+ # expected type error when passing a BaseException to ExceptionGroup
14
+ ExceptionGroup("", (KeyboardInterrupt(),)) # type: ignore[type-var]
15
+
16
+
17
+ # code snippets from the README
18
+
19
+
20
+ def value_key_err_handler(excgroup: BaseExceptionGroup) -> None:
21
+ for exc in excgroup.exceptions:
22
+ print("Caught exception:", type(exc))
23
+
24
+
25
+ def runtime_err_handler(exc: BaseExceptionGroup) -> None:
26
+ print("Caught runtime error")
27
+
28
+
29
+ with catch(
30
+ {(ValueError, KeyError): value_key_err_handler, RuntimeError: runtime_err_handler}
31
+ ):
32
+ ...
33
+
34
+
35
+ with suppress(RuntimeError):
36
+ raise ExceptionGroup("", [RuntimeError("boo")])
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/conftest.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import sys
2
+
3
+ if sys.version_info < (3, 11):
4
+ collect_ignore_glob = ["*_py311.py"]
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_apport_monkeypatching.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ import exceptiongroup
11
+
12
+
13
+ def run_script(name: str) -> subprocess.CompletedProcess[bytes]:
14
+ exceptiongroup_path = Path(exceptiongroup.__file__).parent.parent
15
+ script_path = Path(__file__).parent / name
16
+
17
+ env = dict(os.environ)
18
+ print("parent PYTHONPATH:", env.get("PYTHONPATH"))
19
+ if "PYTHONPATH" in env: # pragma: no cover
20
+ pp = env["PYTHONPATH"].split(os.pathsep)
21
+ else:
22
+ pp = []
23
+
24
+ pp.insert(0, str(exceptiongroup_path))
25
+ pp.insert(0, str(script_path.parent))
26
+ env["PYTHONPATH"] = os.pathsep.join(pp)
27
+ print("subprocess PYTHONPATH:", env.get("PYTHONPATH"))
28
+
29
+ cmd = [sys.executable, "-u", str(script_path)]
30
+ print("running:", cmd)
31
+ completed = subprocess.run(
32
+ cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
33
+ )
34
+ print("process output:")
35
+ print(completed.stdout.decode("utf-8"))
36
+ return completed
37
+
38
+
39
+ @pytest.mark.skipif(
40
+ sys.version_info > (3, 11),
41
+ reason="No patching is done on Python >= 3.11",
42
+ )
43
+ @pytest.mark.skipif(
44
+ not Path("/usr/lib/python3/dist-packages/apport_python_hook.py").exists(),
45
+ reason="need Ubuntu with python3-apport installed",
46
+ )
47
+ def test_apport_excepthook_monkeypatch_interaction():
48
+ completed = run_script("apport_excepthook.py")
49
+ stdout = completed.stdout.decode("utf-8")
50
+ file = Path(__file__).parent / "apport_excepthook.py"
51
+ assert stdout == (
52
+ f"""\
53
+ + Exception Group Traceback (most recent call last):
54
+ | File "{file}", line 13, in <module>
55
+ | raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")])
56
+ | exceptiongroup.ExceptionGroup: msg1 (2 sub-exceptions)
57
+ +-+---------------- 1 ----------------
58
+ | KeyError: 'msg2'
59
+ +---------------- 2 ----------------
60
+ | ValueError: msg3
61
+ +------------------------------------
62
+ """
63
+ )
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_catch.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch
4
+
5
+
6
+ def test_bad_arg():
7
+ with pytest.raises(TypeError, match="the argument must be a mapping"):
8
+ with catch(1):
9
+ pass
10
+
11
+
12
+ def test_bad_handler():
13
+ with pytest.raises(TypeError, match="handlers must be callable"):
14
+ with catch({RuntimeError: None}):
15
+ pass
16
+
17
+
18
+ @pytest.mark.parametrize(
19
+ "exc_type",
20
+ [
21
+ pytest.param(BaseExceptionGroup, id="naked_basegroup"),
22
+ pytest.param(ExceptionGroup, id="naked_group"),
23
+ pytest.param((ValueError, BaseExceptionGroup), id="iterable_basegroup"),
24
+ pytest.param((ValueError, ExceptionGroup), id="iterable_group"),
25
+ ],
26
+ )
27
+ def test_catch_exceptiongroup(exc_type):
28
+ with pytest.raises(TypeError, match="catching ExceptionGroup with catch"):
29
+ with catch({exc_type: (lambda e: True)}):
30
+ pass
31
+
32
+
33
+ def test_catch_ungrouped():
34
+ value_type_errors = []
35
+ zero_division_errors = []
36
+ for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]:
37
+ with catch(
38
+ {
39
+ (ValueError, TypeError): value_type_errors.append,
40
+ ZeroDivisionError: zero_division_errors.append,
41
+ }
42
+ ):
43
+ raise exc
44
+
45
+ assert len(value_type_errors) == 2
46
+
47
+ assert isinstance(value_type_errors[0], ExceptionGroup)
48
+ assert len(value_type_errors[0].exceptions) == 1
49
+ assert isinstance(value_type_errors[0].exceptions[0], ValueError)
50
+
51
+ assert isinstance(value_type_errors[1], ExceptionGroup)
52
+ assert len(value_type_errors[1].exceptions) == 1
53
+ assert isinstance(value_type_errors[1].exceptions[0], TypeError)
54
+
55
+ assert len(zero_division_errors) == 1
56
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
57
+ assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError)
58
+ assert len(zero_division_errors[0].exceptions) == 1
59
+
60
+
61
+ def test_catch_group():
62
+ value_runtime_errors = []
63
+ zero_division_errors = []
64
+ with catch(
65
+ {
66
+ (ValueError, RuntimeError): value_runtime_errors.append,
67
+ ZeroDivisionError: zero_division_errors.append,
68
+ }
69
+ ):
70
+ raise ExceptionGroup(
71
+ "booboo",
72
+ [
73
+ ValueError("foo"),
74
+ ValueError("bar"),
75
+ RuntimeError("bar"),
76
+ ZeroDivisionError(),
77
+ ],
78
+ )
79
+
80
+ assert len(value_runtime_errors) == 1
81
+ assert isinstance(value_runtime_errors[0], ExceptionGroup)
82
+ exceptions = value_runtime_errors[0].exceptions
83
+ assert isinstance(exceptions[0], ValueError)
84
+ assert isinstance(exceptions[1], ValueError)
85
+ assert isinstance(exceptions[2], RuntimeError)
86
+
87
+ assert len(zero_division_errors) == 1
88
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
89
+ exceptions = zero_division_errors[0].exceptions
90
+ assert isinstance(exceptions[0], ZeroDivisionError)
91
+
92
+
93
+ def test_catch_nested_group():
94
+ value_runtime_errors = []
95
+ zero_division_errors = []
96
+ with catch(
97
+ {
98
+ (ValueError, RuntimeError): value_runtime_errors.append,
99
+ ZeroDivisionError: zero_division_errors.append,
100
+ }
101
+ ):
102
+ nested_group = ExceptionGroup(
103
+ "nested", [RuntimeError("bar"), ZeroDivisionError()]
104
+ )
105
+ raise ExceptionGroup("booboo", [ValueError("foo"), nested_group])
106
+
107
+ assert len(value_runtime_errors) == 1
108
+ exceptions = value_runtime_errors[0].exceptions
109
+ assert isinstance(exceptions[0], ValueError)
110
+ assert isinstance(exceptions[1], ExceptionGroup)
111
+ assert isinstance(exceptions[1].exceptions[0], RuntimeError)
112
+
113
+ assert len(zero_division_errors) == 1
114
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
115
+ assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup)
116
+ assert isinstance(
117
+ zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError
118
+ )
119
+
120
+
121
+ def test_catch_no_match():
122
+ try:
123
+ with catch({(ValueError, RuntimeError): (lambda e: None)}):
124
+ group = ExceptionGroup("booboo", [ZeroDivisionError()])
125
+ raise group
126
+ except ExceptionGroup as exc:
127
+ assert exc is not group
128
+ else:
129
+ pytest.fail("Did not raise an ExceptionGroup")
130
+
131
+
132
+ def test_catch_single_no_match():
133
+ try:
134
+ with catch({(ValueError, RuntimeError): (lambda e: None)}):
135
+ raise ZeroDivisionError
136
+ except ZeroDivisionError:
137
+ pass
138
+ else:
139
+ pytest.fail("Did not raise an ZeroDivisionError")
140
+
141
+
142
+ def test_catch_full_match():
143
+ with catch({(ValueError, RuntimeError): (lambda e: None)}):
144
+ raise ExceptionGroup("booboo", [ValueError()])
145
+
146
+
147
+ def test_catch_handler_raises():
148
+ def handler(exc):
149
+ raise RuntimeError("new")
150
+
151
+ with pytest.raises(RuntimeError, match="new") as exc:
152
+ with catch({(ValueError, ValueError): handler}):
153
+ excgrp = ExceptionGroup("booboo", [ValueError("bar")])
154
+ raise excgrp
155
+
156
+ context = exc.value.__context__
157
+ assert isinstance(context, ExceptionGroup)
158
+ assert str(context) == "booboo (1 sub-exception)"
159
+ assert len(context.exceptions) == 1
160
+ assert isinstance(context.exceptions[0], ValueError)
161
+ assert exc.value.__cause__ is None
162
+
163
+
164
+ def test_bare_raise_in_handler():
165
+ """Test that a bare "raise" "middle" ecxeption group gets discarded."""
166
+
167
+ def handler(exc):
168
+ raise
169
+
170
+ with pytest.raises(ExceptionGroup) as excgrp:
171
+ with catch({(ValueError,): handler, (RuntimeError,): lambda eg: None}):
172
+ try:
173
+ first_exc = RuntimeError("first")
174
+ raise first_exc
175
+ except RuntimeError as exc:
176
+ middle_exc = ExceptionGroup(
177
+ "bad", [ValueError(), ValueError(), TypeError()]
178
+ )
179
+ raise middle_exc from exc
180
+
181
+ assert len(excgrp.value.exceptions) == 2
182
+ assert all(isinstance(exc, ValueError) for exc in excgrp.value.exceptions)
183
+ assert excgrp.value is not middle_exc
184
+ assert excgrp.value.__cause__ is first_exc
185
+ assert excgrp.value.__context__ is first_exc
186
+
187
+
188
+ def test_catch_subclass():
189
+ lookup_errors = []
190
+ with catch({LookupError: lookup_errors.append}):
191
+ raise KeyError("foo")
192
+
193
+ assert len(lookup_errors) == 1
194
+ assert isinstance(lookup_errors[0], ExceptionGroup)
195
+ exceptions = lookup_errors[0].exceptions
196
+ assert isinstance(exceptions[0], KeyError)
197
+
198
+
199
+ def test_async_handler(request):
200
+ async def handler(eg):
201
+ pass
202
+
203
+ def delegate(eg):
204
+ coro = handler(eg)
205
+ request.addfinalizer(coro.close)
206
+ return coro
207
+
208
+ with pytest.raises(TypeError, match="Exception handler must be a sync function."):
209
+ with catch({TypeError: delegate}):
210
+ raise ExceptionGroup("message", [TypeError("uh-oh")])
211
+
212
+
213
+ def test_bare_reraise_from_naked_exception():
214
+ def handler(eg):
215
+ raise
216
+
217
+ with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}):
218
+ raise KeyError("foo")
219
+
220
+ assert len(excgrp.value.exceptions) == 1
221
+ assert isinstance(excgrp.value.exceptions[0], KeyError)
222
+ assert str(excgrp.value.exceptions[0]) == "'foo'"
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_catch_py311.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ from exceptiongroup import ExceptionGroup
6
+
7
+
8
+ def test_catch_ungrouped():
9
+ value_type_errors = []
10
+ zero_division_errors = []
11
+ for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]:
12
+ try:
13
+ raise exc
14
+ except* (ValueError, TypeError) as e:
15
+ value_type_errors.append(e)
16
+ except* ZeroDivisionError as e:
17
+ zero_division_errors.append(e)
18
+
19
+ assert len(value_type_errors) == 2
20
+
21
+ assert isinstance(value_type_errors[0], ExceptionGroup)
22
+ assert len(value_type_errors[0].exceptions) == 1
23
+ assert isinstance(value_type_errors[0].exceptions[0], ValueError)
24
+
25
+ assert isinstance(value_type_errors[1], ExceptionGroup)
26
+ assert len(value_type_errors[1].exceptions) == 1
27
+ assert isinstance(value_type_errors[1].exceptions[0], TypeError)
28
+
29
+ assert len(zero_division_errors) == 1
30
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
31
+ assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError)
32
+ assert len(zero_division_errors[0].exceptions) == 1
33
+
34
+
35
+ def test_catch_group():
36
+ value_runtime_errors = []
37
+ zero_division_errors = []
38
+ try:
39
+ raise ExceptionGroup(
40
+ "booboo",
41
+ [
42
+ ValueError("foo"),
43
+ ValueError("bar"),
44
+ RuntimeError("bar"),
45
+ ZeroDivisionError(),
46
+ ],
47
+ )
48
+ except* (ValueError, RuntimeError) as exc:
49
+ value_runtime_errors.append(exc)
50
+ except* ZeroDivisionError as exc:
51
+ zero_division_errors.append(exc)
52
+
53
+ assert len(value_runtime_errors) == 1
54
+ assert isinstance(value_runtime_errors[0], ExceptionGroup)
55
+ exceptions = value_runtime_errors[0].exceptions
56
+ assert isinstance(exceptions[0], ValueError)
57
+ assert isinstance(exceptions[1], ValueError)
58
+ assert isinstance(exceptions[2], RuntimeError)
59
+
60
+ assert len(zero_division_errors) == 1
61
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
62
+ exceptions = zero_division_errors[0].exceptions
63
+ assert isinstance(exceptions[0], ZeroDivisionError)
64
+
65
+
66
+ def test_catch_nested_group():
67
+ value_runtime_errors = []
68
+ zero_division_errors = []
69
+ try:
70
+ nested_group = ExceptionGroup(
71
+ "nested", [RuntimeError("bar"), ZeroDivisionError()]
72
+ )
73
+ raise ExceptionGroup("booboo", [ValueError("foo"), nested_group])
74
+ except* (ValueError, RuntimeError) as exc:
75
+ value_runtime_errors.append(exc)
76
+ except* ZeroDivisionError as exc:
77
+ zero_division_errors.append(exc)
78
+
79
+ assert len(value_runtime_errors) == 1
80
+ exceptions = value_runtime_errors[0].exceptions
81
+ assert isinstance(exceptions[0], ValueError)
82
+ assert isinstance(exceptions[1], ExceptionGroup)
83
+ assert isinstance(exceptions[1].exceptions[0], RuntimeError)
84
+
85
+ assert len(zero_division_errors) == 1
86
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
87
+ assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup)
88
+ assert isinstance(
89
+ zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError
90
+ )
91
+
92
+
93
+ def test_catch_no_match():
94
+ try:
95
+ try:
96
+ group = ExceptionGroup("booboo", [ZeroDivisionError()])
97
+ raise group
98
+ except* (ValueError, RuntimeError):
99
+ pass
100
+ except ExceptionGroup as exc:
101
+ assert isinstance(exc.exceptions[0], ZeroDivisionError)
102
+ assert exc is not group
103
+ else:
104
+ pytest.fail("Did not raise an ExceptionGroup")
105
+
106
+
107
+ def test_catch_single_no_match():
108
+ try:
109
+ try:
110
+ raise ZeroDivisionError
111
+ except* (ValueError, RuntimeError):
112
+ pass
113
+ except ZeroDivisionError:
114
+ pass
115
+ else:
116
+ pytest.fail("Did not raise an ZeroDivisionError")
117
+
118
+
119
+ def test_catch_full_match():
120
+ try:
121
+ raise ExceptionGroup("booboo", [ValueError()])
122
+ except* (ValueError, RuntimeError):
123
+ pass
124
+
125
+
126
+ @pytest.mark.skipif(
127
+ sys.version_info < (3, 11, 4),
128
+ reason="Behavior was changed in 3.11.4",
129
+ )
130
+ def test_catch_handler_raises():
131
+ with pytest.raises(RuntimeError, match="new") as exc:
132
+ try:
133
+ excgrp = ExceptionGroup("booboo", [ValueError("bar")])
134
+ raise excgrp
135
+ except* ValueError:
136
+ raise RuntimeError("new")
137
+
138
+ context = exc.value.__context__
139
+ assert isinstance(context, ExceptionGroup)
140
+ assert str(context) == "booboo (1 sub-exception)"
141
+ assert len(context.exceptions) == 1
142
+ assert isinstance(context.exceptions[0], ValueError)
143
+ assert exc.value.__cause__ is None
144
+
145
+
146
+ def test_catch_subclass():
147
+ lookup_errors = []
148
+ try:
149
+ raise KeyError("foo")
150
+ except* LookupError as e:
151
+ lookup_errors.append(e)
152
+
153
+ assert len(lookup_errors) == 1
154
+ assert isinstance(lookup_errors[0], ExceptionGroup)
155
+ exceptions = lookup_errors[0].exceptions
156
+ assert isinstance(exceptions[0], KeyError)
157
+
158
+
159
+ def test_bare_raise_in_handler():
160
+ """Test that the "middle" ecxeption group gets discarded."""
161
+ with pytest.raises(ExceptionGroup) as excgrp:
162
+ try:
163
+ try:
164
+ first_exc = RuntimeError("first")
165
+ raise first_exc
166
+ except RuntimeError as exc:
167
+ middle_exc = ExceptionGroup(
168
+ "bad", [ValueError(), ValueError(), TypeError()]
169
+ )
170
+ raise middle_exc from exc
171
+ except* ValueError:
172
+ raise
173
+ except* TypeError:
174
+ pass
175
+
176
+ assert excgrp.value is not middle_exc
177
+ assert excgrp.value.__cause__ is first_exc
178
+ assert excgrp.value.__context__ is first_exc
179
+
180
+
181
+ def test_bare_reraise_from_naked_exception():
182
+ with pytest.raises(ExceptionGroup) as excgrp:
183
+ try:
184
+ raise KeyError("foo")
185
+ except* KeyError:
186
+ raise
187
+
188
+ assert len(excgrp.value.exceptions) == 1
189
+ assert isinstance(excgrp.value.exceptions[0], KeyError)
190
+ assert str(excgrp.value.exceptions[0]) == "'foo'"
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_exceptions.py ADDED
@@ -0,0 +1,845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from the standard library
2
+ import collections.abc
3
+ import sys
4
+ import unittest
5
+
6
+ import pytest
7
+
8
+ from exceptiongroup import BaseExceptionGroup, ExceptionGroup
9
+
10
+
11
+ class TestExceptionGroupTypeHierarchy(unittest.TestCase):
12
+ def test_exception_group_types(self):
13
+ self.assertTrue(issubclass(ExceptionGroup, Exception))
14
+ self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup))
15
+ self.assertTrue(issubclass(BaseExceptionGroup, BaseException))
16
+
17
+ def test_exception_group_is_generic_type(self):
18
+ E = OSError
19
+ self.assertEqual(ExceptionGroup[E].__origin__, ExceptionGroup)
20
+ self.assertEqual(BaseExceptionGroup[E].__origin__, BaseExceptionGroup)
21
+
22
+
23
+ class BadConstructorArgs(unittest.TestCase):
24
+ def test_bad_EG_construction__too_few_args(self):
25
+ if sys.version_info >= (3, 11):
26
+ MSG = (
27
+ r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(1 given\)"
28
+ )
29
+ else:
30
+ MSG = (
31
+ r"__new__\(\) missing 1 required positional argument: "
32
+ r"'_ExceptionGroup__exceptions'"
33
+ )
34
+
35
+ with self.assertRaisesRegex(TypeError, MSG):
36
+ ExceptionGroup("no errors")
37
+ with self.assertRaisesRegex(TypeError, MSG):
38
+ ExceptionGroup([ValueError("no msg")])
39
+
40
+ def test_bad_EG_construction__too_many_args(self):
41
+ if sys.version_info >= (3, 11):
42
+ MSG = (
43
+ r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(3 given\)"
44
+ )
45
+ else:
46
+ MSG = r"__new__\(\) takes 3 positional arguments but 4 were given"
47
+
48
+ with self.assertRaisesRegex(TypeError, MSG):
49
+ ExceptionGroup("eg", [ValueError("too")], [TypeError("many")])
50
+
51
+ def test_bad_EG_construction__bad_message(self):
52
+ MSG = "argument 1 must be str, not "
53
+ with self.assertRaisesRegex(TypeError, MSG):
54
+ ExceptionGroup(ValueError(12), SyntaxError("bad syntax"))
55
+ with self.assertRaisesRegex(TypeError, MSG):
56
+ ExceptionGroup(None, [ValueError(12)])
57
+
58
+ def test_bad_EG_construction__bad_excs_sequence(self):
59
+ MSG = r"second argument \(exceptions\) must be a sequence"
60
+ with self.assertRaisesRegex(TypeError, MSG):
61
+ ExceptionGroup("errors not sequence", {ValueError(42)})
62
+ with self.assertRaisesRegex(TypeError, MSG):
63
+ ExceptionGroup("eg", None)
64
+
65
+ MSG = r"second argument \(exceptions\) must be a non-empty sequence"
66
+ with self.assertRaisesRegex(ValueError, MSG):
67
+ ExceptionGroup("eg", [])
68
+
69
+ def test_bad_EG_construction__nested_non_exceptions(self):
70
+ MSG = r"Item [0-9]+ of second argument \(exceptions\) is not an exception"
71
+ with self.assertRaisesRegex(ValueError, MSG):
72
+ ExceptionGroup("expect instance, not type", [OSError])
73
+ with self.assertRaisesRegex(ValueError, MSG):
74
+ ExceptionGroup("bad error", ["not an exception"])
75
+
76
+
77
+ class InstanceCreation(unittest.TestCase):
78
+ def test_EG_wraps_Exceptions__creates_EG(self):
79
+ excs = [ValueError(1), TypeError(2)]
80
+ self.assertIs(type(ExceptionGroup("eg", excs)), ExceptionGroup)
81
+
82
+ def test_BEG_wraps_Exceptions__creates_EG(self):
83
+ excs = [ValueError(1), TypeError(2)]
84
+ self.assertIs(type(BaseExceptionGroup("beg", excs)), ExceptionGroup)
85
+
86
+ def test_EG_wraps_BaseException__raises_TypeError(self):
87
+ MSG = "Cannot nest BaseExceptions in an ExceptionGroup"
88
+ with self.assertRaisesRegex(TypeError, MSG):
89
+ ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)])
90
+
91
+ def test_BEG_wraps_BaseException__creates_BEG(self):
92
+ beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)])
93
+ self.assertIs(type(beg), BaseExceptionGroup)
94
+
95
+ def test_EG_subclass_wraps_non_base_exceptions(self):
96
+ class MyEG(ExceptionGroup):
97
+ pass
98
+
99
+ self.assertIs(type(MyEG("eg", [ValueError(12), TypeError(42)])), MyEG)
100
+
101
+ @pytest.mark.skipif(
102
+ sys.version_info[:3] == (3, 11, 0),
103
+ reason="Behavior was made stricter in 3.11.1",
104
+ )
105
+ def test_EG_subclass_does_not_wrap_base_exceptions(self):
106
+ class MyEG(ExceptionGroup):
107
+ pass
108
+
109
+ msg = "Cannot nest BaseExceptions in 'MyEG'"
110
+ with self.assertRaisesRegex(TypeError, msg):
111
+ MyEG("eg", [ValueError(12), KeyboardInterrupt(42)])
112
+
113
+ @pytest.mark.skipif(
114
+ sys.version_info[:3] == (3, 11, 0),
115
+ reason="Behavior was made stricter in 3.11.1",
116
+ )
117
+ def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self):
118
+ class MyEG(BaseExceptionGroup, ValueError):
119
+ pass
120
+
121
+ msg = "Cannot nest BaseExceptions in 'MyEG'"
122
+ with self.assertRaisesRegex(TypeError, msg):
123
+ MyEG("eg", [ValueError(12), KeyboardInterrupt(42)])
124
+
125
+
126
+ def create_simple_eg():
127
+ excs = []
128
+ try:
129
+ try:
130
+ raise MemoryError("context and cause for ValueError(1)")
131
+ except MemoryError as e:
132
+ raise ValueError(1) from e
133
+ except ValueError as e:
134
+ excs.append(e)
135
+
136
+ try:
137
+ try:
138
+ raise OSError("context for TypeError")
139
+ except OSError:
140
+ raise TypeError(int)
141
+ except TypeError as e:
142
+ excs.append(e)
143
+
144
+ try:
145
+ try:
146
+ raise ImportError("context for ValueError(2)")
147
+ except ImportError:
148
+ raise ValueError(2)
149
+ except ValueError as e:
150
+ excs.append(e)
151
+
152
+ try:
153
+ raise ExceptionGroup("simple eg", excs)
154
+ except ExceptionGroup as e:
155
+ return e
156
+
157
+
158
+ class ExceptionGroupFields(unittest.TestCase):
159
+ def test_basics_ExceptionGroup_fields(self):
160
+ eg = create_simple_eg()
161
+
162
+ # check msg
163
+ self.assertEqual(eg.message, "simple eg")
164
+ self.assertEqual(eg.args[0], "simple eg")
165
+
166
+ # check cause and context
167
+ self.assertIsInstance(eg.exceptions[0], ValueError)
168
+ self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError)
169
+ self.assertIsInstance(eg.exceptions[0].__context__, MemoryError)
170
+ self.assertIsInstance(eg.exceptions[1], TypeError)
171
+ self.assertIsNone(eg.exceptions[1].__cause__)
172
+ self.assertIsInstance(eg.exceptions[1].__context__, OSError)
173
+ self.assertIsInstance(eg.exceptions[2], ValueError)
174
+ self.assertIsNone(eg.exceptions[2].__cause__)
175
+ self.assertIsInstance(eg.exceptions[2].__context__, ImportError)
176
+
177
+ # check tracebacks
178
+ line0 = create_simple_eg.__code__.co_firstlineno
179
+ tb_linenos = [line0 + 27, [line0 + 6, line0 + 14, line0 + 22]]
180
+ self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0])
181
+ self.assertIsNone(eg.__traceback__.tb_next)
182
+ for i in range(3):
183
+ tb = eg.exceptions[i].__traceback__
184
+ self.assertIsNone(tb.tb_next)
185
+ self.assertEqual(tb.tb_lineno, tb_linenos[1][i])
186
+
187
+ def test_fields_are_readonly(self):
188
+ eg = ExceptionGroup("eg", [TypeError(1), OSError(2)])
189
+
190
+ self.assertEqual(type(eg.exceptions), tuple)
191
+
192
+ eg.message
193
+ with self.assertRaises(AttributeError):
194
+ eg.message = "new msg"
195
+
196
+ eg.exceptions
197
+ with self.assertRaises(AttributeError):
198
+ eg.exceptions = [OSError("xyz")]
199
+
200
+ def test_notes_is_list_of_strings_if_it_exists(self):
201
+ eg = create_simple_eg()
202
+
203
+ note = "This is a happy note for the exception group"
204
+ self.assertFalse(hasattr(eg, "__notes__"))
205
+ eg.add_note(note)
206
+ self.assertEqual(eg.__notes__, [note])
207
+
208
+ def test_derive_doesn_copy_notes(self):
209
+ eg = create_simple_eg()
210
+ eg.add_note("hello")
211
+ assert eg.__notes__ == ["hello"]
212
+ eg2 = eg.derive([ValueError()])
213
+ assert not hasattr(eg2, "__notes__")
214
+
215
+
216
+ class ExceptionGroupTestBase(unittest.TestCase):
217
+ def assertMatchesTemplate(self, exc, exc_type, template):
218
+ """Assert that the exception matches the template
219
+
220
+ A template describes the shape of exc. If exc is a
221
+ leaf exception (i.e., not an exception group) then
222
+ template is an exception instance that has the
223
+ expected type and args value of exc. If exc is an
224
+ exception group, then template is a list of the
225
+ templates of its nested exceptions.
226
+ """
227
+ if exc_type is not None:
228
+ self.assertIs(type(exc), exc_type)
229
+
230
+ if isinstance(exc, BaseExceptionGroup):
231
+ self.assertIsInstance(template, collections.abc.Sequence)
232
+ self.assertEqual(len(exc.exceptions), len(template))
233
+ for e, t in zip(exc.exceptions, template):
234
+ self.assertMatchesTemplate(e, None, t)
235
+ else:
236
+ self.assertIsInstance(template, BaseException)
237
+ self.assertEqual(type(exc), type(template))
238
+ self.assertEqual(exc.args, template.args)
239
+
240
+
241
+ class ExceptionGroupSubgroupTests(ExceptionGroupTestBase):
242
+ def setUp(self):
243
+ self.eg = create_simple_eg()
244
+ self.eg_template = [ValueError(1), TypeError(int), ValueError(2)]
245
+
246
+ def test_basics_subgroup_split__bad_arg_type(self):
247
+ bad_args = [
248
+ "bad arg",
249
+ OSError("instance not type"),
250
+ [OSError, TypeError],
251
+ (OSError, 42),
252
+ ]
253
+ for arg in bad_args:
254
+ with self.assertRaises(TypeError):
255
+ self.eg.subgroup(arg)
256
+ with self.assertRaises(TypeError):
257
+ self.eg.split(arg)
258
+
259
+ def test_basics_subgroup_by_type__passthrough(self):
260
+ eg = self.eg
261
+ # self.assertIs(eg, eg.subgroup(BaseException))
262
+ # self.assertIs(eg, eg.subgroup(Exception))
263
+ self.assertIs(eg, eg.subgroup(BaseExceptionGroup))
264
+ self.assertIs(eg, eg.subgroup(ExceptionGroup))
265
+
266
+ def test_basics_subgroup_by_type__no_match(self):
267
+ self.assertIsNone(self.eg.subgroup(OSError))
268
+
269
+ def test_basics_subgroup_by_type__match(self):
270
+ eg = self.eg
271
+ testcases = [
272
+ # (match_type, result_template)
273
+ (ValueError, [ValueError(1), ValueError(2)]),
274
+ (TypeError, [TypeError(int)]),
275
+ ((ValueError, TypeError), self.eg_template),
276
+ ]
277
+
278
+ for match_type, template in testcases:
279
+ with self.subTest(match=match_type):
280
+ subeg = eg.subgroup(match_type)
281
+ self.assertEqual(subeg.message, eg.message)
282
+ self.assertMatchesTemplate(subeg, ExceptionGroup, template)
283
+
284
+ def test_basics_subgroup_by_predicate__passthrough(self):
285
+ self.assertIs(self.eg, self.eg.subgroup(lambda e: True))
286
+
287
+ def test_basics_subgroup_by_predicate__no_match(self):
288
+ self.assertIsNone(self.eg.subgroup(lambda e: False))
289
+
290
+ def test_basics_subgroup_by_predicate__match(self):
291
+ eg = self.eg
292
+ testcases = [
293
+ # (match_type, result_template)
294
+ (ValueError, [ValueError(1), ValueError(2)]),
295
+ (TypeError, [TypeError(int)]),
296
+ ((ValueError, TypeError), self.eg_template),
297
+ ]
298
+
299
+ for match_type, template in testcases:
300
+ subeg = eg.subgroup(lambda e: isinstance(e, match_type))
301
+ self.assertEqual(subeg.message, eg.message)
302
+ self.assertMatchesTemplate(subeg, ExceptionGroup, template)
303
+
304
+
305
+ class ExceptionGroupSplitTests(ExceptionGroupTestBase):
306
+ def setUp(self):
307
+ self.eg = create_simple_eg()
308
+ self.eg_template = [ValueError(1), TypeError(int), ValueError(2)]
309
+
310
+ def test_basics_split_by_type__passthrough(self):
311
+ for E in [BaseException, Exception, BaseExceptionGroup, ExceptionGroup]:
312
+ match, rest = self.eg.split(E)
313
+ self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template)
314
+ self.assertIsNone(rest)
315
+
316
+ def test_basics_split_by_type__no_match(self):
317
+ match, rest = self.eg.split(OSError)
318
+ self.assertIsNone(match)
319
+ self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template)
320
+
321
+ def test_basics_split_by_type__match(self):
322
+ eg = self.eg
323
+ VE = ValueError
324
+ TE = TypeError
325
+ testcases = [
326
+ # (matcher, match_template, rest_template)
327
+ (VE, [VE(1), VE(2)], [TE(int)]),
328
+ (TE, [TE(int)], [VE(1), VE(2)]),
329
+ ((VE, TE), self.eg_template, None),
330
+ ((OSError, VE), [VE(1), VE(2)], [TE(int)]),
331
+ ]
332
+
333
+ for match_type, match_template, rest_template in testcases:
334
+ match, rest = eg.split(match_type)
335
+ self.assertEqual(match.message, eg.message)
336
+ self.assertMatchesTemplate(match, ExceptionGroup, match_template)
337
+ if rest_template is not None:
338
+ self.assertEqual(rest.message, eg.message)
339
+ self.assertMatchesTemplate(rest, ExceptionGroup, rest_template)
340
+ else:
341
+ self.assertIsNone(rest)
342
+
343
+ def test_basics_split_by_predicate__passthrough(self):
344
+ match, rest = self.eg.split(lambda e: True)
345
+ self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template)
346
+ self.assertIsNone(rest)
347
+
348
+ def test_basics_split_by_predicate__no_match(self):
349
+ match, rest = self.eg.split(lambda e: False)
350
+ self.assertIsNone(match)
351
+ self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template)
352
+
353
+ def test_basics_split_by_predicate__match(self):
354
+ eg = self.eg
355
+ VE = ValueError
356
+ TE = TypeError
357
+ testcases = [
358
+ # (matcher, match_template, rest_template)
359
+ (VE, [VE(1), VE(2)], [TE(int)]),
360
+ (TE, [TE(int)], [VE(1), VE(2)]),
361
+ ((VE, TE), self.eg_template, None),
362
+ ]
363
+
364
+ for match_type, match_template, rest_template in testcases:
365
+ match, rest = eg.split(lambda e: isinstance(e, match_type))
366
+ self.assertEqual(match.message, eg.message)
367
+ self.assertMatchesTemplate(match, ExceptionGroup, match_template)
368
+ if rest_template is not None:
369
+ self.assertEqual(rest.message, eg.message)
370
+ self.assertMatchesTemplate(rest, ExceptionGroup, rest_template)
371
+
372
+
373
+ class DeepRecursionInSplitAndSubgroup(unittest.TestCase):
374
+ def make_deep_eg(self):
375
+ e = TypeError(1)
376
+ for _ in range(10000):
377
+ e = ExceptionGroup("eg", [e])
378
+ return e
379
+
380
+ def test_deep_split(self):
381
+ e = self.make_deep_eg()
382
+ with self.assertRaises(RecursionError):
383
+ e.split(TypeError)
384
+
385
+ def test_deep_subgroup(self):
386
+ e = self.make_deep_eg()
387
+ with self.assertRaises(RecursionError):
388
+ e.subgroup(TypeError)
389
+
390
+
391
+ def leaf_generator(exc, tbs=None):
392
+ if tbs is None:
393
+ tbs = []
394
+ tbs.append(exc.__traceback__)
395
+ if isinstance(exc, BaseExceptionGroup):
396
+ for e in exc.exceptions:
397
+ yield from leaf_generator(e, tbs)
398
+ else:
399
+ # exc is a leaf exception and its traceback
400
+ # is the concatenation of the traceback
401
+ # segments in tbs
402
+ yield exc, tbs
403
+ tbs.pop()
404
+
405
+
406
+ class LeafGeneratorTest(unittest.TestCase):
407
+ # The leaf_generator is mentioned in PEP 654 as a suggestion
408
+ # on how to iterate over leaf nodes of an EG. Is is also
409
+ # used below as a test utility. So we test it here.
410
+
411
+ def test_leaf_generator(self):
412
+ eg = create_simple_eg()
413
+
414
+ self.assertSequenceEqual([e for e, _ in leaf_generator(eg)], eg.exceptions)
415
+
416
+ for e, tbs in leaf_generator(eg):
417
+ self.assertSequenceEqual(tbs, [eg.__traceback__, e.__traceback__])
418
+
419
+
420
+ def create_nested_eg():
421
+ excs = []
422
+ try:
423
+ try:
424
+ raise TypeError(bytes)
425
+ except TypeError as e:
426
+ raise ExceptionGroup("nested", [e])
427
+ except ExceptionGroup as e:
428
+ excs.append(e)
429
+
430
+ try:
431
+ try:
432
+ raise MemoryError("out of memory")
433
+ except MemoryError as e:
434
+ raise ValueError(1) from e
435
+ except ValueError as e:
436
+ excs.append(e)
437
+
438
+ try:
439
+ raise ExceptionGroup("root", excs)
440
+ except ExceptionGroup as eg:
441
+ return eg
442
+
443
+
444
+ class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase):
445
+ def test_nested_group_matches_template(self):
446
+ eg = create_nested_eg()
447
+ self.assertMatchesTemplate(
448
+ eg, ExceptionGroup, [[TypeError(bytes)], ValueError(1)]
449
+ )
450
+
451
+ def test_nested_group_chaining(self):
452
+ eg = create_nested_eg()
453
+ self.assertIsInstance(eg.exceptions[1].__context__, MemoryError)
454
+ self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError)
455
+ self.assertIsInstance(eg.exceptions[0].__context__, TypeError)
456
+
457
+ def test_nested_exception_group_tracebacks(self):
458
+ eg = create_nested_eg()
459
+
460
+ line0 = create_nested_eg.__code__.co_firstlineno
461
+ for tb, expected in [
462
+ (eg.__traceback__, line0 + 19),
463
+ (eg.exceptions[0].__traceback__, line0 + 6),
464
+ (eg.exceptions[1].__traceback__, line0 + 14),
465
+ (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4),
466
+ ]:
467
+ self.assertEqual(tb.tb_lineno, expected)
468
+ self.assertIsNone(tb.tb_next)
469
+
470
+ def test_iteration_full_tracebacks(self):
471
+ eg = create_nested_eg()
472
+ # check that iteration over leaves
473
+ # produces the expected tracebacks
474
+ self.assertEqual(len(list(leaf_generator(eg))), 2)
475
+
476
+ line0 = create_nested_eg.__code__.co_firstlineno
477
+ expected_tbs = [[line0 + 19, line0 + 6, line0 + 4], [line0 + 19, line0 + 14]]
478
+
479
+ for i, (_, tbs) in enumerate(leaf_generator(eg)):
480
+ self.assertSequenceEqual([tb.tb_lineno for tb in tbs], expected_tbs[i])
481
+
482
+
483
+ class ExceptionGroupSplitTestBase(ExceptionGroupTestBase):
484
+ def split_exception_group(self, eg, types):
485
+ """Split an EG and do some sanity checks on the result"""
486
+ self.assertIsInstance(eg, BaseExceptionGroup)
487
+
488
+ match, rest = eg.split(types)
489
+ sg = eg.subgroup(types)
490
+
491
+ if match is not None:
492
+ self.assertIsInstance(match, BaseExceptionGroup)
493
+ for e, _ in leaf_generator(match):
494
+ self.assertIsInstance(e, types)
495
+
496
+ self.assertIsNotNone(sg)
497
+ self.assertIsInstance(sg, BaseExceptionGroup)
498
+ for e, _ in leaf_generator(sg):
499
+ self.assertIsInstance(e, types)
500
+
501
+ if rest is not None:
502
+ self.assertIsInstance(rest, BaseExceptionGroup)
503
+
504
+ def leaves(exc):
505
+ return [] if exc is None else [e for e, _ in leaf_generator(exc)]
506
+
507
+ # match and subgroup have the same leaves
508
+ self.assertSequenceEqual(leaves(match), leaves(sg))
509
+
510
+ match_leaves = leaves(match)
511
+ rest_leaves = leaves(rest)
512
+ # each leaf exception of eg is in exactly one of match and rest
513
+ self.assertEqual(len(leaves(eg)), len(leaves(match)) + len(leaves(rest)))
514
+
515
+ for e in leaves(eg):
516
+ self.assertNotEqual(match and e in match_leaves, rest and e in rest_leaves)
517
+
518
+ # message, cause and context, traceback and note equal to eg
519
+ for part in [match, rest, sg]:
520
+ if part is not None:
521
+ self.assertEqual(eg.message, part.message)
522
+ self.assertIs(eg.__cause__, part.__cause__)
523
+ self.assertIs(eg.__context__, part.__context__)
524
+ self.assertIs(eg.__traceback__, part.__traceback__)
525
+ self.assertEqual(
526
+ getattr(eg, "__notes__", None),
527
+ getattr(part, "__notes__", None),
528
+ )
529
+
530
+ def tbs_for_leaf(leaf, eg):
531
+ for e, tbs in leaf_generator(eg):
532
+ if e is leaf:
533
+ return tbs
534
+
535
+ def tb_linenos(tbs):
536
+ return [tb.tb_lineno for tb in tbs if tb]
537
+
538
+ # full tracebacks match
539
+ for part in [match, rest, sg]:
540
+ for e in leaves(part):
541
+ self.assertSequenceEqual(
542
+ tb_linenos(tbs_for_leaf(e, eg)), tb_linenos(tbs_for_leaf(e, part))
543
+ )
544
+
545
+ return match, rest
546
+
547
+
548
+ class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase):
549
+ def test_split_by_type(self):
550
+ class MyExceptionGroup(ExceptionGroup):
551
+ pass
552
+
553
+ def raiseVE(v):
554
+ raise ValueError(v)
555
+
556
+ def raiseTE(t):
557
+ raise TypeError(t)
558
+
559
+ def nested_group():
560
+ def level1(i):
561
+ excs = []
562
+ for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i + 1)]:
563
+ try:
564
+ f(arg)
565
+ except Exception as e:
566
+ excs.append(e)
567
+ raise ExceptionGroup("msg1", excs)
568
+
569
+ def level2(i):
570
+ excs = []
571
+ for f, arg in [(level1, i), (level1, i + 1), (raiseVE, i + 2)]:
572
+ try:
573
+ f(arg)
574
+ except Exception as e:
575
+ excs.append(e)
576
+ raise MyExceptionGroup("msg2", excs)
577
+
578
+ def level3(i):
579
+ excs = []
580
+ for f, arg in [(level2, i + 1), (raiseVE, i + 2)]:
581
+ try:
582
+ f(arg)
583
+ except Exception as e:
584
+ excs.append(e)
585
+ raise ExceptionGroup("msg3", excs)
586
+
587
+ level3(5)
588
+
589
+ try:
590
+ nested_group()
591
+ except ExceptionGroup as e:
592
+ e.add_note(f"the note: {id(e)}")
593
+ eg = e
594
+
595
+ eg_template = [
596
+ [
597
+ [ValueError(6), TypeError(int), ValueError(7)],
598
+ [ValueError(7), TypeError(int), ValueError(8)],
599
+ ValueError(8),
600
+ ],
601
+ ValueError(7),
602
+ ]
603
+
604
+ valueErrors_template = [
605
+ [
606
+ [ValueError(6), ValueError(7)],
607
+ [ValueError(7), ValueError(8)],
608
+ ValueError(8),
609
+ ],
610
+ ValueError(7),
611
+ ]
612
+
613
+ typeErrors_template = [[[TypeError(int)], [TypeError(int)]]]
614
+
615
+ self.assertMatchesTemplate(eg, ExceptionGroup, eg_template)
616
+
617
+ # Match Nothing
618
+ match, rest = self.split_exception_group(eg, SyntaxError)
619
+ self.assertIsNone(match)
620
+ self.assertMatchesTemplate(rest, ExceptionGroup, eg_template)
621
+
622
+ # Match Everything
623
+ match, rest = self.split_exception_group(eg, BaseException)
624
+ self.assertMatchesTemplate(match, ExceptionGroup, eg_template)
625
+ self.assertIsNone(rest)
626
+ match, rest = self.split_exception_group(eg, (ValueError, TypeError))
627
+ self.assertMatchesTemplate(match, ExceptionGroup, eg_template)
628
+ self.assertIsNone(rest)
629
+
630
+ # Match ValueErrors
631
+ match, rest = self.split_exception_group(eg, ValueError)
632
+ self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template)
633
+ self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template)
634
+
635
+ # Match TypeErrors
636
+ match, rest = self.split_exception_group(eg, (TypeError, SyntaxError))
637
+ self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template)
638
+ self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template)
639
+
640
+ # Match ExceptionGroup
641
+ match, rest = eg.split(ExceptionGroup)
642
+ self.assertIs(match, eg)
643
+ self.assertIsNone(rest)
644
+
645
+ # Match MyExceptionGroup (ExceptionGroup subclass)
646
+ match, rest = eg.split(MyExceptionGroup)
647
+ self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]])
648
+ self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]])
649
+
650
+ def test_split_BaseExceptionGroup(self):
651
+ def exc(ex):
652
+ try:
653
+ raise ex
654
+ except BaseException as e:
655
+ return e
656
+
657
+ try:
658
+ raise BaseExceptionGroup(
659
+ "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))]
660
+ )
661
+ except BaseExceptionGroup as e:
662
+ beg = e
663
+
664
+ # Match Nothing
665
+ match, rest = self.split_exception_group(beg, TypeError)
666
+ self.assertIsNone(match)
667
+ self.assertMatchesTemplate(
668
+ rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)]
669
+ )
670
+
671
+ # Match Everything
672
+ match, rest = self.split_exception_group(beg, (ValueError, KeyboardInterrupt))
673
+ self.assertMatchesTemplate(
674
+ match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)]
675
+ )
676
+ self.assertIsNone(rest)
677
+
678
+ # Match ValueErrors
679
+ match, rest = self.split_exception_group(beg, ValueError)
680
+ self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)])
681
+ self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)])
682
+
683
+ # Match KeyboardInterrupts
684
+ match, rest = self.split_exception_group(beg, KeyboardInterrupt)
685
+ self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)])
686
+ self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)])
687
+
688
+
689
+ class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase):
690
+ def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self):
691
+ class EG(ExceptionGroup):
692
+ pass
693
+
694
+ try:
695
+ try:
696
+ try:
697
+ raise TypeError(2)
698
+ except TypeError as te:
699
+ raise EG("nested", [te])
700
+ except EG as nested:
701
+ try:
702
+ raise ValueError(1)
703
+ except ValueError as ve:
704
+ raise EG("eg", [ve, nested])
705
+ except EG as e:
706
+ eg = e
707
+
708
+ self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]])
709
+
710
+ # Match Nothing
711
+ match, rest = self.split_exception_group(eg, OSError)
712
+ self.assertIsNone(match)
713
+ self.assertMatchesTemplate(
714
+ rest, ExceptionGroup, [ValueError(1), [TypeError(2)]]
715
+ )
716
+
717
+ # Match Everything
718
+ match, rest = self.split_exception_group(eg, (ValueError, TypeError))
719
+ self.assertMatchesTemplate(
720
+ match, ExceptionGroup, [ValueError(1), [TypeError(2)]]
721
+ )
722
+ self.assertIsNone(rest)
723
+
724
+ # Match ValueErrors
725
+ match, rest = self.split_exception_group(eg, ValueError)
726
+ self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)])
727
+ self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]])
728
+
729
+ # Match TypeErrors
730
+ match, rest = self.split_exception_group(eg, TypeError)
731
+ self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]])
732
+ self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)])
733
+
734
+ def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self):
735
+ class EG(BaseExceptionGroup):
736
+ def __new__(cls, message, excs, unused):
737
+ # The "unused" arg is here to show that split() doesn't call
738
+ # the actual class constructor from the default derive()
739
+ # implementation (it would fail on unused arg if so because
740
+ # it assumes the BaseExceptionGroup.__new__ signature).
741
+ return super().__new__(cls, message, excs)
742
+
743
+ try:
744
+ raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused")
745
+ except EG as e:
746
+ eg = e
747
+
748
+ self.assertMatchesTemplate(eg, EG, [ValueError(1), KeyboardInterrupt(2)])
749
+
750
+ # Match Nothing
751
+ match, rest = self.split_exception_group(eg, OSError)
752
+ self.assertIsNone(match)
753
+ self.assertMatchesTemplate(
754
+ rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)]
755
+ )
756
+
757
+ # Match Everything
758
+ match, rest = self.split_exception_group(eg, (ValueError, KeyboardInterrupt))
759
+ self.assertMatchesTemplate(
760
+ match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)]
761
+ )
762
+ self.assertIsNone(rest)
763
+
764
+ # Match ValueErrors
765
+ match, rest = self.split_exception_group(eg, ValueError)
766
+ self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)])
767
+ self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)])
768
+
769
+ # Match KeyboardInterrupt
770
+ match, rest = self.split_exception_group(eg, KeyboardInterrupt)
771
+ self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)])
772
+ self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)])
773
+
774
+ def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self):
775
+ class EG(ExceptionGroup):
776
+ def __new__(cls, message, excs, code):
777
+ obj = super().__new__(cls, message, excs)
778
+ obj.code = code
779
+ return obj
780
+
781
+ def derive(self, excs):
782
+ return EG(self.message, excs, self.code)
783
+
784
+ try:
785
+ try:
786
+ try:
787
+ raise TypeError(2)
788
+ except TypeError as te:
789
+ raise EG("nested", [te], 101)
790
+ except EG as nested:
791
+ try:
792
+ raise ValueError(1)
793
+ except ValueError as ve:
794
+ raise EG("eg", [ve, nested], 42)
795
+ except EG as e:
796
+ e.add_note("hello")
797
+ eg = e
798
+
799
+ self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]])
800
+
801
+ # Match Nothing
802
+ match, rest = self.split_exception_group(eg, OSError)
803
+ self.assertIsNone(match)
804
+ self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]])
805
+ self.assertEqual(rest.code, 42)
806
+ self.assertEqual(rest.exceptions[1].code, 101)
807
+ self.assertEqual(rest.__notes__, ["hello"])
808
+
809
+ # Match Everything
810
+ match, rest = self.split_exception_group(eg, (ValueError, TypeError))
811
+ self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]])
812
+ self.assertEqual(match.code, 42)
813
+ self.assertEqual(match.exceptions[1].code, 101)
814
+ self.assertEqual(match.__notes__, ["hello"])
815
+ self.assertIsNone(rest)
816
+
817
+ # Match ValueErrors
818
+ match, rest = self.split_exception_group(eg, ValueError)
819
+ self.assertMatchesTemplate(match, EG, [ValueError(1)])
820
+ self.assertEqual(match.code, 42)
821
+ self.assertEqual(match.__notes__, ["hello"])
822
+ self.assertMatchesTemplate(rest, EG, [[TypeError(2)]])
823
+ self.assertEqual(rest.code, 42)
824
+ self.assertEqual(rest.exceptions[0].code, 101)
825
+ self.assertEqual(rest.__notes__, ["hello"])
826
+
827
+ # Match TypeErrors
828
+ match, rest = self.split_exception_group(eg, TypeError)
829
+ self.assertMatchesTemplate(match, EG, [[TypeError(2)]])
830
+ self.assertEqual(match.code, 42)
831
+ self.assertEqual(match.exceptions[0].code, 101)
832
+ self.assertEqual(match.__notes__, ["hello"])
833
+ self.assertMatchesTemplate(rest, EG, [ValueError(1)])
834
+ self.assertEqual(rest.code, 42)
835
+ self.assertEqual(rest.__notes__, ["hello"])
836
+
837
+
838
+ def test_repr():
839
+ group = BaseExceptionGroup("foo", [ValueError(1), KeyboardInterrupt()])
840
+ assert repr(group) == (
841
+ "BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()])"
842
+ )
843
+
844
+ group = ExceptionGroup("foo", [ValueError(1), RuntimeError("bar")])
845
+ assert repr(group) == "ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')])"
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_formatting.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import traceback
3
+ from typing import NoReturn
4
+ from urllib.error import HTTPError
5
+
6
+ import pytest
7
+ from _pytest.capture import CaptureFixture
8
+ from _pytest.fixtures import SubRequest
9
+ from _pytest.monkeypatch import MonkeyPatch
10
+
11
+ from exceptiongroup import ExceptionGroup
12
+
13
+
14
+ def raise_excgroup() -> NoReturn:
15
+ exceptions = []
16
+ try:
17
+ raise ValueError("foo")
18
+ except ValueError as exc:
19
+ exceptions.append(exc)
20
+
21
+ try:
22
+ raise RuntimeError("bar")
23
+ except RuntimeError as exc:
24
+ exc.__notes__ = ["Note from bar handler"]
25
+ exceptions.append(exc)
26
+
27
+ exc = ExceptionGroup("test message", exceptions)
28
+ exc.add_note("Displays notes attached to the group too")
29
+ raise exc
30
+
31
+
32
+ @pytest.fixture(
33
+ params=[
34
+ pytest.param(True, id="patched"),
35
+ pytest.param(
36
+ False,
37
+ id="unpatched",
38
+ marks=[
39
+ pytest.mark.skipif(
40
+ sys.version_info >= (3, 11),
41
+ reason="No patching is done on Python >= 3.11",
42
+ )
43
+ ],
44
+ ),
45
+ ],
46
+ )
47
+ def patched(request: SubRequest) -> bool:
48
+ return request.param
49
+
50
+
51
+ @pytest.fixture(
52
+ params=[pytest.param(False, id="newstyle"), pytest.param(True, id="oldstyle")]
53
+ )
54
+ def old_argstyle(request: SubRequest) -> bool:
55
+ return request.param
56
+
57
+
58
+ def test_exceptionhook(capsys: CaptureFixture) -> None:
59
+ try:
60
+ raise_excgroup()
61
+ except ExceptionGroup as exc:
62
+ sys.excepthook(type(exc), exc, exc.__traceback__)
63
+
64
+ local_lineno = test_exceptionhook.__code__.co_firstlineno
65
+ lineno = raise_excgroup.__code__.co_firstlineno
66
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
67
+ underline_suffix = (
68
+ "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^"
69
+ )
70
+ output = capsys.readouterr().err
71
+ assert output == (
72
+ f"""\
73
+ + Exception Group Traceback (most recent call last):
74
+ | File "{__file__}", line {local_lineno + 2}, in test_exceptionhook
75
+ | raise_excgroup(){underline_suffix}
76
+ | File "{__file__}", line {lineno + 15}, in raise_excgroup
77
+ | raise exc
78
+ | {module_prefix}ExceptionGroup: test message (2 sub-exceptions)
79
+ | Displays notes attached to the group too
80
+ +-+---------------- 1 ----------------
81
+ | Traceback (most recent call last):
82
+ | File "{__file__}", line {lineno + 3}, in raise_excgroup
83
+ | raise ValueError("foo")
84
+ | ValueError: foo
85
+ +---------------- 2 ----------------
86
+ | Traceback (most recent call last):
87
+ | File "{__file__}", line {lineno + 8}, in raise_excgroup
88
+ | raise RuntimeError("bar")
89
+ | RuntimeError: bar
90
+ | Note from bar handler
91
+ +------------------------------------
92
+ """
93
+ )
94
+
95
+
96
+ def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None:
97
+ try:
98
+ raise Exception() from ExceptionGroup("", (Exception(),))
99
+ except Exception as exc:
100
+ sys.excepthook(type(exc), exc, exc.__traceback__)
101
+
102
+ lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno
103
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
104
+ output = capsys.readouterr().err
105
+ assert output == (
106
+ f"""\
107
+ | {module_prefix}ExceptionGroup: (1 sub-exception)
108
+ +-+---------------- 1 ----------------
109
+ | Exception
110
+ +------------------------------------
111
+
112
+ The above exception was the direct cause of the following exception:
113
+
114
+ Traceback (most recent call last):
115
+ File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause
116
+ raise Exception() from ExceptionGroup("", (Exception(),))
117
+ Exception
118
+ """
119
+ )
120
+
121
+
122
+ def test_exceptiongroup_loop(capsys: CaptureFixture) -> None:
123
+ e0 = Exception("e0")
124
+ eg0 = ExceptionGroup("eg0", (e0,))
125
+ eg1 = ExceptionGroup("eg1", (eg0,))
126
+
127
+ try:
128
+ raise eg0 from eg1
129
+ except ExceptionGroup as exc:
130
+ sys.excepthook(type(exc), exc, exc.__traceback__)
131
+
132
+ lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6
133
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
134
+ output = capsys.readouterr().err
135
+ assert output == (
136
+ f"""\
137
+ | {module_prefix}ExceptionGroup: eg1 (1 sub-exception)
138
+ +-+---------------- 1 ----------------
139
+ | Exception Group Traceback (most recent call last):
140
+ | File "{__file__}", line {lineno}, in test_exceptiongroup_loop
141
+ | raise eg0 from eg1
142
+ | {module_prefix}ExceptionGroup: eg0 (1 sub-exception)
143
+ +-+---------------- 1 ----------------
144
+ | Exception: e0
145
+ +------------------------------------
146
+
147
+ The above exception was the direct cause of the following exception:
148
+
149
+ + Exception Group Traceback (most recent call last):
150
+ | File "{__file__}", line {lineno}, in test_exceptiongroup_loop
151
+ | raise eg0 from eg1
152
+ | {module_prefix}ExceptionGroup: eg0 (1 sub-exception)
153
+ +-+---------------- 1 ----------------
154
+ | Exception: e0
155
+ +------------------------------------
156
+ """
157
+ )
158
+
159
+
160
+ def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None:
161
+ try:
162
+ raise_excgroup()
163
+ except ExceptionGroup as exc:
164
+ sys.excepthook(type(exc), exc, exc.__traceback__)
165
+
166
+ local_lineno = test_exceptionhook_format_exception_only.__code__.co_firstlineno
167
+ lineno = raise_excgroup.__code__.co_firstlineno
168
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
169
+ underline_suffix = (
170
+ "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^"
171
+ )
172
+ output = capsys.readouterr().err
173
+ assert output == (
174
+ f"""\
175
+ + Exception Group Traceback (most recent call last):
176
+ | File "{__file__}", line {local_lineno + 2}, in \
177
+ test_exceptionhook_format_exception_only
178
+ | raise_excgroup(){underline_suffix}
179
+ | File "{__file__}", line {lineno + 15}, in raise_excgroup
180
+ | raise exc
181
+ | {module_prefix}ExceptionGroup: test message (2 sub-exceptions)
182
+ | Displays notes attached to the group too
183
+ +-+---------------- 1 ----------------
184
+ | Traceback (most recent call last):
185
+ | File "{__file__}", line {lineno + 3}, in raise_excgroup
186
+ | raise ValueError("foo")
187
+ | ValueError: foo
188
+ +---------------- 2 ----------------
189
+ | Traceback (most recent call last):
190
+ | File "{__file__}", line {lineno + 8}, in raise_excgroup
191
+ | raise RuntimeError("bar")
192
+ | RuntimeError: bar
193
+ | Note from bar handler
194
+ +------------------------------------
195
+ """
196
+ )
197
+
198
+
199
+ def test_formatting_syntax_error(capsys: CaptureFixture) -> None:
200
+ try:
201
+ exec("//serser")
202
+ except SyntaxError as exc:
203
+ sys.excepthook(type(exc), exc, exc.__traceback__)
204
+
205
+ if sys.version_info >= (3, 10):
206
+ underline = "\n ^^"
207
+ elif sys.version_info >= (3, 8):
208
+ underline = "\n ^"
209
+ else:
210
+ underline = "\n ^"
211
+
212
+ lineno = test_formatting_syntax_error.__code__.co_firstlineno
213
+ underline_suffix = "" if sys.version_info < (3, 13) else "\n ~~~~^^^^^^^^^^^^"
214
+ output = capsys.readouterr().err
215
+ assert output == (
216
+ f"""\
217
+ Traceback (most recent call last):
218
+ File "{__file__}", line {lineno + 2}, \
219
+ in test_formatting_syntax_error
220
+ exec("//serser"){underline_suffix}
221
+ File "<string>", line 1
222
+ //serser{underline}
223
+ SyntaxError: invalid syntax
224
+ """
225
+ )
226
+
227
+
228
+ def test_format_exception(
229
+ patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch
230
+ ) -> None:
231
+ if not patched:
232
+ # Block monkey patching, then force the module to be re-imported
233
+ del sys.modules["traceback"]
234
+ del sys.modules["exceptiongroup"]
235
+ del sys.modules["exceptiongroup._formatting"]
236
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
237
+
238
+ from exceptiongroup import format_exception
239
+
240
+ exceptions = []
241
+ try:
242
+ raise ValueError("foo")
243
+ except ValueError as exc:
244
+ exceptions.append(exc)
245
+
246
+ try:
247
+ raise RuntimeError("bar")
248
+ except RuntimeError as exc:
249
+ exc.__notes__ = ["Note from bar handler"]
250
+ exceptions.append(exc)
251
+
252
+ try:
253
+ raise_excgroup()
254
+ except ExceptionGroup as exc:
255
+ if old_argstyle:
256
+ lines = format_exception(type(exc), exc, exc.__traceback__)
257
+ else:
258
+ lines = format_exception(exc)
259
+
260
+ local_lineno = test_format_exception.__code__.co_firstlineno
261
+ lineno = raise_excgroup.__code__.co_firstlineno
262
+ assert isinstance(lines, list)
263
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
264
+ underline_suffix = (
265
+ "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^"
266
+ )
267
+ assert "".join(lines) == (
268
+ f"""\
269
+ + Exception Group Traceback (most recent call last):
270
+ | File "{__file__}", line {local_lineno + 25}, in test_format_exception
271
+ | raise_excgroup(){underline_suffix}
272
+ | File "{__file__}", line {lineno + 15}, in raise_excgroup
273
+ | raise exc
274
+ | {module_prefix}ExceptionGroup: test message (2 sub-exceptions)
275
+ | Displays notes attached to the group too
276
+ +-+---------------- 1 ----------------
277
+ | Traceback (most recent call last):
278
+ | File "{__file__}", line {lineno + 3}, in raise_excgroup
279
+ | raise ValueError("foo")
280
+ | ValueError: foo
281
+ +---------------- 2 ----------------
282
+ | Traceback (most recent call last):
283
+ | File "{__file__}", line {lineno + 8}, in raise_excgroup
284
+ | raise RuntimeError("bar")
285
+ | RuntimeError: bar
286
+ | Note from bar handler
287
+ +------------------------------------
288
+ """
289
+ )
290
+
291
+
292
+ def test_format_nested(monkeypatch: MonkeyPatch) -> None:
293
+ if not patched:
294
+ # Block monkey patching, then force the module to be re-imported
295
+ del sys.modules["traceback"]
296
+ del sys.modules["exceptiongroup"]
297
+ del sys.modules["exceptiongroup._formatting"]
298
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
299
+
300
+ from exceptiongroup import format_exception
301
+
302
+ def raise_exc(max_level: int, level: int = 1) -> NoReturn:
303
+ if level == max_level:
304
+ raise Exception(f"LEVEL_{level}")
305
+ else:
306
+ try:
307
+ raise_exc(max_level, level + 1)
308
+ except Exception:
309
+ raise Exception(f"LEVEL_{level}")
310
+
311
+ try:
312
+ raise_exc(3)
313
+ except Exception as exc:
314
+ lines = format_exception(type(exc), exc, exc.__traceback__)
315
+
316
+ underline_suffix1 = (
317
+ "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^"
318
+ )
319
+ underline_suffix2 = "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^"
320
+ local_lineno = test_format_nested.__code__.co_firstlineno + 20
321
+ raise_exc_lineno1 = raise_exc.__code__.co_firstlineno + 2
322
+ raise_exc_lineno2 = raise_exc.__code__.co_firstlineno + 5
323
+ raise_exc_lineno3 = raise_exc.__code__.co_firstlineno + 7
324
+ assert isinstance(lines, list)
325
+ assert "".join(lines) == (
326
+ f"""\
327
+ Traceback (most recent call last):
328
+ File "{__file__}", line {raise_exc_lineno2}, in raise_exc
329
+ raise_exc(max_level, level + 1){underline_suffix1}
330
+ File "{__file__}", line {raise_exc_lineno1}, in raise_exc
331
+ raise Exception(f"LEVEL_{{level}}")
332
+ Exception: LEVEL_3
333
+
334
+ During handling of the above exception, another exception occurred:
335
+
336
+ Traceback (most recent call last):
337
+ File "{__file__}", line {raise_exc_lineno2}, in raise_exc
338
+ raise_exc(max_level, level + 1){underline_suffix1}
339
+ File "{__file__}", line {raise_exc_lineno3}, in raise_exc
340
+ raise Exception(f"LEVEL_{{level}}")
341
+ Exception: LEVEL_2
342
+
343
+ During handling of the above exception, another exception occurred:
344
+
345
+ Traceback (most recent call last):
346
+ File "{__file__}", line {local_lineno}, in test_format_nested
347
+ raise_exc(3){underline_suffix2}
348
+ File "{__file__}", line {raise_exc_lineno3}, in raise_exc
349
+ raise Exception(f"LEVEL_{{level}}")
350
+ Exception: LEVEL_1
351
+ """
352
+ )
353
+
354
+
355
+ def test_format_exception_only(
356
+ patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch
357
+ ) -> None:
358
+ if not patched:
359
+ # Block monkey patching, then force the module to be re-imported
360
+ del sys.modules["traceback"]
361
+ del sys.modules["exceptiongroup"]
362
+ del sys.modules["exceptiongroup._formatting"]
363
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
364
+
365
+ from exceptiongroup import format_exception_only
366
+
367
+ try:
368
+ raise_excgroup()
369
+ except ExceptionGroup as exc:
370
+ if old_argstyle:
371
+ output = format_exception_only(type(exc), exc)
372
+ else:
373
+ output = format_exception_only(exc)
374
+
375
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
376
+ assert output == [
377
+ f"{module_prefix}ExceptionGroup: test message (2 sub-exceptions)\n",
378
+ "Displays notes attached to the group too\n",
379
+ ]
380
+
381
+
382
+ def test_print_exception(
383
+ patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
384
+ ) -> None:
385
+ if not patched:
386
+ # Block monkey patching, then force the module to be re-imported
387
+ del sys.modules["traceback"]
388
+ del sys.modules["exceptiongroup"]
389
+ del sys.modules["exceptiongroup._formatting"]
390
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
391
+
392
+ from exceptiongroup import print_exception
393
+
394
+ try:
395
+ raise_excgroup()
396
+ except ExceptionGroup as exc:
397
+ if old_argstyle:
398
+ print_exception(type(exc), exc, exc.__traceback__)
399
+ else:
400
+ print_exception(exc)
401
+
402
+ local_lineno = test_print_exception.__code__.co_firstlineno
403
+ lineno = raise_excgroup.__code__.co_firstlineno
404
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
405
+ underline_suffix = (
406
+ "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^"
407
+ )
408
+ output = capsys.readouterr().err
409
+ assert output == (
410
+ f"""\
411
+ + Exception Group Traceback (most recent call last):
412
+ | File "{__file__}", line {local_lineno + 13}, in test_print_exception
413
+ | raise_excgroup(){underline_suffix}
414
+ | File "{__file__}", line {lineno + 15}, in raise_excgroup
415
+ | raise exc
416
+ | {module_prefix}ExceptionGroup: test message (2 sub-exceptions)
417
+ | Displays notes attached to the group too
418
+ +-+---------------- 1 ----------------
419
+ | Traceback (most recent call last):
420
+ | File "{__file__}", line {lineno + 3}, in raise_excgroup
421
+ | raise ValueError("foo")
422
+ | ValueError: foo
423
+ +---------------- 2 ----------------
424
+ | Traceback (most recent call last):
425
+ | File "{__file__}", line {lineno + 8}, in raise_excgroup
426
+ | raise RuntimeError("bar")
427
+ | RuntimeError: bar
428
+ | Note from bar handler
429
+ +------------------------------------
430
+ """
431
+ )
432
+
433
+
434
+ def test_print_exc(
435
+ patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
436
+ ) -> None:
437
+ if not patched:
438
+ # Block monkey patching, then force the module to be re-imported
439
+ del sys.modules["traceback"]
440
+ del sys.modules["exceptiongroup"]
441
+ del sys.modules["exceptiongroup._formatting"]
442
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
443
+
444
+ from exceptiongroup import print_exc
445
+
446
+ try:
447
+ raise_excgroup()
448
+ except ExceptionGroup:
449
+ print_exc()
450
+ local_lineno = test_print_exc.__code__.co_firstlineno
451
+ lineno = raise_excgroup.__code__.co_firstlineno
452
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
453
+ underline_suffix = (
454
+ "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^"
455
+ )
456
+ output = capsys.readouterr().err
457
+ assert output == (
458
+ f"""\
459
+ + Exception Group Traceback (most recent call last):
460
+ | File "{__file__}", line {local_lineno + 13}, in test_print_exc
461
+ | raise_excgroup(){underline_suffix}
462
+ | File "{__file__}", line {lineno + 15}, in raise_excgroup
463
+ | raise exc
464
+ | {module_prefix}ExceptionGroup: test message (2 sub-exceptions)
465
+ | Displays notes attached to the group too
466
+ +-+---------------- 1 ----------------
467
+ | Traceback (most recent call last):
468
+ | File "{__file__}", line {lineno + 3}, in raise_excgroup
469
+ | raise ValueError("foo")
470
+ | ValueError: foo
471
+ +---------------- 2 ----------------
472
+ | Traceback (most recent call last):
473
+ | File "{__file__}", line {lineno + 8}, in raise_excgroup
474
+ | raise RuntimeError("bar")
475
+ | RuntimeError: bar
476
+ | Note from bar handler
477
+ +------------------------------------
478
+ """
479
+ )
480
+
481
+
482
+ @pytest.mark.skipif(
483
+ not hasattr(NameError, "name") or sys.version_info[:2] == (3, 11),
484
+ reason="only works if NameError exposes the missing name",
485
+ )
486
+ def test_nameerror_suggestions(
487
+ patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
488
+ ) -> None:
489
+ if not patched:
490
+ # Block monkey patching, then force the module to be re-imported
491
+ del sys.modules["traceback"]
492
+ del sys.modules["exceptiongroup"]
493
+ del sys.modules["exceptiongroup._formatting"]
494
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
495
+
496
+ from exceptiongroup import print_exc
497
+
498
+ try:
499
+ folder
500
+ except NameError:
501
+ print_exc()
502
+ output = capsys.readouterr().err
503
+ assert "Did you mean" in output and "'filter'?" in output
504
+
505
+
506
+ @pytest.mark.skipif(
507
+ not hasattr(AttributeError, "name") or sys.version_info[:2] == (3, 11),
508
+ reason="only works if AttributeError exposes the missing name",
509
+ )
510
+ def test_nameerror_suggestions_in_group(
511
+ patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
512
+ ) -> None:
513
+ if not patched:
514
+ # Block monkey patching, then force the module to be re-imported
515
+ del sys.modules["traceback"]
516
+ del sys.modules["exceptiongroup"]
517
+ del sys.modules["exceptiongroup._formatting"]
518
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
519
+
520
+ from exceptiongroup import print_exception
521
+
522
+ try:
523
+ [].attend
524
+ except AttributeError as e:
525
+ eg = ExceptionGroup("a", [e])
526
+ print_exception(eg)
527
+ output = capsys.readouterr().err
528
+ assert "Did you mean" in output and "'append'?" in output
529
+
530
+
531
+ def test_bug_suggestions_attributeerror_no_obj(
532
+ patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
533
+ ) -> None:
534
+ if not patched:
535
+ # Block monkey patching, then force the module to be re-imported
536
+ del sys.modules["traceback"]
537
+ del sys.modules["exceptiongroup"]
538
+ del sys.modules["exceptiongroup._formatting"]
539
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
540
+
541
+ from exceptiongroup import print_exception
542
+
543
+ class NamedAttributeError(AttributeError):
544
+ def __init__(self, name: str) -> None:
545
+ self.name: str = name
546
+
547
+ try:
548
+ raise NamedAttributeError(name="mykey")
549
+ except AttributeError as e:
550
+ print_exception(e) # does not crash
551
+ output = capsys.readouterr().err
552
+ assert "NamedAttributeError" in output
553
+
554
+
555
+ def test_works_around_httperror_bug():
556
+ # See https://github.com/python/cpython/issues/98778 in Python <= 3.9
557
+ err = HTTPError("url", 405, "METHOD NOT ALLOWED", None, None)
558
+ traceback.TracebackException(type(err), err, None)
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_suppress.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ from exceptiongroup import suppress
6
+
7
+ if sys.version_info < (3, 11):
8
+ from exceptiongroup import BaseExceptionGroup, ExceptionGroup
9
+
10
+
11
+ def test_suppress_exception():
12
+ with pytest.raises(ExceptionGroup) as exc, suppress(SystemExit):
13
+ raise BaseExceptionGroup("", [SystemExit(1), RuntimeError("boo")])
14
+
15
+ assert len(exc.value.exceptions) == 1
16
+ assert isinstance(exc.value.exceptions[0], RuntimeError)
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/canaries/first-hunk-only.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -Eeuo pipefail
3
+ cd /testbed/repo
4
+ cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL'
5
+ diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py
6
+ index 4799553204e5b1221dc6b0be9d7ea94c7e3be4f9..a4a7acea822d43ba91183cff0b44f31313171d1a 100644
7
+ --- a/src/exceptiongroup/_exceptions.py
8
+ +++ b/src/exceptiongroup/_exceptions.py
9
+ @@ -110,9 +110,7 @@
10
+
11
+ @property
12
+ def message(self) -> str:
13
+ - if hasattr(self, '_msg'):
14
+ - return self._msg
15
+ - return ""
16
+ + return self._message
17
+
18
+ @property
19
+ def exceptions(
20
+ OPENENV_PARTIAL
21
+ /usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/canaries/original-bug.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -Eeuo pipefail
3
+ :
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/openenv.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "canaries": "validation/canaries",
3
+ "profile": "harbor-semantic-v1",
4
+ "requires_credentials": false,
5
+ "resources": {
6
+ "cpu": 2,
7
+ "disk_mb": 16384,
8
+ "episode_timeout_s": 1800,
9
+ "memory_mb": 8192
10
+ },
11
+ "reward": {
12
+ "floor_margin": 0.1,
13
+ "oracle_tolerance": 0,
14
+ "range": [
15
+ 0,
16
+ 1
17
+ ]
18
+ },
19
+ "reward_key": "reward",
20
+ "types": {
21
+ "tags": [
22
+ "swe",
23
+ "python",
24
+ "mutation-repair"
25
+ ]
26
+ }
27
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/LICENSE.source ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Alex Grönholm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+
23
+ This project contains code copied from the Python standard library.
24
+ The following is the required license notice for those parts.
25
+
26
+ PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
27
+ --------------------------------------------
28
+
29
+ 1. This LICENSE AGREEMENT is between the Python Software Foundation
30
+ ("PSF"), and the Individual or Organization ("Licensee") accessing and
31
+ otherwise using this software ("Python") in source or binary form and
32
+ its associated documentation.
33
+
34
+ 2. Subject to the terms and conditions of this License Agreement, PSF hereby
35
+ grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
36
+ analyze, test, perform and/or display publicly, prepare derivative works,
37
+ distribute, and otherwise use Python alone or in any derivative version,
38
+ provided, however, that PSF's License Agreement and PSF's notice of copyright,
39
+ i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
40
+ 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation;
41
+ All Rights Reserved" are retained in Python alone or in any derivative version
42
+ prepared by Licensee.
43
+
44
+ 3. In the event Licensee prepares a derivative work that is based on
45
+ or incorporates Python or any part thereof, and wants to make
46
+ the derivative work available to others as provided herein, then
47
+ Licensee hereby agrees to include in any such work a brief summary of
48
+ the changes made to Python.
49
+
50
+ 4. PSF is making Python available to Licensee on an "AS IS"
51
+ basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
52
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
53
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
54
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
55
+ INFRINGE ANY THIRD PARTY RIGHTS.
56
+
57
+ 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
58
+ FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
59
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
60
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
61
+
62
+ 6. This License Agreement will automatically terminate upon a material
63
+ breach of its terms and conditions.
64
+
65
+ 7. Nothing in this License Agreement shall be deemed to create any
66
+ relationship of agency, partnership, or joint venture between PSF and
67
+ Licensee. This License Agreement does not grant permission to use PSF
68
+ trademarks or trade name in a trademark sense to endorse or promote
69
+ products or services of Licensee, or any third party.
70
+
71
+ 8. By copying, installing or otherwise using Python, Licensee
72
+ agrees to be bound by the terms and conditions of this License
73
+ Agreement.
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/adapter.json ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.",
3
+ "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481",
4
+ "dependency_installation_pinned": false,
5
+ "dependency_setup_sha256": "6780ef55e5987924663b6e2b917a1b319de74c1108bf39a9fe6f5dc719935dfe",
6
+ "gold_patch_sha256": "c68ac6e7d7b1b38e90c59ce45d47c6a722ce8e9971b65335f1c598bd59a7a8d7",
7
+ "hostile_code_isolation_established": false,
8
+ "known_wrong_semantic_implementations": 0,
9
+ "native_inventory_sha256": "369230b94ab16c256349bf5d5b2670133aee18bbcf1d80f52adf8b31b5cd057c",
10
+ "new_files_deletions_and_executable_modes_supported": true,
11
+ "official_profile": {
12
+ "eval_sets": [],
13
+ "profile_class": "Exceptiongroup0b4f4937",
14
+ "profile_lines": [
15
+ 327,
16
+ 330
17
+ ],
18
+ "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f",
19
+ "profile_source_path": "swesmith/profiles/python.py",
20
+ "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286",
21
+ "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
22
+ "upstream_repo": "agronholm/exceptiongroup"
23
+ },
24
+ "original_bug_canary_nop_equivalent": true,
25
+ "original_bug_runtime_wrongness_established": false,
26
+ "partial_repair_canary": true,
27
+ "partial_repair_sha256": "715122d022d258ff100be2a0ccf1faa694f1973b4e317b84d9fdd63d98caa8c2",
28
+ "partial_repair_wrongness_established": false,
29
+ "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained",
30
+ "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7",
31
+ "private_checker_version": "matched-failure-precedence-v2",
32
+ "provided_original_bug_control": true,
33
+ "repo_url": "https://github.com/swesmith/agronholm__exceptiongroup.0b4f4937.git",
34
+ "runtime_image": null,
35
+ "runtime_ready": false,
36
+ "runtime_recipe": {
37
+ "dependency_installation_pinned": false,
38
+ "official_install_cmds": [
39
+ "python -m pip install -e ."
40
+ ],
41
+ "official_pytest_argv": [
42
+ "pytest",
43
+ "--disable-warnings",
44
+ "--color=no",
45
+ "--tb=no",
46
+ "--verbose"
47
+ ],
48
+ "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose",
49
+ "operator_test_runner_prerequisites": [
50
+ "python -m pip install pytest==8.4.2"
51
+ ],
52
+ "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.",
53
+ "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.",
54
+ "python_version": "3.10",
55
+ "source_bound_test_dependency_cmds": [
56
+ "python -m pip install -e '.[test]'"
57
+ ],
58
+ "test_dependency_source_sha256": {
59
+ "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5"
60
+ }
61
+ },
62
+ "runtime_resource_review_required": false,
63
+ "schema": "python-git-patch-jobs-v1",
64
+ "source_base_commit": "8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1",
65
+ "source_completion_sha256": "5db6ea55490a17844eb972c9dcce31a84c1ae0933ba8626b570059867468266b",
66
+ "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f",
67
+ "source_pr_url": null,
68
+ "source_record": {
69
+ "anti_training_canary": false,
70
+ "anti_training_reviewed": true,
71
+ "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m",
72
+ "cloud_launch_ready": false,
73
+ "eligibility": {
74
+ "reasons": [],
75
+ "semantic_nonoverlap_established": false,
76
+ "status": "eligible_for_controls",
77
+ "training_admissible": false,
78
+ "warnings": []
79
+ },
80
+ "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473",
81
+ "instruction_sha256": "c45d1874947b267e4b292561e2648ebe51913ef3e2a68f6901977cb4d52abd2d",
82
+ "is_fork": true,
83
+ "learner_path": "tasks/fe67ef95fd9d5db546113c55/learner",
84
+ "license_evidence": {
85
+ "source_code": {
86
+ "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
87
+ "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE",
88
+ "reviewed": true,
89
+ "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c",
90
+ "spdx": "MIT",
91
+ "training_allowed": true,
92
+ "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1/LICENSE"
93
+ },
94
+ "task_bundle": {
95
+ "reviewed": true,
96
+ "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808",
97
+ "spdx": "MIT",
98
+ "training_allowed": true,
99
+ "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md"
100
+ }
101
+ },
102
+ "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
103
+ "patch_sha256": "36b6dca9cc55639e2236e8be375369c4a7a6631d6124753dbac800c26e27407d",
104
+ "provenance_path": "tasks/fe67ef95fd9d5db546113c55/source-proof.json",
105
+ "repository_lineage": [
106
+ "swesmith/agronholm__exceptiongroup.0b4f4937",
107
+ "agronholm/exceptiongroup"
108
+ ],
109
+ "rfc008_complete": false,
110
+ "runtime_qualified": false,
111
+ "semantic_nonoverlap_established": false,
112
+ "source_commit": "8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1",
113
+ "source_dataset": "SWE-bench/SWE-smith-py",
114
+ "source_head_commit": "fd596d13e9491292248ca347cb2b2eafb56f9bd7",
115
+ "source_kind": "mutation",
116
+ "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937",
117
+ "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e",
118
+ "source_split": "train",
119
+ "target_model_calibrated": false,
120
+ "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m",
121
+ "task_sha256": "5e37ded2ca383688e19c649414dc2aa9186db9c8637ee00ced36634e1345e5a1",
122
+ "training_admissible": false,
123
+ "upstream_identity_reviewed": true,
124
+ "upstream_repo": "agronholm/exceptiongroup",
125
+ "usage": "quarantine_only"
126
+ },
127
+ "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937",
128
+ "symlink_submodule_changes_supported": false,
129
+ "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m",
130
+ "transfer": "index-independent-worktree-to-Git-binary-patch",
131
+ "transfer_path": "/testbed/submission.patch",
132
+ "upstream_repo": "agronholm/exceptiongroup"
133
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/dependency-setup.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -Eeuo pipefail
3
+ source /opt/miniconda3/bin/activate
4
+ conda activate testbed
5
+ cd /testbed/repo
6
+ python -c 'import sys; assert sys.version_info[:2] == (3, 10)'
7
+ python -m pip install pytest==8.4.2
8
+ python -m pip install -e .
9
+ python -m pip install -e '.[test]'
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Runtime is selected only by an independently qualified immutable amd64 receipt.
2
+ FROM ubuntu:22.04
3
+ RUN false
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/instruction.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BaseExceptionGroup constructor validation broken after recent changes
2
+
3
+ #### Description
4
+
5
+ The BaseExceptionGroup constructor is not properly validating input arguments and has broken type checking logic. When creating exception groups with invalid arguments or mixed exception types, the validation either fails completely or produces incorrect error messages.
6
+
7
+ #### Steps/Code to Reproduce
8
+
9
+ ```python
10
+ from exceptiongroup import BaseExceptionGroup, ExceptionGroup
11
+
12
+ # This should raise TypeError but doesn't validate properly
13
+ try:
14
+ BaseExceptionGroup(123, [ValueError("test")])
15
+ except Exception as e:
16
+ print(f"Got: {e}")
17
+
18
+ # This should work but validation logic is broken
19
+ try:
20
+ ExceptionGroup("test", [ValueError("foo"), KeyboardInterrupt("bar")])
21
+ except Exception as e:
22
+ print(f"Got: {e}")
23
+
24
+ # Constructor argument validation is inconsistent
25
+ try:
26
+ BaseExceptionGroup("test", "not a sequence")
27
+ except Exception as e:
28
+ print(f"Got: {e}")
29
+ ```
30
+
31
+ The error messages and validation behavior are inconsistent with what's expected. The constructor should properly validate that the message is a string, exceptions parameter is a non-empty sequence, and handle the type hierarchy correctly between BaseExceptionGroup and ExceptionGroup.
32
+
33
+ ## Environment
34
+
35
+ The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest <tests>`. Don't install packages: the tests need nothing else, and the sandbox may have no network access.
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/metadata.json ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "all_runtime_and_training_flags": false,
3
+ "official_profile": {
4
+ "eval_sets": [],
5
+ "profile_class": "Exceptiongroup0b4f4937",
6
+ "profile_lines": [
7
+ 327,
8
+ 330
9
+ ],
10
+ "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f",
11
+ "profile_source_path": "swesmith/profiles/python.py",
12
+ "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286",
13
+ "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
14
+ "upstream_repo": "agronholm/exceptiongroup"
15
+ },
16
+ "source_healthy_reference_proof": {
17
+ "FAIL_TO_PASS": [
18
+ "tests/test_catch.py::test_catch_ungrouped",
19
+ "tests/test_catch.py::test_catch_group",
20
+ "tests/test_catch.py::test_catch_nested_group",
21
+ "tests/test_catch.py::test_catch_no_match",
22
+ "tests/test_catch.py::test_bare_raise_in_handler",
23
+ "tests/test_catch.py::test_catch_subclass",
24
+ "tests/test_catch.py::test_bare_reraise_from_naked_exception",
25
+ "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence",
26
+ "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message",
27
+ "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions",
28
+ "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions",
29
+ "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG",
30
+ "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions",
31
+ "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError",
32
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match",
33
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match",
34
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match",
35
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match",
36
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match",
37
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match",
38
+ "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup",
39
+ "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type",
40
+ "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override",
41
+ "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override",
42
+ "tests/test_formatting.py::test_exceptionhook",
43
+ "tests/test_formatting.py::test_exceptiongroup_as_cause",
44
+ "tests/test_formatting.py::test_exceptiongroup_loop",
45
+ "tests/test_formatting.py::test_exceptionhook_format_exception_only",
46
+ "tests/test_formatting.py::test_format_exception[patched-newstyle]",
47
+ "tests/test_formatting.py::test_format_exception[patched-oldstyle]",
48
+ "tests/test_formatting.py::test_format_exception[unpatched-newstyle]",
49
+ "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]",
50
+ "tests/test_formatting.py::test_print_exception[patched-newstyle]",
51
+ "tests/test_formatting.py::test_print_exception[patched-oldstyle]",
52
+ "tests/test_formatting.py::test_print_exception[unpatched-newstyle]",
53
+ "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]",
54
+ "tests/test_formatting.py::test_print_exc[patched]",
55
+ "tests/test_formatting.py::test_print_exc[unpatched]",
56
+ "tests/test_suppress.py::test_suppress_exception"
57
+ ],
58
+ "PASS_TO_PASS": [
59
+ "tests/test_catch.py::test_bad_arg",
60
+ "tests/test_catch.py::test_bad_handler",
61
+ "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]",
62
+ "tests/test_catch.py::test_catch_exceptiongroup[naked_group]",
63
+ "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]",
64
+ "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]",
65
+ "tests/test_catch.py::test_catch_single_no_match",
66
+ "tests/test_catch.py::test_catch_full_match",
67
+ "tests/test_catch.py::test_catch_handler_raises",
68
+ "tests/test_catch.py::test_async_handler",
69
+ "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type",
70
+ "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types",
71
+ "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args",
72
+ "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args",
73
+ "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG",
74
+ "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions",
75
+ "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG",
76
+ "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields",
77
+ "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes",
78
+ "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly",
79
+ "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists",
80
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match",
81
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough",
82
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match",
83
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough",
84
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type",
85
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough",
86
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough",
87
+ "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split",
88
+ "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup",
89
+ "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator",
90
+ "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks",
91
+ "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks",
92
+ "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining",
93
+ "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template",
94
+ "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides",
95
+ "tests/test_exceptions.py::test_repr",
96
+ "tests/test_formatting.py::test_formatting_syntax_error",
97
+ "tests/test_formatting.py::test_format_nested",
98
+ "tests/test_formatting.py::test_format_exception_only[patched-newstyle]",
99
+ "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]",
100
+ "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]",
101
+ "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]",
102
+ "tests/test_formatting.py::test_nameerror_suggestions[patched]",
103
+ "tests/test_formatting.py::test_nameerror_suggestions[unpatched]",
104
+ "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]",
105
+ "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]",
106
+ "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]",
107
+ "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]",
108
+ "tests/test_formatting.py::test_works_around_httperror_bug"
109
+ ],
110
+ "all_git_blobs_modes_verified": true,
111
+ "cloud_launch_ready": false,
112
+ "commits": {
113
+ "bug": "fd596d13e9491292248ca347cb2b2eafb56f9bd7",
114
+ "healthy": "2afba2eefd1899b919eac83e3e73360deca0d473",
115
+ "learner": "8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1"
116
+ },
117
+ "existing_squirrel_snapshot_reused": false,
118
+ "full_transfer_allowlist": [
119
+ "/testbed/.github/ISSUE_TEMPLATE/bug_report.yaml",
120
+ "/testbed/.github/ISSUE_TEMPLATE/config.yml",
121
+ "/testbed/.github/ISSUE_TEMPLATE/features_request.yaml",
122
+ "/testbed/.gitignore",
123
+ "/testbed/.pre-commit-config.yaml",
124
+ "/testbed/CHANGES.rst",
125
+ "/testbed/LICENSE",
126
+ "/testbed/README.rst",
127
+ "/testbed/pyproject.toml",
128
+ "/testbed/src/exceptiongroup/__init__.py",
129
+ "/testbed/src/exceptiongroup/_catch.py",
130
+ "/testbed/src/exceptiongroup/_exceptions.py",
131
+ "/testbed/src/exceptiongroup/_formatting.py",
132
+ "/testbed/src/exceptiongroup/_suppress.py",
133
+ "/testbed/src/exceptiongroup/py.typed",
134
+ "/testbed/tests/__init__.py",
135
+ "/testbed/tests/apport_excepthook.py",
136
+ "/testbed/tests/check_types.py",
137
+ "/testbed/tests/conftest.py",
138
+ "/testbed/tests/test_apport_monkeypatching.py",
139
+ "/testbed/tests/test_catch_py311.py"
140
+ ],
141
+ "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed",
142
+ "mutation_matches_dataset_and_git_blobs": true,
143
+ "official_profile": {
144
+ "eval_sets": [],
145
+ "profile_class": "Exceptiongroup0b4f4937",
146
+ "profile_lines": [
147
+ 327,
148
+ 330
149
+ ],
150
+ "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f",
151
+ "profile_source_path": "swesmith/profiles/python.py",
152
+ "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286",
153
+ "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
154
+ "upstream_repo": "agronholm/exceptiongroup"
155
+ },
156
+ "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
157
+ "private_test_paths": [
158
+ "tests/test_catch.py",
159
+ "tests/test_exceptions.py",
160
+ "tests/test_formatting.py",
161
+ "tests/test_suppress.py"
162
+ ],
163
+ "private_tests_unchanged": true,
164
+ "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference",
165
+ "qwen_calibrated": false,
166
+ "runtime_qualified": false,
167
+ "source_paths": [
168
+ "src/exceptiongroup/_exceptions.py",
169
+ "src/exceptiongroup/_formatting.py"
170
+ ],
171
+ "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937",
172
+ "source_stages_bytes": 324118,
173
+ "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m",
174
+ "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter",
175
+ "upstream_repo": "agronholm/exceptiongroup"
176
+ },
177
+ "source_record": {
178
+ "anti_training_canary": false,
179
+ "anti_training_reviewed": true,
180
+ "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m",
181
+ "cloud_launch_ready": false,
182
+ "eligibility": {
183
+ "reasons": [],
184
+ "semantic_nonoverlap_established": false,
185
+ "status": "eligible_for_controls",
186
+ "training_admissible": false,
187
+ "warnings": []
188
+ },
189
+ "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473",
190
+ "instruction_sha256": "c45d1874947b267e4b292561e2648ebe51913ef3e2a68f6901977cb4d52abd2d",
191
+ "is_fork": true,
192
+ "learner_path": "tasks/fe67ef95fd9d5db546113c55/learner",
193
+ "license_evidence": {
194
+ "source_code": {
195
+ "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
196
+ "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE",
197
+ "reviewed": true,
198
+ "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c",
199
+ "spdx": "MIT",
200
+ "training_allowed": true,
201
+ "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1/LICENSE"
202
+ },
203
+ "task_bundle": {
204
+ "reviewed": true,
205
+ "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808",
206
+ "spdx": "MIT",
207
+ "training_allowed": true,
208
+ "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md"
209
+ }
210
+ },
211
+ "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
212
+ "patch_sha256": "36b6dca9cc55639e2236e8be375369c4a7a6631d6124753dbac800c26e27407d",
213
+ "provenance_path": "tasks/fe67ef95fd9d5db546113c55/source-proof.json",
214
+ "repository_lineage": [
215
+ "swesmith/agronholm__exceptiongroup.0b4f4937",
216
+ "agronholm/exceptiongroup"
217
+ ],
218
+ "rfc008_complete": false,
219
+ "runtime_qualified": false,
220
+ "semantic_nonoverlap_established": false,
221
+ "source_commit": "8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1",
222
+ "source_dataset": "SWE-bench/SWE-smith-py",
223
+ "source_head_commit": "fd596d13e9491292248ca347cb2b2eafb56f9bd7",
224
+ "source_kind": "mutation",
225
+ "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937",
226
+ "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e",
227
+ "source_split": "train",
228
+ "target_model_calibrated": false,
229
+ "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m",
230
+ "task_sha256": "5e37ded2ca383688e19c649414dc2aa9186db9c8637ee00ced36634e1345e5a1",
231
+ "training_admissible": false,
232
+ "upstream_identity_reviewed": true,
233
+ "upstream_repo": "agronholm/exceptiongroup",
234
+ "usage": "quarantine_only"
235
+ },
236
+ "task_kind": "original-source-mutation"
237
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/provenance.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "generated_reference": false,
3
+ "healthy_reference_delta_sha256": "c68ac6e7d7b1b38e90c59ce45d47c6a722ce8e9971b65335f1c598bd59a7a8d7",
4
+ "native_pytest_ids_preserved": true,
5
+ "original_source_code_license": {
6
+ "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
7
+ "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE",
8
+ "reviewed": true,
9
+ "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c",
10
+ "spdx": "MIT",
11
+ "training_allowed": true,
12
+ "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1/LICENSE"
13
+ },
14
+ "provided_reference": true,
15
+ "qwen_calibrated": false,
16
+ "runtime_qualified": false,
17
+ "source_completion_sha256": "5db6ea55490a17844eb972c9dcce31a84c1ae0933ba8626b570059867468266b",
18
+ "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f",
19
+ "source_proof_sha256": "8bdda4562087d1c42374a06ae27cf04eb5548aef236de2bd17df953f39c04aef",
20
+ "source_record": {
21
+ "anti_training_canary": false,
22
+ "anti_training_reviewed": true,
23
+ "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m",
24
+ "cloud_launch_ready": false,
25
+ "eligibility": {
26
+ "reasons": [],
27
+ "semantic_nonoverlap_established": false,
28
+ "status": "eligible_for_controls",
29
+ "training_admissible": false,
30
+ "warnings": []
31
+ },
32
+ "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473",
33
+ "instruction_sha256": "c45d1874947b267e4b292561e2648ebe51913ef3e2a68f6901977cb4d52abd2d",
34
+ "is_fork": true,
35
+ "learner_path": "tasks/fe67ef95fd9d5db546113c55/learner",
36
+ "license_evidence": {
37
+ "source_code": {
38
+ "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
39
+ "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE",
40
+ "reviewed": true,
41
+ "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c",
42
+ "spdx": "MIT",
43
+ "training_allowed": true,
44
+ "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1/LICENSE"
45
+ },
46
+ "task_bundle": {
47
+ "reviewed": true,
48
+ "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808",
49
+ "spdx": "MIT",
50
+ "training_allowed": true,
51
+ "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md"
52
+ }
53
+ },
54
+ "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
55
+ "patch_sha256": "36b6dca9cc55639e2236e8be375369c4a7a6631d6124753dbac800c26e27407d",
56
+ "provenance_path": "tasks/fe67ef95fd9d5db546113c55/source-proof.json",
57
+ "repository_lineage": [
58
+ "swesmith/agronholm__exceptiongroup.0b4f4937",
59
+ "agronholm/exceptiongroup"
60
+ ],
61
+ "rfc008_complete": false,
62
+ "runtime_qualified": false,
63
+ "semantic_nonoverlap_established": false,
64
+ "source_commit": "8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1",
65
+ "source_dataset": "SWE-bench/SWE-smith-py",
66
+ "source_head_commit": "fd596d13e9491292248ca347cb2b2eafb56f9bd7",
67
+ "source_kind": "mutation",
68
+ "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937",
69
+ "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e",
70
+ "source_split": "train",
71
+ "target_model_calibrated": false,
72
+ "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m",
73
+ "task_sha256": "5e37ded2ca383688e19c649414dc2aa9186db9c8637ee00ced36634e1345e5a1",
74
+ "training_admissible": false,
75
+ "upstream_identity_reviewed": true,
76
+ "upstream_repo": "agronholm/exceptiongroup",
77
+ "usage": "quarantine_only"
78
+ },
79
+ "task_bundle_license": {
80
+ "reviewed": true,
81
+ "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808",
82
+ "spdx": "MIT",
83
+ "training_allowed": true,
84
+ "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md"
85
+ },
86
+ "training_admissible": false,
87
+ "trusted_tests_sha256": "1a8481adc545af13be5f1f3f791b88d9b11668589fbbd44bc619ce8ed322bb55"
88
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/provided-gold.diff ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py
2
+ index e39c9f74e783a6b30a39dd0fb19bc5883e7ff54a..a4a7acea822d43ba91183cff0b44f31313171d1a 100644
3
+ --- a/src/exceptiongroup/_exceptions.py
4
+ +++ b/src/exceptiongroup/_exceptions.py
5
+ @@ -56,26 +56,47 @@
6
+ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
7
+ """A combination of multiple unrelated exceptions."""
8
+
9
+ - def __new__(cls: type[_BaseExceptionGroupSelf], __message: str,
10
+ - __exceptions: Sequence[_BaseExceptionT_co]) ->_BaseExceptionGroupSelf:
11
+ - """Create a new BaseExceptionGroup instance."""
12
+ + def __new__(
13
+ + cls: type[_BaseExceptionGroupSelf],
14
+ + __message: str,
15
+ + __exceptions: Sequence[_BaseExceptionT_co],
16
+ + ) -> _BaseExceptionGroupSelf:
17
+ if not isinstance(__message, str):
18
+ - raise TypeError(f"message must be a string, not {type(__message).__name__}")
19
+ -
20
+ + raise TypeError(f"argument 1 must be str, not {type(__message)}")
21
+ + if not isinstance(__exceptions, Sequence):
22
+ + raise TypeError("second argument (exceptions) must be a sequence")
23
+ if not __exceptions:
24
+ - raise ValueError("exceptions must be a non-empty sequence")
25
+ -
26
+ + raise ValueError(
27
+ + "second argument (exceptions) must be a non-empty sequence"
28
+ + )
29
+ +
30
+ for i, exc in enumerate(__exceptions):
31
+ if not isinstance(exc, BaseException):
32
+ - raise TypeError(
33
+ - f"Item {i} of exceptions sequence: expected an exception object, "
34
+ - f"got {type(exc).__name__}"
35
+ + raise ValueError(
36
+ + f"Item {i} of second argument (exceptions) is not an exception"
37
+ )
38
+ -
39
+ - instance = super().__new__(cls)
40
+ +
41
+ + if cls is BaseExceptionGroup:
42
+ + if all(isinstance(exc, Exception) for exc in __exceptions):
43
+ + cls = ExceptionGroup
44
+ +
45
+ + if issubclass(cls, Exception):
46
+ + for exc in __exceptions:
47
+ + if not isinstance(exc, Exception):
48
+ + if cls is ExceptionGroup:
49
+ + raise TypeError(
50
+ + "Cannot nest BaseExceptions in an ExceptionGroup"
51
+ + )
52
+ + else:
53
+ + raise TypeError(
54
+ + f"Cannot nest BaseExceptions in {cls.__name__!r}"
55
+ + )
56
+ +
57
+ + instance = super().__new__(cls, __message, __exceptions)
58
+ instance._message = __message
59
+ - instance._exceptions = list(__exceptions)
60
+ + instance._exceptions = __exceptions
61
+ return instance
62
+ +
63
+ def add_note(self, note: str) -> None:
64
+ if not isinstance(note, str):
65
+ raise TypeError(
66
+ diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py
67
+ index 04d09861d6a071d23c9c2b88b009fe880124f7bb..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644
68
+ --- a/src/exceptiongroup/_formatting.py
69
+ +++ b/src/exceptiongroup/_formatting.py
70
+ @@ -267,10 +267,10 @@
71
+ if num_excs <= max_group_width:
72
+ n = num_excs
73
+ else:
74
+ - n = max_group_width + 0
75
+ + n = max_group_width + 1
76
+ _ctx.need_close = False
77
+ for i in range(n):
78
+ - last_exc = i == n - 0
79
+ + last_exc = i == n - 1
80
+ if last_exc:
81
+ # The closing frame may be added by a recursive call
82
+ _ctx.need_close = True
83
+ @@ -303,6 +303,7 @@
84
+ if is_toplevel:
85
+ assert _ctx.exception_group_depth == 1
86
+ _ctx.exception_group_depth = 0
87
+ +
88
+ def format_exception_only(self):
89
+ """Format the exception part of the traceback.
90
+ The return value is a generator of strings, each ending in a newline.
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/solution/solve.sh ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -Eeuo pipefail
3
+ cd /testbed/repo
4
+ cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE'
5
+ diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py
6
+ index e39c9f74e783a6b30a39dd0fb19bc5883e7ff54a..a4a7acea822d43ba91183cff0b44f31313171d1a 100644
7
+ --- a/src/exceptiongroup/_exceptions.py
8
+ +++ b/src/exceptiongroup/_exceptions.py
9
+ @@ -56,26 +56,47 @@
10
+ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
11
+ """A combination of multiple unrelated exceptions."""
12
+
13
+ - def __new__(cls: type[_BaseExceptionGroupSelf], __message: str,
14
+ - __exceptions: Sequence[_BaseExceptionT_co]) ->_BaseExceptionGroupSelf:
15
+ - """Create a new BaseExceptionGroup instance."""
16
+ + def __new__(
17
+ + cls: type[_BaseExceptionGroupSelf],
18
+ + __message: str,
19
+ + __exceptions: Sequence[_BaseExceptionT_co],
20
+ + ) -> _BaseExceptionGroupSelf:
21
+ if not isinstance(__message, str):
22
+ - raise TypeError(f"message must be a string, not {type(__message).__name__}")
23
+ -
24
+ + raise TypeError(f"argument 1 must be str, not {type(__message)}")
25
+ + if not isinstance(__exceptions, Sequence):
26
+ + raise TypeError("second argument (exceptions) must be a sequence")
27
+ if not __exceptions:
28
+ - raise ValueError("exceptions must be a non-empty sequence")
29
+ -
30
+ + raise ValueError(
31
+ + "second argument (exceptions) must be a non-empty sequence"
32
+ + )
33
+ +
34
+ for i, exc in enumerate(__exceptions):
35
+ if not isinstance(exc, BaseException):
36
+ - raise TypeError(
37
+ - f"Item {i} of exceptions sequence: expected an exception object, "
38
+ - f"got {type(exc).__name__}"
39
+ + raise ValueError(
40
+ + f"Item {i} of second argument (exceptions) is not an exception"
41
+ )
42
+ -
43
+ - instance = super().__new__(cls)
44
+ +
45
+ + if cls is BaseExceptionGroup:
46
+ + if all(isinstance(exc, Exception) for exc in __exceptions):
47
+ + cls = ExceptionGroup
48
+ +
49
+ + if issubclass(cls, Exception):
50
+ + for exc in __exceptions:
51
+ + if not isinstance(exc, Exception):
52
+ + if cls is ExceptionGroup:
53
+ + raise TypeError(
54
+ + "Cannot nest BaseExceptions in an ExceptionGroup"
55
+ + )
56
+ + else:
57
+ + raise TypeError(
58
+ + f"Cannot nest BaseExceptions in {cls.__name__!r}"
59
+ + )
60
+ +
61
+ + instance = super().__new__(cls, __message, __exceptions)
62
+ instance._message = __message
63
+ - instance._exceptions = list(__exceptions)
64
+ + instance._exceptions = __exceptions
65
+ return instance
66
+ +
67
+ def add_note(self, note: str) -> None:
68
+ if not isinstance(note, str):
69
+ raise TypeError(
70
+ diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py
71
+ index 04d09861d6a071d23c9c2b88b009fe880124f7bb..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644
72
+ --- a/src/exceptiongroup/_formatting.py
73
+ +++ b/src/exceptiongroup/_formatting.py
74
+ @@ -267,10 +267,10 @@
75
+ if num_excs <= max_group_width:
76
+ n = num_excs
77
+ else:
78
+ - n = max_group_width + 0
79
+ + n = max_group_width + 1
80
+ _ctx.need_close = False
81
+ for i in range(n):
82
+ - last_exc = i == n - 0
83
+ + last_exc = i == n - 1
84
+ if last_exc:
85
+ # The closing frame may be added by a recursive call
86
+ _ctx.need_close = True
87
+ @@ -303,6 +303,7 @@
88
+ if is_toplevel:
89
+ assert _ctx.exception_group_depth == 1
90
+ _ctx.exception_group_depth = 0
91
+ +
92
+ def format_exception_only(self):
93
+ """Format the exception part of the traceback.
94
+ The return value is a generator of strings, each ending in a newline.
95
+ OPENENV_REFERENCE
96
+ /usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/task.toml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [agent]
4
+ timeout_sec = 1800.0
5
+
6
+ [verifier]
7
+ timeout_sec = 900.0
8
+
9
+ [environment]
10
+ docker_image = "ghcr.io/younesbelkada/scale800@sha256:c8802faa2d33fb485669d94da83b6ca4d9317e8549f24bf1f890a8a3c38f18f6"
11
+ build_timeout_sec = 600.0
12
+ cpus = 2
13
+ memory_mb = 8192
14
+ storage_mb = 16384
15
+
16
+ [metadata]
17
+ author_name = "SWE-smith source adapter"
18
+ category = "bugfix"
19
+ tags = ["swe", "python", "mutation-repair"]
20
+
21
+ [environment.env]
22
+ # The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's
23
+ # non-interactive shells never run `conda activate`
24
+ PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/check_pytest.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Preserve confirmed requested assertion failures; keep positive checks strict."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import re
7
+ import xml.etree.ElementTree as ET
8
+ from pathlib import Path
9
+
10
+ GROUPS = ("pass-to-pass", "fail-to-pass")
11
+
12
+
13
+ def split_nodeid(target):
14
+ prefix, bracket, parameter = target.partition("[")
15
+ parts = prefix.split("::")
16
+ if bracket:
17
+ parts[-1] += bracket + parameter
18
+ return parts
19
+
20
+
21
+ def matches(case, target):
22
+ parts = split_nodeid(target)
23
+ module = parts[0].removesuffix(".py").replace("/", ".")
24
+ classname, name = case.get("classname", ""), case.get("name", "")
25
+ if not (classname == module or classname.startswith(module + ".")):
26
+ return False
27
+ selector = parts[-1] if len(parts) > 1 else ""
28
+ classes = parts[1:-1]
29
+ if classes and classname != module + "." + ".".join(classes):
30
+ return False
31
+ return (
32
+ not selector
33
+ or name == selector
34
+ or ("[" not in selector and name.startswith(selector + "["))
35
+ )
36
+
37
+
38
+ def capture_panels(root):
39
+ panels, digests = {}, {}
40
+ for group in GROUPS:
41
+ path = Path(root) / (group + ".xml")
42
+ if not path.exists():
43
+ panels[group] = None
44
+ continue
45
+ with path.open("rb") as stream:
46
+ raw = stream.read(4 * 1024**2 + 1)
47
+ if not 0 < len(raw) <= 4 * 1024**2 or re.search(
48
+ rb"<!\s*(?:DOCTYPE|ENTITY)", raw, re.I
49
+ ):
50
+ raise ValueError("Unbounded or unsafe pytest XML")
51
+ try:
52
+ tree = ET.fromstring(raw)
53
+ except ET.ParseError:
54
+ raise ValueError("Malformed pytest XML") from None
55
+ cases = list(tree.iter("testcase"))
56
+ if len(cases) > 20000:
57
+ raise ValueError("Too many pytest cases")
58
+ identities = [(case.get("classname"), case.get("name")) for case in cases]
59
+ if len(identities) != len(set(identities)):
60
+ raise ValueError("Duplicate pytest case evidence")
61
+ panels[group] = cases
62
+ digests[group] = hashlib.sha256(raw).hexdigest()
63
+ return panels, digests
64
+
65
+
66
+ def strict_assess(panels, expected, native_exit):
67
+ """The original positive-approval conditions, applied to captured cases."""
68
+ all_cases, actual_failure = [], False
69
+ for group in GROUPS:
70
+ cases = panels[group]
71
+ if cases is None:
72
+ if actual_failure:
73
+ continue
74
+ raise ValueError("Missing preceding pytest panel")
75
+ if actual_failure:
76
+ raise ValueError(
77
+ "Pytest evidence continued after the native stop-on-failure"
78
+ )
79
+ targets = expected[group]
80
+ if any(not any(matches(case, target) for target in targets) for case in cases):
81
+ raise ValueError("Unexpected pytest case")
82
+ all_cases.extend(cases)
83
+ failures = [case for case in cases if case.find("failure") is not None]
84
+ if any(
85
+ case.find("error") is not None or case.find("skipped") is not None
86
+ for case in cases
87
+ ):
88
+ raise ValueError("Pytest collection/error/skip is not a completed panel")
89
+ actual_failure = actual_failure or bool(failures)
90
+ if not failures and any(
91
+ not any(matches(case, target) for case in cases) for target in targets
92
+ ):
93
+ raise ValueError("Declared pytest target never ran")
94
+ if actual_failure:
95
+ if native_exit == 0:
96
+ raise ValueError("Native verifier exit disagrees with pytest failure")
97
+ return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)}
98
+ if native_exit != 0:
99
+ raise ValueError("Setup or native verifier failed without a real test failure")
100
+ if any(panels[group] is None for group in GROUPS):
101
+ raise ValueError("Missing completed pytest panel")
102
+ return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)}
103
+
104
+
105
+ def assess(root, expected, native_exit):
106
+ if type(native_exit) is not int:
107
+ raise ValueError("Native verifier exit must be an integer")
108
+ if not isinstance(expected, dict) or any(
109
+ not isinstance(expected.get(group), list)
110
+ or not expected[group]
111
+ or any(not isinstance(target, str) or not target for target in expected[group])
112
+ for group in GROUPS
113
+ ):
114
+ raise ValueError("Complete exact native pytest targets required")
115
+ panels, digests = capture_panels(root)
116
+ counts = {
117
+ "cases": 0,
118
+ "matched_failures": 0,
119
+ "unexpected_cases": 0,
120
+ "unmatched_failures": 0,
121
+ "skipped_cases": 0,
122
+ "error_cases": 0,
123
+ "missing_panels": 0,
124
+ "missing_targets": 0,
125
+ }
126
+ for group in GROUPS:
127
+ cases = panels[group]
128
+ if cases is None:
129
+ counts["missing_panels"] += 1
130
+ counts["missing_targets"] += len(expected[group])
131
+ continue
132
+ counts["cases"] += len(cases)
133
+ for case in cases:
134
+ requested = any(matches(case, target) for target in expected[group])
135
+ failure = case.find("failure") is not None
136
+ counts["matched_failures"] += int(requested and failure)
137
+ counts["unmatched_failures"] += int(not requested and failure)
138
+ counts["unexpected_cases"] += int(not requested)
139
+ counts["skipped_cases"] += int(case.find("skipped") is not None)
140
+ counts["error_cases"] += int(case.find("error") is not None)
141
+ counts["missing_targets"] += sum(
142
+ not any(matches(case, target) for case in cases)
143
+ for target in expected[group]
144
+ )
145
+ if counts["matched_failures"]:
146
+ if native_exit == 0:
147
+ raise ValueError(
148
+ "Native verifier exit disagrees with requested pytest failure"
149
+ )
150
+ return {
151
+ "reward": 0,
152
+ "valid_test_failure": True,
153
+ "cases": counts["cases"],
154
+ "diagnostic_counts": counts,
155
+ "panel_sha256": digests,
156
+ "decision": "confirmed_requested_failure_precedence",
157
+ }
158
+ result = strict_assess(panels, expected, native_exit)
159
+ result.update(diagnostic_counts=counts, panel_sha256=digests)
160
+ return result
161
+
162
+
163
+ if __name__ == "__main__":
164
+ parser = argparse.ArgumentParser()
165
+ parser.add_argument("--root", required=True)
166
+ parser.add_argument("--expected", required=True)
167
+ parser.add_argument("--native-exit", type=int, required=True)
168
+ args = parser.parse_args()
169
+ result = assess(
170
+ args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit
171
+ )
172
+ reward = Path(args.root) / "reward.txt"
173
+ if reward.read_text().strip() != str(result["reward"]):
174
+ raise ValueError("Native raw reward disagrees with pytest evidence")
175
+ (Path(args.root) / "pytest-evidence.json").write_text(
176
+ json.dumps(result, sort_keys=True) + "\n"
177
+ )
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/expected-panels.json ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fail-to-pass": [
3
+ "tests/test_catch.py::test_catch_ungrouped",
4
+ "tests/test_catch.py::test_catch_group",
5
+ "tests/test_catch.py::test_catch_nested_group",
6
+ "tests/test_catch.py::test_catch_no_match",
7
+ "tests/test_catch.py::test_bare_raise_in_handler",
8
+ "tests/test_catch.py::test_catch_subclass",
9
+ "tests/test_catch.py::test_bare_reraise_from_naked_exception",
10
+ "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence",
11
+ "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message",
12
+ "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions",
13
+ "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions",
14
+ "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG",
15
+ "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions",
16
+ "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError",
17
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match",
18
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match",
19
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match",
20
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match",
21
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match",
22
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match",
23
+ "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup",
24
+ "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type",
25
+ "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override",
26
+ "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override",
27
+ "tests/test_formatting.py::test_exceptionhook",
28
+ "tests/test_formatting.py::test_exceptiongroup_as_cause",
29
+ "tests/test_formatting.py::test_exceptiongroup_loop",
30
+ "tests/test_formatting.py::test_exceptionhook_format_exception_only",
31
+ "tests/test_formatting.py::test_format_exception[patched-newstyle]",
32
+ "tests/test_formatting.py::test_format_exception[patched-oldstyle]",
33
+ "tests/test_formatting.py::test_format_exception[unpatched-newstyle]",
34
+ "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]",
35
+ "tests/test_formatting.py::test_print_exception[patched-newstyle]",
36
+ "tests/test_formatting.py::test_print_exception[patched-oldstyle]",
37
+ "tests/test_formatting.py::test_print_exception[unpatched-newstyle]",
38
+ "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]",
39
+ "tests/test_formatting.py::test_print_exc[patched]",
40
+ "tests/test_formatting.py::test_print_exc[unpatched]",
41
+ "tests/test_suppress.py::test_suppress_exception"
42
+ ],
43
+ "pass-to-pass": [
44
+ "tests/test_catch.py::test_bad_arg",
45
+ "tests/test_catch.py::test_bad_handler",
46
+ "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]",
47
+ "tests/test_catch.py::test_catch_exceptiongroup[naked_group]",
48
+ "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]",
49
+ "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]",
50
+ "tests/test_catch.py::test_catch_single_no_match",
51
+ "tests/test_catch.py::test_catch_full_match",
52
+ "tests/test_catch.py::test_catch_handler_raises",
53
+ "tests/test_catch.py::test_async_handler",
54
+ "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type",
55
+ "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types",
56
+ "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args",
57
+ "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args",
58
+ "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG",
59
+ "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions",
60
+ "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG",
61
+ "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields",
62
+ "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes",
63
+ "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly",
64
+ "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists",
65
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match",
66
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough",
67
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match",
68
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough",
69
+ "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type",
70
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough",
71
+ "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough",
72
+ "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split",
73
+ "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup",
74
+ "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator",
75
+ "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks",
76
+ "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks",
77
+ "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining",
78
+ "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template",
79
+ "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides",
80
+ "tests/test_exceptions.py::test_repr",
81
+ "tests/test_formatting.py::test_formatting_syntax_error",
82
+ "tests/test_formatting.py::test_format_nested",
83
+ "tests/test_formatting.py::test_format_exception_only[patched-newstyle]",
84
+ "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]",
85
+ "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]",
86
+ "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]",
87
+ "tests/test_formatting.py::test_nameerror_suggestions[patched]",
88
+ "tests/test_formatting.py::test_nameerror_suggestions[unpatched]",
89
+ "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]",
90
+ "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]",
91
+ "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]",
92
+ "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]",
93
+ "tests/test_formatting.py::test_works_around_httperror_bug"
94
+ ]
95
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/grade.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trusted private pytest panel runner. Installed only in a fresh grader Job."""
2
+
3
+ import hashlib
4
+ import importlib.util
5
+ import json
6
+ import os
7
+ import shutil
8
+ import stat
9
+ import subprocess
10
+ from pathlib import Path, PurePosixPath
11
+
12
+
13
+ def sha(raw):
14
+ return hashlib.sha256(raw).hexdigest()
15
+
16
+
17
+ def safe(value):
18
+ path = PurePosixPath(value)
19
+ if (
20
+ path.is_absolute()
21
+ or path.as_posix() != value
22
+ or not path.parts
23
+ or any(part in {".", "..", ".git"} for part in path.parts)
24
+ ):
25
+ raise ValueError("Unsafe trusted test path")
26
+ return path
27
+
28
+
29
+ def restore(worktree, private, manifest):
30
+ worktree, private = Path(worktree), Path(private)
31
+ captured = {}
32
+ for name, expected in manifest["files"].items():
33
+ path = private / safe(name)
34
+ info = path.lstat()
35
+ raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b""
36
+ if (
37
+ not stat.S_ISREG(info.st_mode)
38
+ or len(raw) != expected["bytes"]
39
+ or sha(raw) != expected["sha256"]
40
+ or stat.S_IMODE(info.st_mode) != expected["mode"]
41
+ ):
42
+ raise ValueError("Trusted private test bytes or modes drifted")
43
+ captured[name] = (raw, expected["mode"])
44
+ # Capture and verify every private byte before changing the submitted tree.
45
+ for name in manifest["directory_roots"]:
46
+ destination = worktree / safe(name)
47
+ if destination.is_symlink():
48
+ raise ValueError("Submitted test directory is a symlink")
49
+ for parent in destination.parents:
50
+ if parent == worktree:
51
+ break
52
+ if parent.is_symlink():
53
+ raise ValueError("Submitted test parent is a symlink")
54
+ if destination.exists():
55
+ if not destination.is_dir():
56
+ raise ValueError("Submitted test directory is not a directory")
57
+ shutil.rmtree(destination)
58
+ for name, (raw, mode) in captured.items():
59
+ destination = worktree / safe(name)
60
+ for parent in destination.parents:
61
+ if parent == worktree:
62
+ break
63
+ if parent.is_symlink():
64
+ raise ValueError("Submitted test parent is a symlink")
65
+ if destination.is_symlink():
66
+ raise ValueError("Submitted trusted file is a symlink")
67
+ destination.parent.mkdir(parents=True, exist_ok=True)
68
+ destination.write_bytes(raw)
69
+ destination.chmod(mode)
70
+
71
+
72
+ def run(worktree, private_root, output, invoke=None):
73
+ private_root, output, worktree = Path(private_root), Path(output), Path(worktree)
74
+ expected = json.loads((private_root / "expected-panels.json").read_bytes())
75
+ config = json.loads((private_root / "panel-config.json").read_bytes())
76
+ manifest = json.loads((private_root / "trusted-inventory.json").read_bytes())
77
+ restore(worktree, private_root / "trusted", manifest)
78
+ output.mkdir(parents=True, exist_ok=True)
79
+ for name in (
80
+ "reward.txt",
81
+ "pass-to-pass.xml",
82
+ "fail-to-pass.xml",
83
+ "pytest-evidence.json",
84
+ ):
85
+ (output / name).unlink(missing_ok=True)
86
+ environment = dict(os.environ)
87
+ for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"):
88
+ environment.pop(key, None)
89
+ commands, native_exit = [], 0
90
+ invoke = invoke or subprocess.run
91
+ for group in ("pass-to-pass", "fail-to-pass"):
92
+ if (
93
+ not isinstance(expected[group], list)
94
+ or not expected[group]
95
+ or any(
96
+ not isinstance(target, str) or not target for target in expected[group]
97
+ )
98
+ ):
99
+ raise ValueError("Frozen native pytest selectors are incomplete")
100
+ command = [
101
+ *config["official_pytest_argv"],
102
+ "--override-ini=addopts=",
103
+ "--junitxml=" + str(output / (group + ".xml")),
104
+ *expected[group],
105
+ ]
106
+ result = invoke(command, cwd=worktree, env=environment, check=False)
107
+ native_exit = result.returncode
108
+ commands.append({"group": group, "argv": command, "exit_code": native_exit})
109
+ if native_exit != 0:
110
+ break
111
+ (output / "pytest-commands.json").write_text(
112
+ json.dumps(commands, sort_keys=True) + "\n"
113
+ )
114
+ spec = importlib.util.spec_from_file_location(
115
+ "trusted_pytest_result", private_root / "check_pytest.py"
116
+ )
117
+ checker = importlib.util.module_from_spec(spec)
118
+ spec.loader.exec_module(checker)
119
+ result = checker.assess(output, expected, native_exit)
120
+ (output / "reward.txt").write_text(str(result["reward"]) + "\n")
121
+ (output / "pytest-evidence.json").write_text(
122
+ json.dumps(result, sort_keys=True) + "\n"
123
+ )
124
+ return result
125
+
126
+
127
+ if __name__ == "__main__":
128
+ run("/testbed/repo", "/tests", "/logs/verifier")
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/panel-config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dependency_installation_pinned": false,
3
+ "official_install_cmds": [
4
+ "python -m pip install -e ."
5
+ ],
6
+ "official_pytest_argv": [
7
+ "pytest",
8
+ "--disable-warnings",
9
+ "--color=no",
10
+ "--tb=no",
11
+ "--verbose"
12
+ ],
13
+ "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose",
14
+ "operator_test_runner_prerequisites": [
15
+ "python -m pip install pytest==8.4.2"
16
+ ],
17
+ "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.",
18
+ "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.",
19
+ "python_version": "3.10",
20
+ "source_bound_test_dependency_cmds": [
21
+ "python -m pip install -e '.[test]'"
22
+ ],
23
+ "test_dependency_source_sha256": {
24
+ "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5"
25
+ }
26
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/test.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -Eeuo pipefail
3
+ source /opt/miniconda3/bin/activate
4
+ conda activate testbed
5
+ cd /testbed/repo
6
+ exec python -I /tests/grade.py
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted-inventory.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "directory_roots": [
3
+ "tests"
4
+ ],
5
+ "files": {
6
+ "pyproject.toml": {
7
+ "bytes": 2630,
8
+ "mode": 420,
9
+ "sha256": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5"
10
+ },
11
+ "tests/__init__.py": {
12
+ "bytes": 0,
13
+ "mode": 420,
14
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
15
+ },
16
+ "tests/apport_excepthook.py": {
17
+ "bytes": 466,
18
+ "mode": 420,
19
+ "sha256": "5b5a85531a20839ff1c624a2b5a8eb2d00b41e5a5c467b037daa9f23acbb126d"
20
+ },
21
+ "tests/check_types.py": {
22
+ "bytes": 1025,
23
+ "mode": 420,
24
+ "sha256": "07bc5f001f4194d6910999aa5c76c5d2e99a3274fa970f77015c0ed7cebf5fea"
25
+ },
26
+ "tests/conftest.py": {
27
+ "bytes": 84,
28
+ "mode": 420,
29
+ "sha256": "10fde0caa2257622444f0452ba321c9a34349d7d50dad6291ab189ea31033381"
30
+ },
31
+ "tests/test_apport_monkeypatching.py": {
32
+ "bytes": 1925,
33
+ "mode": 420,
34
+ "sha256": "50bddad2c699f04e60f757d00b4071bde931d8583cbdd39a0b24f29cb174f138"
35
+ },
36
+ "tests/test_catch.py": {
37
+ "bytes": 7163,
38
+ "mode": 420,
39
+ "sha256": "9e19d73b5eb2796eb2bacc1cae633f63f85b6a0179fd80645b2e26340ae53f80"
40
+ },
41
+ "tests/test_catch_py311.py": {
42
+ "bytes": 5958,
43
+ "mode": 420,
44
+ "sha256": "bdcee13b4edcef13bdf5a8c8ea1ff19480267fc9c2cfd6493b85b84c1c03325e"
45
+ },
46
+ "tests/test_exceptions.py": {
47
+ "bytes": 31247,
48
+ "mode": 420,
49
+ "sha256": "254cc73bddbd8e9903d1fe1b0403f3b7eb5af337acd16557ed445ad0ee72f747"
50
+ },
51
+ "tests/test_formatting.py": {
52
+ "bytes": 19274,
53
+ "mode": 420,
54
+ "sha256": "d1d4252253b81ca7bc2f5a00605e9ceeb82b4d3348eccd9331b0c2251a07da7b"
55
+ },
56
+ "tests/test_suppress.py": {
57
+ "bytes": 442,
58
+ "mode": 420,
59
+ "sha256": "d166b2e9aac0d9983afe8894aa10904c8b57b7977100df0cb2b0799d07f309fc"
60
+ }
61
+ }
62
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/pyproject.toml ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["flit_scm"]
3
+ build-backend = "flit_scm:buildapi"
4
+
5
+ [project]
6
+ name = "exceptiongroup"
7
+ description = "Backport of PEP 654 (exception groups)"
8
+ readme = "README.rst"
9
+ classifiers = [
10
+ "Development Status :: 5 - Production/Stable",
11
+ "Intended Audience :: Developers",
12
+ "License :: OSI Approved :: MIT License",
13
+ "Programming Language :: Python",
14
+ "Programming Language :: Python :: 3 :: Only",
15
+ "Typing :: Typed"
16
+ ]
17
+ authors = [{name = "Alex Grönholm", email = "alex.gronholm@nextday.fi"}]
18
+ license = {file = "LICENSE"}
19
+ requires-python = ">=3.7"
20
+ dynamic = ["version"]
21
+
22
+ [project.urls]
23
+ Changelog = "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst"
24
+ "Source code" = "https://github.com/agronholm/exceptiongroup"
25
+ "Issue Tracker" = "https://github.com/agronholm/exceptiongroup/issues"
26
+
27
+ [project.optional-dependencies]
28
+ test = [
29
+ "pytest >= 6"
30
+ ]
31
+
32
+ [tool.flit.sdist]
33
+ include = [
34
+ "CHANGES.rst",
35
+ "tests",
36
+ ]
37
+ exclude = [
38
+ ".github/*",
39
+ ".gitignore",
40
+ ".pre-commit-config.yaml"
41
+ ]
42
+
43
+ [tool.setuptools_scm]
44
+ version_scheme = "post-release"
45
+ local_scheme = "dirty-tag"
46
+ write_to = "src/exceptiongroup/_version.py"
47
+
48
+ [tool.ruff.lint]
49
+ extend-select = [
50
+ "I", # isort
51
+ "ISC", # flake8-implicit-str-concat
52
+ "PGH", # pygrep-hooks
53
+ "RUF100", # unused noqa (yesqa)
54
+ "UP", # pyupgrade
55
+ "W", # pycodestyle warnings
56
+ ]
57
+
58
+ [tool.ruff.lint.pyupgrade]
59
+ # Preserve types, even if a file imports `from __future__ import annotations`.
60
+ keep-runtime-typing = true
61
+
62
+ [tool.ruff.lint.isort]
63
+ known-first-party = ["exceptiongroup"]
64
+
65
+ [tool.pytest.ini_options]
66
+ addopts = "-rsx --tb=short --strict-config --strict-markers"
67
+ testpaths = ["tests"]
68
+
69
+ [tool.coverage.run]
70
+ source = ["exceptiongroup"]
71
+ relative_files = true
72
+
73
+ [tool.coverage.report]
74
+ exclude_also = [
75
+ "if TYPE_CHECKING:",
76
+ "@overload",
77
+ ]
78
+
79
+ [tool.pyright]
80
+ # for type tests, the code itself isn't type checked in CI
81
+ reportUnnecessaryTypeIgnoreComment = true
82
+
83
+ [tool.mypy]
84
+ # for type tests, the code itself isn't type checked in CI
85
+ warn_unused_ignores = true
86
+
87
+ [tool.tox]
88
+ legacy_tox_ini = """
89
+ [tox]
90
+ envlist = py37, py38, py39, py310, py311, py312, py313, pypy3
91
+ labels =
92
+ typing = py{310,311,312}-typing
93
+ skip_missing_interpreters = true
94
+ minversion = 4.0
95
+
96
+ [testenv]
97
+ extras = test
98
+ commands = python -m pytest {posargs}
99
+ package = editable
100
+ usedevelop = true
101
+
102
+ [testenv:{py37-,py38-,py39-,py310-,py311-,py312-,}typing]
103
+ deps =
104
+ pyright
105
+ mypy
106
+ commands =
107
+ pyright --verifytypes exceptiongroup
108
+ pyright tests/check_types.py
109
+ mypy tests/check_types.py
110
+ usedevelop = true
111
+ """
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/__init__.py ADDED
File without changes
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/apport_excepthook.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The apport_python_hook package is only installed as part of Ubuntu's system
2
+ # python, and not available in venvs. So before we can import it we have to
3
+ # make sure it's on sys.path.
4
+ import sys
5
+
6
+ sys.path.append("/usr/lib/python3/dist-packages")
7
+ import apport_python_hook # unsorted import
8
+
9
+ apport_python_hook.install()
10
+
11
+ from exceptiongroup import ExceptionGroup # noqa: E402 # unsorted import
12
+
13
+ raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")])
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/check_types.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing_extensions import assert_type
2
+
3
+ from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch, suppress
4
+
5
+ # issue 117
6
+ a = BaseExceptionGroup("", (KeyboardInterrupt(),))
7
+ assert_type(a, BaseExceptionGroup[KeyboardInterrupt])
8
+ b = BaseExceptionGroup("", (ValueError(),))
9
+ assert_type(b, BaseExceptionGroup[ValueError])
10
+ c = ExceptionGroup("", (ValueError(),))
11
+ assert_type(c, ExceptionGroup[ValueError])
12
+
13
+ # expected type error when passing a BaseException to ExceptionGroup
14
+ ExceptionGroup("", (KeyboardInterrupt(),)) # type: ignore[type-var]
15
+
16
+
17
+ # code snippets from the README
18
+
19
+
20
+ def value_key_err_handler(excgroup: BaseExceptionGroup) -> None:
21
+ for exc in excgroup.exceptions:
22
+ print("Caught exception:", type(exc))
23
+
24
+
25
+ def runtime_err_handler(exc: BaseExceptionGroup) -> None:
26
+ print("Caught runtime error")
27
+
28
+
29
+ with catch(
30
+ {(ValueError, KeyError): value_key_err_handler, RuntimeError: runtime_err_handler}
31
+ ):
32
+ ...
33
+
34
+
35
+ with suppress(RuntimeError):
36
+ raise ExceptionGroup("", [RuntimeError("boo")])
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/conftest.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import sys
2
+
3
+ if sys.version_info < (3, 11):
4
+ collect_ignore_glob = ["*_py311.py"]
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_apport_monkeypatching.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ import exceptiongroup
11
+
12
+
13
+ def run_script(name: str) -> subprocess.CompletedProcess[bytes]:
14
+ exceptiongroup_path = Path(exceptiongroup.__file__).parent.parent
15
+ script_path = Path(__file__).parent / name
16
+
17
+ env = dict(os.environ)
18
+ print("parent PYTHONPATH:", env.get("PYTHONPATH"))
19
+ if "PYTHONPATH" in env: # pragma: no cover
20
+ pp = env["PYTHONPATH"].split(os.pathsep)
21
+ else:
22
+ pp = []
23
+
24
+ pp.insert(0, str(exceptiongroup_path))
25
+ pp.insert(0, str(script_path.parent))
26
+ env["PYTHONPATH"] = os.pathsep.join(pp)
27
+ print("subprocess PYTHONPATH:", env.get("PYTHONPATH"))
28
+
29
+ cmd = [sys.executable, "-u", str(script_path)]
30
+ print("running:", cmd)
31
+ completed = subprocess.run(
32
+ cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
33
+ )
34
+ print("process output:")
35
+ print(completed.stdout.decode("utf-8"))
36
+ return completed
37
+
38
+
39
+ @pytest.mark.skipif(
40
+ sys.version_info > (3, 11),
41
+ reason="No patching is done on Python >= 3.11",
42
+ )
43
+ @pytest.mark.skipif(
44
+ not Path("/usr/lib/python3/dist-packages/apport_python_hook.py").exists(),
45
+ reason="need Ubuntu with python3-apport installed",
46
+ )
47
+ def test_apport_excepthook_monkeypatch_interaction():
48
+ completed = run_script("apport_excepthook.py")
49
+ stdout = completed.stdout.decode("utf-8")
50
+ file = Path(__file__).parent / "apport_excepthook.py"
51
+ assert stdout == (
52
+ f"""\
53
+ + Exception Group Traceback (most recent call last):
54
+ | File "{file}", line 13, in <module>
55
+ | raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")])
56
+ | exceptiongroup.ExceptionGroup: msg1 (2 sub-exceptions)
57
+ +-+---------------- 1 ----------------
58
+ | KeyError: 'msg2'
59
+ +---------------- 2 ----------------
60
+ | ValueError: msg3
61
+ +------------------------------------
62
+ """
63
+ )
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_catch.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch
4
+
5
+
6
+ def test_bad_arg():
7
+ with pytest.raises(TypeError, match="the argument must be a mapping"):
8
+ with catch(1):
9
+ pass
10
+
11
+
12
+ def test_bad_handler():
13
+ with pytest.raises(TypeError, match="handlers must be callable"):
14
+ with catch({RuntimeError: None}):
15
+ pass
16
+
17
+
18
+ @pytest.mark.parametrize(
19
+ "exc_type",
20
+ [
21
+ pytest.param(BaseExceptionGroup, id="naked_basegroup"),
22
+ pytest.param(ExceptionGroup, id="naked_group"),
23
+ pytest.param((ValueError, BaseExceptionGroup), id="iterable_basegroup"),
24
+ pytest.param((ValueError, ExceptionGroup), id="iterable_group"),
25
+ ],
26
+ )
27
+ def test_catch_exceptiongroup(exc_type):
28
+ with pytest.raises(TypeError, match="catching ExceptionGroup with catch"):
29
+ with catch({exc_type: (lambda e: True)}):
30
+ pass
31
+
32
+
33
+ def test_catch_ungrouped():
34
+ value_type_errors = []
35
+ zero_division_errors = []
36
+ for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]:
37
+ with catch(
38
+ {
39
+ (ValueError, TypeError): value_type_errors.append,
40
+ ZeroDivisionError: zero_division_errors.append,
41
+ }
42
+ ):
43
+ raise exc
44
+
45
+ assert len(value_type_errors) == 2
46
+
47
+ assert isinstance(value_type_errors[0], ExceptionGroup)
48
+ assert len(value_type_errors[0].exceptions) == 1
49
+ assert isinstance(value_type_errors[0].exceptions[0], ValueError)
50
+
51
+ assert isinstance(value_type_errors[1], ExceptionGroup)
52
+ assert len(value_type_errors[1].exceptions) == 1
53
+ assert isinstance(value_type_errors[1].exceptions[0], TypeError)
54
+
55
+ assert len(zero_division_errors) == 1
56
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
57
+ assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError)
58
+ assert len(zero_division_errors[0].exceptions) == 1
59
+
60
+
61
+ def test_catch_group():
62
+ value_runtime_errors = []
63
+ zero_division_errors = []
64
+ with catch(
65
+ {
66
+ (ValueError, RuntimeError): value_runtime_errors.append,
67
+ ZeroDivisionError: zero_division_errors.append,
68
+ }
69
+ ):
70
+ raise ExceptionGroup(
71
+ "booboo",
72
+ [
73
+ ValueError("foo"),
74
+ ValueError("bar"),
75
+ RuntimeError("bar"),
76
+ ZeroDivisionError(),
77
+ ],
78
+ )
79
+
80
+ assert len(value_runtime_errors) == 1
81
+ assert isinstance(value_runtime_errors[0], ExceptionGroup)
82
+ exceptions = value_runtime_errors[0].exceptions
83
+ assert isinstance(exceptions[0], ValueError)
84
+ assert isinstance(exceptions[1], ValueError)
85
+ assert isinstance(exceptions[2], RuntimeError)
86
+
87
+ assert len(zero_division_errors) == 1
88
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
89
+ exceptions = zero_division_errors[0].exceptions
90
+ assert isinstance(exceptions[0], ZeroDivisionError)
91
+
92
+
93
+ def test_catch_nested_group():
94
+ value_runtime_errors = []
95
+ zero_division_errors = []
96
+ with catch(
97
+ {
98
+ (ValueError, RuntimeError): value_runtime_errors.append,
99
+ ZeroDivisionError: zero_division_errors.append,
100
+ }
101
+ ):
102
+ nested_group = ExceptionGroup(
103
+ "nested", [RuntimeError("bar"), ZeroDivisionError()]
104
+ )
105
+ raise ExceptionGroup("booboo", [ValueError("foo"), nested_group])
106
+
107
+ assert len(value_runtime_errors) == 1
108
+ exceptions = value_runtime_errors[0].exceptions
109
+ assert isinstance(exceptions[0], ValueError)
110
+ assert isinstance(exceptions[1], ExceptionGroup)
111
+ assert isinstance(exceptions[1].exceptions[0], RuntimeError)
112
+
113
+ assert len(zero_division_errors) == 1
114
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
115
+ assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup)
116
+ assert isinstance(
117
+ zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError
118
+ )
119
+
120
+
121
+ def test_catch_no_match():
122
+ try:
123
+ with catch({(ValueError, RuntimeError): (lambda e: None)}):
124
+ group = ExceptionGroup("booboo", [ZeroDivisionError()])
125
+ raise group
126
+ except ExceptionGroup as exc:
127
+ assert exc is not group
128
+ else:
129
+ pytest.fail("Did not raise an ExceptionGroup")
130
+
131
+
132
+ def test_catch_single_no_match():
133
+ try:
134
+ with catch({(ValueError, RuntimeError): (lambda e: None)}):
135
+ raise ZeroDivisionError
136
+ except ZeroDivisionError:
137
+ pass
138
+ else:
139
+ pytest.fail("Did not raise an ZeroDivisionError")
140
+
141
+
142
+ def test_catch_full_match():
143
+ with catch({(ValueError, RuntimeError): (lambda e: None)}):
144
+ raise ExceptionGroup("booboo", [ValueError()])
145
+
146
+
147
+ def test_catch_handler_raises():
148
+ def handler(exc):
149
+ raise RuntimeError("new")
150
+
151
+ with pytest.raises(RuntimeError, match="new") as exc:
152
+ with catch({(ValueError, ValueError): handler}):
153
+ excgrp = ExceptionGroup("booboo", [ValueError("bar")])
154
+ raise excgrp
155
+
156
+ context = exc.value.__context__
157
+ assert isinstance(context, ExceptionGroup)
158
+ assert str(context) == "booboo (1 sub-exception)"
159
+ assert len(context.exceptions) == 1
160
+ assert isinstance(context.exceptions[0], ValueError)
161
+ assert exc.value.__cause__ is None
162
+
163
+
164
+ def test_bare_raise_in_handler():
165
+ """Test that a bare "raise" "middle" ecxeption group gets discarded."""
166
+
167
+ def handler(exc):
168
+ raise
169
+
170
+ with pytest.raises(ExceptionGroup) as excgrp:
171
+ with catch({(ValueError,): handler, (RuntimeError,): lambda eg: None}):
172
+ try:
173
+ first_exc = RuntimeError("first")
174
+ raise first_exc
175
+ except RuntimeError as exc:
176
+ middle_exc = ExceptionGroup(
177
+ "bad", [ValueError(), ValueError(), TypeError()]
178
+ )
179
+ raise middle_exc from exc
180
+
181
+ assert len(excgrp.value.exceptions) == 2
182
+ assert all(isinstance(exc, ValueError) for exc in excgrp.value.exceptions)
183
+ assert excgrp.value is not middle_exc
184
+ assert excgrp.value.__cause__ is first_exc
185
+ assert excgrp.value.__context__ is first_exc
186
+
187
+
188
+ def test_catch_subclass():
189
+ lookup_errors = []
190
+ with catch({LookupError: lookup_errors.append}):
191
+ raise KeyError("foo")
192
+
193
+ assert len(lookup_errors) == 1
194
+ assert isinstance(lookup_errors[0], ExceptionGroup)
195
+ exceptions = lookup_errors[0].exceptions
196
+ assert isinstance(exceptions[0], KeyError)
197
+
198
+
199
+ def test_async_handler(request):
200
+ async def handler(eg):
201
+ pass
202
+
203
+ def delegate(eg):
204
+ coro = handler(eg)
205
+ request.addfinalizer(coro.close)
206
+ return coro
207
+
208
+ with pytest.raises(TypeError, match="Exception handler must be a sync function."):
209
+ with catch({TypeError: delegate}):
210
+ raise ExceptionGroup("message", [TypeError("uh-oh")])
211
+
212
+
213
+ def test_bare_reraise_from_naked_exception():
214
+ def handler(eg):
215
+ raise
216
+
217
+ with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}):
218
+ raise KeyError("foo")
219
+
220
+ assert len(excgrp.value.exceptions) == 1
221
+ assert isinstance(excgrp.value.exceptions[0], KeyError)
222
+ assert str(excgrp.value.exceptions[0]) == "'foo'"
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_catch_py311.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ from exceptiongroup import ExceptionGroup
6
+
7
+
8
+ def test_catch_ungrouped():
9
+ value_type_errors = []
10
+ zero_division_errors = []
11
+ for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]:
12
+ try:
13
+ raise exc
14
+ except* (ValueError, TypeError) as e:
15
+ value_type_errors.append(e)
16
+ except* ZeroDivisionError as e:
17
+ zero_division_errors.append(e)
18
+
19
+ assert len(value_type_errors) == 2
20
+
21
+ assert isinstance(value_type_errors[0], ExceptionGroup)
22
+ assert len(value_type_errors[0].exceptions) == 1
23
+ assert isinstance(value_type_errors[0].exceptions[0], ValueError)
24
+
25
+ assert isinstance(value_type_errors[1], ExceptionGroup)
26
+ assert len(value_type_errors[1].exceptions) == 1
27
+ assert isinstance(value_type_errors[1].exceptions[0], TypeError)
28
+
29
+ assert len(zero_division_errors) == 1
30
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
31
+ assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError)
32
+ assert len(zero_division_errors[0].exceptions) == 1
33
+
34
+
35
+ def test_catch_group():
36
+ value_runtime_errors = []
37
+ zero_division_errors = []
38
+ try:
39
+ raise ExceptionGroup(
40
+ "booboo",
41
+ [
42
+ ValueError("foo"),
43
+ ValueError("bar"),
44
+ RuntimeError("bar"),
45
+ ZeroDivisionError(),
46
+ ],
47
+ )
48
+ except* (ValueError, RuntimeError) as exc:
49
+ value_runtime_errors.append(exc)
50
+ except* ZeroDivisionError as exc:
51
+ zero_division_errors.append(exc)
52
+
53
+ assert len(value_runtime_errors) == 1
54
+ assert isinstance(value_runtime_errors[0], ExceptionGroup)
55
+ exceptions = value_runtime_errors[0].exceptions
56
+ assert isinstance(exceptions[0], ValueError)
57
+ assert isinstance(exceptions[1], ValueError)
58
+ assert isinstance(exceptions[2], RuntimeError)
59
+
60
+ assert len(zero_division_errors) == 1
61
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
62
+ exceptions = zero_division_errors[0].exceptions
63
+ assert isinstance(exceptions[0], ZeroDivisionError)
64
+
65
+
66
+ def test_catch_nested_group():
67
+ value_runtime_errors = []
68
+ zero_division_errors = []
69
+ try:
70
+ nested_group = ExceptionGroup(
71
+ "nested", [RuntimeError("bar"), ZeroDivisionError()]
72
+ )
73
+ raise ExceptionGroup("booboo", [ValueError("foo"), nested_group])
74
+ except* (ValueError, RuntimeError) as exc:
75
+ value_runtime_errors.append(exc)
76
+ except* ZeroDivisionError as exc:
77
+ zero_division_errors.append(exc)
78
+
79
+ assert len(value_runtime_errors) == 1
80
+ exceptions = value_runtime_errors[0].exceptions
81
+ assert isinstance(exceptions[0], ValueError)
82
+ assert isinstance(exceptions[1], ExceptionGroup)
83
+ assert isinstance(exceptions[1].exceptions[0], RuntimeError)
84
+
85
+ assert len(zero_division_errors) == 1
86
+ assert isinstance(zero_division_errors[0], ExceptionGroup)
87
+ assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup)
88
+ assert isinstance(
89
+ zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError
90
+ )
91
+
92
+
93
+ def test_catch_no_match():
94
+ try:
95
+ try:
96
+ group = ExceptionGroup("booboo", [ZeroDivisionError()])
97
+ raise group
98
+ except* (ValueError, RuntimeError):
99
+ pass
100
+ except ExceptionGroup as exc:
101
+ assert isinstance(exc.exceptions[0], ZeroDivisionError)
102
+ assert exc is not group
103
+ else:
104
+ pytest.fail("Did not raise an ExceptionGroup")
105
+
106
+
107
+ def test_catch_single_no_match():
108
+ try:
109
+ try:
110
+ raise ZeroDivisionError
111
+ except* (ValueError, RuntimeError):
112
+ pass
113
+ except ZeroDivisionError:
114
+ pass
115
+ else:
116
+ pytest.fail("Did not raise an ZeroDivisionError")
117
+
118
+
119
+ def test_catch_full_match():
120
+ try:
121
+ raise ExceptionGroup("booboo", [ValueError()])
122
+ except* (ValueError, RuntimeError):
123
+ pass
124
+
125
+
126
+ @pytest.mark.skipif(
127
+ sys.version_info < (3, 11, 4),
128
+ reason="Behavior was changed in 3.11.4",
129
+ )
130
+ def test_catch_handler_raises():
131
+ with pytest.raises(RuntimeError, match="new") as exc:
132
+ try:
133
+ excgrp = ExceptionGroup("booboo", [ValueError("bar")])
134
+ raise excgrp
135
+ except* ValueError:
136
+ raise RuntimeError("new")
137
+
138
+ context = exc.value.__context__
139
+ assert isinstance(context, ExceptionGroup)
140
+ assert str(context) == "booboo (1 sub-exception)"
141
+ assert len(context.exceptions) == 1
142
+ assert isinstance(context.exceptions[0], ValueError)
143
+ assert exc.value.__cause__ is None
144
+
145
+
146
+ def test_catch_subclass():
147
+ lookup_errors = []
148
+ try:
149
+ raise KeyError("foo")
150
+ except* LookupError as e:
151
+ lookup_errors.append(e)
152
+
153
+ assert len(lookup_errors) == 1
154
+ assert isinstance(lookup_errors[0], ExceptionGroup)
155
+ exceptions = lookup_errors[0].exceptions
156
+ assert isinstance(exceptions[0], KeyError)
157
+
158
+
159
+ def test_bare_raise_in_handler():
160
+ """Test that the "middle" ecxeption group gets discarded."""
161
+ with pytest.raises(ExceptionGroup) as excgrp:
162
+ try:
163
+ try:
164
+ first_exc = RuntimeError("first")
165
+ raise first_exc
166
+ except RuntimeError as exc:
167
+ middle_exc = ExceptionGroup(
168
+ "bad", [ValueError(), ValueError(), TypeError()]
169
+ )
170
+ raise middle_exc from exc
171
+ except* ValueError:
172
+ raise
173
+ except* TypeError:
174
+ pass
175
+
176
+ assert excgrp.value is not middle_exc
177
+ assert excgrp.value.__cause__ is first_exc
178
+ assert excgrp.value.__context__ is first_exc
179
+
180
+
181
+ def test_bare_reraise_from_naked_exception():
182
+ with pytest.raises(ExceptionGroup) as excgrp:
183
+ try:
184
+ raise KeyError("foo")
185
+ except* KeyError:
186
+ raise
187
+
188
+ assert len(excgrp.value.exceptions) == 1
189
+ assert isinstance(excgrp.value.exceptions[0], KeyError)
190
+ assert str(excgrp.value.exceptions[0]) == "'foo'"
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_exceptions.py ADDED
@@ -0,0 +1,845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from the standard library
2
+ import collections.abc
3
+ import sys
4
+ import unittest
5
+
6
+ import pytest
7
+
8
+ from exceptiongroup import BaseExceptionGroup, ExceptionGroup
9
+
10
+
11
+ class TestExceptionGroupTypeHierarchy(unittest.TestCase):
12
+ def test_exception_group_types(self):
13
+ self.assertTrue(issubclass(ExceptionGroup, Exception))
14
+ self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup))
15
+ self.assertTrue(issubclass(BaseExceptionGroup, BaseException))
16
+
17
+ def test_exception_group_is_generic_type(self):
18
+ E = OSError
19
+ self.assertEqual(ExceptionGroup[E].__origin__, ExceptionGroup)
20
+ self.assertEqual(BaseExceptionGroup[E].__origin__, BaseExceptionGroup)
21
+
22
+
23
+ class BadConstructorArgs(unittest.TestCase):
24
+ def test_bad_EG_construction__too_few_args(self):
25
+ if sys.version_info >= (3, 11):
26
+ MSG = (
27
+ r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(1 given\)"
28
+ )
29
+ else:
30
+ MSG = (
31
+ r"__new__\(\) missing 1 required positional argument: "
32
+ r"'_ExceptionGroup__exceptions'"
33
+ )
34
+
35
+ with self.assertRaisesRegex(TypeError, MSG):
36
+ ExceptionGroup("no errors")
37
+ with self.assertRaisesRegex(TypeError, MSG):
38
+ ExceptionGroup([ValueError("no msg")])
39
+
40
+ def test_bad_EG_construction__too_many_args(self):
41
+ if sys.version_info >= (3, 11):
42
+ MSG = (
43
+ r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(3 given\)"
44
+ )
45
+ else:
46
+ MSG = r"__new__\(\) takes 3 positional arguments but 4 were given"
47
+
48
+ with self.assertRaisesRegex(TypeError, MSG):
49
+ ExceptionGroup("eg", [ValueError("too")], [TypeError("many")])
50
+
51
+ def test_bad_EG_construction__bad_message(self):
52
+ MSG = "argument 1 must be str, not "
53
+ with self.assertRaisesRegex(TypeError, MSG):
54
+ ExceptionGroup(ValueError(12), SyntaxError("bad syntax"))
55
+ with self.assertRaisesRegex(TypeError, MSG):
56
+ ExceptionGroup(None, [ValueError(12)])
57
+
58
+ def test_bad_EG_construction__bad_excs_sequence(self):
59
+ MSG = r"second argument \(exceptions\) must be a sequence"
60
+ with self.assertRaisesRegex(TypeError, MSG):
61
+ ExceptionGroup("errors not sequence", {ValueError(42)})
62
+ with self.assertRaisesRegex(TypeError, MSG):
63
+ ExceptionGroup("eg", None)
64
+
65
+ MSG = r"second argument \(exceptions\) must be a non-empty sequence"
66
+ with self.assertRaisesRegex(ValueError, MSG):
67
+ ExceptionGroup("eg", [])
68
+
69
+ def test_bad_EG_construction__nested_non_exceptions(self):
70
+ MSG = r"Item [0-9]+ of second argument \(exceptions\) is not an exception"
71
+ with self.assertRaisesRegex(ValueError, MSG):
72
+ ExceptionGroup("expect instance, not type", [OSError])
73
+ with self.assertRaisesRegex(ValueError, MSG):
74
+ ExceptionGroup("bad error", ["not an exception"])
75
+
76
+
77
+ class InstanceCreation(unittest.TestCase):
78
+ def test_EG_wraps_Exceptions__creates_EG(self):
79
+ excs = [ValueError(1), TypeError(2)]
80
+ self.assertIs(type(ExceptionGroup("eg", excs)), ExceptionGroup)
81
+
82
+ def test_BEG_wraps_Exceptions__creates_EG(self):
83
+ excs = [ValueError(1), TypeError(2)]
84
+ self.assertIs(type(BaseExceptionGroup("beg", excs)), ExceptionGroup)
85
+
86
+ def test_EG_wraps_BaseException__raises_TypeError(self):
87
+ MSG = "Cannot nest BaseExceptions in an ExceptionGroup"
88
+ with self.assertRaisesRegex(TypeError, MSG):
89
+ ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)])
90
+
91
+ def test_BEG_wraps_BaseException__creates_BEG(self):
92
+ beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)])
93
+ self.assertIs(type(beg), BaseExceptionGroup)
94
+
95
+ def test_EG_subclass_wraps_non_base_exceptions(self):
96
+ class MyEG(ExceptionGroup):
97
+ pass
98
+
99
+ self.assertIs(type(MyEG("eg", [ValueError(12), TypeError(42)])), MyEG)
100
+
101
+ @pytest.mark.skipif(
102
+ sys.version_info[:3] == (3, 11, 0),
103
+ reason="Behavior was made stricter in 3.11.1",
104
+ )
105
+ def test_EG_subclass_does_not_wrap_base_exceptions(self):
106
+ class MyEG(ExceptionGroup):
107
+ pass
108
+
109
+ msg = "Cannot nest BaseExceptions in 'MyEG'"
110
+ with self.assertRaisesRegex(TypeError, msg):
111
+ MyEG("eg", [ValueError(12), KeyboardInterrupt(42)])
112
+
113
+ @pytest.mark.skipif(
114
+ sys.version_info[:3] == (3, 11, 0),
115
+ reason="Behavior was made stricter in 3.11.1",
116
+ )
117
+ def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self):
118
+ class MyEG(BaseExceptionGroup, ValueError):
119
+ pass
120
+
121
+ msg = "Cannot nest BaseExceptions in 'MyEG'"
122
+ with self.assertRaisesRegex(TypeError, msg):
123
+ MyEG("eg", [ValueError(12), KeyboardInterrupt(42)])
124
+
125
+
126
+ def create_simple_eg():
127
+ excs = []
128
+ try:
129
+ try:
130
+ raise MemoryError("context and cause for ValueError(1)")
131
+ except MemoryError as e:
132
+ raise ValueError(1) from e
133
+ except ValueError as e:
134
+ excs.append(e)
135
+
136
+ try:
137
+ try:
138
+ raise OSError("context for TypeError")
139
+ except OSError:
140
+ raise TypeError(int)
141
+ except TypeError as e:
142
+ excs.append(e)
143
+
144
+ try:
145
+ try:
146
+ raise ImportError("context for ValueError(2)")
147
+ except ImportError:
148
+ raise ValueError(2)
149
+ except ValueError as e:
150
+ excs.append(e)
151
+
152
+ try:
153
+ raise ExceptionGroup("simple eg", excs)
154
+ except ExceptionGroup as e:
155
+ return e
156
+
157
+
158
+ class ExceptionGroupFields(unittest.TestCase):
159
+ def test_basics_ExceptionGroup_fields(self):
160
+ eg = create_simple_eg()
161
+
162
+ # check msg
163
+ self.assertEqual(eg.message, "simple eg")
164
+ self.assertEqual(eg.args[0], "simple eg")
165
+
166
+ # check cause and context
167
+ self.assertIsInstance(eg.exceptions[0], ValueError)
168
+ self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError)
169
+ self.assertIsInstance(eg.exceptions[0].__context__, MemoryError)
170
+ self.assertIsInstance(eg.exceptions[1], TypeError)
171
+ self.assertIsNone(eg.exceptions[1].__cause__)
172
+ self.assertIsInstance(eg.exceptions[1].__context__, OSError)
173
+ self.assertIsInstance(eg.exceptions[2], ValueError)
174
+ self.assertIsNone(eg.exceptions[2].__cause__)
175
+ self.assertIsInstance(eg.exceptions[2].__context__, ImportError)
176
+
177
+ # check tracebacks
178
+ line0 = create_simple_eg.__code__.co_firstlineno
179
+ tb_linenos = [line0 + 27, [line0 + 6, line0 + 14, line0 + 22]]
180
+ self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0])
181
+ self.assertIsNone(eg.__traceback__.tb_next)
182
+ for i in range(3):
183
+ tb = eg.exceptions[i].__traceback__
184
+ self.assertIsNone(tb.tb_next)
185
+ self.assertEqual(tb.tb_lineno, tb_linenos[1][i])
186
+
187
+ def test_fields_are_readonly(self):
188
+ eg = ExceptionGroup("eg", [TypeError(1), OSError(2)])
189
+
190
+ self.assertEqual(type(eg.exceptions), tuple)
191
+
192
+ eg.message
193
+ with self.assertRaises(AttributeError):
194
+ eg.message = "new msg"
195
+
196
+ eg.exceptions
197
+ with self.assertRaises(AttributeError):
198
+ eg.exceptions = [OSError("xyz")]
199
+
200
+ def test_notes_is_list_of_strings_if_it_exists(self):
201
+ eg = create_simple_eg()
202
+
203
+ note = "This is a happy note for the exception group"
204
+ self.assertFalse(hasattr(eg, "__notes__"))
205
+ eg.add_note(note)
206
+ self.assertEqual(eg.__notes__, [note])
207
+
208
+ def test_derive_doesn_copy_notes(self):
209
+ eg = create_simple_eg()
210
+ eg.add_note("hello")
211
+ assert eg.__notes__ == ["hello"]
212
+ eg2 = eg.derive([ValueError()])
213
+ assert not hasattr(eg2, "__notes__")
214
+
215
+
216
+ class ExceptionGroupTestBase(unittest.TestCase):
217
+ def assertMatchesTemplate(self, exc, exc_type, template):
218
+ """Assert that the exception matches the template
219
+
220
+ A template describes the shape of exc. If exc is a
221
+ leaf exception (i.e., not an exception group) then
222
+ template is an exception instance that has the
223
+ expected type and args value of exc. If exc is an
224
+ exception group, then template is a list of the
225
+ templates of its nested exceptions.
226
+ """
227
+ if exc_type is not None:
228
+ self.assertIs(type(exc), exc_type)
229
+
230
+ if isinstance(exc, BaseExceptionGroup):
231
+ self.assertIsInstance(template, collections.abc.Sequence)
232
+ self.assertEqual(len(exc.exceptions), len(template))
233
+ for e, t in zip(exc.exceptions, template):
234
+ self.assertMatchesTemplate(e, None, t)
235
+ else:
236
+ self.assertIsInstance(template, BaseException)
237
+ self.assertEqual(type(exc), type(template))
238
+ self.assertEqual(exc.args, template.args)
239
+
240
+
241
+ class ExceptionGroupSubgroupTests(ExceptionGroupTestBase):
242
+ def setUp(self):
243
+ self.eg = create_simple_eg()
244
+ self.eg_template = [ValueError(1), TypeError(int), ValueError(2)]
245
+
246
+ def test_basics_subgroup_split__bad_arg_type(self):
247
+ bad_args = [
248
+ "bad arg",
249
+ OSError("instance not type"),
250
+ [OSError, TypeError],
251
+ (OSError, 42),
252
+ ]
253
+ for arg in bad_args:
254
+ with self.assertRaises(TypeError):
255
+ self.eg.subgroup(arg)
256
+ with self.assertRaises(TypeError):
257
+ self.eg.split(arg)
258
+
259
+ def test_basics_subgroup_by_type__passthrough(self):
260
+ eg = self.eg
261
+ # self.assertIs(eg, eg.subgroup(BaseException))
262
+ # self.assertIs(eg, eg.subgroup(Exception))
263
+ self.assertIs(eg, eg.subgroup(BaseExceptionGroup))
264
+ self.assertIs(eg, eg.subgroup(ExceptionGroup))
265
+
266
+ def test_basics_subgroup_by_type__no_match(self):
267
+ self.assertIsNone(self.eg.subgroup(OSError))
268
+
269
+ def test_basics_subgroup_by_type__match(self):
270
+ eg = self.eg
271
+ testcases = [
272
+ # (match_type, result_template)
273
+ (ValueError, [ValueError(1), ValueError(2)]),
274
+ (TypeError, [TypeError(int)]),
275
+ ((ValueError, TypeError), self.eg_template),
276
+ ]
277
+
278
+ for match_type, template in testcases:
279
+ with self.subTest(match=match_type):
280
+ subeg = eg.subgroup(match_type)
281
+ self.assertEqual(subeg.message, eg.message)
282
+ self.assertMatchesTemplate(subeg, ExceptionGroup, template)
283
+
284
+ def test_basics_subgroup_by_predicate__passthrough(self):
285
+ self.assertIs(self.eg, self.eg.subgroup(lambda e: True))
286
+
287
+ def test_basics_subgroup_by_predicate__no_match(self):
288
+ self.assertIsNone(self.eg.subgroup(lambda e: False))
289
+
290
+ def test_basics_subgroup_by_predicate__match(self):
291
+ eg = self.eg
292
+ testcases = [
293
+ # (match_type, result_template)
294
+ (ValueError, [ValueError(1), ValueError(2)]),
295
+ (TypeError, [TypeError(int)]),
296
+ ((ValueError, TypeError), self.eg_template),
297
+ ]
298
+
299
+ for match_type, template in testcases:
300
+ subeg = eg.subgroup(lambda e: isinstance(e, match_type))
301
+ self.assertEqual(subeg.message, eg.message)
302
+ self.assertMatchesTemplate(subeg, ExceptionGroup, template)
303
+
304
+
305
+ class ExceptionGroupSplitTests(ExceptionGroupTestBase):
306
+ def setUp(self):
307
+ self.eg = create_simple_eg()
308
+ self.eg_template = [ValueError(1), TypeError(int), ValueError(2)]
309
+
310
+ def test_basics_split_by_type__passthrough(self):
311
+ for E in [BaseException, Exception, BaseExceptionGroup, ExceptionGroup]:
312
+ match, rest = self.eg.split(E)
313
+ self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template)
314
+ self.assertIsNone(rest)
315
+
316
+ def test_basics_split_by_type__no_match(self):
317
+ match, rest = self.eg.split(OSError)
318
+ self.assertIsNone(match)
319
+ self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template)
320
+
321
+ def test_basics_split_by_type__match(self):
322
+ eg = self.eg
323
+ VE = ValueError
324
+ TE = TypeError
325
+ testcases = [
326
+ # (matcher, match_template, rest_template)
327
+ (VE, [VE(1), VE(2)], [TE(int)]),
328
+ (TE, [TE(int)], [VE(1), VE(2)]),
329
+ ((VE, TE), self.eg_template, None),
330
+ ((OSError, VE), [VE(1), VE(2)], [TE(int)]),
331
+ ]
332
+
333
+ for match_type, match_template, rest_template in testcases:
334
+ match, rest = eg.split(match_type)
335
+ self.assertEqual(match.message, eg.message)
336
+ self.assertMatchesTemplate(match, ExceptionGroup, match_template)
337
+ if rest_template is not None:
338
+ self.assertEqual(rest.message, eg.message)
339
+ self.assertMatchesTemplate(rest, ExceptionGroup, rest_template)
340
+ else:
341
+ self.assertIsNone(rest)
342
+
343
+ def test_basics_split_by_predicate__passthrough(self):
344
+ match, rest = self.eg.split(lambda e: True)
345
+ self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template)
346
+ self.assertIsNone(rest)
347
+
348
+ def test_basics_split_by_predicate__no_match(self):
349
+ match, rest = self.eg.split(lambda e: False)
350
+ self.assertIsNone(match)
351
+ self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template)
352
+
353
+ def test_basics_split_by_predicate__match(self):
354
+ eg = self.eg
355
+ VE = ValueError
356
+ TE = TypeError
357
+ testcases = [
358
+ # (matcher, match_template, rest_template)
359
+ (VE, [VE(1), VE(2)], [TE(int)]),
360
+ (TE, [TE(int)], [VE(1), VE(2)]),
361
+ ((VE, TE), self.eg_template, None),
362
+ ]
363
+
364
+ for match_type, match_template, rest_template in testcases:
365
+ match, rest = eg.split(lambda e: isinstance(e, match_type))
366
+ self.assertEqual(match.message, eg.message)
367
+ self.assertMatchesTemplate(match, ExceptionGroup, match_template)
368
+ if rest_template is not None:
369
+ self.assertEqual(rest.message, eg.message)
370
+ self.assertMatchesTemplate(rest, ExceptionGroup, rest_template)
371
+
372
+
373
+ class DeepRecursionInSplitAndSubgroup(unittest.TestCase):
374
+ def make_deep_eg(self):
375
+ e = TypeError(1)
376
+ for _ in range(10000):
377
+ e = ExceptionGroup("eg", [e])
378
+ return e
379
+
380
+ def test_deep_split(self):
381
+ e = self.make_deep_eg()
382
+ with self.assertRaises(RecursionError):
383
+ e.split(TypeError)
384
+
385
+ def test_deep_subgroup(self):
386
+ e = self.make_deep_eg()
387
+ with self.assertRaises(RecursionError):
388
+ e.subgroup(TypeError)
389
+
390
+
391
+ def leaf_generator(exc, tbs=None):
392
+ if tbs is None:
393
+ tbs = []
394
+ tbs.append(exc.__traceback__)
395
+ if isinstance(exc, BaseExceptionGroup):
396
+ for e in exc.exceptions:
397
+ yield from leaf_generator(e, tbs)
398
+ else:
399
+ # exc is a leaf exception and its traceback
400
+ # is the concatenation of the traceback
401
+ # segments in tbs
402
+ yield exc, tbs
403
+ tbs.pop()
404
+
405
+
406
+ class LeafGeneratorTest(unittest.TestCase):
407
+ # The leaf_generator is mentioned in PEP 654 as a suggestion
408
+ # on how to iterate over leaf nodes of an EG. Is is also
409
+ # used below as a test utility. So we test it here.
410
+
411
+ def test_leaf_generator(self):
412
+ eg = create_simple_eg()
413
+
414
+ self.assertSequenceEqual([e for e, _ in leaf_generator(eg)], eg.exceptions)
415
+
416
+ for e, tbs in leaf_generator(eg):
417
+ self.assertSequenceEqual(tbs, [eg.__traceback__, e.__traceback__])
418
+
419
+
420
+ def create_nested_eg():
421
+ excs = []
422
+ try:
423
+ try:
424
+ raise TypeError(bytes)
425
+ except TypeError as e:
426
+ raise ExceptionGroup("nested", [e])
427
+ except ExceptionGroup as e:
428
+ excs.append(e)
429
+
430
+ try:
431
+ try:
432
+ raise MemoryError("out of memory")
433
+ except MemoryError as e:
434
+ raise ValueError(1) from e
435
+ except ValueError as e:
436
+ excs.append(e)
437
+
438
+ try:
439
+ raise ExceptionGroup("root", excs)
440
+ except ExceptionGroup as eg:
441
+ return eg
442
+
443
+
444
+ class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase):
445
+ def test_nested_group_matches_template(self):
446
+ eg = create_nested_eg()
447
+ self.assertMatchesTemplate(
448
+ eg, ExceptionGroup, [[TypeError(bytes)], ValueError(1)]
449
+ )
450
+
451
+ def test_nested_group_chaining(self):
452
+ eg = create_nested_eg()
453
+ self.assertIsInstance(eg.exceptions[1].__context__, MemoryError)
454
+ self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError)
455
+ self.assertIsInstance(eg.exceptions[0].__context__, TypeError)
456
+
457
+ def test_nested_exception_group_tracebacks(self):
458
+ eg = create_nested_eg()
459
+
460
+ line0 = create_nested_eg.__code__.co_firstlineno
461
+ for tb, expected in [
462
+ (eg.__traceback__, line0 + 19),
463
+ (eg.exceptions[0].__traceback__, line0 + 6),
464
+ (eg.exceptions[1].__traceback__, line0 + 14),
465
+ (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4),
466
+ ]:
467
+ self.assertEqual(tb.tb_lineno, expected)
468
+ self.assertIsNone(tb.tb_next)
469
+
470
+ def test_iteration_full_tracebacks(self):
471
+ eg = create_nested_eg()
472
+ # check that iteration over leaves
473
+ # produces the expected tracebacks
474
+ self.assertEqual(len(list(leaf_generator(eg))), 2)
475
+
476
+ line0 = create_nested_eg.__code__.co_firstlineno
477
+ expected_tbs = [[line0 + 19, line0 + 6, line0 + 4], [line0 + 19, line0 + 14]]
478
+
479
+ for i, (_, tbs) in enumerate(leaf_generator(eg)):
480
+ self.assertSequenceEqual([tb.tb_lineno for tb in tbs], expected_tbs[i])
481
+
482
+
483
+ class ExceptionGroupSplitTestBase(ExceptionGroupTestBase):
484
+ def split_exception_group(self, eg, types):
485
+ """Split an EG and do some sanity checks on the result"""
486
+ self.assertIsInstance(eg, BaseExceptionGroup)
487
+
488
+ match, rest = eg.split(types)
489
+ sg = eg.subgroup(types)
490
+
491
+ if match is not None:
492
+ self.assertIsInstance(match, BaseExceptionGroup)
493
+ for e, _ in leaf_generator(match):
494
+ self.assertIsInstance(e, types)
495
+
496
+ self.assertIsNotNone(sg)
497
+ self.assertIsInstance(sg, BaseExceptionGroup)
498
+ for e, _ in leaf_generator(sg):
499
+ self.assertIsInstance(e, types)
500
+
501
+ if rest is not None:
502
+ self.assertIsInstance(rest, BaseExceptionGroup)
503
+
504
+ def leaves(exc):
505
+ return [] if exc is None else [e for e, _ in leaf_generator(exc)]
506
+
507
+ # match and subgroup have the same leaves
508
+ self.assertSequenceEqual(leaves(match), leaves(sg))
509
+
510
+ match_leaves = leaves(match)
511
+ rest_leaves = leaves(rest)
512
+ # each leaf exception of eg is in exactly one of match and rest
513
+ self.assertEqual(len(leaves(eg)), len(leaves(match)) + len(leaves(rest)))
514
+
515
+ for e in leaves(eg):
516
+ self.assertNotEqual(match and e in match_leaves, rest and e in rest_leaves)
517
+
518
+ # message, cause and context, traceback and note equal to eg
519
+ for part in [match, rest, sg]:
520
+ if part is not None:
521
+ self.assertEqual(eg.message, part.message)
522
+ self.assertIs(eg.__cause__, part.__cause__)
523
+ self.assertIs(eg.__context__, part.__context__)
524
+ self.assertIs(eg.__traceback__, part.__traceback__)
525
+ self.assertEqual(
526
+ getattr(eg, "__notes__", None),
527
+ getattr(part, "__notes__", None),
528
+ )
529
+
530
+ def tbs_for_leaf(leaf, eg):
531
+ for e, tbs in leaf_generator(eg):
532
+ if e is leaf:
533
+ return tbs
534
+
535
+ def tb_linenos(tbs):
536
+ return [tb.tb_lineno for tb in tbs if tb]
537
+
538
+ # full tracebacks match
539
+ for part in [match, rest, sg]:
540
+ for e in leaves(part):
541
+ self.assertSequenceEqual(
542
+ tb_linenos(tbs_for_leaf(e, eg)), tb_linenos(tbs_for_leaf(e, part))
543
+ )
544
+
545
+ return match, rest
546
+
547
+
548
+ class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase):
549
+ def test_split_by_type(self):
550
+ class MyExceptionGroup(ExceptionGroup):
551
+ pass
552
+
553
+ def raiseVE(v):
554
+ raise ValueError(v)
555
+
556
+ def raiseTE(t):
557
+ raise TypeError(t)
558
+
559
+ def nested_group():
560
+ def level1(i):
561
+ excs = []
562
+ for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i + 1)]:
563
+ try:
564
+ f(arg)
565
+ except Exception as e:
566
+ excs.append(e)
567
+ raise ExceptionGroup("msg1", excs)
568
+
569
+ def level2(i):
570
+ excs = []
571
+ for f, arg in [(level1, i), (level1, i + 1), (raiseVE, i + 2)]:
572
+ try:
573
+ f(arg)
574
+ except Exception as e:
575
+ excs.append(e)
576
+ raise MyExceptionGroup("msg2", excs)
577
+
578
+ def level3(i):
579
+ excs = []
580
+ for f, arg in [(level2, i + 1), (raiseVE, i + 2)]:
581
+ try:
582
+ f(arg)
583
+ except Exception as e:
584
+ excs.append(e)
585
+ raise ExceptionGroup("msg3", excs)
586
+
587
+ level3(5)
588
+
589
+ try:
590
+ nested_group()
591
+ except ExceptionGroup as e:
592
+ e.add_note(f"the note: {id(e)}")
593
+ eg = e
594
+
595
+ eg_template = [
596
+ [
597
+ [ValueError(6), TypeError(int), ValueError(7)],
598
+ [ValueError(7), TypeError(int), ValueError(8)],
599
+ ValueError(8),
600
+ ],
601
+ ValueError(7),
602
+ ]
603
+
604
+ valueErrors_template = [
605
+ [
606
+ [ValueError(6), ValueError(7)],
607
+ [ValueError(7), ValueError(8)],
608
+ ValueError(8),
609
+ ],
610
+ ValueError(7),
611
+ ]
612
+
613
+ typeErrors_template = [[[TypeError(int)], [TypeError(int)]]]
614
+
615
+ self.assertMatchesTemplate(eg, ExceptionGroup, eg_template)
616
+
617
+ # Match Nothing
618
+ match, rest = self.split_exception_group(eg, SyntaxError)
619
+ self.assertIsNone(match)
620
+ self.assertMatchesTemplate(rest, ExceptionGroup, eg_template)
621
+
622
+ # Match Everything
623
+ match, rest = self.split_exception_group(eg, BaseException)
624
+ self.assertMatchesTemplate(match, ExceptionGroup, eg_template)
625
+ self.assertIsNone(rest)
626
+ match, rest = self.split_exception_group(eg, (ValueError, TypeError))
627
+ self.assertMatchesTemplate(match, ExceptionGroup, eg_template)
628
+ self.assertIsNone(rest)
629
+
630
+ # Match ValueErrors
631
+ match, rest = self.split_exception_group(eg, ValueError)
632
+ self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template)
633
+ self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template)
634
+
635
+ # Match TypeErrors
636
+ match, rest = self.split_exception_group(eg, (TypeError, SyntaxError))
637
+ self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template)
638
+ self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template)
639
+
640
+ # Match ExceptionGroup
641
+ match, rest = eg.split(ExceptionGroup)
642
+ self.assertIs(match, eg)
643
+ self.assertIsNone(rest)
644
+
645
+ # Match MyExceptionGroup (ExceptionGroup subclass)
646
+ match, rest = eg.split(MyExceptionGroup)
647
+ self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]])
648
+ self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]])
649
+
650
+ def test_split_BaseExceptionGroup(self):
651
+ def exc(ex):
652
+ try:
653
+ raise ex
654
+ except BaseException as e:
655
+ return e
656
+
657
+ try:
658
+ raise BaseExceptionGroup(
659
+ "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))]
660
+ )
661
+ except BaseExceptionGroup as e:
662
+ beg = e
663
+
664
+ # Match Nothing
665
+ match, rest = self.split_exception_group(beg, TypeError)
666
+ self.assertIsNone(match)
667
+ self.assertMatchesTemplate(
668
+ rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)]
669
+ )
670
+
671
+ # Match Everything
672
+ match, rest = self.split_exception_group(beg, (ValueError, KeyboardInterrupt))
673
+ self.assertMatchesTemplate(
674
+ match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)]
675
+ )
676
+ self.assertIsNone(rest)
677
+
678
+ # Match ValueErrors
679
+ match, rest = self.split_exception_group(beg, ValueError)
680
+ self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)])
681
+ self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)])
682
+
683
+ # Match KeyboardInterrupts
684
+ match, rest = self.split_exception_group(beg, KeyboardInterrupt)
685
+ self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)])
686
+ self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)])
687
+
688
+
689
+ class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase):
690
+ def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self):
691
+ class EG(ExceptionGroup):
692
+ pass
693
+
694
+ try:
695
+ try:
696
+ try:
697
+ raise TypeError(2)
698
+ except TypeError as te:
699
+ raise EG("nested", [te])
700
+ except EG as nested:
701
+ try:
702
+ raise ValueError(1)
703
+ except ValueError as ve:
704
+ raise EG("eg", [ve, nested])
705
+ except EG as e:
706
+ eg = e
707
+
708
+ self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]])
709
+
710
+ # Match Nothing
711
+ match, rest = self.split_exception_group(eg, OSError)
712
+ self.assertIsNone(match)
713
+ self.assertMatchesTemplate(
714
+ rest, ExceptionGroup, [ValueError(1), [TypeError(2)]]
715
+ )
716
+
717
+ # Match Everything
718
+ match, rest = self.split_exception_group(eg, (ValueError, TypeError))
719
+ self.assertMatchesTemplate(
720
+ match, ExceptionGroup, [ValueError(1), [TypeError(2)]]
721
+ )
722
+ self.assertIsNone(rest)
723
+
724
+ # Match ValueErrors
725
+ match, rest = self.split_exception_group(eg, ValueError)
726
+ self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)])
727
+ self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]])
728
+
729
+ # Match TypeErrors
730
+ match, rest = self.split_exception_group(eg, TypeError)
731
+ self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]])
732
+ self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)])
733
+
734
+ def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self):
735
+ class EG(BaseExceptionGroup):
736
+ def __new__(cls, message, excs, unused):
737
+ # The "unused" arg is here to show that split() doesn't call
738
+ # the actual class constructor from the default derive()
739
+ # implementation (it would fail on unused arg if so because
740
+ # it assumes the BaseExceptionGroup.__new__ signature).
741
+ return super().__new__(cls, message, excs)
742
+
743
+ try:
744
+ raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused")
745
+ except EG as e:
746
+ eg = e
747
+
748
+ self.assertMatchesTemplate(eg, EG, [ValueError(1), KeyboardInterrupt(2)])
749
+
750
+ # Match Nothing
751
+ match, rest = self.split_exception_group(eg, OSError)
752
+ self.assertIsNone(match)
753
+ self.assertMatchesTemplate(
754
+ rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)]
755
+ )
756
+
757
+ # Match Everything
758
+ match, rest = self.split_exception_group(eg, (ValueError, KeyboardInterrupt))
759
+ self.assertMatchesTemplate(
760
+ match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)]
761
+ )
762
+ self.assertIsNone(rest)
763
+
764
+ # Match ValueErrors
765
+ match, rest = self.split_exception_group(eg, ValueError)
766
+ self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)])
767
+ self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)])
768
+
769
+ # Match KeyboardInterrupt
770
+ match, rest = self.split_exception_group(eg, KeyboardInterrupt)
771
+ self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)])
772
+ self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)])
773
+
774
+ def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self):
775
+ class EG(ExceptionGroup):
776
+ def __new__(cls, message, excs, code):
777
+ obj = super().__new__(cls, message, excs)
778
+ obj.code = code
779
+ return obj
780
+
781
+ def derive(self, excs):
782
+ return EG(self.message, excs, self.code)
783
+
784
+ try:
785
+ try:
786
+ try:
787
+ raise TypeError(2)
788
+ except TypeError as te:
789
+ raise EG("nested", [te], 101)
790
+ except EG as nested:
791
+ try:
792
+ raise ValueError(1)
793
+ except ValueError as ve:
794
+ raise EG("eg", [ve, nested], 42)
795
+ except EG as e:
796
+ e.add_note("hello")
797
+ eg = e
798
+
799
+ self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]])
800
+
801
+ # Match Nothing
802
+ match, rest = self.split_exception_group(eg, OSError)
803
+ self.assertIsNone(match)
804
+ self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]])
805
+ self.assertEqual(rest.code, 42)
806
+ self.assertEqual(rest.exceptions[1].code, 101)
807
+ self.assertEqual(rest.__notes__, ["hello"])
808
+
809
+ # Match Everything
810
+ match, rest = self.split_exception_group(eg, (ValueError, TypeError))
811
+ self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]])
812
+ self.assertEqual(match.code, 42)
813
+ self.assertEqual(match.exceptions[1].code, 101)
814
+ self.assertEqual(match.__notes__, ["hello"])
815
+ self.assertIsNone(rest)
816
+
817
+ # Match ValueErrors
818
+ match, rest = self.split_exception_group(eg, ValueError)
819
+ self.assertMatchesTemplate(match, EG, [ValueError(1)])
820
+ self.assertEqual(match.code, 42)
821
+ self.assertEqual(match.__notes__, ["hello"])
822
+ self.assertMatchesTemplate(rest, EG, [[TypeError(2)]])
823
+ self.assertEqual(rest.code, 42)
824
+ self.assertEqual(rest.exceptions[0].code, 101)
825
+ self.assertEqual(rest.__notes__, ["hello"])
826
+
827
+ # Match TypeErrors
828
+ match, rest = self.split_exception_group(eg, TypeError)
829
+ self.assertMatchesTemplate(match, EG, [[TypeError(2)]])
830
+ self.assertEqual(match.code, 42)
831
+ self.assertEqual(match.exceptions[0].code, 101)
832
+ self.assertEqual(match.__notes__, ["hello"])
833
+ self.assertMatchesTemplate(rest, EG, [ValueError(1)])
834
+ self.assertEqual(rest.code, 42)
835
+ self.assertEqual(rest.__notes__, ["hello"])
836
+
837
+
838
+ def test_repr():
839
+ group = BaseExceptionGroup("foo", [ValueError(1), KeyboardInterrupt()])
840
+ assert repr(group) == (
841
+ "BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()])"
842
+ )
843
+
844
+ group = ExceptionGroup("foo", [ValueError(1), RuntimeError("bar")])
845
+ assert repr(group) == "ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')])"
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_formatting.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import traceback
3
+ from typing import NoReturn
4
+ from urllib.error import HTTPError
5
+
6
+ import pytest
7
+ from _pytest.capture import CaptureFixture
8
+ from _pytest.fixtures import SubRequest
9
+ from _pytest.monkeypatch import MonkeyPatch
10
+
11
+ from exceptiongroup import ExceptionGroup
12
+
13
+
14
+ def raise_excgroup() -> NoReturn:
15
+ exceptions = []
16
+ try:
17
+ raise ValueError("foo")
18
+ except ValueError as exc:
19
+ exceptions.append(exc)
20
+
21
+ try:
22
+ raise RuntimeError("bar")
23
+ except RuntimeError as exc:
24
+ exc.__notes__ = ["Note from bar handler"]
25
+ exceptions.append(exc)
26
+
27
+ exc = ExceptionGroup("test message", exceptions)
28
+ exc.add_note("Displays notes attached to the group too")
29
+ raise exc
30
+
31
+
32
+ @pytest.fixture(
33
+ params=[
34
+ pytest.param(True, id="patched"),
35
+ pytest.param(
36
+ False,
37
+ id="unpatched",
38
+ marks=[
39
+ pytest.mark.skipif(
40
+ sys.version_info >= (3, 11),
41
+ reason="No patching is done on Python >= 3.11",
42
+ )
43
+ ],
44
+ ),
45
+ ],
46
+ )
47
+ def patched(request: SubRequest) -> bool:
48
+ return request.param
49
+
50
+
51
+ @pytest.fixture(
52
+ params=[pytest.param(False, id="newstyle"), pytest.param(True, id="oldstyle")]
53
+ )
54
+ def old_argstyle(request: SubRequest) -> bool:
55
+ return request.param
56
+
57
+
58
+ def test_exceptionhook(capsys: CaptureFixture) -> None:
59
+ try:
60
+ raise_excgroup()
61
+ except ExceptionGroup as exc:
62
+ sys.excepthook(type(exc), exc, exc.__traceback__)
63
+
64
+ local_lineno = test_exceptionhook.__code__.co_firstlineno
65
+ lineno = raise_excgroup.__code__.co_firstlineno
66
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
67
+ underline_suffix = (
68
+ "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^"
69
+ )
70
+ output = capsys.readouterr().err
71
+ assert output == (
72
+ f"""\
73
+ + Exception Group Traceback (most recent call last):
74
+ | File "{__file__}", line {local_lineno + 2}, in test_exceptionhook
75
+ | raise_excgroup(){underline_suffix}
76
+ | File "{__file__}", line {lineno + 15}, in raise_excgroup
77
+ | raise exc
78
+ | {module_prefix}ExceptionGroup: test message (2 sub-exceptions)
79
+ | Displays notes attached to the group too
80
+ +-+---------------- 1 ----------------
81
+ | Traceback (most recent call last):
82
+ | File "{__file__}", line {lineno + 3}, in raise_excgroup
83
+ | raise ValueError("foo")
84
+ | ValueError: foo
85
+ +---------------- 2 ----------------
86
+ | Traceback (most recent call last):
87
+ | File "{__file__}", line {lineno + 8}, in raise_excgroup
88
+ | raise RuntimeError("bar")
89
+ | RuntimeError: bar
90
+ | Note from bar handler
91
+ +------------------------------------
92
+ """
93
+ )
94
+
95
+
96
+ def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None:
97
+ try:
98
+ raise Exception() from ExceptionGroup("", (Exception(),))
99
+ except Exception as exc:
100
+ sys.excepthook(type(exc), exc, exc.__traceback__)
101
+
102
+ lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno
103
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
104
+ output = capsys.readouterr().err
105
+ assert output == (
106
+ f"""\
107
+ | {module_prefix}ExceptionGroup: (1 sub-exception)
108
+ +-+---------------- 1 ----------------
109
+ | Exception
110
+ +------------------------------------
111
+
112
+ The above exception was the direct cause of the following exception:
113
+
114
+ Traceback (most recent call last):
115
+ File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause
116
+ raise Exception() from ExceptionGroup("", (Exception(),))
117
+ Exception
118
+ """
119
+ )
120
+
121
+
122
+ def test_exceptiongroup_loop(capsys: CaptureFixture) -> None:
123
+ e0 = Exception("e0")
124
+ eg0 = ExceptionGroup("eg0", (e0,))
125
+ eg1 = ExceptionGroup("eg1", (eg0,))
126
+
127
+ try:
128
+ raise eg0 from eg1
129
+ except ExceptionGroup as exc:
130
+ sys.excepthook(type(exc), exc, exc.__traceback__)
131
+
132
+ lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6
133
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
134
+ output = capsys.readouterr().err
135
+ assert output == (
136
+ f"""\
137
+ | {module_prefix}ExceptionGroup: eg1 (1 sub-exception)
138
+ +-+---------------- 1 ----------------
139
+ | Exception Group Traceback (most recent call last):
140
+ | File "{__file__}", line {lineno}, in test_exceptiongroup_loop
141
+ | raise eg0 from eg1
142
+ | {module_prefix}ExceptionGroup: eg0 (1 sub-exception)
143
+ +-+---------------- 1 ----------------
144
+ | Exception: e0
145
+ +------------------------------------
146
+
147
+ The above exception was the direct cause of the following exception:
148
+
149
+ + Exception Group Traceback (most recent call last):
150
+ | File "{__file__}", line {lineno}, in test_exceptiongroup_loop
151
+ | raise eg0 from eg1
152
+ | {module_prefix}ExceptionGroup: eg0 (1 sub-exception)
153
+ +-+---------------- 1 ----------------
154
+ | Exception: e0
155
+ +------------------------------------
156
+ """
157
+ )
158
+
159
+
160
+ def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None:
161
+ try:
162
+ raise_excgroup()
163
+ except ExceptionGroup as exc:
164
+ sys.excepthook(type(exc), exc, exc.__traceback__)
165
+
166
+ local_lineno = test_exceptionhook_format_exception_only.__code__.co_firstlineno
167
+ lineno = raise_excgroup.__code__.co_firstlineno
168
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
169
+ underline_suffix = (
170
+ "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^"
171
+ )
172
+ output = capsys.readouterr().err
173
+ assert output == (
174
+ f"""\
175
+ + Exception Group Traceback (most recent call last):
176
+ | File "{__file__}", line {local_lineno + 2}, in \
177
+ test_exceptionhook_format_exception_only
178
+ | raise_excgroup(){underline_suffix}
179
+ | File "{__file__}", line {lineno + 15}, in raise_excgroup
180
+ | raise exc
181
+ | {module_prefix}ExceptionGroup: test message (2 sub-exceptions)
182
+ | Displays notes attached to the group too
183
+ +-+---------------- 1 ----------------
184
+ | Traceback (most recent call last):
185
+ | File "{__file__}", line {lineno + 3}, in raise_excgroup
186
+ | raise ValueError("foo")
187
+ | ValueError: foo
188
+ +---------------- 2 ----------------
189
+ | Traceback (most recent call last):
190
+ | File "{__file__}", line {lineno + 8}, in raise_excgroup
191
+ | raise RuntimeError("bar")
192
+ | RuntimeError: bar
193
+ | Note from bar handler
194
+ +------------------------------------
195
+ """
196
+ )
197
+
198
+
199
+ def test_formatting_syntax_error(capsys: CaptureFixture) -> None:
200
+ try:
201
+ exec("//serser")
202
+ except SyntaxError as exc:
203
+ sys.excepthook(type(exc), exc, exc.__traceback__)
204
+
205
+ if sys.version_info >= (3, 10):
206
+ underline = "\n ^^"
207
+ elif sys.version_info >= (3, 8):
208
+ underline = "\n ^"
209
+ else:
210
+ underline = "\n ^"
211
+
212
+ lineno = test_formatting_syntax_error.__code__.co_firstlineno
213
+ underline_suffix = "" if sys.version_info < (3, 13) else "\n ~~~~^^^^^^^^^^^^"
214
+ output = capsys.readouterr().err
215
+ assert output == (
216
+ f"""\
217
+ Traceback (most recent call last):
218
+ File "{__file__}", line {lineno + 2}, \
219
+ in test_formatting_syntax_error
220
+ exec("//serser"){underline_suffix}
221
+ File "<string>", line 1
222
+ //serser{underline}
223
+ SyntaxError: invalid syntax
224
+ """
225
+ )
226
+
227
+
228
+ def test_format_exception(
229
+ patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch
230
+ ) -> None:
231
+ if not patched:
232
+ # Block monkey patching, then force the module to be re-imported
233
+ del sys.modules["traceback"]
234
+ del sys.modules["exceptiongroup"]
235
+ del sys.modules["exceptiongroup._formatting"]
236
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
237
+
238
+ from exceptiongroup import format_exception
239
+
240
+ exceptions = []
241
+ try:
242
+ raise ValueError("foo")
243
+ except ValueError as exc:
244
+ exceptions.append(exc)
245
+
246
+ try:
247
+ raise RuntimeError("bar")
248
+ except RuntimeError as exc:
249
+ exc.__notes__ = ["Note from bar handler"]
250
+ exceptions.append(exc)
251
+
252
+ try:
253
+ raise_excgroup()
254
+ except ExceptionGroup as exc:
255
+ if old_argstyle:
256
+ lines = format_exception(type(exc), exc, exc.__traceback__)
257
+ else:
258
+ lines = format_exception(exc)
259
+
260
+ local_lineno = test_format_exception.__code__.co_firstlineno
261
+ lineno = raise_excgroup.__code__.co_firstlineno
262
+ assert isinstance(lines, list)
263
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
264
+ underline_suffix = (
265
+ "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^"
266
+ )
267
+ assert "".join(lines) == (
268
+ f"""\
269
+ + Exception Group Traceback (most recent call last):
270
+ | File "{__file__}", line {local_lineno + 25}, in test_format_exception
271
+ | raise_excgroup(){underline_suffix}
272
+ | File "{__file__}", line {lineno + 15}, in raise_excgroup
273
+ | raise exc
274
+ | {module_prefix}ExceptionGroup: test message (2 sub-exceptions)
275
+ | Displays notes attached to the group too
276
+ +-+---------------- 1 ----------------
277
+ | Traceback (most recent call last):
278
+ | File "{__file__}", line {lineno + 3}, in raise_excgroup
279
+ | raise ValueError("foo")
280
+ | ValueError: foo
281
+ +---------------- 2 ----------------
282
+ | Traceback (most recent call last):
283
+ | File "{__file__}", line {lineno + 8}, in raise_excgroup
284
+ | raise RuntimeError("bar")
285
+ | RuntimeError: bar
286
+ | Note from bar handler
287
+ +------------------------------------
288
+ """
289
+ )
290
+
291
+
292
+ def test_format_nested(monkeypatch: MonkeyPatch) -> None:
293
+ if not patched:
294
+ # Block monkey patching, then force the module to be re-imported
295
+ del sys.modules["traceback"]
296
+ del sys.modules["exceptiongroup"]
297
+ del sys.modules["exceptiongroup._formatting"]
298
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
299
+
300
+ from exceptiongroup import format_exception
301
+
302
+ def raise_exc(max_level: int, level: int = 1) -> NoReturn:
303
+ if level == max_level:
304
+ raise Exception(f"LEVEL_{level}")
305
+ else:
306
+ try:
307
+ raise_exc(max_level, level + 1)
308
+ except Exception:
309
+ raise Exception(f"LEVEL_{level}")
310
+
311
+ try:
312
+ raise_exc(3)
313
+ except Exception as exc:
314
+ lines = format_exception(type(exc), exc, exc.__traceback__)
315
+
316
+ underline_suffix1 = (
317
+ "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^"
318
+ )
319
+ underline_suffix2 = "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^"
320
+ local_lineno = test_format_nested.__code__.co_firstlineno + 20
321
+ raise_exc_lineno1 = raise_exc.__code__.co_firstlineno + 2
322
+ raise_exc_lineno2 = raise_exc.__code__.co_firstlineno + 5
323
+ raise_exc_lineno3 = raise_exc.__code__.co_firstlineno + 7
324
+ assert isinstance(lines, list)
325
+ assert "".join(lines) == (
326
+ f"""\
327
+ Traceback (most recent call last):
328
+ File "{__file__}", line {raise_exc_lineno2}, in raise_exc
329
+ raise_exc(max_level, level + 1){underline_suffix1}
330
+ File "{__file__}", line {raise_exc_lineno1}, in raise_exc
331
+ raise Exception(f"LEVEL_{{level}}")
332
+ Exception: LEVEL_3
333
+
334
+ During handling of the above exception, another exception occurred:
335
+
336
+ Traceback (most recent call last):
337
+ File "{__file__}", line {raise_exc_lineno2}, in raise_exc
338
+ raise_exc(max_level, level + 1){underline_suffix1}
339
+ File "{__file__}", line {raise_exc_lineno3}, in raise_exc
340
+ raise Exception(f"LEVEL_{{level}}")
341
+ Exception: LEVEL_2
342
+
343
+ During handling of the above exception, another exception occurred:
344
+
345
+ Traceback (most recent call last):
346
+ File "{__file__}", line {local_lineno}, in test_format_nested
347
+ raise_exc(3){underline_suffix2}
348
+ File "{__file__}", line {raise_exc_lineno3}, in raise_exc
349
+ raise Exception(f"LEVEL_{{level}}")
350
+ Exception: LEVEL_1
351
+ """
352
+ )
353
+
354
+
355
+ def test_format_exception_only(
356
+ patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch
357
+ ) -> None:
358
+ if not patched:
359
+ # Block monkey patching, then force the module to be re-imported
360
+ del sys.modules["traceback"]
361
+ del sys.modules["exceptiongroup"]
362
+ del sys.modules["exceptiongroup._formatting"]
363
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
364
+
365
+ from exceptiongroup import format_exception_only
366
+
367
+ try:
368
+ raise_excgroup()
369
+ except ExceptionGroup as exc:
370
+ if old_argstyle:
371
+ output = format_exception_only(type(exc), exc)
372
+ else:
373
+ output = format_exception_only(exc)
374
+
375
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
376
+ assert output == [
377
+ f"{module_prefix}ExceptionGroup: test message (2 sub-exceptions)\n",
378
+ "Displays notes attached to the group too\n",
379
+ ]
380
+
381
+
382
+ def test_print_exception(
383
+ patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
384
+ ) -> None:
385
+ if not patched:
386
+ # Block monkey patching, then force the module to be re-imported
387
+ del sys.modules["traceback"]
388
+ del sys.modules["exceptiongroup"]
389
+ del sys.modules["exceptiongroup._formatting"]
390
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
391
+
392
+ from exceptiongroup import print_exception
393
+
394
+ try:
395
+ raise_excgroup()
396
+ except ExceptionGroup as exc:
397
+ if old_argstyle:
398
+ print_exception(type(exc), exc, exc.__traceback__)
399
+ else:
400
+ print_exception(exc)
401
+
402
+ local_lineno = test_print_exception.__code__.co_firstlineno
403
+ lineno = raise_excgroup.__code__.co_firstlineno
404
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
405
+ underline_suffix = (
406
+ "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^"
407
+ )
408
+ output = capsys.readouterr().err
409
+ assert output == (
410
+ f"""\
411
+ + Exception Group Traceback (most recent call last):
412
+ | File "{__file__}", line {local_lineno + 13}, in test_print_exception
413
+ | raise_excgroup(){underline_suffix}
414
+ | File "{__file__}", line {lineno + 15}, in raise_excgroup
415
+ | raise exc
416
+ | {module_prefix}ExceptionGroup: test message (2 sub-exceptions)
417
+ | Displays notes attached to the group too
418
+ +-+---------------- 1 ----------------
419
+ | Traceback (most recent call last):
420
+ | File "{__file__}", line {lineno + 3}, in raise_excgroup
421
+ | raise ValueError("foo")
422
+ | ValueError: foo
423
+ +---------------- 2 ----------------
424
+ | Traceback (most recent call last):
425
+ | File "{__file__}", line {lineno + 8}, in raise_excgroup
426
+ | raise RuntimeError("bar")
427
+ | RuntimeError: bar
428
+ | Note from bar handler
429
+ +------------------------------------
430
+ """
431
+ )
432
+
433
+
434
+ def test_print_exc(
435
+ patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
436
+ ) -> None:
437
+ if not patched:
438
+ # Block monkey patching, then force the module to be re-imported
439
+ del sys.modules["traceback"]
440
+ del sys.modules["exceptiongroup"]
441
+ del sys.modules["exceptiongroup._formatting"]
442
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
443
+
444
+ from exceptiongroup import print_exc
445
+
446
+ try:
447
+ raise_excgroup()
448
+ except ExceptionGroup:
449
+ print_exc()
450
+ local_lineno = test_print_exc.__code__.co_firstlineno
451
+ lineno = raise_excgroup.__code__.co_firstlineno
452
+ module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
453
+ underline_suffix = (
454
+ "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^"
455
+ )
456
+ output = capsys.readouterr().err
457
+ assert output == (
458
+ f"""\
459
+ + Exception Group Traceback (most recent call last):
460
+ | File "{__file__}", line {local_lineno + 13}, in test_print_exc
461
+ | raise_excgroup(){underline_suffix}
462
+ | File "{__file__}", line {lineno + 15}, in raise_excgroup
463
+ | raise exc
464
+ | {module_prefix}ExceptionGroup: test message (2 sub-exceptions)
465
+ | Displays notes attached to the group too
466
+ +-+---------------- 1 ----------------
467
+ | Traceback (most recent call last):
468
+ | File "{__file__}", line {lineno + 3}, in raise_excgroup
469
+ | raise ValueError("foo")
470
+ | ValueError: foo
471
+ +---------------- 2 ----------------
472
+ | Traceback (most recent call last):
473
+ | File "{__file__}", line {lineno + 8}, in raise_excgroup
474
+ | raise RuntimeError("bar")
475
+ | RuntimeError: bar
476
+ | Note from bar handler
477
+ +------------------------------------
478
+ """
479
+ )
480
+
481
+
482
+ @pytest.mark.skipif(
483
+ not hasattr(NameError, "name") or sys.version_info[:2] == (3, 11),
484
+ reason="only works if NameError exposes the missing name",
485
+ )
486
+ def test_nameerror_suggestions(
487
+ patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
488
+ ) -> None:
489
+ if not patched:
490
+ # Block monkey patching, then force the module to be re-imported
491
+ del sys.modules["traceback"]
492
+ del sys.modules["exceptiongroup"]
493
+ del sys.modules["exceptiongroup._formatting"]
494
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
495
+
496
+ from exceptiongroup import print_exc
497
+
498
+ try:
499
+ folder
500
+ except NameError:
501
+ print_exc()
502
+ output = capsys.readouterr().err
503
+ assert "Did you mean" in output and "'filter'?" in output
504
+
505
+
506
+ @pytest.mark.skipif(
507
+ not hasattr(AttributeError, "name") or sys.version_info[:2] == (3, 11),
508
+ reason="only works if AttributeError exposes the missing name",
509
+ )
510
+ def test_nameerror_suggestions_in_group(
511
+ patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
512
+ ) -> None:
513
+ if not patched:
514
+ # Block monkey patching, then force the module to be re-imported
515
+ del sys.modules["traceback"]
516
+ del sys.modules["exceptiongroup"]
517
+ del sys.modules["exceptiongroup._formatting"]
518
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
519
+
520
+ from exceptiongroup import print_exception
521
+
522
+ try:
523
+ [].attend
524
+ except AttributeError as e:
525
+ eg = ExceptionGroup("a", [e])
526
+ print_exception(eg)
527
+ output = capsys.readouterr().err
528
+ assert "Did you mean" in output and "'append'?" in output
529
+
530
+
531
+ def test_bug_suggestions_attributeerror_no_obj(
532
+ patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
533
+ ) -> None:
534
+ if not patched:
535
+ # Block monkey patching, then force the module to be re-imported
536
+ del sys.modules["traceback"]
537
+ del sys.modules["exceptiongroup"]
538
+ del sys.modules["exceptiongroup._formatting"]
539
+ monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
540
+
541
+ from exceptiongroup import print_exception
542
+
543
+ class NamedAttributeError(AttributeError):
544
+ def __init__(self, name: str) -> None:
545
+ self.name: str = name
546
+
547
+ try:
548
+ raise NamedAttributeError(name="mykey")
549
+ except AttributeError as e:
550
+ print_exception(e) # does not crash
551
+ output = capsys.readouterr().err
552
+ assert "NamedAttributeError" in output
553
+
554
+
555
+ def test_works_around_httperror_bug():
556
+ # See https://github.com/python/cpython/issues/98778 in Python <= 3.9
557
+ err = HTTPError("url", 405, "METHOD NOT ALLOWED", None, None)
558
+ traceback.TracebackException(type(err), err, None)
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_suppress.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ from exceptiongroup import suppress
6
+
7
+ if sys.version_info < (3, 11):
8
+ from exceptiongroup import BaseExceptionGroup, ExceptionGroup
9
+
10
+
11
+ def test_suppress_exception():
12
+ with pytest.raises(ExceptionGroup) as exc, suppress(SystemExit):
13
+ raise BaseExceptionGroup("", [SystemExit(1), RuntimeError("boo")])
14
+
15
+ assert len(exc.value.exceptions) == 1
16
+ assert isinstance(exc.value.exceptions[0], RuntimeError)
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/canaries/first-hunk-only.sh ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -Eeuo pipefail
3
+ cd /testbed/repo
4
+ cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL'
5
+ diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py
6
+ index e39c9f74e783a6b30a39dd0fb19bc5883e7ff54a..a4a7acea822d43ba91183cff0b44f31313171d1a 100644
7
+ --- a/src/exceptiongroup/_exceptions.py
8
+ +++ b/src/exceptiongroup/_exceptions.py
9
+ @@ -56,26 +56,47 @@
10
+ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
11
+ """A combination of multiple unrelated exceptions."""
12
+
13
+ - def __new__(cls: type[_BaseExceptionGroupSelf], __message: str,
14
+ - __exceptions: Sequence[_BaseExceptionT_co]) ->_BaseExceptionGroupSelf:
15
+ - """Create a new BaseExceptionGroup instance."""
16
+ + def __new__(
17
+ + cls: type[_BaseExceptionGroupSelf],
18
+ + __message: str,
19
+ + __exceptions: Sequence[_BaseExceptionT_co],
20
+ + ) -> _BaseExceptionGroupSelf:
21
+ if not isinstance(__message, str):
22
+ - raise TypeError(f"message must be a string, not {type(__message).__name__}")
23
+ -
24
+ + raise TypeError(f"argument 1 must be str, not {type(__message)}")
25
+ + if not isinstance(__exceptions, Sequence):
26
+ + raise TypeError("second argument (exceptions) must be a sequence")
27
+ if not __exceptions:
28
+ - raise ValueError("exceptions must be a non-empty sequence")
29
+ -
30
+ + raise ValueError(
31
+ + "second argument (exceptions) must be a non-empty sequence"
32
+ + )
33
+ +
34
+ for i, exc in enumerate(__exceptions):
35
+ if not isinstance(exc, BaseException):
36
+ - raise TypeError(
37
+ - f"Item {i} of exceptions sequence: expected an exception object, "
38
+ - f"got {type(exc).__name__}"
39
+ + raise ValueError(
40
+ + f"Item {i} of second argument (exceptions) is not an exception"
41
+ )
42
+ -
43
+ - instance = super().__new__(cls)
44
+ +
45
+ + if cls is BaseExceptionGroup:
46
+ + if all(isinstance(exc, Exception) for exc in __exceptions):
47
+ + cls = ExceptionGroup
48
+ +
49
+ + if issubclass(cls, Exception):
50
+ + for exc in __exceptions:
51
+ + if not isinstance(exc, Exception):
52
+ + if cls is ExceptionGroup:
53
+ + raise TypeError(
54
+ + "Cannot nest BaseExceptions in an ExceptionGroup"
55
+ + )
56
+ + else:
57
+ + raise TypeError(
58
+ + f"Cannot nest BaseExceptions in {cls.__name__!r}"
59
+ + )
60
+ +
61
+ + instance = super().__new__(cls, __message, __exceptions)
62
+ instance._message = __message
63
+ - instance._exceptions = list(__exceptions)
64
+ + instance._exceptions = __exceptions
65
+ return instance
66
+ +
67
+ def add_note(self, note: str) -> None:
68
+ if not isinstance(note, str):
69
+ raise TypeError(
70
+ OPENENV_PARTIAL
71
+ /usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/canaries/original-bug.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -Eeuo pipefail
3
+ :
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/openenv.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "canaries": "validation/canaries",
3
+ "profile": "harbor-semantic-v1",
4
+ "requires_credentials": false,
5
+ "resources": {
6
+ "cpu": 2,
7
+ "disk_mb": 16384,
8
+ "episode_timeout_s": 1800,
9
+ "memory_mb": 8192
10
+ },
11
+ "reward": {
12
+ "floor_margin": 0.1,
13
+ "oracle_tolerance": 0,
14
+ "range": [
15
+ 0,
16
+ 1
17
+ ]
18
+ },
19
+ "reward_key": "reward",
20
+ "types": {
21
+ "tags": [
22
+ "swe",
23
+ "python",
24
+ "mutation-repair"
25
+ ]
26
+ }
27
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/LICENSE.source ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Alex Grönholm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+
23
+ This project contains code copied from the Python standard library.
24
+ The following is the required license notice for those parts.
25
+
26
+ PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
27
+ --------------------------------------------
28
+
29
+ 1. This LICENSE AGREEMENT is between the Python Software Foundation
30
+ ("PSF"), and the Individual or Organization ("Licensee") accessing and
31
+ otherwise using this software ("Python") in source or binary form and
32
+ its associated documentation.
33
+
34
+ 2. Subject to the terms and conditions of this License Agreement, PSF hereby
35
+ grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
36
+ analyze, test, perform and/or display publicly, prepare derivative works,
37
+ distribute, and otherwise use Python alone or in any derivative version,
38
+ provided, however, that PSF's License Agreement and PSF's notice of copyright,
39
+ i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
40
+ 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation;
41
+ All Rights Reserved" are retained in Python alone or in any derivative version
42
+ prepared by Licensee.
43
+
44
+ 3. In the event Licensee prepares a derivative work that is based on
45
+ or incorporates Python or any part thereof, and wants to make
46
+ the derivative work available to others as provided herein, then
47
+ Licensee hereby agrees to include in any such work a brief summary of
48
+ the changes made to Python.
49
+
50
+ 4. PSF is making Python available to Licensee on an "AS IS"
51
+ basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
52
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
53
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
54
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
55
+ INFRINGE ANY THIRD PARTY RIGHTS.
56
+
57
+ 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
58
+ FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
59
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
60
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
61
+
62
+ 6. This License Agreement will automatically terminate upon a material
63
+ breach of its terms and conditions.
64
+
65
+ 7. Nothing in this License Agreement shall be deemed to create any
66
+ relationship of agency, partnership, or joint venture between PSF and
67
+ Licensee. This License Agreement does not grant permission to use PSF
68
+ trademarks or trade name in a trademark sense to endorse or promote
69
+ products or services of Licensee, or any third party.
70
+
71
+ 8. By copying, installing or otherwise using Python, Licensee
72
+ agrees to be bound by the terms and conditions of this License
73
+ Agreement.
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/adapter.json ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.",
3
+ "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481",
4
+ "dependency_installation_pinned": false,
5
+ "dependency_setup_sha256": "6780ef55e5987924663b6e2b917a1b319de74c1108bf39a9fe6f5dc719935dfe",
6
+ "gold_patch_sha256": "86d9d20479db2f1aa8c5825ae73b6c0e1b87bff882bcb1f0b48b7ff5985f272f",
7
+ "hostile_code_isolation_established": false,
8
+ "known_wrong_semantic_implementations": 0,
9
+ "native_inventory_sha256": "083e4f98e67149b4389983d445b9e333b7d6ddb6e7b7016f747c3d44fe1b17bf",
10
+ "new_files_deletions_and_executable_modes_supported": true,
11
+ "official_profile": {
12
+ "eval_sets": [],
13
+ "profile_class": "Exceptiongroup0b4f4937",
14
+ "profile_lines": [
15
+ 327,
16
+ 330
17
+ ],
18
+ "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f",
19
+ "profile_source_path": "swesmith/profiles/python.py",
20
+ "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286",
21
+ "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
22
+ "upstream_repo": "agronholm/exceptiongroup"
23
+ },
24
+ "original_bug_canary_nop_equivalent": true,
25
+ "original_bug_runtime_wrongness_established": false,
26
+ "partial_repair_canary": true,
27
+ "partial_repair_sha256": "6589d58b5ee2923cfc11fdc66c4dc24099e21eafe663019cdcfbe69b2ab4a244",
28
+ "partial_repair_wrongness_established": false,
29
+ "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained",
30
+ "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7",
31
+ "private_checker_version": "matched-failure-precedence-v2",
32
+ "provided_original_bug_control": true,
33
+ "repo_url": "https://github.com/swesmith/agronholm__exceptiongroup.0b4f4937.git",
34
+ "runtime_image": null,
35
+ "runtime_ready": false,
36
+ "runtime_recipe": {
37
+ "dependency_installation_pinned": false,
38
+ "official_install_cmds": [
39
+ "python -m pip install -e ."
40
+ ],
41
+ "official_pytest_argv": [
42
+ "pytest",
43
+ "--disable-warnings",
44
+ "--color=no",
45
+ "--tb=no",
46
+ "--verbose"
47
+ ],
48
+ "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose",
49
+ "operator_test_runner_prerequisites": [
50
+ "python -m pip install pytest==8.4.2"
51
+ ],
52
+ "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.",
53
+ "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.",
54
+ "python_version": "3.10",
55
+ "source_bound_test_dependency_cmds": [
56
+ "python -m pip install -e '.[test]'"
57
+ ],
58
+ "test_dependency_source_sha256": {
59
+ "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5"
60
+ }
61
+ },
62
+ "runtime_resource_review_required": false,
63
+ "schema": "python-git-patch-jobs-v1",
64
+ "source_base_commit": "2750f7c388bd518feb6b45219c330cff71f470c1",
65
+ "source_completion_sha256": "0ec6674d9ad4043253b50b5c3554b00fe724dc3165e347546526f0a09829dbe9",
66
+ "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f",
67
+ "source_pr_url": null,
68
+ "source_record": {
69
+ "anti_training_canary": false,
70
+ "anti_training_reviewed": true,
71
+ "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj",
72
+ "cloud_launch_ready": false,
73
+ "eligibility": {
74
+ "reasons": [],
75
+ "semantic_nonoverlap_established": false,
76
+ "status": "eligible_for_controls",
77
+ "training_admissible": false,
78
+ "warnings": []
79
+ },
80
+ "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473",
81
+ "instruction_sha256": "5af60e46dd7f066bf33d8f5858007b2de56b337800241f782fca55c91f3f53b4",
82
+ "is_fork": true,
83
+ "learner_path": "tasks/55cac8b782ebef1096fe86f9/learner",
84
+ "license_evidence": {
85
+ "source_code": {
86
+ "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
87
+ "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE",
88
+ "reviewed": true,
89
+ "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c",
90
+ "spdx": "MIT",
91
+ "training_allowed": true,
92
+ "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/2750f7c388bd518feb6b45219c330cff71f470c1/LICENSE"
93
+ },
94
+ "task_bundle": {
95
+ "reviewed": true,
96
+ "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808",
97
+ "spdx": "MIT",
98
+ "training_allowed": true,
99
+ "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md"
100
+ }
101
+ },
102
+ "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b",
103
+ "patch_sha256": "8211158489028bd6338d1ab8bfd0687b638490a68981bf154643bfb38f330bae",
104
+ "provenance_path": "tasks/55cac8b782ebef1096fe86f9/source-proof.json",
105
+ "repository_lineage": [
106
+ "swesmith/agronholm__exceptiongroup.0b4f4937",
107
+ "agronholm/exceptiongroup"
108
+ ],
109
+ "rfc008_complete": false,
110
+ "runtime_qualified": false,
111
+ "semantic_nonoverlap_established": false,
112
+ "source_commit": "2750f7c388bd518feb6b45219c330cff71f470c1",
113
+ "source_dataset": "SWE-bench/SWE-smith-py",
114
+ "source_head_commit": "e939f1ed942290f930fe672c8587d886cf349cce",
115
+ "source_kind": "mutation",
116
+ "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937",
117
+ "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e",
118
+ "source_split": "train",
119
+ "target_model_calibrated": false,
120
+ "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj",
121
+ "task_sha256": "eb6b62b4f64af92d7c51c86b7817b2fd0cd9f2a106de1c21ef3d206ac52bf0ba",
122
+ "training_admissible": false,
123
+ "upstream_identity_reviewed": true,
124
+ "upstream_repo": "agronholm/exceptiongroup",
125
+ "usage": "quarantine_only"
126
+ },
127
+ "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937",
128
+ "symlink_submodule_changes_supported": false,
129
+ "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj",
130
+ "transfer": "index-independent-worktree-to-Git-binary-patch",
131
+ "transfer_path": "/testbed/submission.patch",
132
+ "upstream_repo": "agronholm/exceptiongroup"
133
+ }
tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/dependency-setup.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -Eeuo pipefail
3
+ source /opt/miniconda3/bin/activate
4
+ conda activate testbed
5
+ cd /testbed/repo
6
+ python -c 'import sys; assert sys.version_info[:2] == (3, 10)'
7
+ python -m pip install pytest==8.4.2
8
+ python -m pip install -e .
9
+ python -m pip install -e '.[test]'