aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/python/grpcio/tests/unit/framework/interfaces/base/_control.py
blob: 94bcc1428e2649578e0be8e37f6825cecb6e534c (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
# Copyright 2015-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.

"""Part of the tests of the base interface of RPC Framework."""

from __future__ import division

import abc
import collections
import enum
import random  # pylint: disable=unused-import
import threading
import time

import six

from grpc.framework.interfaces.base import base
from tests.unit.framework.common import test_constants
from tests.unit.framework.interfaces.base import _sequence
from tests.unit.framework.interfaces.base import _state
from tests.unit.framework.interfaces.base import test_interfaces  # pylint: disable=unused-import

_GROUP = 'base test cases test group'
_METHOD = 'base test cases test method'

_PAYLOAD_RANDOM_SECTION_MAXIMUM_SIZE = test_constants.PAYLOAD_SIZE // 20
_MINIMUM_PAYLOAD_SIZE = test_constants.PAYLOAD_SIZE // 600


def _create_payload(randomness):
  length = randomness.randint(
      _MINIMUM_PAYLOAD_SIZE, test_constants.PAYLOAD_SIZE)
  random_section_length = randomness.randint(
      0, min(_PAYLOAD_RANDOM_SECTION_MAXIMUM_SIZE, length))
  random_section = bytes(
      bytearray(
          randomness.getrandbits(8) for _ in range(random_section_length)))
  sevens_section = b'\x07' * (length - random_section_length)
  return b''.join(randomness.sample((random_section, sevens_section), 2))


def _anything_in_flight(state):
  return (
      state.invocation_initial_metadata_in_flight is not None or
      state.invocation_payloads_in_flight or
      state.invocation_completion_in_flight is not None or
      state.service_initial_metadata_in_flight is not None or
      state.service_payloads_in_flight or
      state.service_completion_in_flight is not None or
      0 < state.invocation_allowance_in_flight or
      0 < state.service_allowance_in_flight
  )


def _verify_service_advance_and_update_state(
    initial_metadata, payload, completion, allowance, state, implementation):
  if initial_metadata is not None:
    if state.invocation_initial_metadata_received:
      return 'Later invocation initial metadata received: %s' % (
          initial_metadata,)
    if state.invocation_payloads_received:
      return 'Invocation initial metadata received after payloads: %s' % (
          state.invocation_payloads_received)
    if state.invocation_completion_received:
      return 'Invocation initial metadata received after invocation completion!'
    if not implementation.metadata_transmitted(
        state.invocation_initial_metadata_in_flight, initial_metadata):
      return 'Invocation initial metadata maltransmitted: %s, %s' % (
          state.invocation_initial_metadata_in_flight, initial_metadata)
    else:
      state.invocation_initial_metadata_in_flight = None
      state.invocation_initial_metadata_received = True

  if payload is not None:
    if state.invocation_completion_received:
      return 'Invocation payload received after invocation completion!'
    elif not state.invocation_payloads_in_flight:
      return 'Invocation payload "%s" received but not in flight!' % (payload,)
    elif state.invocation_payloads_in_flight[0] != payload:
      return 'Invocation payload mismatch: %s, %s' % (
          state.invocation_payloads_in_flight[0], payload)
    elif state.service_side_invocation_allowance < 1:
      return 'Disallowed invocation payload!'
    else:
      state.invocation_payloads_in_flight.pop(0)
      state.invocation_payloads_received += 1
      state.service_side_invocation_allowance -= 1

  if completion is not None:
    if state.invocation_completion_received:
      return 'Later invocation completion received: %s' % (completion,)
    elif not implementation.completion_transmitted(
        state.invocation_completion_in_flight, completion):
      return 'Invocation completion maltransmitted: %s, %s' % (
          state.invocation_completion_in_flight, completion)
    else:
      state.invocation_completion_in_flight = None
      state.invocation_completion_received = True

  if allowance is not None:
    if allowance <= 0:
      return 'Illegal allowance value: %s' % (allowance,)
    else:
      state.service_allowance_in_flight -= allowance
      state.service_side_service_allowance += allowance


def _verify_invocation_advance_and_update_state(
    initial_metadata, payload, completion, allowance, state, implementation):
  if initial_metadata is not None:
    if state.service_initial_metadata_received:
      return 'Later service initial metadata received: %s' % (initial_metadata,)
    if state.service_payloads_received:
      return 'Service initial metadata received after service payloads: %s' % (
          state.service_payloads_received)
    if state.service_completion_received:
      return 'Service initial metadata received after service completion!'
    if not implementation.metadata_transmitted(
        state.service_initial_metadata_in_flight, initial_metadata):
      return 'Service initial metadata maltransmitted: %s, %s' % (
          state.service_initial_metadata_in_flight, initial_metadata)
    else:
      state.service_initial_metadata_in_flight = None
      state.service_initial_metadata_received = True

  if payload is not None:
    if state.service_completion_received:
      return 'Service payload received after service completion!'
    elif not state.service_payloads_in_flight:
      return 'Service payload "%s" received but not in flight!' % (payload,)
    elif state.service_payloads_in_flight[0] != payload:
      return 'Service payload mismatch: %s, %s' % (
          state.invocation_payloads_in_flight[0], payload)
    elif state.invocation_side_service_allowance < 1:
      return 'Disallowed service payload!'
    else:
      state.service_payloads_in_flight.pop(0)
      state.service_payloads_received += 1
      state.invocation_side_service_allowance -= 1

  if completion is not None:
    if state.service_completion_received:
      return 'Later service completion received: %s' % (completion,)
    elif not implementation.completion_transmitted(
        state.service_completion_in_flight, completion):
      return 'Service completion maltransmitted: %s, %s' % (
          state.service_completion_in_flight, completion)
    else:
      state.service_completion_in_flight = None
      state.service_completion_received = True

  if allowance is not None:
    if allowance <= 0:
      return 'Illegal allowance value: %s' % (allowance,)
    else:
      state.invocation_allowance_in_flight -= allowance
      state.invocation_side_service_allowance += allowance


class Invocation(
    collections.namedtuple(
        'Invocation',
        ('group', 'method', 'subscription_kind', 'timeout', 'initial_metadata',
         'payload', 'completion',))):
  """A description of operation invocation.

  Attributes:
    group: The group identifier for the operation.
    method: The method identifier for the operation.
    subscription_kind: A base.Subscription.Kind value describing the kind of
      subscription to use for the operation.
    timeout: A duration in seconds to pass as the timeout value for the
      operation.
    initial_metadata: An object to pass as the initial metadata for the
      operation or None.
    payload: An object to pass as a payload value for the operation or None.
    completion: An object to pass as a completion value for the operation or
      None.
  """


class OnAdvance(
    collections.namedtuple(
        'OnAdvance',
        ('kind', 'initial_metadata', 'payload', 'completion', 'allowance'))):
  """Describes action to be taken in a test in response to an advance call.

  Attributes:
    kind: A Kind value describing the overall kind of response.
    initial_metadata: An initial metadata value to pass to a call of the advance
      method of the operator under test. Only valid if kind is Kind.ADVANCE and
      may be None.
    payload: A payload value to pass to a call of the advance method of the
      operator under test. Only valid if kind is Kind.ADVANCE and may be None.
    completion: A base.Completion value to pass to a call of the advance method
      of the operator under test. Only valid if kind is Kind.ADVANCE and may be
      None.
    allowance: An allowance value to pass to a call of the advance method of the
      operator under test. Only valid if kind is Kind.ADVANCE and may be None.
  """

  @enum.unique
  class Kind(enum.Enum):
    ADVANCE = 'advance'
    DEFECT = 'defect'
    IDLE = 'idle'


_DEFECT_ON_ADVANCE = OnAdvance(OnAdvance.Kind.DEFECT, None, None, None, None)
_IDLE_ON_ADVANCE = OnAdvance(OnAdvance.Kind.IDLE, None, None, None, None)


class Instruction(
    collections.namedtuple(
        'Instruction',
        ('kind', 'advance_args', 'advance_kwargs', 'conclude_success',
         'conclude_message', 'conclude_invocation_outcome_kind',
         'conclude_service_outcome_kind',))):
  """"""

  @enum.unique
  class Kind(enum.Enum):
    ADVANCE = 'ADVANCE'
    CANCEL = 'CANCEL'
    CONCLUDE = 'CONCLUDE'


class Controller(six.with_metaclass(abc.ABCMeta)):

  @abc.abstractmethod
  def failed(self, message):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def serialize_request(self, request):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def deserialize_request(self, serialized_request):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def serialize_response(self, response):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def deserialize_response(self, serialized_response):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def invocation(self):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def poll(self):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def on_service_advance(
      self, initial_metadata, payload, completion, allowance):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def on_invocation_advance(
      self, initial_metadata, payload, completion, allowance):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def service_on_termination(self, outcome):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def invocation_on_termination(self, outcome):
    """"""
    raise NotImplementedError()


class ControllerCreator(six.with_metaclass(abc.ABCMeta)):

  @abc.abstractmethod
  def name(self):
    """"""
    raise NotImplementedError()

  @abc.abstractmethod
  def controller(self, implementation, randomness):
    """"""
    raise NotImplementedError()


class _Remainder(
    collections.namedtuple(
        '_Remainder',
        ('invocation_payloads', 'service_payloads', 'invocation_completion',
         'service_completion',))):
  """Describes work remaining to be done in a portion of a test.

  Attributes:
    invocation_payloads: The number of payloads to be sent from the invocation
      side of the operation to the service side of the operation.
    service_payloads: The number of payloads to be sent from the service side of
      the operation to the invocation side of the operation.
    invocation_completion: Whether or not completion from the invocation side of
      the operation should be indicated and has yet to be indicated.
    service_completion: Whether or not completion from the service side of the
      operation should be indicated and has yet to be indicated.
  """


class _SequenceController(Controller):

  def __init__(self, sequence, implementation, randomness):
    """Constructor.

    Args:
      sequence: A _sequence.Sequence describing the steps to be taken in the
        test at a relatively high level.
      implementation: A test_interfaces.Implementation encapsulating the
        base interface implementation that is the system under test.
      randomness: A random.Random instance for use in the test.
    """
    self._condition = threading.Condition()
    self._sequence = sequence
    self._implementation = implementation
    self._randomness = randomness

    self._until = None
    self._remaining_elements = None
    self._poll_next = None
    self._message = None

    self._state = _state.OperationState()
    self._todo = None

  # called with self._condition
  def _failed(self, message):
    self._message = message
    self._condition.notify_all()

  def _passed(self, invocation_outcome, service_outcome):
    self._poll_next = Instruction(
        Instruction.Kind.CONCLUDE, None, None, True, None, invocation_outcome,
        service_outcome)
    self._condition.notify_all()

  def failed(self, message):
    with self._condition:
      self._failed(message)

  def serialize_request(self, request):
    return request + request

  def deserialize_request(self, serialized_request):
    return serialized_request[:len(serialized_request) // 2]

  def serialize_response(self, response):
    return response * 3

  def deserialize_response(self, serialized_response):
    return serialized_response[2 * len(serialized_response) // 3:]

  def invocation(self):
    with self._condition:
      self._until = time.time() + self._sequence.maximum_duration
      self._remaining_elements = list(self._sequence.elements)
      if self._sequence.invocation.initial_metadata:
        initial_metadata = self._implementation.invocation_initial_metadata()
        self._state.invocation_initial_metadata_in_flight = initial_metadata
      else:
        initial_metadata = None
      if self._sequence.invocation.payload:
        payload = _create_payload(self._randomness)
        self._state.invocation_payloads_in_flight.append(payload)
      else:
        payload = None
      if self._sequence.invocation.complete:
        completion = self._implementation.invocation_completion()
        self._state.invocation_completion_in_flight = completion
      else:
        completion = None
      return Invocation(
          _GROUP, _METHOD, base.Subscription.Kind.FULL,
          self._sequence.invocation.timeout, initial_metadata, payload,
          completion)

  def poll(self):
    with self._condition:
      while True:
        if self._message is not None:
          return Instruction(
              Instruction.Kind.CONCLUDE, None, None, False, self._message, None,
              None)
        elif self._poll_next:
          poll_next = self._poll_next
          self._poll_next = None
          return poll_next
        elif self._until < time.time():
          return Instruction(
              Instruction.Kind.CONCLUDE, None, None, False,
              'overran allotted time!', None, None)
        else:
          self._condition.wait(timeout=self._until-time.time())

  def on_service_advance(
      self, initial_metadata, payload, completion, allowance):
    with self._condition:
      message = _verify_service_advance_and_update_state(
          initial_metadata, payload, completion, allowance, self._state,
          self._implementation)
      if message is not None:
        self._failed(message)
      if self._todo is not None:
        raise ValueError('TODO!!!')
      elif _anything_in_flight(self._state):
        return _IDLE_ON_ADVANCE
      elif self._remaining_elements:
        element = self._remaining_elements.pop(0)
        if element.kind is _sequence.Element.Kind.SERVICE_TRANSMISSION:
          if element.transmission.initial_metadata:
            initial_metadata = self._implementation.service_initial_metadata()
            self._state.service_initial_metadata_in_flight = initial_metadata
          else:
            initial_metadata = None
          if element.transmission.payload:
            payload = _create_payload(self._randomness)
            self._state.service_payloads_in_flight.append(payload)
            self._state.service_side_service_allowance -= 1
          else:
            payload = None
          if element.transmission.complete:
            completion = self._implementation.service_completion()
            self._state.service_completion_in_flight = completion
          else:
            completion = None
          if (not self._state.invocation_completion_received and
              0 <= self._state.service_side_invocation_allowance):
            allowance = 1
            self._state.service_side_invocation_allowance += 1
            self._state.invocation_allowance_in_flight += 1
          else:
            allowance = None
          return OnAdvance(
              OnAdvance.Kind.ADVANCE, initial_metadata, payload, completion,
              allowance)
        else:
          raise ValueError('TODO!!!')
      else:
        return _IDLE_ON_ADVANCE

  def on_invocation_advance(
      self, initial_metadata, payload, completion, allowance):
    with self._condition:
      message = _verify_invocation_advance_and_update_state(
          initial_metadata, payload, completion, allowance, self._state,
          self._implementation)
      if message is not None:
        self._failed(message)
      if self._todo is not None:
        raise ValueError('TODO!!!')
      elif _anything_in_flight(self._state):
        return _IDLE_ON_ADVANCE
      elif self._remaining_elements:
        element = self._remaining_elements.pop(0)
        if element.kind is _sequence.Element.Kind.INVOCATION_TRANSMISSION:
          if element.transmission.initial_metadata:
            initial_metadata = self._implementation.invocation_initial_metadata()
            self._state.invocation_initial_metadata_in_fight = initial_metadata
          else:
            initial_metadata = None
          if element.transmission.payload:
            payload = _create_payload(self._randomness)
            self._state.invocation_payloads_in_flight.append(payload)
            self._state.invocation_side_invocation_allowance -= 1
          else:
            payload = None
          if element.transmission.complete:
            completion = self._implementation.invocation_completion()
            self._state.invocation_completion_in_flight = completion
          else:
            completion = None
          if (not self._state.service_completion_received and
              0 <= self._state.invocation_side_service_allowance):
            allowance = 1
            self._state.invocation_side_service_allowance += 1
            self._state.service_allowance_in_flight += 1
          else:
            allowance = None
          return OnAdvance(
              OnAdvance.Kind.ADVANCE, initial_metadata, payload, completion,
              allowance)
        else:
          raise ValueError('TODO!!!')
      else:
        return _IDLE_ON_ADVANCE

  def service_on_termination(self, outcome):
    with self._condition:
      self._state.service_side_outcome = outcome
      if self._todo is not None or self._remaining_elements:
        self._failed('Premature service-side outcome %s!' % (outcome,))
      elif outcome.kind is not self._sequence.outcome_kinds.service:
        self._failed(
            'Incorrect service-side outcome kind: %s should have been %s' % (
                outcome.kind, self._sequence.outcome_kinds.service))
      elif self._state.invocation_side_outcome is not None:
        self._passed(self._state.invocation_side_outcome.kind, outcome.kind)

  def invocation_on_termination(self, outcome):
    with self._condition:
      self._state.invocation_side_outcome = outcome
      if self._todo is not None or self._remaining_elements:
        self._failed('Premature invocation-side outcome %s!' % (outcome,))
      elif outcome.kind is not self._sequence.outcome_kinds.invocation:
        self._failed(
            'Incorrect invocation-side outcome kind: %s should have been %s' % (
                outcome.kind, self._sequence.outcome_kinds.invocation))
      elif self._state.service_side_outcome is not None:
        self._passed(outcome.kind, self._state.service_side_outcome.kind)


class _SequenceControllerCreator(ControllerCreator):

  def __init__(self, sequence):
    self._sequence = sequence

  def name(self):
    return self._sequence.name

  def controller(self, implementation, randomness):
    return _SequenceController(self._sequence, implementation, randomness)


CONTROLLER_CREATORS = tuple(
    _SequenceControllerCreator(sequence) for sequence in _sequence.SEQUENCES)