|
| 1 | +# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- |
| 2 | +# vi: set ft=python sts=4 ts=4 sw=4 et: |
| 3 | +### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## |
| 4 | +# |
| 5 | +# See COPYING file distributed along with the NiBabel package for the |
| 6 | +# copyright and license terms. |
| 7 | +# |
| 8 | +### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## |
| 9 | +''' Contexts for *with* statement allowing checks for warnings |
| 10 | +
|
| 11 | +When we give up 2.5 compatibility we can use python's own |
| 12 | +``tests.test_support.check_warnings`` |
| 13 | +
|
| 14 | +''' |
| 15 | +from __future__ import with_statement |
| 16 | + |
| 17 | +import warnings |
| 18 | + |
| 19 | + |
| 20 | +class ErrorWarnings(object): |
| 21 | + """ Context manager to check for warnings as errors. Usually used with |
| 22 | + ``assert_raises`` in the with block |
| 23 | +
|
| 24 | + Examples |
| 25 | + -------- |
| 26 | + >>> with ErrorWarnings(): |
| 27 | + ... try: |
| 28 | + ... warnings.warn('Message', UserWarning) |
| 29 | + ... except UserWarning: |
| 30 | + ... print 'I consider myself warned' |
| 31 | + I consider myself warned |
| 32 | +
|
| 33 | + Notes |
| 34 | + ----- |
| 35 | + The manager will raise a RuntimeError if another warning filter gets put on |
| 36 | + top of the one it has just added. |
| 37 | + """ |
| 38 | + def __init__(self): |
| 39 | + self.added = None |
| 40 | + |
| 41 | + def __enter__(self): |
| 42 | + warnings.simplefilter('error') |
| 43 | + self.added = warnings.filters[0] |
| 44 | + |
| 45 | + def __exit__(self, exc, value, tb): |
| 46 | + if warnings.filters[0] != self.added: |
| 47 | + raise RuntimeError('Somone has done something to the filters') |
| 48 | + warnings.filters.pop(0) |
| 49 | + return False # allow any exceptions to propagate |
| 50 | + |
| 51 | + |
| 52 | +class IgnoreWarnings(ErrorWarnings): |
| 53 | + """ Context manager to ignore warnings |
| 54 | +
|
| 55 | + Examples |
| 56 | + -------- |
| 57 | + >>> with IgnoreWarnings(): |
| 58 | + ... warnings.warn('Message', UserWarning) |
| 59 | +
|
| 60 | + (and you get no warning) |
| 61 | +
|
| 62 | + Notes |
| 63 | + ----- |
| 64 | + The manager will raise a RuntimeError if another warning filter gets put on |
| 65 | + top of the one it has just added. |
| 66 | + """ |
| 67 | + |
| 68 | + def __enter__(self): |
| 69 | + warnings.simplefilter('ignore') |
| 70 | + self.added = warnings.filters[0] |
0 commit comments