Debian Codegraph @

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

raw
1 # Copyright 2019 The 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 dynamic stub import API."""
15
16 import contextlib
17 import functools
18 import logging
19 import multiprocessing
20 import os
21 import sys
22 import unittest
23
24 from tests.unit import test_common
25
26 _DATA_DIR = os.path.join("tests", "unit", "data")
27
28
29 @contextlib.contextmanager
30 def _grpc_tools_unimportable():
31 original_sys_path = sys.path
32 sys.path = [path for path in sys.path if "grpcio_tools" not in path]
33 try:
34 import grpc_tools
35 except ImportError:
36 pass
37 else:
38 del grpc_tools
39 sys.path = original_sys_path
40 raise unittest.SkipTest("Failed to make grpc_tools unimportable.")
41 try:
42 yield
43 finally:
44 sys.path = original_sys_path
45
46
47 def _collect_errors(fn):
48
49 @functools.wraps(fn)
50 def _wrapped(error_queue):
51 try:
52 fn()
53 except Exception as e:
54 error_queue.put(e)
55 raise
56
57 return _wrapped
58
59
60 def _python3_check(fn):
61
62 @functools.wraps(fn)
63 def _wrapped():
64 if sys.version_info[0] == 3:
65 fn()
66 else:
67 _assert_unimplemented("Python 3")
68
69 return _wrapped
70
71
72 def _run_in_subprocess(test_case):
73 sys.path.insert(
74 0, os.path.join(os.path.realpath(os.path.dirname(__file__)), ".."))
75 error_queue = multiprocessing.Queue()
76 proc = multiprocessing.Process(target=test_case, args=(error_queue,))
77 proc.start()
78 proc.join()
79 sys.path.pop(0)
80 if not error_queue.empty():
81 raise error_queue.get()
82 assert proc.exitcode == 0, "Process exited with code {}".format(
83 proc.exitcode)
84
85
86 def _assert_unimplemented(msg_substr):
87 import grpc
88 try:
89 protos, services = grpc.protos_and_services(
90 "tests/unit/data/foo/bar.proto")
91 except NotImplementedError as e:
92 assert msg_substr in str(e), "{} was not in '{}'".format(
93 msg_substr, str(e))
94 else:
95 assert False, "Did not raise NotImplementedError"
96
97
98 @_collect_errors
99 @_python3_check
100 def _test_sunny_day():
101 import grpc
102 protos, services = grpc.protos_and_services(
103 os.path.join(_DATA_DIR, "foo", "bar.proto"))
104 assert protos.BarMessage is not None
105 assert services.BarStub is not None
106
107
108 @_collect_errors
109 @_python3_check
110 def _test_well_known_types():
111 import grpc
112 protos, services = grpc.protos_and_services(
113 os.path.join(_DATA_DIR, "foo", "bar_with_wkt.proto"))
114 assert protos.BarMessage is not None
115 assert services.BarStub is not None
116
117
118 @_collect_errors
119 @_python3_check
120 def _test_grpc_tools_unimportable():
121 with _grpc_tools_unimportable():
122 _assert_unimplemented("grpcio-tools")
123
124
125 # NOTE(rbellevi): multiprocessing.Process fails to pickle function objects
126 # when they do not come from the "__main__" module, so this test passes
127 # if run directly on Windows, but not if started by the test runner.
128 @unittest.skipIf(os.name == "nt", "Windows multiprocessing unsupported")
129 @unittest.skipIf(test_common.running_under_gevent(),
130 "Import paths do not work with gevent runner.")
131 class DynamicStubTest(unittest.TestCase):
132
133 def test_sunny_day(self):
134 _run_in_subprocess(_test_sunny_day)
135
136 def test_well_known_types(self):
137 _run_in_subprocess(_test_well_known_types)
138
139 def test_grpc_tools_unimportable(self):
140 _run_in_subprocess(_test_grpc_tools_unimportable)
141
142
143 if __name__ == "__main__":
144 logging.basicConfig()
145 unittest.main(verbosity=2)