| 259 | self.match_expr = match_expr |
| 260 | |
| 261 | def __exit__( |
| 262 | self, |
| 263 | exc_type: Optional[Type[BaseException]], |
| 264 | exc_val: Optional[BaseException], |
| 265 | exc_tb: Optional[TracebackType], |
| 266 | ) -> None: |
| 267 | super().__exit__(exc_type, exc_val, exc_tb) |
| 268 | |
| 269 | __tracebackhide__ = True |
| 270 | |
| 271 | # only check if we're not currently handling an exception |
| 272 | if exc_type is None and exc_val is None and exc_tb is None: |
| 273 | if self.expected_warning is not None: |
| 274 | if not any(issubclass(r.category, self.expected_warning) for r in self): |
| 275 | __tracebackhide__ = True |
| 276 | fail( |
| 277 | "DID NOT WARN. No warnings of type {} were emitted. " |
| 278 | "The list of emitted warnings is: {}.".format( |
| 279 | self.expected_warning, [each.message for each in self] |
| 280 | ) |
| 281 | ) |
| 282 | elif self.match_expr is not None: |
| 283 | for r in self: |
| 284 | if issubclass(r.category, self.expected_warning): |
| 285 | if re.compile(self.match_expr).search(str(r.message)): |
| 286 | break |
| 287 | else: |
| 288 | fail( |
| 289 | "DID NOT WARN. No warnings of type {} matching" |
| 290 | " ('{}') were emitted. The list of emitted warnings" |
| 291 | " is: {}.".format( |
| 292 | self.expected_warning, |
| 293 | self.match_expr, |
| 294 | [each.message for each in self], |
| 295 | ) |
| 296 | ) |