~ubuntu-branches/ubuntu/oneiric/python2.6/oneiric

« back to all changes in this revision

Viewing changes to Lib/test/test_support.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2010-08-07 20:03:08 UTC
  • mfrom: (10.1.27 sid)
  • Revision ID: james.westby@ubuntu.com-20100807200308-bwsyymoc4donr9a9
Tags: 2.6.6~rc1-1ubuntu1
* Merge with Debian; remaining changes:
  - Regenerate the control file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
import shutil
12
12
import warnings
13
13
import unittest
 
14
import re
14
15
 
15
16
__all__ = ["Error", "TestFailed", "TestSkipped", "ResourceDenied", "import_module",
16
17
           "verbose", "use_resources", "max_memuse", "record_original_stdout",
18
19
           "is_resource_enabled", "requires", "find_unused_port", "bind_port",
19
20
           "fcmp", "have_unicode", "is_jython", "TESTFN", "HOST", "FUZZ",
20
21
           "findfile", "verify", "vereq", "sortdict", "check_syntax_error",
21
 
           "open_urlresource", "check_warnings", "CleanImport",
22
 
           "EnvironmentVarGuard", "captured_output",
 
22
           "open_urlresource", "check_warnings", "_check_py3k_warnings",
 
23
           "CleanImport", "EnvironmentVarGuard", "captured_output",
23
24
           "captured_stdout", "TransientResource", "transient_internet",
24
25
           "run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest",
25
26
           "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup",
406
407
       entry to the warnings.catch_warnings() context manager.
407
408
    """
408
409
    def __init__(self, warnings_list):
409
 
        self.warnings = warnings_list
 
410
        self._warnings = warnings_list
 
411
        self._last = 0
410
412
 
411
413
    def __getattr__(self, attr):
412
 
        if self.warnings:
413
 
            return getattr(self.warnings[-1], attr)
 
414
        if len(self._warnings) > self._last:
 
415
            return getattr(self._warnings[-1], attr)
414
416
        elif attr in warnings.WarningMessage._WARNING_DETAILS:
415
417
            return None
416
418
        raise AttributeError("%r has no attribute %r" % (self, attr))
417
419
 
 
420
    @property
 
421
    def warnings(self):
 
422
        return self._warnings[self._last:]
 
423
 
418
424
    def reset(self):
419
 
        del self.warnings[:]
420
 
 
421
 
@contextlib.contextmanager
422
 
def check_warnings():
 
425
        self._last = len(self._warnings)
 
426
 
 
427
 
 
428
def _filterwarnings(filters, quiet=False):
 
429
    """Catch the warnings, then check if all the expected
 
430
    warnings have been raised and re-raise unexpected warnings.
 
431
    If 'quiet' is True, only re-raise the unexpected warnings.
 
432
    """
 
433
    # Clear the warning registry of the calling module
 
434
    # in order to re-raise the warnings.
 
435
    frame = sys._getframe(2)
 
436
    registry = frame.f_globals.get('__warningregistry__')
 
437
    if registry:
 
438
        registry.clear()
423
439
    with warnings.catch_warnings(record=True) as w:
 
440
        # Set filter "always" to record all warnings.  Because
 
441
        # test_warnings swap the module, we need to look up in
 
442
        # the sys.modules dictionary.
 
443
        sys.modules['warnings'].simplefilter("always")
424
444
        yield WarningsRecorder(w)
 
445
    # Filter the recorded warnings
 
446
    reraise = [warning.message for warning in w]
 
447
    missing = []
 
448
    for msg, cat in filters:
 
449
        seen = False
 
450
        for exc in reraise[:]:
 
451
            message = str(exc)
 
452
            # Filter out the matching messages
 
453
            if (re.match(msg, message, re.I) and
 
454
                issubclass(exc.__class__, cat)):
 
455
                seen = True
 
456
                reraise.remove(exc)
 
457
        if not seen and not quiet:
 
458
            # This filter caught nothing
 
459
            missing.append((msg, cat.__name__))
 
460
    if reraise:
 
461
        raise AssertionError("unhandled warning %r" % reraise[0])
 
462
    if missing:
 
463
        raise AssertionError("filter (%r, %s) did not catch any warning" %
 
464
                             missing[0])
 
465
 
 
466
 
 
467
@contextlib.contextmanager
 
468
def check_warnings(*filters, **kwargs):
 
469
    """Context manager to silence warnings.
 
470
 
 
471
    Accept 2-tuples as positional arguments:
 
472
        ("message regexp", WarningCategory)
 
473
 
 
474
    Optional argument:
 
475
     - if 'quiet' is True, it does not fail if a filter catches nothing
 
476
        (default True without argument,
 
477
         default False if some filters are defined)
 
478
 
 
479
    Without argument, it defaults to:
 
480
        check_warnings(("", Warning), quiet=True)
 
481
    """
 
482
    quiet = kwargs.get('quiet')
 
483
    if not filters:
 
484
        filters = (("", Warning),)
 
485
        # Preserve backward compatibility
 
486
        if quiet is None:
 
487
            quiet = True
 
488
    return _filterwarnings(filters, quiet)
 
489
 
 
490
 
 
491
@contextlib.contextmanager
 
492
def _check_py3k_warnings(*filters, **kwargs):
 
493
    """Context manager to silence py3k warnings.
 
494
 
 
495
    Accept 2-tuples as positional arguments:
 
496
        ("message regexp", WarningCategory)
 
497
 
 
498
    Optional argument:
 
499
     - if 'quiet' is True, it does not fail if a filter catches nothing
 
500
        (default False)
 
501
 
 
502
    Without argument, it defaults to:
 
503
        _check_py3k_warnings(("", DeprecationWarning), quiet=False)
 
504
    """
 
505
    if sys.py3kwarning:
 
506
        if not filters:
 
507
            filters = (("", DeprecationWarning),)
 
508
    else:
 
509
        # It should not raise any py3k warning
 
510
        filters = ()
 
511
    return _filterwarnings(filters, kwargs.get('quiet'))
425
512
 
426
513
 
427
514
class CleanImport(object):
595
682
MAX_Py_ssize_t = sys.maxsize
596
683
 
597
684
def set_memlimit(limit):
598
 
    import re
599
685
    global max_memuse
600
686
    global real_max_memuse
601
687
    sizes = {