Debian Codegraph @

src/python/grpcio_tests/tests/unit/_logging_test.py

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