aboutsummaryrefslogtreecommitdiff
path: root/src/python/grpcio_tests/tests/protoc_plugin/_python_plugin_test.py
blob: c6e41b3ae8c85ca3afe2a17e20fd772bbef3cbd5 (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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import collections
import contextlib
import errno
import itertools
import os
import shutil
import subprocess
import sys
import tempfile
import threading
import unittest

import grpc
import grpc.experimental

import tests.protoc_plugin.protos.payload.test_payload_pb2 as payload_pb2
import tests.protoc_plugin.protos.requests.r.test_requests_pb2 as request_pb2
import tests.protoc_plugin.protos.responses.test_responses_pb2 as response_pb2
import tests.protoc_plugin.protos.service.test_service_pb2_grpc as service_pb2_grpc
from tests.unit import test_common
from tests.unit.framework.common import test_constants

# Identifiers of entities we expect to find in the generated module.
STUB_IDENTIFIER = "TestServiceStub"
SERVICER_IDENTIFIER = "TestServiceServicer"
ADD_SERVICER_TO_SERVER_IDENTIFIER = "add_TestServiceServicer_to_server"


class _ServicerMethods(object):
    def __init__(self):
        self._condition = threading.Condition()
        self._paused = False
        self._fail = False

    @contextlib.contextmanager
    def pause(self):  # pylint: disable=invalid-name
        with self._condition:
            self._paused = True
        yield
        with self._condition:
            self._paused = False
            self._condition.notify_all()

    @contextlib.contextmanager
    def fail(self):  # pylint: disable=invalid-name
        with self._condition:
            self._fail = True
        yield
        with self._condition:
            self._fail = False

    def _control(self):  # pylint: disable=invalid-name
        with self._condition:
            if self._fail:
                raise ValueError()
            while self._paused:
                self._condition.wait()

    def UnaryCall(self, request, unused_rpc_context):
        response = response_pb2.SimpleResponse()
        response.payload.payload_type = payload_pb2.COMPRESSABLE
        response.payload.payload_compressable = "a" * request.response_size
        self._control()
        return response

    def StreamingOutputCall(self, request, unused_rpc_context):
        for parameter in request.response_parameters:
            response = response_pb2.StreamingOutputCallResponse()
            response.payload.payload_type = payload_pb2.COMPRESSABLE
            response.payload.payload_compressable = "a" * parameter.size
            self._control()
            yield response

    def StreamingInputCall(self, request_iter, unused_rpc_context):
        response = response_pb2.StreamingInputCallResponse()
        aggregated_payload_size = 0
        for request in request_iter:
            aggregated_payload_size += len(request.payload.payload_compressable)
        response.aggregated_payload_size = aggregated_payload_size
        self._control()
        return response

    def FullDuplexCall(self, request_iter, unused_rpc_context):
        for request in request_iter:
            for parameter in request.response_parameters:
                response = response_pb2.StreamingOutputCallResponse()
                response.payload.payload_type = payload_pb2.COMPRESSABLE
                response.payload.payload_compressable = "a" * parameter.size
                self._control()
                yield response

    def HalfDuplexCall(self, request_iter, unused_rpc_context):
        responses = []
        for request in request_iter:
            for parameter in request.response_parameters:
                response = response_pb2.StreamingOutputCallResponse()
                response.payload.payload_type = payload_pb2.COMPRESSABLE
                response.payload.payload_compressable = "a" * parameter.size
                self._control()
                responses.append(response)
        for response in responses:
            yield response


class _Service(
    collections.namedtuple(
        "_Service",
        (
            "servicer_methods",
            "server",
            "stub",
        ),
    )
):
    """A live and running service.

    Attributes:
      servicer_methods: The _ServicerMethods servicing RPCs.
      server: The grpc.Server servicing RPCs.
      stub: A stub on which to invoke RPCs.
    """


def _CreateService():
    """Provides a servicer backend and a stub.

    Returns:
      A _Service with which to test RPCs.
    """
    servicer_methods = _ServicerMethods()

    class Servicer(getattr(service_pb2_grpc, SERVICER_IDENTIFIER)):
        def UnaryCall(self, request, context):
            return servicer_methods.UnaryCall(request, context)

        def StreamingOutputCall(self, request, context):
            return servicer_methods.StreamingOutputCall(request, context)

        def StreamingInputCall(self, request_iterator, context):
            return servicer_methods.StreamingInputCall(
                request_iterator, context
            )

        def FullDuplexCall(self, request_iterator, context):
            return servicer_methods.FullDuplexCall(request_iterator, context)

        def HalfDuplexCall(self, request_iterator, context):
            return servicer_methods.HalfDuplexCall(request_iterator, context)

    server = test_common.test_server()
    getattr(service_pb2_grpc, ADD_SERVICER_TO_SERVER_IDENTIFIER)(
        Servicer(), server
    )
    port = server.add_insecure_port("[::]:0")
    server.start()
    channel = grpc.insecure_channel("localhost:{}".format(port))
    stub = getattr(service_pb2_grpc, STUB_IDENTIFIER)(channel)
    return _Service(servicer_methods, server, stub)


def _CreateIncompleteService():
    """Provides a servicer backend that fails to implement methods and its stub.

    Returns:
      A _Service with which to test RPCs. The returned _Service's
        servicer_methods implements none of the methods required of it.
    """

    class Servicer(getattr(service_pb2_grpc, SERVICER_IDENTIFIER)):
        pass

    server = test_common.test_server()
    getattr(service_pb2_grpc, ADD_SERVICER_TO_SERVER_IDENTIFIER)(
        Servicer(), server
    )
    port = server.add_insecure_port("[::]:0")
    server.start()
    channel = grpc.insecure_channel("localhost:{}".format(port))
    stub = getattr(service_pb2_grpc, STUB_IDENTIFIER)(channel)
    return _Service(None, server, stub)


def _streaming_input_request_iterator():
    for _ in range(3):
        request = request_pb2.StreamingInputCallRequest()
        request.payload.payload_type = payload_pb2.COMPRESSABLE
        request.payload.payload_compressable = "a"
        yield request


def _streaming_output_request():
    request = request_pb2.StreamingOutputCallRequest()
    sizes = [1, 2, 3]
    request.response_parameters.add(size=sizes[0], interval_us=0)
    request.response_parameters.add(size=sizes[1], interval_us=0)
    request.response_parameters.add(size=sizes[2], interval_us=0)
    return request


def _full_duplex_request_iterator():
    request = request_pb2.StreamingOutputCallRequest()
    request.response_parameters.add(size=1, interval_us=0)
    yield request
    request = request_pb2.StreamingOutputCallRequest()
    request.response_parameters.add(size=2, interval_us=0)
    request.response_parameters.add(size=3, interval_us=0)
    yield request


class PythonPluginTest(unittest.TestCase):
    """Test case for the gRPC Python protoc-plugin.

    While reading these tests, remember that the futures API
    (`stub.method.future()`) only gives futures for the *response-unary*
    methods and does not exist for response-streaming methods.
    """

    def testImportAttributes(self):
        # check that we can access the generated module and its members.
        self.assertIsNotNone(getattr(service_pb2_grpc, STUB_IDENTIFIER, None))
        self.assertIsNotNone(
            getattr(service_pb2_grpc, SERVICER_IDENTIFIER, None)
        )
        self.assertIsNotNone(
            getattr(service_pb2_grpc, ADD_SERVICER_TO_SERVER_IDENTIFIER, None)
        )

    def testUpDown(self):
        service = _CreateService()
        self.assertIsNotNone(service.servicer_methods)
        self.assertIsNotNone(service.server)
        self.assertIsNotNone(service.stub)
        service.server.stop(None)

    def testIncompleteServicer(self):
        service = _CreateIncompleteService()
        request = request_pb2.SimpleRequest(response_size=13)
        with self.assertRaises(grpc.RpcError) as exception_context:
            service.stub.UnaryCall(request)
        self.assertIs(
            exception_context.exception.code(), grpc.StatusCode.UNIMPLEMENTED
        )
        service.server.stop(None)

    def testUnaryCall(self):
        service = _CreateService()
        request = request_pb2.SimpleRequest(response_size=13)
        response = service.stub.UnaryCall(request)
        expected_response = service.servicer_methods.UnaryCall(
            request, "not a real context!"
        )
        self.assertEqual(expected_response, response)
        service.server.stop(None)

    def testUnaryCallFuture(self):
        service = _CreateService()
        request = request_pb2.SimpleRequest(response_size=13)
        # Check that the call does not block waiting for the server to respond.
        with service.servicer_methods.pause():
            response_future = service.stub.UnaryCall.future(request)
        response = response_future.result()
        expected_response = service.servicer_methods.UnaryCall(
            request, "not a real RpcContext!"
        )
        self.assertEqual(expected_response, response)
        service.server.stop(None)

    def testUnaryCallFutureExpired(self):
        service = _CreateService()
        request = request_pb2.SimpleRequest(response_size=13)
        with service.servicer_methods.pause():
            response_future = service.stub.UnaryCall.future(
                request, timeout=test_constants.SHORT_TIMEOUT
            )
            with self.assertRaises(grpc.RpcError) as exception_context:
                response_future.result()
        self.assertIs(
            exception_context.exception.code(),
            grpc.StatusCode.DEADLINE_EXCEEDED,
        )
        self.assertIs(response_future.code(), grpc.StatusCode.DEADLINE_EXCEEDED)
        service.server.stop(None)

    def testUnaryCallFutureCancelled(self):
        service = _CreateService()
        request = request_pb2.SimpleRequest(response_size=13)
        with service.servicer_methods.pause():
            response_future = service.stub.UnaryCall.future(request)
            response_future.cancel()
        self.assertTrue(response_future.cancelled())
        self.assertIs(response_future.code(), grpc.StatusCode.CANCELLED)
        service.server.stop(None)

    def testUnaryCallFutureFailed(self):
        service = _CreateService()
        request = request_pb2.SimpleRequest(response_size=13)
        with service.servicer_methods.fail():
            response_future = service.stub.UnaryCall.future(request)
            self.assertIsNotNone(response_future.exception())
        self.assertIs(response_future.code(), grpc.StatusCode.UNKNOWN)
        service.server.stop(None)

    def testStreamingOutputCall(self):
        service = _CreateService()
        request = _streaming_output_request()
        responses = service.stub.StreamingOutputCall(request)
        expected_responses = service.servicer_methods.StreamingOutputCall(
            request, "not a real RpcContext!"
        )
        for expected_response, response in itertools.zip_longest(
            expected_responses, responses
        ):
            self.assertEqual(expected_response, response)
        service.server.stop(None)

    def testStreamingOutputCallExpired(self):
        service = _CreateService()
        request = _streaming_output_request()
        with service.servicer_methods.pause():
            responses = service.stub.StreamingOutputCall(
                request, timeout=test_constants.SHORT_TIMEOUT
            )
            with self.assertRaises(grpc.RpcError) as exception_context:
                list(responses)
        self.assertIs(
            exception_context.exception.code(),
            grpc.StatusCode.DEADLINE_EXCEEDED,
        )
        service.server.stop(None)

    def testStreamingOutputCallCancelled(self):
        service = _CreateService()
        request = _streaming_output_request()
        responses = service.stub.StreamingOutputCall(request)
        next(responses)
        responses.cancel()
        with self.assertRaises(grpc.RpcError) as exception_context:
            next(responses)
        self.assertIs(responses.code(), grpc.StatusCode.CANCELLED)
        service.server.stop(None)

    def testStreamingOutputCallFailed(self):
        service = _CreateService()
        request = _streaming_output_request()
        with service.servicer_methods.fail():
            responses = service.stub.StreamingOutputCall(request)
            self.assertIsNotNone(responses)
            with self.assertRaises(grpc.RpcError) as exception_context:
                next(responses)
        self.assertIs(
            exception_context.exception.code(), grpc.StatusCode.UNKNOWN
        )
        service.server.stop(None)

    def testStreamingInputCall(self):
        service = _CreateService()
        response = service.stub.StreamingInputCall(
            _streaming_input_request_iterator()
        )
        expected_response = service.servicer_methods.StreamingInputCall(
            _streaming_input_request_iterator(), "not a real RpcContext!"
        )
        self.assertEqual(expected_response, response)
        service.server.stop(None)

    def testStreamingInputCallFuture(self):
        service = _CreateService()
        with service.servicer_methods.pause():
            response_future = service.stub.StreamingInputCall.future(
                _streaming_input_request_iterator()
            )
        response = response_future.result()
        expected_response = service.servicer_methods.StreamingInputCall(
            _streaming_input_request_iterator(), "not a real RpcContext!"
        )
        self.assertEqual(expected_response, response)
        service.server.stop(None)

    def testStreamingInputCallFutureExpired(self):
        service = _CreateService()
        with service.servicer_methods.pause():
            response_future = service.stub.StreamingInputCall.future(
                _streaming_input_request_iterator(),
                timeout=test_constants.SHORT_TIMEOUT,
            )
            with self.assertRaises(grpc.RpcError) as exception_context:
                response_future.result()
        self.assertIsInstance(response_future.exception(), grpc.RpcError)
        self.assertIs(
            response_future.exception().code(),
            grpc.StatusCode.DEADLINE_EXCEEDED,
        )
        self.assertIs(
            exception_context.exception.code(),
            grpc.StatusCode.DEADLINE_EXCEEDED,
        )
        service.server.stop(None)

    def testStreamingInputCallFutureCancelled(self):
        service = _CreateService()
        with service.servicer_methods.pause():
            response_future = service.stub.StreamingInputCall.future(
                _streaming_input_request_iterator()
            )
            response_future.cancel()
        self.assertTrue(response_future.cancelled())
        with self.assertRaises(grpc.FutureCancelledError):
            response_future.result()
        service.server.stop(None)

    def testStreamingInputCallFutureFailed(self):
        service = _CreateService()
        with service.servicer_methods.fail():
            response_future = service.stub.StreamingInputCall.future(
                _streaming_input_request_iterator()
            )
            self.assertIsNotNone(response_future.exception())
            self.assertIs(response_future.code(), grpc.StatusCode.UNKNOWN)
        service.server.stop(None)

    def testFullDuplexCall(self):
        service = _CreateService()
        responses = service.stub.FullDuplexCall(_full_duplex_request_iterator())
        expected_responses = service.servicer_methods.FullDuplexCall(
            _full_duplex_request_iterator(), "not a real RpcContext!"
        )
        for expected_response, response in itertools.zip_longest(
            expected_responses, responses
        ):
            self.assertEqual(expected_response, response)
        service.server.stop(None)

    def testFullDuplexCallExpired(self):
        request_iterator = _full_duplex_request_iterator()
        service = _CreateService()
        with service.servicer_methods.pause():
            responses = service.stub.FullDuplexCall(
                request_iterator, timeout=test_constants.SHORT_TIMEOUT
            )
            with self.assertRaises(grpc.RpcError) as exception_context:
                list(responses)
        self.assertIs(
            exception_context.exception.code(),
            grpc.StatusCode.DEADLINE_EXCEEDED,
        )
        service.server.stop(None)

    def testFullDuplexCallCancelled(self):
        service = _CreateService()
        request_iterator = _full_duplex_request_iterator()
        responses = service.stub.FullDuplexCall(request_iterator)
        next(responses)
        responses.cancel()
        with self.assertRaises(grpc.RpcError) as exception_context:
            next(responses)
        self.assertIs(
            exception_context.exception.code(), grpc.StatusCode.CANCELLED
        )
        service.server.stop(None)

    def testFullDuplexCallFailed(self):
        request_iterator = _full_duplex_request_iterator()
        service = _CreateService()
        with service.servicer_methods.fail():
            responses = service.stub.FullDuplexCall(request_iterator)
            with self.assertRaises(grpc.RpcError) as exception_context:
                next(responses)
        self.assertIs(
            exception_context.exception.code(), grpc.StatusCode.UNKNOWN
        )
        service.server.stop(None)

    def testHalfDuplexCall(self):
        service = _CreateService()

        def half_duplex_request_iterator():
            request = request_pb2.StreamingOutputCallRequest()
            request.response_parameters.add(size=1, interval_us=0)
            yield request
            request = request_pb2.StreamingOutputCallRequest()
            request.response_parameters.add(size=2, interval_us=0)
            request.response_parameters.add(size=3, interval_us=0)
            yield request

        responses = service.stub.HalfDuplexCall(half_duplex_request_iterator())
        expected_responses = service.servicer_methods.HalfDuplexCall(
            half_duplex_request_iterator(), "not a real RpcContext!"
        )
        for expected_response, response in itertools.zip_longest(
            expected_responses, responses
        ):
            self.assertEqual(expected_response, response)
        service.server.stop(None)

    def testHalfDuplexCallWedged(self):
        condition = threading.Condition()
        wait_cell = [False]

        @contextlib.contextmanager
        def wait():  # pylint: disable=invalid-name
            # Where's Python 3's 'nonlocal' statement when you need it?
            with condition:
                wait_cell[0] = True
            yield
            with condition:
                wait_cell[0] = False
                condition.notify_all()

        def half_duplex_request_iterator():
            request = request_pb2.StreamingOutputCallRequest()
            request.response_parameters.add(size=1, interval_us=0)
            yield request
            with condition:
                while wait_cell[0]:
                    condition.wait()

        service = _CreateService()
        with wait():
            responses = service.stub.HalfDuplexCall(
                half_duplex_request_iterator(),
                timeout=test_constants.SHORT_TIMEOUT,
            )
            # half-duplex waits for the client to send all info
            with self.assertRaises(grpc.RpcError) as exception_context:
                next(responses)
        self.assertIs(
            exception_context.exception.code(),
            grpc.StatusCode.DEADLINE_EXCEEDED,
        )
        service.server.stop(None)

    def testRegisteredMethod(self):
        """Tests that we're setting _registered_call_handle when create call using generated stub."""
        service = _CreateService()
        self.assertTrue(service.stub.UnaryCall._registered_call_handle)
        self.assertTrue(
            service.stub.StreamingOutputCall._registered_call_handle
        )
        self.assertTrue(service.stub.StreamingInputCall._registered_call_handle)
        self.assertTrue(service.stub.FullDuplexCall._registered_call_handle)
        service.server.stop(None)


@unittest.skipIf(
    sys.version_info[0] < 3 or sys.version_info[1] < 6,
    "Unsupported on Python 2.",
)
class SimpleStubsPluginTest(unittest.TestCase):
    servicer_methods = _ServicerMethods()

    class Servicer(service_pb2_grpc.TestServiceServicer):
        def UnaryCall(self, request, context):
            return SimpleStubsPluginTest.servicer_methods.UnaryCall(
                request, context
            )

        def StreamingOutputCall(self, request, context):
            return SimpleStubsPluginTest.servicer_methods.StreamingOutputCall(
                request, context
            )

        def StreamingInputCall(self, request_iterator, context):
            return SimpleStubsPluginTest.servicer_methods.StreamingInputCall(
                request_iterator, context
            )

        def FullDuplexCall(self, request_iterator, context):
            return SimpleStubsPluginTest.servicer_methods.FullDuplexCall(
                request_iterator, context
            )

        def HalfDuplexCall(self, request_iterator, context):
            return SimpleStubsPluginTest.servicer_methods.HalfDuplexCall(
                request_iterator, context
            )

    def setUp(self):
        super(SimpleStubsPluginTest, self).setUp()
        self._server = test_common.test_server()
        service_pb2_grpc.add_TestServiceServicer_to_server(
            self.Servicer(), self._server
        )
        self._port = self._server.add_insecure_port("[::]:0")
        self._server.start()
        self._target = "localhost:{}".format(self._port)

    def tearDown(self):
        self._server.stop(None)
        super(SimpleStubsPluginTest, self).tearDown()

    def testUnaryCall(self):
        request = request_pb2.SimpleRequest(response_size=13)
        response = service_pb2_grpc.TestService.UnaryCall(
            request,
            self._target,
            channel_credentials=grpc.experimental.insecure_channel_credentials(),
            wait_for_ready=True,
        )
        expected_response = self.servicer_methods.UnaryCall(
            request, "not a real context!"
        )
        self.assertEqual(expected_response, response)

    def testUnaryCallInsecureSugar(self):
        request = request_pb2.SimpleRequest(response_size=13)
        response = service_pb2_grpc.TestService.UnaryCall(
            request, self._target, insecure=True, wait_for_ready=True
        )
        expected_response = self.servicer_methods.UnaryCall(
            request, "not a real context!"
        )
        self.assertEqual(expected_response, response)

    def testStreamingOutputCall(self):
        request = _streaming_output_request()
        expected_responses = self.servicer_methods.StreamingOutputCall(
            request, "not a real RpcContext!"
        )
        responses = service_pb2_grpc.TestService.StreamingOutputCall(
            request,
            self._target,
            channel_credentials=grpc.experimental.insecure_channel_credentials(),
            wait_for_ready=True,
        )
        for expected_response, response in itertools.zip_longest(
            expected_responses, responses
        ):
            self.assertEqual(expected_response, response)

    def testStreamingInputCall(self):
        response = service_pb2_grpc.TestService.StreamingInputCall(
            _streaming_input_request_iterator(),
            self._target,
            channel_credentials=grpc.experimental.insecure_channel_credentials(),
            wait_for_ready=True,
        )
        expected_response = self.servicer_methods.StreamingInputCall(
            _streaming_input_request_iterator(), "not a real RpcContext!"
        )
        self.assertEqual(expected_response, response)

    def testFullDuplexCall(self):
        responses = service_pb2_grpc.TestService.FullDuplexCall(
            _full_duplex_request_iterator(),
            self._target,
            channel_credentials=grpc.experimental.insecure_channel_credentials(),
            wait_for_ready=True,
        )
        expected_responses = self.servicer_methods.FullDuplexCall(
            _full_duplex_request_iterator(), "not a real RpcContext!"
        )
        for expected_response, response in itertools.zip_longest(
            expected_responses, responses
        ):
            self.assertEqual(expected_response, response)

    def testHalfDuplexCall(self):
        def half_duplex_request_iterator():
            request = request_pb2.StreamingOutputCallRequest()
            request.response_parameters.add(size=1, interval_us=0)
            yield request
            request = request_pb2.StreamingOutputCallRequest()
            request.response_parameters.add(size=2, interval_us=0)
            request.response_parameters.add(size=3, interval_us=0)
            yield request

        responses = service_pb2_grpc.TestService.HalfDuplexCall(
            half_duplex_request_iterator(),
            self._target,
            channel_credentials=grpc.experimental.insecure_channel_credentials(),
            wait_for_ready=True,
        )
        expected_responses = self.servicer_methods.HalfDuplexCall(
            half_duplex_request_iterator(), "not a real RpcContext!"
        )
        for expected_response, response in itertools.zip_longest(
            expected_responses, responses
        ):
            self.assertEqual(expected_response, response)


class ModuleMainTest(unittest.TestCase):
    """Test case for running `python -m grpc_tools.protoc`."""

    def test_clean_output(self):
        if sys.executable is None:
            raise unittest.SkipTest(
                "Running on a interpreter that cannot be invoked from the CLI."
            )
        proto_dir_path = os.path.join("src", "proto")
        test_proto_path = os.path.join(
            proto_dir_path, "grpc", "testing", "empty.proto"
        )
        streams = tuple(tempfile.TemporaryFile() for _ in range(2))
        work_dir = tempfile.mkdtemp()
        try:
            invocation = (
                sys.executable,
                "-m",
                "grpc_tools.protoc",
                "--proto_path",
                proto_dir_path,
                "--python_out",
                work_dir,
                "--grpc_python_out",
                work_dir,
                test_proto_path,
            )
            proc = subprocess.Popen(
                invocation, stdout=streams[0], stderr=streams[1]
            )
            proc.wait()
            outs = []
            for stream in streams:
                stream.seek(0)
                self.assertEqual(0, len(stream.read()))
            self.assertEqual(0, proc.returncode)
        except Exception:  # pylint: disable=broad-except
            shutil.rmtree(work_dir)


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