Skip to content

Commit 8deb2be

Browse files
committed
Fixed mock server tests
1 parent f9b4823 commit 8deb2be

File tree

5 files changed

+54
-52
lines changed

5 files changed

+54
-52
lines changed

google/cloud/spanner_v1/metrics/metrics_exporter.py

Lines changed: 22 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
)
2424

2525
import logging
26-
from typing import Optional, List, Union, NoReturn, Tuple
26+
from typing import Optional, List, Union, NoReturn, Tuple, Dict
2727

2828
import google.auth
2929
from google.api.distribution_pb2 import ( # pylint: disable=no-name-in-module
@@ -39,10 +39,6 @@
3939
MonitoredResource,
4040
)
4141

42-
from google.cloud.monitoring_v3.services.metric_service.transports.grpc import (
43-
MetricServiceGrpcTransport,
44-
)
45-
4642
# pylint: disable=no-name-in-module
4743
from google.protobuf.timestamp_pb2 import Timestamp
4844
from google.cloud.spanner_v1.gapic_version import __version__
@@ -60,12 +56,9 @@
6056
Sum,
6157
)
6258
from opentelemetry.sdk.resources import Resource
63-
64-
HAS_OPENTELEMETRY_INSTALLED = True
65-
except ImportError: # pragma: NO COVER
66-
HAS_OPENTELEMETRY_INSTALLED = False
67-
68-
try:
59+
from google.cloud.monitoring_v3.services.metric_service.transports.grpc import (
60+
MetricServiceGrpcTransport,
61+
)
6962
from google.cloud.monitoring_v3 import (
7063
CreateTimeSeriesRequest,
7164
MetricServiceClient,
@@ -75,13 +68,10 @@
7568
TypedValue,
7669
)
7770

78-
HAS_GOOGLE_CLOUD_MONITORING_INSTALLED = True
79-
except ImportError:
80-
HAS_GOOGLE_CLOUD_MONITORING_INSTALLED = False
81-
82-
HAS_DEPENDENCIES_INSTALLED = (
83-
HAS_OPENTELEMETRY_INSTALLED and HAS_GOOGLE_CLOUD_MONITORING_INSTALLED
84-
)
71+
HAS_OPENTELEMETRY_INSTALLED = True
72+
except ImportError: # pragma: NO COVER
73+
HAS_OPENTELEMETRY_INSTALLED = False
74+
MetricExporter = object
8575

8676
logger = logging.getLogger(__name__)
8777
MAX_BATCH_WRITE = 200
@@ -120,7 +110,7 @@ class CloudMonitoringMetricsExporter(MetricExporter):
120110
def __init__(
121111
self,
122112
project_id: Optional[str] = None,
123-
client: Optional[MetricServiceClient] = None,
113+
client: Optional["MetricServiceClient"] = None,
124114
):
125115
"""Initialize a custom exporter to send metrics for the Spanner Service Metrics."""
126116
# Default preferred_temporality is all CUMULATIVE so need to customize
@@ -144,7 +134,7 @@ def __init__(
144134
self.project_id = project_id
145135
self.project_name = self.client.common_project_path(self.project_id)
146136

147-
def _batch_write(self, series: List[TimeSeries], timeout_millis: float) -> None:
137+
def _batch_write(self, series: List["TimeSeries"], timeout_millis: float) -> None:
148138
"""Cloud Monitoring allows writing up to 200 time series at once.
149139
150140
:param series: ProtoBuf TimeSeries
@@ -166,8 +156,8 @@ def _batch_write(self, series: List[TimeSeries], timeout_millis: float) -> None:
166156

167157
@staticmethod
168158
def _resource_to_monitored_resource_pb(
169-
resource: Resource, labels: any
170-
) -> MonitoredResource:
159+
resource: "Resource", labels: Dict[str, str]
160+
) -> "MonitoredResource":
171161
"""
172162
Convert the resource to a Google Cloud Monitoring monitored resource.
173163
@@ -182,7 +172,7 @@ def _resource_to_monitored_resource_pb(
182172
return monitored_resource
183173

184174
@staticmethod
185-
def _to_metric_kind(metric: Metric) -> MetricDescriptor.MetricKind:
175+
def _to_metric_kind(metric: "Metric") -> MetricDescriptor.MetricKind:
186176
"""
187177
Convert the metric to a Google Cloud Monitoring metric kind.
188178
@@ -210,7 +200,7 @@ def _to_metric_kind(metric: Metric) -> MetricDescriptor.MetricKind:
210200

211201
@staticmethod
212202
def _extract_metric_labels(
213-
data_point: Union[NumberDataPoint, HistogramDataPoint]
203+
data_point: Union["NumberDataPoint", "HistogramDataPoint"]
214204
) -> Tuple[dict, dict]:
215205
"""
216206
Extract the metric labels from the data point.
@@ -233,8 +223,8 @@ def _extract_metric_labels(
233223
@staticmethod
234224
def _to_point(
235225
kind: "MetricDescriptor.MetricKind.V",
236-
data_point: Union[NumberDataPoint, HistogramDataPoint],
237-
) -> Point:
226+
data_point: Union["NumberDataPoint", "HistogramDataPoint"],
227+
) -> "Point":
238228
# Create a Google Cloud Monitoring data point value based on the OpenTelemetry metric data point type
239229
## For histograms, we need to calculate the mean and bucket counts
240230
if isinstance(data_point, HistogramDataPoint):
@@ -281,7 +271,7 @@ def _data_point_to_timeseries_pb(
281271
metric,
282272
monitored_resource,
283273
labels,
284-
) -> TimeSeries:
274+
) -> "TimeSeries":
285275
"""
286276
Convert the data point to a Google Cloud Monitoring time series.
287277
@@ -308,8 +298,8 @@ def _data_point_to_timeseries_pb(
308298

309299
@staticmethod
310300
def _resource_metrics_to_timeseries_pb(
311-
metrics_data: MetricsData,
312-
) -> List[TimeSeries]:
301+
metrics_data: "MetricsData",
302+
) -> List["TimeSeries"]:
313303
"""
314304
Convert the metrics data to a list of Google Cloud Monitoring time series.
315305
@@ -346,18 +336,18 @@ def _resource_metrics_to_timeseries_pb(
346336

347337
def export(
348338
self,
349-
metrics_data: MetricsData,
339+
metrics_data: "MetricsData",
350340
timeout_millis: float = 10_000,
351341
**kwargs,
352-
) -> MetricExportResult:
342+
) -> "MetricExportResult":
353343
"""
354344
Export the metrics data to Google Cloud Monitoring.
355345
356346
:param metrics_data: OpenTelemetry metrics data
357347
:param timeout_millis: timeout in milliseconds
358348
:return: MetricExportResult
359349
"""
360-
if not HAS_DEPENDENCIES_INSTALLED:
350+
if not HAS_OPENTELEMETRY_INSTALLED:
361351
logger.warning("Metric exporter called without dependencies installed.")
362352
return False
363353

google/cloud/spanner_v1/metrics/metrics_tracer.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ def client_attributes(self) -> Dict[str, str]:
251251
return self._client_attributes
252252

253253
@property
254-
def instrument_attempt_counter(self) -> Counter:
254+
def instrument_attempt_counter(self) -> "Counter":
255255
"""
256256
Return the instrument for counting attempts.
257257
@@ -264,7 +264,7 @@ def instrument_attempt_counter(self) -> Counter:
264264
return self._instrument_attempt_counter
265265

266266
@property
267-
def instrument_attempt_latency(self) -> Histogram:
267+
def instrument_attempt_latency(self) -> "Histogram":
268268
"""
269269
Return the instrument for measuring attempt latency.
270270
@@ -277,7 +277,7 @@ def instrument_attempt_latency(self) -> Histogram:
277277
return self._instrument_attempt_latency
278278

279279
@property
280-
def instrument_operation_counter(self) -> Counter:
280+
def instrument_operation_counter(self) -> "Counter":
281281
"""
282282
Return the instrument for counting operations.
283283
@@ -290,7 +290,7 @@ def instrument_operation_counter(self) -> Counter:
290290
return self._instrument_operation_counter
291291

292292
@property
293-
def instrument_operation_latency(self) -> Histogram:
293+
def instrument_operation_latency(self) -> "Histogram":
294294
"""
295295
Return the instrument for measuring operation latency.
296296

google/cloud/spanner_v1/metrics/metrics_tracer_factory.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,26 +50,26 @@ class MetricsTracerFactory:
5050
"""Factory class for creating MetricTracer instances. This class facilitates the creation of MetricTracer objects, which are responsible for collecting and tracing metrics."""
5151

5252
enabled: bool
53-
_instrument_attempt_latency: Histogram
54-
_instrument_attempt_counter: Counter
55-
_instrument_operation_latency: Histogram
56-
_instrument_operation_counter: Counter
53+
_instrument_attempt_latency: "Histogram"
54+
_instrument_attempt_counter: "Counter"
55+
_instrument_operation_latency: "Histogram"
56+
_instrument_operation_counter: "Counter"
5757
_client_attributes: Dict[str, str]
5858

5959
@property
60-
def instrument_attempt_latency(self) -> Histogram:
60+
def instrument_attempt_latency(self) -> "Histogram":
6161
return self._instrument_attempt_latency
6262

6363
@property
64-
def instrument_attempt_counter(self) -> Counter:
64+
def instrument_attempt_counter(self) -> "Counter":
6565
return self._instrument_attempt_counter
6666

6767
@property
68-
def instrument_operation_latency(self) -> Histogram:
68+
def instrument_operation_latency(self) -> "Histogram":
6969
return self._instrument_operation_latency
7070

7171
@property
72-
def instrument_operation_counter(self) -> Counter:
72+
def instrument_operation_counter(self) -> "Counter":
7373
return self._instrument_operation_counter
7474

7575
def __init__(self, enabled: bool, service_name: str):

google/cloud/spanner_v1/metrics/spanner_metrics_tracer_factory.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,18 @@
2323
GOOGLE_CLOUD_REGION_KEY,
2424
GOOGLE_CLOUD_REGION_GLOBAL,
2525
)
26-
from opentelemetry.resourcedetector.gcp_resource_detector import (
27-
GoogleCloudResourceDetector,
28-
)
26+
27+
try:
28+
from opentelemetry.resourcedetector.gcp_resource_detector import (
29+
GoogleCloudResourceDetector,
30+
)
31+
import mmh3
32+
HAS_OPENTELEMETRY_INSTALLED = True
33+
except ImportError: # pragma: NO COVER
34+
HAS_OPENTELEMETRY_INSTALLED = False
35+
2936
from .metrics_tracer import MetricsTracer
3037
from google.cloud.spanner_v1 import __version__
31-
import mmh3
3238
from uuid import uuid4
3339

3440

@@ -105,6 +111,8 @@ def _generate_client_hash(client_uid: str) -> str:
105111
@staticmethod
106112
def _get_location() -> str:
107113
"""Get the location of the resource."""
114+
if not HAS_OPENTELEMETRY_INSTALLED:
115+
return GOOGLE_CLOUD_REGION_GLOBAL
108116
detector = GoogleCloudResourceDetector()
109117
resources = detector.detect()
110118
if GOOGLE_CLOUD_REGION_KEY not in resources.attributes:

tests/mockserver_tests/test_tags.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -181,10 +181,14 @@ def test_request_tag_is_cleared(self):
181181
# This query will not have a request tag.
182182
cursor.execute("select name from singers")
183183
requests = self.spanner_service.requests
184-
self.assertTrue(isinstance(requests[1], ExecuteSqlRequest))
185-
self.assertTrue(isinstance(requests[2], ExecuteSqlRequest))
186-
self.assertEqual("my_tag", requests[1].request_options.request_tag)
187-
self.assertEqual("", requests[2].request_options.request_tag)
184+
185+
# Filter for SQL requests calls
186+
sql_requests = [request for request in requests if isinstance(request, ExecuteSqlRequest)]
187+
188+
self.assertTrue(isinstance(sql_requests[0], ExecuteSqlRequest))
189+
self.assertTrue(isinstance(sql_requests[1], ExecuteSqlRequest))
190+
self.assertEqual("my_tag", sql_requests[0].request_options.request_tag)
191+
self.assertEqual("", sql_requests[1].request_options.request_tag)
188192

189193
def _execute_and_verify_select_singers(
190194
self, connection: Connection, request_tag: str = "", transaction_tag: str = ""

0 commit comments

Comments
 (0)