aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/python/grpcio_tests/tests/protoc_plugin/_split_definitions_test.py
blob: f8ae05bb7a97a3f102ec889e1dbe08b5f551612b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# Copyright 2016, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import collections
from concurrent import futures
import contextlib
import distutils.spawn
import errno
import importlib
import os
import os.path
import pkgutil
import shutil
import subprocess
import sys
import tempfile
import threading
import unittest

import grpc
from grpc_tools import protoc
from tests.unit.framework.common import test_constants

_MESSAGES_IMPORT = b'import "messages.proto";'

@contextlib.contextmanager
def _system_path(path):
  old_system_path = sys.path[:]
  sys.path = sys.path[0:1] + path + sys.path[1:]
  yield
  sys.path = old_system_path


class DummySplitServicer(object):

  def __init__(self, request_class, response_class):
    self.request_class = request_class
    self.response_class = response_class

  def Call(self, request, context):
    return self.response_class()


class SeparateTestMixin(object):

  def testImportAttributes(self):
    with _system_path([self.python_out_directory]):
      pb2 = importlib.import_module(self.pb2_import)
    pb2.Request
    pb2.Response
    if self.should_find_services_in_pb2:
      pb2.TestServiceServicer
    else:
      with self.assertRaises(AttributeError):
        pb2.TestServiceServicer

    with _system_path([self.grpc_python_out_directory]):
      pb2_grpc = importlib.import_module(self.pb2_grpc_import)
    pb2_grpc.TestServiceServicer
    with self.assertRaises(AttributeError):
      pb2_grpc.Request
    with self.assertRaises(AttributeError):
      pb2_grpc.Response

  def testCall(self):
    with _system_path([self.python_out_directory]):
      pb2 = importlib.import_module(self.pb2_import)
    with _system_path([self.grpc_python_out_directory]):
      pb2_grpc = importlib.import_module(self.pb2_grpc_import)
    server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=test_constants.POOL_SIZE))
    pb2_grpc.add_TestServiceServicer_to_server(
        DummySplitServicer(
            pb2.Request, pb2.Response), server)
    port = server.add_insecure_port('[::]:0')
    server.start()
    channel = grpc.insecure_channel('localhost:{}'.format(port))
    stub = pb2_grpc.TestServiceStub(channel)
    request = pb2.Request()
    expected_response = pb2.Response()
    response = stub.Call(request)
    self.assertEqual(expected_response, response)


class CommonTestMixin(object):

  def testImportAttributes(self):
    with _system_path([self.python_out_directory]):
      pb2 = importlib.import_module(self.pb2_import)
    pb2.Request
    pb2.Response
    if self.should_find_services_in_pb2:
      pb2.TestServiceServicer
    else:
      with self.assertRaises(AttributeError):
        pb2.TestServiceServicer

    with _system_path([self.grpc_python_out_directory]):
      pb2_grpc = importlib.import_module(self.pb2_grpc_import)
    pb2_grpc.TestServiceServicer
    with self.assertRaises(AttributeError):
      pb2_grpc.Request
    with self.assertRaises(AttributeError):
      pb2_grpc.Response

  def testCall(self):
    with _system_path([self.python_out_directory]):
      pb2 = importlib.import_module(self.pb2_import)
    with _system_path([self.grpc_python_out_directory]):
      pb2_grpc = importlib.import_module(self.pb2_grpc_import)
    server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=test_constants.POOL_SIZE))
    pb2_grpc.add_TestServiceServicer_to_server(
        DummySplitServicer(
            pb2.Request, pb2.Response), server)
    port = server.add_insecure_port('[::]:0')
    server.start()
    channel = grpc.insecure_channel('localhost:{}'.format(port))
    stub = pb2_grpc.TestServiceStub(channel)
    request = pb2.Request()
    expected_response = pb2.Response()
    response = stub.Call(request)
    self.assertEqual(expected_response, response)


class SameSeparateTest(unittest.TestCase, SeparateTestMixin):

  def setUp(self):
    same_proto_contents = pkgutil.get_data(
        'tests.protoc_plugin.protos.invocation_testing', 'same.proto')
    self.directory = tempfile.mkdtemp(suffix='same_separate', dir='.')
    self.proto_directory = os.path.join(self.directory, 'proto_path')
    self.python_out_directory = os.path.join(self.directory, 'python_out')
    self.grpc_python_out_directory = os.path.join(self.directory, 'grpc_python_out')
    os.makedirs(self.proto_directory)
    os.makedirs(self.python_out_directory)
    os.makedirs(self.grpc_python_out_directory)
    same_proto_file = os.path.join(self.proto_directory, 'same_separate.proto')
    open(same_proto_file, 'wb').write(same_proto_contents)
    protoc_result = protoc.main([
        '',
        '--proto_path={}'.format(self.proto_directory),
        '--python_out={}'.format(self.python_out_directory),
        '--grpc_python_out=grpc_2_0:{}'.format(self.grpc_python_out_directory),
        same_proto_file,
    ])
    if protoc_result != 0:
      raise Exception("unexpected protoc error")
    open(os.path.join(self.grpc_python_out_directory, '__init__.py'), 'w').write('')
    open(os.path.join(self.python_out_directory, '__init__.py'), 'w').write('')
    self.pb2_import = 'same_separate_pb2'
    self.pb2_grpc_import = 'same_separate_pb2_grpc'
    self.should_find_services_in_pb2 = False

  def tearDown(self):
    shutil.rmtree(self.directory)


class SameCommonTest(unittest.TestCase, CommonTestMixin):

  def setUp(self):
    same_proto_contents = pkgutil.get_data(
        'tests.protoc_plugin.protos.invocation_testing', 'same.proto')
    self.directory = tempfile.mkdtemp(suffix='same_common', dir='.')
    self.proto_directory = os.path.join(self.directory, 'proto_path')
    self.python_out_directory = os.path.join(self.directory, 'python_out')
    self.grpc_python_out_directory = self.python_out_directory
    os.makedirs(self.proto_directory)
    os.makedirs(self.python_out_directory)
    same_proto_file = os.path.join(self.proto_directory, 'same_common.proto')
    open(same_proto_file, 'wb').write(same_proto_contents)
    protoc_result = protoc.main([
        '',
        '--proto_path={}'.format(self.proto_directory),
        '--python_out={}'.format(self.python_out_directory),
        '--grpc_python_out={}'.format(self.grpc_python_out_directory),
        same_proto_file,
    ])
    if protoc_result != 0:
      raise Exception("unexpected protoc error")
    open(os.path.join(self.python_out_directory, '__init__.py'), 'w').write('')
    self.pb2_import = 'same_common_pb2'
    self.pb2_grpc_import = 'same_common_pb2_grpc'
    self.should_find_services_in_pb2 = True

  def tearDown(self):
    shutil.rmtree(self.directory)


class SplitCommonTest(unittest.TestCase, CommonTestMixin):

  def setUp(self):
    services_proto_contents = pkgutil.get_data(
        'tests.protoc_plugin.protos.invocation_testing.split_services',
        'services.proto')
    messages_proto_contents = pkgutil.get_data(
        'tests.protoc_plugin.protos.invocation_testing.split_messages',
        'messages.proto')
    self.directory = tempfile.mkdtemp(suffix='split_common', dir='.')
    self.proto_directory = os.path.join(self.directory, 'proto_path')
    self.python_out_directory = os.path.join(self.directory, 'python_out')
    self.grpc_python_out_directory = self.python_out_directory
    os.makedirs(self.proto_directory)
    os.makedirs(self.python_out_directory)
    services_proto_file = os.path.join(self.proto_directory,
                                       'split_common_services.proto')
    messages_proto_file = os.path.join(self.proto_directory,
                                       'split_common_messages.proto')
    open(services_proto_file, 'wb').write(services_proto_contents.replace(
        _MESSAGES_IMPORT,
        b'import "split_common_messages.proto";'
    ))
    open(messages_proto_file, 'wb').write(messages_proto_contents)
    protoc_result = protoc.main([
        '',
        '--proto_path={}'.format(self.proto_directory),
        '--python_out={}'.format(self.python_out_directory),
        '--grpc_python_out={}'.format(self.grpc_python_out_directory),
        services_proto_file,
        messages_proto_file,
    ])
    if protoc_result != 0:
      raise Exception("unexpected protoc error")
    open(os.path.join(self.python_out_directory, '__init__.py'), 'w').write('')
    self.pb2_import = 'split_common_messages_pb2'
    self.pb2_grpc_import = 'split_common_services_pb2_grpc'
    self.should_find_services_in_pb2 = False

  def tearDown(self):
    shutil.rmtree(self.directory)


class SplitSeparateTest(unittest.TestCase, SeparateTestMixin):

  def setUp(self):
    services_proto_contents = pkgutil.get_data(
        'tests.protoc_plugin.protos.invocation_testing.split_services',
        'services.proto')
    messages_proto_contents = pkgutil.get_data(
        'tests.protoc_plugin.protos.invocation_testing.split_messages',
        'messages.proto')
    self.directory = tempfile.mkdtemp(suffix='split_separate', dir='.')
    self.proto_directory = os.path.join(self.directory, 'proto_path')
    self.python_out_directory = os.path.join(self.directory, 'python_out')
    self.grpc_python_out_directory = os.path.join(self.directory, 'grpc_python_out')
    os.makedirs(self.proto_directory)
    os.makedirs(self.python_out_directory)
    os.makedirs(self.grpc_python_out_directory)
    services_proto_file = os.path.join(self.proto_directory,
                                       'split_separate_services.proto')
    messages_proto_file = os.path.join(self.proto_directory,
                                       'split_separate_messages.proto')
    open(services_proto_file, 'wb').write(services_proto_contents.replace(
        _MESSAGES_IMPORT,
        b'import "split_separate_messages.proto";'
    ))
    open(messages_proto_file, 'wb').write(messages_proto_contents)
    protoc_result = protoc.main([
        '',
        '--proto_path={}'.format(self.proto_directory),
        '--python_out={}'.format(self.python_out_directory),
        '--grpc_python_out=grpc_2_0:{}'.format(self.grpc_python_out_directory),
        services_proto_file,
        messages_proto_file,
    ])
    if protoc_result != 0:
      raise Exception("unexpected protoc error")
    open(os.path.join(self.python_out_directory, '__init__.py'), 'w').write('')
    self.pb2_import = 'split_separate_messages_pb2'
    self.pb2_grpc_import = 'split_separate_services_pb2_grpc'
    self.should_find_services_in_pb2 = False

  def tearDown(self):
    shutil.rmtree(self.directory)


if __name__ == '__main__':
  unittest.main(verbosity=2)