util_warnings.py revision dcecc0c8d22e894525e25a122ce25129b51338f2
1'''Redirect the Python warnings into the log.'''
2
3import warnings
4
5from . import util_log
6
7_OLD_WARNINGS_HANDLER = None
8
9
10def redirect_warnings():
11    '''Redirect all warnings issued by warnings::warn to the log.
12
13    By default all python warnings are printed into sys.stderr. This method
14    will force to redirect them into the test suite logger.
15    '''
16
17    # pylint: disable=global-statement
18    global _OLD_WARNINGS_HANDLER
19
20    # Already redirecting?
21    if _OLD_WARNINGS_HANDLER:
22        return None
23
24    _OLD_WARNINGS_HANDLER = warnings.showwarning
25
26    log = util_log.get_logger()
27
28    def _redirect_warnings_to_log(*args):
29        '''Redirect the warnings to the Logger.'''
30        log.warn(warnings.formatwarning(*args).rstrip())
31
32    warnings.showwarning = _redirect_warnings_to_log
33
34
35def restore_warnings():
36    '''Restore the reporting of warnings::warn as before.'''
37
38    # pylint: disable=global-statement
39    global _OLD_WARNINGS_HANDLER
40
41    if _OLD_WARNINGS_HANDLER:
42        warnings.showwarning = _OLD_WARNINGS_HANDLER
43        _OLD_WARNINGS_HANDLER = None
44
45