1# Copyright (C) 2016 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15'''Redirect the Python warnings into the log.'''
16
17from __future__ import absolute_import
18
19import warnings
20
21from . import util_log
22
23_OLD_WARNINGS_HANDLER = None
24
25
26def redirect_warnings():
27    '''Redirect all warnings issued by warnings::warn to the log.
28
29    By default all python warnings are printed into sys.stderr. This method
30    will force to redirect them into the test suite logger.
31    '''
32
33    # pylint: disable=global-statement
34    global _OLD_WARNINGS_HANDLER
35
36    # Already redirecting?
37    if _OLD_WARNINGS_HANDLER:
38        return None
39
40    _OLD_WARNINGS_HANDLER = warnings.showwarning
41
42    log = util_log.get_logger()
43
44    def _redirect_warnings_to_log(*args):
45        '''Redirect the warnings to the Logger.'''
46        log.warn(warnings.formatwarning(*args).rstrip())
47
48    warnings.showwarning = _redirect_warnings_to_log
49
50
51def restore_warnings():
52    '''Restore the reporting of warnings::warn as before.'''
53
54    # pylint: disable=global-statement
55    global _OLD_WARNINGS_HANDLER
56
57    if _OLD_WARNINGS_HANDLER:
58        warnings.showwarning = _OLD_WARNINGS_HANDLER
59        _OLD_WARNINGS_HANDLER = None
60
61