def test_list_sessions(self): # Setup Expected Response next_page_token = '' sessions_element = {} sessions = [sessions_element] expected_response = { 'next_page_token': next_page_token, 'sessions': sessions } expected_response = spanner_pb2.ListSessionsResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = spanner_v1.SpannerClient(channel=channel) # Setup Request database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') paged_list_response = client.list_sessions(database) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.sessions[0] == resources[0] assert len(channel.requests) == 1 expected_request = spanner_pb2.ListSessionsRequest(database=database) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_list_sessions(self): # Setup Expected Response next_page_token = "" sessions_element = {} sessions = [sessions_element] expected_response = { "next_page_token": next_page_token, "sessions": sessions } expected_response = spanner_pb2.ListSessionsResponse( **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 database = client.database_path("[PROJECT]", "[INSTANCE]", "[DATABASE]") paged_list_response = client.list_sessions(database) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.sessions[0] == resources[0] assert len(channel.requests) == 1 expected_request = spanner_pb2.ListSessionsRequest(database=database) actual_request = channel.requests[0][1] assert expected_request == actual_request
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 list_sessions(self, database, page_size=None, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Lists all sessions in a given database. Example: >>> from google.cloud import spanner_v1 >>> >>> client = spanner_v1.SpannerClient() >>> >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') >>> >>> >>> # Iterate over all results >>> for element in client.list_sessions(database): ... # process element ... pass >>> >>> # Or iterate over results one page at a time >>> for page in client.list_sessions(database, options=CallOptions(page_token=INITIAL_PAGE)): ... for element in page: ... # process element ... pass Args: database (str): Required. The database in which to list sessions. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. filter_ (str): An expression for filtering the results of the request. Filter rules are case insensitive. The fields eligible for filtering are: * ``labels.key`` where key is the name of a label Some examples of using filters are: * ``labels.env:*`` --> The session has the label \"env\". * ``labels.env:dev`` --> The session has the label \"env\" and the value of :: the label contains the string \"dev\". 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.gax.PageIterator` instance. By default, this is an iterable of :class:`~google.cloud.spanner_v1.types.Session` instances. This object can also be configured to iterate over the pages of the response through the `options` parameter. 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.ListSessionsRequest( database=database, page_size=page_size, filter=filter_, ) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._list_sessions, retry=retry, timeout=timeout, metadata=metadata), request=request, items_field='sessions', request_token_field='page_token', response_token_field='next_page_token', ) return iterator