Skip to content

Commit 93efce3

Browse files
committed
fix: Fail gracefully if could not import rpc_status module
1 parent 3c5e034 commit 93efce3

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

google/api_core/exceptions.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,21 @@
2828

2929
from google.rpc import error_details_pb2
3030

31+
32+
def _warn_could_not_import_grpcio_status():
33+
warnings.warn(
34+
"Please install grpcio-status to obtain helpful grpc error messages.",
35+
ImportWarning,
36+
)
37+
38+
3139
try:
3240
import grpc
3341

3442
try:
3543
from grpc_status import rpc_status
3644
except ImportError: # pragma: NO COVER
37-
warnings.warn(
38-
"Please install grpcio-status to obtain helpful grpc error messages.",
39-
ImportWarning,
40-
)
45+
_warn_could_not_import_grpcio_status()
4146
rpc_status = None
4247
except ImportError: # pragma: NO COVER
4348
grpc = None
@@ -560,6 +565,11 @@ def _is_informative_grpc_error(rpc_exc):
560565

561566

562567
def _parse_grpc_error_details(rpc_exc):
568+
# pragma: NO COVER
569+
if not rpc_status:
570+
_warn_could_not_import_grpcio_status()
571+
return [], None
572+
# pragma: NO COVER
563573
try:
564574
status = rpc_status.from_call(rpc_exc)
565575
except NotImplementedError: # workaround

tests/unit/test_exceptions.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,3 +393,24 @@ def test_error_details_from_grpc_response_unknown_error():
393393
and exception.domain is None
394394
and exception.metadata is None
395395
)
396+
397+
398+
@pytest.mark.skipif(grpc is None, reason="gRPC not importable")
399+
def test_from_grpc_error_warns_if_not_grpc():
400+
try:
401+
from grpc_status import rpc_status
402+
del rpc_status # Unused.
403+
# Warning won't trigger.
404+
return
405+
except ImportError: # pragma: NO COVER
406+
# Proceed to rest of test.
407+
pass
408+
409+
error = mock.create_autospec(grpc.Call, instance=True)
410+
411+
with mock.patch("warnings.warn", autospec=True) as mock_warn:
412+
exceptions.from_grpc_error(error)
413+
mock_warn.assert_called_with(
414+
"Please install grpcio-status to obtain helpful grpc error messages.",
415+
ImportWarning,
416+
)

0 commit comments

Comments
 (0)