1# Copyright 2018 gRPC authors. 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"""Test of gRPC Python's interaction with the python logging module""" 15 16import logging 17import subprocess 18import sys 19import unittest 20 21import grpc 22 23INTERPRETER = sys.executable 24 25 26class LoggingTest(unittest.TestCase): 27 def test_logger_not_occupied(self): 28 script = """if True: 29 import logging 30 31 import grpc 32 33 if len(logging.getLogger().handlers) != 0: 34 raise Exception('expected 0 logging handlers') 35 36 """ 37 self._verifyScriptSucceeds(script) 38 39 def test_handler_found(self): 40 script = """if True: 41 import logging 42 43 import grpc 44 """ 45 out, err = self._verifyScriptSucceeds(script) 46 self.assertEqual(0, len(err), "unexpected output to stderr") 47 48 def test_can_configure_logger(self): 49 script = """if True: 50 import logging 51 52 import grpc 53 import io 54 55 intended_stream = io.StringIO() 56 logging.basicConfig(stream=intended_stream) 57 58 if len(logging.getLogger().handlers) != 1: 59 raise Exception('expected 1 logging handler') 60 61 if logging.getLogger().handlers[0].stream is not intended_stream: 62 raise Exception('wrong handler stream') 63 64 """ 65 self._verifyScriptSucceeds(script) 66 67 def test_grpc_logger(self): 68 script = """if True: 69 import logging 70 71 import grpc 72 73 if "grpc" not in logging.Logger.manager.loggerDict: 74 raise Exception('grpc logger not found') 75 76 root_logger = logging.getLogger("grpc") 77 if len(root_logger.handlers) != 1: 78 raise Exception('expected 1 root logger handler') 79 if not isinstance(root_logger.handlers[0], logging.NullHandler): 80 raise Exception('expected logging.NullHandler') 81 82 """ 83 self._verifyScriptSucceeds(script) 84 85 def _verifyScriptSucceeds(self, script): 86 process = subprocess.Popen( 87 [INTERPRETER, "-c", script], 88 stdout=subprocess.PIPE, 89 stderr=subprocess.PIPE, 90 ) 91 out, err = process.communicate() 92 self.assertEqual( 93 0, 94 process.returncode, 95 "process failed with exit code %d (stdout: %s, stderr: %s)" 96 % (process.returncode, out, err), 97 ) 98 return out, err 99 100 101if __name__ == "__main__": 102 unittest.main(verbosity=2) 103