Debian Codegraph @

src/python/grpcio_tests/tests/protoc_plugin/_split_definitions_test.py

raw
1 # Copyright 2016 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
15 import abc
16 import contextlib
17 import importlib
18 import os
19 from os import path
20 import pkgutil
21 import platform
22 import shutil
23 import sys
24 import tempfile
25 import unittest
26
27 import grpc
28 from grpc_tools import protoc
29 import pkg_resources
30
31 from tests.unit import test_common
32
33 _MESSAGES_IMPORT = b'import "messages.proto";'
34 _SPLIT_NAMESPACE = b'package grpc_protoc_plugin.invocation_testing.split;'
35 _COMMON_NAMESPACE = b'package grpc_protoc_plugin.invocation_testing;'
36
37 _RELATIVE_PROTO_PATH = 'relative_proto_path'
38 _RELATIVE_PYTHON_OUT = 'relative_python_out'
39
40 _TEST_DIR = os.path.dirname(os.path.realpath(__file__))
41
42
43 @contextlib.contextmanager
44 def _system_path(path_insertion):
45 old_system_path = sys.path[:]
46 sys.path = sys.path[0:1] + path_insertion + sys.path[1:]
47 yield
48 sys.path = old_system_path
49
50
51 # NOTE(nathaniel): https://twitter.com/exoplaneteer/status/677259364256747520
52 # Life lesson "just always default to idempotence" reinforced.
53 def _create_directory_tree(root, path_components_sequence):
54 created = set()
55 for path_components in path_components_sequence:
56 thus_far = ''
57 for path_component in path_components:
58 relative_path = path.join(thus_far, path_component)
59 if relative_path not in created:
60 os.makedirs(path.join(root, relative_path))
61 created.add(relative_path)
62 thus_far = path.join(thus_far, path_component)
63
64
65 def _massage_proto_content(proto_content, test_name_bytes,
66 messages_proto_relative_file_name_bytes):
67 package_substitution = (b'package grpc_protoc_plugin.invocation_testing.' +
68 test_name_bytes + b';')
69 common_namespace_substituted = proto_content.replace(
70 _COMMON_NAMESPACE, package_substitution)
71 split_namespace_substituted = common_namespace_substituted.replace(
72 _SPLIT_NAMESPACE, package_substitution)
73 message_import_replaced = split_namespace_substituted.replace(
74 _MESSAGES_IMPORT,
75 b'import "' + messages_proto_relative_file_name_bytes + b'";')
76 return message_import_replaced
77
78
79 def _packagify(directory):
80 for subdirectory, _, _ in os.walk(directory):
81 init_file_name = path.join(subdirectory, '__init__.py')
82 with open(init_file_name, 'wb') as init_file:
83 init_file.write(b'')
84
85
86 class _Servicer(object):
87
88 def __init__(self, response_class):
89 self._response_class = response_class
90
91 def Call(self, request, context):
92 return self._response_class()
93
94
95 def _protoc(proto_path, python_out, grpc_python_out_flag, grpc_python_out,
96 absolute_proto_file_names):
97 args = [
98 '',
99 '--proto_path={}'.format(proto_path),
100 ]
101 if python_out is not None:
102 args.append('--python_out={}'.format(python_out))
103 if grpc_python_out is not None:
104 args.append('--grpc_python_out={}:{}'.format(grpc_python_out_flag,
105 grpc_python_out))
106 args.extend(absolute_proto_file_names)
107 return protoc.main(args)
108
109
110 class _Mid2016ProtocStyle(object):
111
112 def name(self):
113 return 'Mid2016ProtocStyle'
114
115 def grpc_in_pb2_expected(self):
116 return True
117
118 def protoc(self, proto_path, python_out, absolute_proto_file_names):
119 return (_protoc(proto_path, python_out, 'grpc_1_0', python_out,
120 absolute_proto_file_names),)
121
122
123 class _SingleProtocExecutionProtocStyle(object):
124
125 def name(self):
126 return 'SingleProtocExecutionProtocStyle'
127
128 def grpc_in_pb2_expected(self):
129 return False
130
131 def protoc(self, proto_path, python_out, absolute_proto_file_names):
132 return (_protoc(proto_path, python_out, 'grpc_2_0', python_out,
133 absolute_proto_file_names),)
134
135
136 class _ProtoBeforeGrpcProtocStyle(object):
137
138 def name(self):
139 return 'ProtoBeforeGrpcProtocStyle'
140
141 def grpc_in_pb2_expected(self):
142 return False
143
144 def protoc(self, proto_path, python_out, absolute_proto_file_names):
145 pb2_protoc_exit_code = _protoc(proto_path, python_out, None, None,
146 absolute_proto_file_names)
147 pb2_grpc_protoc_exit_code = _protoc(proto_path, None, 'grpc_2_0',
148 python_out,
149 absolute_proto_file_names)
150 return pb2_protoc_exit_code, pb2_grpc_protoc_exit_code
151
152
153 class _GrpcBeforeProtoProtocStyle(object):
154
155 def name(self):
156 return 'GrpcBeforeProtoProtocStyle'
157
158 def grpc_in_pb2_expected(self):
159 return False
160
161 def protoc(self, proto_path, python_out, absolute_proto_file_names):
162 pb2_grpc_protoc_exit_code = _protoc(proto_path, None, 'grpc_2_0',
163 python_out,
164 absolute_proto_file_names)
165 pb2_protoc_exit_code = _protoc(proto_path, python_out, None, None,
166 absolute_proto_file_names)
167 return pb2_grpc_protoc_exit_code, pb2_protoc_exit_code
168
169
170 _PROTOC_STYLES = (
171 _Mid2016ProtocStyle(),
172 _SingleProtocExecutionProtocStyle(),
173 _ProtoBeforeGrpcProtocStyle(),
174 _GrpcBeforeProtoProtocStyle(),
175 )
176
177
178 @unittest.skipIf(platform.python_implementation() == 'PyPy',
179 'Skip test if run with PyPy!')
180 class _Test(unittest.TestCase, metaclass=abc.ABCMeta):
181
182 def setUp(self):
183 self._directory = tempfile.mkdtemp(suffix=self.NAME, dir='.')
184 self._proto_path = path.join(self._directory, _RELATIVE_PROTO_PATH)
185 self._python_out = path.join(self._directory, _RELATIVE_PYTHON_OUT)
186
187 os.makedirs(self._proto_path)
188 os.makedirs(self._python_out)
189
190 proto_directories_and_names = {
191 (
192 self.MESSAGES_PROTO_RELATIVE_DIRECTORY_NAMES,
193 self.MESSAGES_PROTO_FILE_NAME,
194 ),
195 (
196 self.SERVICES_PROTO_RELATIVE_DIRECTORY_NAMES,
197 self.SERVICES_PROTO_FILE_NAME,
198 ),
199 }
200 messages_proto_relative_file_name_forward_slashes = '/'.join(
201 self.MESSAGES_PROTO_RELATIVE_DIRECTORY_NAMES +
202 (self.MESSAGES_PROTO_FILE_NAME,))
203 _create_directory_tree(
204 self._proto_path,
205 (relative_proto_directory_names for relative_proto_directory_names,
206 _ in proto_directories_and_names))
207 self._absolute_proto_file_names = set()
208 for relative_directory_names, file_name in proto_directories_and_names:
209 absolute_proto_file_name = path.join(
210 self._proto_path, *relative_directory_names + (file_name,))
211 raw_proto_content = pkgutil.get_data(
212 'tests.protoc_plugin.protos.invocation_testing',
213 path.join(*relative_directory_names + (file_name,)))
214 massaged_proto_content = _massage_proto_content(
215 raw_proto_content, self.NAME.encode(),
216 messages_proto_relative_file_name_forward_slashes.encode())
217 with open(absolute_proto_file_name, 'wb') as proto_file:
218 proto_file.write(massaged_proto_content)
219 self._absolute_proto_file_names.add(absolute_proto_file_name)
220
221 def tearDown(self):
222 shutil.rmtree(self._directory)
223
224 def _protoc(self):
225 protoc_exit_codes = self.PROTOC_STYLE.protoc(
226 self._proto_path, self._python_out, self._absolute_proto_file_names)
227 for protoc_exit_code in protoc_exit_codes:
228 self.assertEqual(0, protoc_exit_code)
229
230 _packagify(self._python_out)
231
232 generated_modules = {}
233 expected_generated_full_module_names = {
234 self.EXPECTED_MESSAGES_PB2,
235 self.EXPECTED_SERVICES_PB2,
236 self.EXPECTED_SERVICES_PB2_GRPC,
237 }
238 with _system_path([self._python_out]):
239 for full_module_name in expected_generated_full_module_names:
240 module = importlib.import_module(full_module_name)
241 generated_modules[full_module_name] = module
242
243 self._messages_pb2 = generated_modules[self.EXPECTED_MESSAGES_PB2]
244 self._services_pb2 = generated_modules[self.EXPECTED_SERVICES_PB2]
245 self._services_pb2_grpc = generated_modules[
246 self.EXPECTED_SERVICES_PB2_GRPC]
247
248 def _services_modules(self):
249 if self.PROTOC_STYLE.grpc_in_pb2_expected():
250 return self._services_pb2, self._services_pb2_grpc
251 else:
252 return (self._services_pb2_grpc,)
253
254 def test_imported_attributes(self):
255 self._protoc()
256
257 self._messages_pb2.Request
258 self._messages_pb2.Response
259 self._services_pb2.DESCRIPTOR.services_by_name['TestService']
260 for services_module in self._services_modules():
261 services_module.TestServiceStub
262 services_module.TestServiceServicer
263 services_module.add_TestServiceServicer_to_server
264
265 def test_call(self):
266 self._protoc()
267
268 for services_module in self._services_modules():
269 server = test_common.test_server()
270 services_module.add_TestServiceServicer_to_server(
271 _Servicer(self._messages_pb2.Response), server)
272 port = server.add_insecure_port('[::]:0')
273 server.start()
274 channel = grpc.insecure_channel('localhost:{}'.format(port))
275 stub = services_module.TestServiceStub(channel)
276 response = stub.Call(self._messages_pb2.Request())
277 self.assertEqual(self._messages_pb2.Response(), response)
278 server.stop(None)
279
280
281 def _create_test_case_class(split_proto, protoc_style):
282 attributes = {}
283
284 name = '{}{}'.format('SplitProto' if split_proto else 'SameProto',
285 protoc_style.name())
286 attributes['NAME'] = name
287
288 if split_proto:
289 attributes['MESSAGES_PROTO_RELATIVE_DIRECTORY_NAMES'] = (
290 'split_messages',
291 'sub',
292 )
293 attributes['MESSAGES_PROTO_FILE_NAME'] = 'messages.proto'
294 attributes['SERVICES_PROTO_RELATIVE_DIRECTORY_NAMES'] = (
295 'split_services',)
296 attributes['SERVICES_PROTO_FILE_NAME'] = 'services.proto'
297 attributes['EXPECTED_MESSAGES_PB2'] = 'split_messages.sub.messages_pb2'
298 attributes['EXPECTED_SERVICES_PB2'] = 'split_services.services_pb2'
299 attributes['EXPECTED_SERVICES_PB2_GRPC'] = (
300 'split_services.services_pb2_grpc')
301 else:
302 attributes['MESSAGES_PROTO_RELATIVE_DIRECTORY_NAMES'] = ()
303 attributes['MESSAGES_PROTO_FILE_NAME'] = 'same.proto'
304 attributes['SERVICES_PROTO_RELATIVE_DIRECTORY_NAMES'] = ()
305 attributes['SERVICES_PROTO_FILE_NAME'] = 'same.proto'
306 attributes['EXPECTED_MESSAGES_PB2'] = 'same_pb2'
307 attributes['EXPECTED_SERVICES_PB2'] = 'same_pb2'
308 attributes['EXPECTED_SERVICES_PB2_GRPC'] = 'same_pb2_grpc'
309
310 attributes['PROTOC_STYLE'] = protoc_style
311
312 attributes['__module__'] = _Test.__module__
313
314 return type('{}Test'.format(name), (_Test,), attributes)
315
316
317 def _create_test_case_classes():
318 for split_proto in (
319 False,
320 True,
321 ):
322 for protoc_style in _PROTOC_STYLES:
323 yield _create_test_case_class(split_proto, protoc_style)
324
325
326 class WellKnownTypesTest(unittest.TestCase):
327
328 def testWellKnownTypes(self):
329 os.chdir(_TEST_DIR)
330 out_dir = tempfile.mkdtemp(suffix="wkt_test", dir='.')
331 well_known_protos_include = pkg_resources.resource_filename(
332 'grpc_tools', '_proto')
333 args = [
334 'grpc_tools.protoc',
335 '--proto_path=protos',
336 '--proto_path={}'.format(well_known_protos_include),
337 '--python_out={}'.format(out_dir),
338 '--grpc_python_out={}'.format(out_dir),
339 'protos/invocation_testing/compiler.proto',
340 ]
341 rc = protoc.main(args)
342 self.assertEqual(0, rc)
343
344
345 def load_tests(loader, tests, pattern):
346 tests = (tuple(
347 loader.loadTestsFromTestCase(test_case_class)
348 for test_case_class in _create_test_case_classes()) +
349 tuple(loader.loadTestsFromTestCase(WellKnownTypesTest)))
350 return unittest.TestSuite(tests=tests)
351
352
353 if __name__ == '__main__':
354 unittest.main(verbosity=2)