Make client_info work without gRPC installed. (#5075)
diff --git a/google/api_core/gapic_v1/client_info.py b/google/api_core/gapic_v1/client_info.py
index a76754d..7feeaf1 100644
--- a/google/api_core/gapic_v1/client_info.py
+++ b/google/api_core/gapic_v1/client_info.py
@@ -23,8 +23,13 @@
import pkg_resources
_PY_VERSION = platform.python_version()
-_GRPC_VERSION = pkg_resources.get_distribution('grpcio').version
_API_CORE_VERSION = pkg_resources.get_distribution('google-api-core').version
+
+try:
+ _GRPC_VERSION = pkg_resources.get_distribution('grpcio').version
+except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GRPC_VERSION = None
+
METRICS_METADATA_KEY = 'x-goog-api-client'
@@ -38,7 +43,7 @@
Args:
python_version (str): The Python interpreter version, for example,
``'2.7.13'``.
- grpc_version (str): The gRPC library version.
+ grpc_version (Optional[str]): The gRPC library version.
api_core_version (str): The google-api-core library version.
gapic_version (Optional[str]): The sversion of gapic-generated client
library, if the library was generated by gapic.
@@ -66,15 +71,18 @@
# expects these items to be in specific locations.
ua = 'gl-python/{python_version} '
- if self.client_library_version is not None:
- ua += 'gccl/{client_library_version} '
+ if self.grpc_version is not None:
+ ua += 'grpc/{grpc_version} '
+
+ ua += 'gax/{api_core_version} '
if self.gapic_version is not None:
ua += 'gapic/{gapic_version} '
- ua += 'gax/{api_core_version} grpc/{grpc_version}'
+ if self.client_library_version is not None:
+ ua += 'gccl/{client_library_version} '
- return ua.format(**self.__dict__)
+ return ua.format(**self.__dict__).strip()
def to_grpc_metadata(self):
"""Returns the gRPC metadata for this client info."""
diff --git a/tests/unit/gapic/test_client_info.py b/tests/unit/gapic/test_client_info.py
index acbcb6a..f83c4d5 100644
--- a/tests/unit/gapic/test_client_info.py
+++ b/tests/unit/gapic/test_client_info.py
@@ -44,12 +44,13 @@
def test_to_user_agent_minimal():
info = client_info.ClientInfo(
python_version='1',
- grpc_version='2',
- api_core_version='3')
+ api_core_version='2',
+ grpc_version=None
+ )
user_agent = info.to_user_agent()
- assert user_agent == 'gl-python/1 gax/3 grpc/2'
+ assert user_agent == 'gl-python/1 gax/2'
def test_to_user_agent_full():
@@ -62,7 +63,7 @@
user_agent = info.to_user_agent()
- assert user_agent == 'gl-python/1 gccl/5 gapic/4 gax/3 grpc/2'
+ assert user_agent == 'gl-python/1 grpc/2 gax/3 gapic/4 gccl/5'
def test_to_grpc_metadata():