@@ -119,6 +119,52 @@ The regexp parameter of the ``match`` method is matched with the ``re.search``
119
119
function, so in the above example ``match='123' `` would have worked as
120
120
well.
121
121
122
+ You can also use the :func: `excinfo.group_contains() <pytest.ExceptionInfo.group_contains> `
123
+ method to test for exceptions returned as part of an ``ExceptionGroup ``:
124
+
125
+ .. code-block :: python
126
+
127
+ def test_exception_in_group ():
128
+ with pytest.raises(RuntimeError ) as excinfo:
129
+ raise ExceptionGroup(
130
+ " Group message" ,
131
+ [
132
+ RuntimeError (" Exception 123 raised" ),
133
+ ],
134
+ )
135
+ assert excinfo.group_contains(RuntimeError , match = r " . * 123 . * " )
136
+ assert not excinfo.group_contains(TypeError )
137
+
138
+ The optional ``match `` keyword parameter works the same way as for
139
+ :func: `pytest.raises `.
140
+
141
+ By default ``group_contains() `` will recursively search for a matching
142
+ exception at any level of nested ``ExceptionGroup `` instances. You can
143
+ specify a ``depth `` keyword parameter if you only want to match an
144
+ exception at a specific level; exceptions contained directly in the top
145
+ ``ExceptionGroup `` would match ``depth=1 ``.
146
+
147
+ .. code-block :: python
148
+
149
+ def test_exception_in_group_at_given_depth ():
150
+ with pytest.raises(RuntimeError ) as excinfo:
151
+ raise ExceptionGroup(
152
+ " Group message" ,
153
+ [
154
+ RuntimeError (),
155
+ ExceptionGroup(
156
+ " Nested group" ,
157
+ [
158
+ TypeError (),
159
+ ],
160
+ ),
161
+ ],
162
+ )
163
+ assert excinfo.group_contains(RuntimeError , depth = 1 )
164
+ assert excinfo.group_contains(TypeError , depth = 2 )
165
+ assert not excinfo.group_contains(RuntimeError , depth = 2 )
166
+ assert not excinfo.group_contains(TypeError , depth = 1 )
167
+
122
168
There's an alternate form of the :func: `pytest.raises ` function where you pass
123
169
a function that will be executed with the given ``*args `` and ``**kwargs `` and
124
170
assert that the given exception is raised:
0 commit comments