예제 #1
0
    def test_get_session(self, mock_create_stub):
        # Mock gRPC layer
        grpc_stub = mock.Mock()
        mock_create_stub.return_value = grpc_stub

        client = spanner_v1.SpannerClient()

        # Mock request
        name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]',
                                   '[SESSION]')

        # Mock response
        name_2 = 'name2-1052831874'
        expected_response = {'name': name_2}
        expected_response = spanner_pb2.Session(**expected_response)
        grpc_stub.GetSession.return_value = expected_response

        response = client.get_session(name)
        self.assertEqual(expected_response, response)

        grpc_stub.GetSession.assert_called_once()
        args, kwargs = grpc_stub.GetSession.call_args
        self.assertEqual(len(args), 2)
        self.assertEqual(len(kwargs), 1)
        self.assertIn('metadata', kwargs)
        actual_request = args[0]

        expected_request = spanner_pb2.GetSessionRequest(name=name)
        self.assertEqual(expected_request, actual_request)
예제 #2
0
    def get_session(self, name, options=None):
        """
        Gets a session. Returns ``NOT_FOUND`` if the session does not exist.
        This is mainly useful for determining whether a session is still
        alive.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>>
            >>> response = client.get_session(name)

        Args:
            name (str): Required. The name of the session to retrieve.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_v1.types.Session` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.GetSessionRequest(name=name)
        return self._get_session(request, options)
예제 #3
0
def _session_management(stub):
    """Probes to test session related grpc call from Spanner stub.

  Includes tests against CreateSession, GetSession, ListSessions, and
  DeleteSession of Spanner stub.

  Args:
    stub: An object of SpannerStub.

  Raises:
    TypeError: An error occurred when result type is not as expected.
    ValueError: An error occurred when session name is not as expected.
  """
    _session_management_tracer = initialize_tracer()
    with _session_management_tracer.span(name='_session_management'):
        session = None
        try:
            # Create session
            with _session_management_tracer.span(name='stub.CreateSession'):
                session = stub.CreateSession(
                    spanner_pb2.CreateSessionRequest(database=_DATABASE))

            if not isinstance(session, spanner_pb2.Session):
                raise TypeError(
                    'response is of type %s, not spanner_pb2.Session!' %
                    type(session))

            # Get session
            with _session_management_tracer.span(name='stub.GetSession'):
                response = stub.GetSession(
                    spanner_pb2.GetSessionRequest(name=session.name))

            if not isinstance(response, spanner_pb2.Session):
                raise TypeError(
                    'response is of type %s, not spanner_pb2.Session!' %
                    type(response))
            if response.name != session.name:
                raise ValueError('incorrect session name %s' % response.name)

            # List session
            with _session_management_tracer.span(name='stub.ListSessions'):
                response = stub.ListSessions(
                    spanner_pb2.ListSessionsRequest(database=_DATABASE))

            session_list = response.sessions

            if session.name not in (s.name for s in session_list):
                raise ValueError(
                    'session name %s is not in the result session list!' %
                    session.name)

        finally:
            if session is not None:
                # Delete session
                with _session_management_tracer.span(
                        name='stub.DeleteSession'):
                    stub.DeleteSession(
                        spanner_pb2.DeleteSessionRequest(name=session.name))
    def get_session(self,
                    name,
                    retry=google.api_core.gapic_v1.method.DEFAULT,
                    timeout=google.api_core.gapic_v1.method.DEFAULT,
                    metadata=None):
        """
        Gets a session. Returns ``NOT_FOUND`` if the session does not exist.
        This is mainly useful for determining whether a session is still
        alive.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>>
            >>> response = client.get_session(name)

        Args:
            name (str): Required. The name of the session to retrieve.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.

        Returns:
            A :class:`~google.cloud.spanner_v1.types.Session` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        request = spanner_pb2.GetSessionRequest(name=name, )
        return self._get_session(
            request, retry=retry, timeout=timeout, metadata=metadata)
예제 #5
0
    def test_get_session(self):
        # Setup Expected Response
        name_2 = 'name2-1052831874'
        expected_response = {'name': name_2}
        expected_response = spanner_pb2.Session(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = spanner_v1.SpannerClient(channel=channel)

        # Setup Request
        name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]',
                                   '[SESSION]')

        response = client.get_session(name)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = spanner_pb2.GetSessionRequest(name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
    def test_get_session(self):
        # Setup Expected Response
        name_2 = "name2-1052831874"
        expected_response = {"name": name_2}
        expected_response = spanner_pb2.Session(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = spanner_v1.SpannerClient()

        # Setup Request
        name = client.session_path("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]")

        response = client.get_session(name)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = spanner_pb2.GetSessionRequest(name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request