MCPcopy Index your code
hub / github.com/python/cpython / _AssertWarnsContext

Class _AssertWarnsContext

Lib/unittest/case.py:290–339  ·  view source on GitHub ↗

A context manager used to implement TestCase.assertWarns* methods.

Source from the content-addressed store, hash-verified

288
289
290class _AssertWarnsContext(_AssertRaisesBaseContext):
291 """A context manager used to implement TestCase.assertWarns* methods."""
292
293 _base_type = Warning
294 _base_type_str = 'a warning type or tuple of warning types'
295
296 def __enter__(self):
297 # The __warningregistry__'s need to be in a pristine state for tests
298 # to work properly.
299 for v in list(sys.modules.values()):
300 if getattr(v, '__warningregistry__', None):
301 v.__warningregistry__ = {}
302 self.warnings_manager = warnings.catch_warnings(record=True)
303 self.warnings = self.warnings_manager.__enter__()
304 warnings.simplefilter("always", self.expected)
305 return self
306
307 def __exit__(self, exc_type, exc_value, tb):
308 self.warnings_manager.__exit__(exc_type, exc_value, tb)
309 if exc_type is not None:
310 # let unexpected exceptions pass through
311 return
312 try:
313 exc_name = self.expected.__name__
314 except AttributeError:
315 exc_name = str(self.expected)
316 first_matching = None
317 for m in self.warnings:
318 w = m.message
319 if not isinstance(w, self.expected):
320 continue
321 if first_matching is None:
322 first_matching = w
323 if (self.expected_regex is not None and
324 not self.expected_regex.search(str(w))):
325 continue
326 # store warning for later retrieval
327 self.warning = w
328 self.filename = m.filename
329 self.lineno = m.lineno
330 return
331 # Now we simply try to choose a helpful failure message
332 if first_matching is not None:
333 self._raiseFailure('"{}" does not match "{}"'.format(
334 self.expected_regex.pattern, str(first_matching)))
335 if self.obj_name:
336 self._raiseFailure("{} not triggered by {}".format(exc_name,
337 self.obj_name))
338 else:
339 self._raiseFailure("{} not triggered".format(exc_name))
340
341
342class _AssertNotWarnsContext(_AssertWarnsContext):

Callers 2

assertWarnsMethod · 0.85
assertWarnsRegexMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…