Skip to content
This repository has been archived by the owner on Sep 5, 2023. It is now read-only.

Commit

Permalink
feat: add context manager support in client (#93)
Browse files Browse the repository at this point in the history
- [ ] Regenerate this pull request now.

chore: fix docstring for first attribute of protos

committer: @busunkim96
PiperOrigin-RevId: 401271153

Source-Link: googleapis/googleapis@787f8c9

Source-Link: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620
Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9
  • Loading branch information
gcf-owl-bot[bot] authored Oct 8, 2021
1 parent 98e114e commit 9a0ef96
Show file tree
Hide file tree
Showing 16 changed files with 190 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,12 @@ async def suggest_queries(
# Done; return the response.
return response

async def __aenter__(self):
return self

async def __aexit__(self, exc_type, exc, tb):
await self.transport.close()


try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -400,10 +400,7 @@ def __init__(
client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
always_use_jwt_access=(
Transport == type(self).get_transport_class("grpc")
or Transport == type(self).get_transport_class("grpc_asyncio")
),
always_use_jwt_access=True,
)

def suggest_queries(
Expand Down Expand Up @@ -454,6 +451,19 @@ def suggest_queries(
# Done; return the response.
return response

def __enter__(self):
return self

def __exit__(self, type, value, traceback):
"""Releases underlying transport's resources.
.. warning::
ONLY use as a context manager if the transport is NOT shared
with other clients! Exiting the with block will CLOSE the transport
and may cause errors in other clients!
"""
self.transport.close()


try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,15 @@ def _prep_wrapped_messages(self, client_info):
),
}

def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()

@property
def suggest_queries(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -325,5 +325,8 @@ def suggest_queries(
)
return self._stubs["suggest_queries"]

def close(self):
self.grpc_channel.close()


__all__ = ("AutoSuggestionServiceGrpcTransport",)
Original file line number Diff line number Diff line change
Expand Up @@ -328,5 +328,8 @@ def suggest_queries(
)
return self._stubs["suggest_queries"]

def close(self):
return self.grpc_channel.close()


__all__ = ("AutoSuggestionServiceGrpcAsyncIOTransport",)
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,12 @@ async def update_user_feedback(
# Done; return the response.
return response

async def __aenter__(self):
return self

async def __aexit__(self, exc_type, exc, tb):
await self.transport.close()


try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
Expand Down
18 changes: 14 additions & 4 deletions google/cloud/dataqna_v1alpha/services/question_service/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,10 +383,7 @@ def __init__(
client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
always_use_jwt_access=(
Transport == type(self).get_transport_class("grpc")
or Transport == type(self).get_transport_class("grpc_asyncio")
),
always_use_jwt_access=True,
)

def get_question(
Expand Down Expand Up @@ -783,6 +780,19 @@ def update_user_feedback(
# Done; return the response.
return response

def __enter__(self):
return self

def __exit__(self, type, value, traceback):
"""Releases underlying transport's resources.
.. warning::
ONLY use as a context manager if the transport is NOT shared
with other clients! Exiting the with block will CLOSE the transport
and may cause errors in other clients!
"""
self.transport.close()


try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,15 @@ def _prep_wrapped_messages(self, client_info):
),
}

def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()

@property
def get_question(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -380,5 +380,8 @@ def update_user_feedback(
)
return self._stubs["update_user_feedback"]

def close(self):
self.grpc_channel.close()


__all__ = ("QuestionServiceGrpcTransport",)
Original file line number Diff line number Diff line change
Expand Up @@ -388,5 +388,8 @@ def update_user_feedback(
)
return self._stubs["update_user_feedback"]

def close(self):
return self.grpc_channel.close()


__all__ = ("QuestionServiceGrpcAsyncIOTransport",)
4 changes: 4 additions & 0 deletions google/cloud/dataqna_v1alpha/types/auto_suggestion_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class SuggestionType(proto.Enum):

class SuggestQueriesRequest(proto.Message):
r"""Request for query suggestions.
Attributes:
parent (str):
Required. The parent of the suggestion query
Expand Down Expand Up @@ -72,6 +73,7 @@ class SuggestQueriesRequest(proto.Message):

class Suggestion(proto.Message):
r"""A suggestion for a query with a ranking score.
Attributes:
suggestion_info (google.cloud.dataqna_v1alpha.types.SuggestionInfo):
Detailed information about the suggestion.
Expand All @@ -91,6 +93,7 @@ class Suggestion(proto.Message):

class SuggestionInfo(proto.Message):
r"""Detailed information about the suggestion.
Attributes:
annotated_suggestion (google.cloud.dataqna_v1alpha.types.AnnotatedString):
Annotations for the suggestion. This provides
Expand Down Expand Up @@ -148,6 +151,7 @@ class MatchInfo(proto.Message):

class SuggestQueriesResponse(proto.Message):
r"""Response to SuggestQueries.
Attributes:
suggestions (Sequence[google.cloud.dataqna_v1alpha.types.Suggestion]):
A list of suggestions.
Expand Down
11 changes: 10 additions & 1 deletion google/cloud/dataqna_v1alpha/types/question.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ class Question(proto.Message):

class InterpretError(proto.Message):
r"""Details on the failure to interpret the question.
Attributes:
message (str):
Error message explaining why this question
Expand All @@ -140,6 +141,7 @@ class InterpretErrorCode(proto.Enum):

class InterpretErrorDetails(proto.Message):
r"""Details on interpretation failure.
Attributes:
unsupported_details (google.cloud.dataqna_v1alpha.types.InterpretError.InterpretUnsupportedDetails):
Populated if parts of the query are
Expand All @@ -166,6 +168,7 @@ class InterpretErrorDetails(proto.Message):

class InterpretUnsupportedDetails(proto.Message):
r"""Details about unsupported parts in a query.
Attributes:
operators (Sequence[str]):
Unsupported operators. For example: median.
Expand All @@ -178,6 +181,7 @@ class InterpretUnsupportedDetails(proto.Message):

class InterpretIncompleteQueryDetails(proto.Message):
r"""Details about an incomplete query.
Attributes:
entities (Sequence[google.cloud.dataqna_v1alpha.types.InterpretEntity]):
List of missing interpret entities.
Expand All @@ -189,7 +193,8 @@ class InterpretAmbiguityDetails(proto.Message):
r"""Details about a query that was too ambiguous. Currently, the
message has no fields and its presence signals that there was
ambiguity.
"""
"""

message = proto.Field(proto.STRING, number=1,)
code = proto.Field(proto.ENUM, number=2, enum=InterpretErrorCode,)
Expand Down Expand Up @@ -252,6 +257,7 @@ class BigQueryJob(proto.Message):

class Interpretation(proto.Message):
r"""An interpretation of a natural language query.
Attributes:
data_sources (Sequence[str]):
List of data sources used in the current
Expand Down Expand Up @@ -310,6 +316,7 @@ class DataQuery(proto.Message):

class HumanReadable(proto.Message):
r"""Human readable interpretation.
Attributes:
generated_interpretation (google.cloud.dataqna_v1alpha.types.AnnotatedString):
Generated query explaining the
Expand Down Expand Up @@ -361,6 +368,7 @@ class VisualizationType(proto.Enum):

class ColumnInfo(proto.Message):
r"""Information about a column.
Attributes:
output_alias (str):
The alias of the output column as used by the
Expand All @@ -382,6 +390,7 @@ class ColumnInfo(proto.Message):

class DebugFlags(proto.Message):
r"""Configuriation of debug flags.
Attributes:
include_va_query (bool):
Whether to include the original VAQuery.
Expand Down
5 changes: 5 additions & 0 deletions google/cloud/dataqna_v1alpha/types/question_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

class GetQuestionRequest(proto.Message):
r"""A request to get a previously created question.
Attributes:
name (str):
Required. The unique identifier for the question. Example:
Expand All @@ -48,6 +49,7 @@ class GetQuestionRequest(proto.Message):

class CreateQuestionRequest(proto.Message):
r"""Request to create a question resource.
Attributes:
parent (str):
Required. The name of the project this data source reference
Expand All @@ -62,6 +64,7 @@ class CreateQuestionRequest(proto.Message):

class ExecuteQuestionRequest(proto.Message):
r"""Request to execute an interpretation.
Attributes:
name (str):
Required. The unique identifier for the question. Example:
Expand All @@ -77,6 +80,7 @@ class ExecuteQuestionRequest(proto.Message):

class GetUserFeedbackRequest(proto.Message):
r"""Request to get user feedback.
Attributes:
name (str):
Required. The unique identifier for the user feedback. User
Expand All @@ -89,6 +93,7 @@ class GetUserFeedbackRequest(proto.Message):

class UpdateUserFeedbackRequest(proto.Message):
r"""Request to updates user feedback.
Attributes:
user_feedback (google.cloud.dataqna_v1alpha.types.UserFeedback):
Required. The user feedback to update. This
Expand Down
1 change: 1 addition & 0 deletions google/cloud/dataqna_v1alpha/types/user_feedback.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

class UserFeedback(proto.Message):
r"""Feedback provided by a user.
Attributes:
name (str):
Required. The unique identifier for the user feedback. User
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.api_core import path_template
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.dataqna_v1alpha.services.auto_suggestion_service import (
Expand Down Expand Up @@ -758,6 +759,9 @@ def test_auto_suggestion_service_base_transport():
with pytest.raises(NotImplementedError):
getattr(transport, method)(request=object())

with pytest.raises(NotImplementedError):
transport.close()


@requires_google_auth_gte_1_25_0
def test_auto_suggestion_service_base_transport_with_credentials_file():
Expand Down Expand Up @@ -1220,3 +1224,49 @@ def test_client_withDEFAULT_CLIENT_INFO():
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)


@pytest.mark.asyncio
async def test_transport_close_async():
client = AutoSuggestionServiceAsyncClient(
credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
)
with mock.patch.object(
type(getattr(client.transport, "grpc_channel")), "close"
) as close:
async with client:
close.assert_not_called()
close.assert_called_once()


def test_transport_close():
transports = {
"grpc": "_grpc_channel",
}

for transport, close_name in transports.items():
client = AutoSuggestionServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport
)
with mock.patch.object(
type(getattr(client.transport, close_name)), "close"
) as close:
with client:
close.assert_not_called()
close.assert_called_once()


def test_client_ctx():
transports = [
"grpc",
]
for transport in transports:
client = AutoSuggestionServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport
)
# Test client calls underlying transport.
with mock.patch.object(type(client.transport), "close") as close:
close.assert_not_called()
with client:
pass
close.assert_called()
Loading

0 comments on commit 9a0ef96

Please sign in to comment.