def test_wrap_method_with_overriding_retry_and_timeout(unusued_sleep):
    method = mock.Mock(spec=['__call__'],
                       side_effect=[exceptions.NotFound(None), 42])
    default_retry = retry.Retry()
    default_timeout = timeout.ConstantTimeout(60)
    wrapped_method = google.api_core.gapic_v1.method.wrap_method(
        method, default_retry, default_timeout)

    result = wrapped_method(retry=retry.Retry(
        retry.if_exception_type(exceptions.NotFound)),
                            timeout=timeout.ConstantTimeout(22))

    assert result == 42
    assert method.call_count == 2
    method.assert_called_with(timeout=22, metadata=mock.ANY)
Esempio n. 2
0
def _determine_timeout(default_timeout, specified_timeout, retry):
    """Determines how timeout should be applied to a wrapped method.

    Args:
        default_timeout (Optional[Timeout]): The default timeout specified
            at method creation time.
        specified_timeout (Optional[Timeout]): The timeout specified at
            invocation time. If :attr:`DEFAULT`, this will be set to
            the ``default_timeout``.
        retry (Optional[Retry]): The retry specified at invocation time.

    Returns:
        Optional[Timeout]: The timeout to apply to the method or ``None``.
    """
    if specified_timeout is DEFAULT:
        specified_timeout = default_timeout

    if specified_timeout is default_timeout:
        # If timeout is the default and the default timeout is exponential and
        # a non-default retry is specified, make sure the timeout's deadline
        # matches the retry's. This handles the case where the user leaves
        # the timeout default but specifies a lower deadline via the retry.
        if (retry and retry is not DEFAULT
                and isinstance(default_timeout, timeout.ExponentialTimeout)):
            return default_timeout.with_deadline(retry._deadline)
        else:
            return default_timeout

    # If timeout is specified as a number instead of a Timeout instance,
    # convert it to a ConstantTimeout.
    if isinstance(specified_timeout, (int, float)):
        return timeout.ConstantTimeout(specified_timeout)
    else:
        return specified_timeout
Esempio n. 3
0
    def test_apply_passthrough(self):
        target = mock.Mock(spec=['__call__', '__name__'], __name__='target')
        timeout_ = timeout.ConstantTimeout(42.0)
        wrapped = timeout_(target)

        wrapped(1, 2, meep='moop')

        target.assert_called_once_with(1, 2, meep='moop', timeout=42.0)
Esempio n. 4
0
    def test_apply(self):
        target = mock.Mock(spec=['__call__', '__name__'], __name__='target')
        timeout_ = timeout.ConstantTimeout(42.0)
        wrapped = timeout_(target)

        wrapped()

        target.assert_called_once_with(timeout=42.0)
Esempio n. 5
0
    def test_apply_passthrough(self):
        target = mock.Mock(spec=["__call__", "__name__"], __name__="target")
        timeout_ = timeout.ConstantTimeout(42.0)
        wrapped = timeout_(target)

        wrapped(1, 2, meep="moop")

        target.assert_called_once_with(1, 2, meep="moop", timeout=42.0)
Esempio n. 6
0
def parse_method_configs(interface_config, retry_impl=retry.Retry):
    """Creates default retry and timeout objects for each method in a gapic
    interface config.

    Args:
        interface_config (Mapping): The interface config section of the full
            gapic library config. For example, If the full configuration has
            an interface named ``google.example.v1.ExampleService`` you would
            pass in just that interface's configuration, for example
            ``gapic_config['interfaces']['google.example.v1.ExampleService']``.
        retry_impl (Callable): The constructor that creates a retry decorator
            that will be applied to the method based on method configs.

    Returns:
        Mapping[str, MethodConfig]: A mapping of RPC method names to their
            configuration.
    """
    # Grab all the retry codes
    retry_codes_map = {
        name: retry_codes
        for name, retry_codes in interface_config.get("retry_codes",
                                                      {}).items()
    }

    # Grab all of the retry params
    retry_params_map = {
        name: retry_params
        for name, retry_params in interface_config.get("retry_params",
                                                       {}).items()
    }

    # Iterate through all the API methods and create a flat MethodConfig
    # instance for each one.
    method_configs = {}

    for method_name, method_params in interface_config.get("methods",
                                                           {}).items():
        retry_params_name = method_params.get("retry_params_name")

        if retry_params_name is not None:
            retry_params = retry_params_map[retry_params_name]
            retry_ = _retry_from_retry_config(
                retry_params,
                retry_codes_map[method_params["retry_codes_name"]],
                retry_impl,
            )
            timeout_ = _timeout_from_retry_config(retry_params)

        # No retry config, so this is a non-retryable method.
        else:
            retry_ = None
            timeout_ = timeout.ConstantTimeout(
                method_params["timeout_millis"] / _MILLIS_PER_SECOND)

        method_configs[method_name] = MethodConfig(retry=retry_,
                                                   timeout=timeout_)

    return method_configs
Esempio n. 7
0
def test_wrap_method_with_overriding_timeout_as_a_number():
    method = mock.Mock(spec=["__call__"], return_value=42)
    default_retry = retry.Retry()
    default_timeout = timeout.ConstantTimeout(60)
    wrapped_method = google.api_core.gapic_v1.method.wrap_method(
        method, default_retry, default_timeout)

    result = wrapped_method(timeout=22)

    assert result == 42
    method.assert_called_once_with(timeout=22, metadata=mock.ANY)
async def test_wrap_method_with_overriding_retry_and_timeout(unused_sleep):
    fake_call = grpc_helpers_async.FakeUnaryUnaryCall(42)
    method = mock.Mock(
        spec=aio.UnaryUnaryMultiCallable,
        side_effect=[exceptions.NotFound(None), fake_call],
    )

    default_retry = retry_async.AsyncRetry()
    default_timeout = timeout.ConstantTimeout(60)
    wrapped_method = gapic_v1.method_async.wrap_method(method, default_retry,
                                                       default_timeout)

    result = await wrapped_method(
        retry=retry_async.AsyncRetry(
            retry_async.if_exception_type(exceptions.NotFound)),
        timeout=timeout.ConstantTimeout(22),
    )

    assert result == 42
    assert method.call_count == 2
    method.assert_called_with(timeout=22, metadata=mock.ANY)
async def test_wrap_method_with_overriding_timeout_as_a_number():
    fake_call = grpc_helpers_async.FakeUnaryUnaryCall(42)
    method = mock.Mock(spec=aio.UnaryUnaryMultiCallable,
                       return_value=fake_call)
    default_retry = retry_async.AsyncRetry()
    default_timeout = timeout.ConstantTimeout(60)
    wrapped_method = gapic_v1.method_async.wrap_method(method, default_retry,
                                                       default_timeout)

    result = await wrapped_method(timeout=22)

    assert result == 42
    method.assert_called_once_with(timeout=22, metadata=mock.ANY)
Esempio n. 10
0
def test_wrap_method_with_default_retry_and_timeout(unusued_sleep):
    method = mock.Mock(spec=["__call__"],
                       side_effect=[exceptions.InternalServerError(None), 42])
    default_retry = retry.Retry()
    default_timeout = timeout.ConstantTimeout(60)
    wrapped_method = google.api_core.gapic_v1.method.wrap_method(
        method, default_retry, default_timeout)

    result = wrapped_method()

    assert result == 42
    assert method.call_count == 2
    method.assert_called_with(timeout=60, metadata=mock.ANY)
Esempio n. 11
0
def test__determine_timeout():
    # Check _determine_timeout always returns a Timeout object.
    timeout_type_timeout = timeout.ConstantTimeout(600.0)
    returned_timeout = google.api_core.gapic_v1.method._determine_timeout(
        600.0, 600.0, None)
    assert isinstance(returned_timeout, timeout.ConstantTimeout)
    returned_timeout = google.api_core.gapic_v1.method._determine_timeout(
        600.0, timeout_type_timeout, None)
    assert isinstance(returned_timeout, timeout.ConstantTimeout)
    returned_timeout = google.api_core.gapic_v1.method._determine_timeout(
        timeout_type_timeout, 600.0, None)
    assert isinstance(returned_timeout, timeout.ConstantTimeout)
    returned_timeout = google.api_core.gapic_v1.method._determine_timeout(
        timeout_type_timeout, timeout_type_timeout, None)
    assert isinstance(returned_timeout, timeout.ConstantTimeout)
async def test_wrap_method_with_default_retry_and_timeout(unused_sleep):
    fake_call = grpc_helpers_async.FakeUnaryUnaryCall(42)
    method = mock.Mock(
        spec=aio.UnaryUnaryMultiCallable,
        side_effect=[exceptions.InternalServerError(None), fake_call],
    )

    default_retry = retry_async.AsyncRetry()
    default_timeout = timeout.ConstantTimeout(60)
    wrapped_method = gapic_v1.method_async.wrap_method(method, default_retry,
                                                       default_timeout)

    result = await wrapped_method()

    assert result == 42
    assert method.call_count == 2
    method.assert_called_with(timeout=60, metadata=mock.ANY)
Esempio n. 13
0
 def test___str__(self):
     timeout_ = timeout.ConstantTimeout(1)
     assert str(timeout_) == '<ConstantTimeout timeout=1.0>'
Esempio n. 14
0
 def test_constructor_args(self):
     timeout_ = timeout.ConstantTimeout(42.0)
     assert timeout_._timeout == 42.0
Esempio n. 15
0
 def test_constructor(self):
     timeout_ = timeout.ConstantTimeout()
     assert timeout_._timeout is None