|
13 | 13 | # See the License for the specific language governing permissions and |
14 | 14 | # limitations under the License. |
15 | 15 |
|
| 16 | +import pytest |
| 17 | +import unittest |
| 18 | +from unittest import mock |
| 19 | + |
| 20 | +from google.cloud.spanner_v1.metrics.constants import GOOGLE_CLOUD_REGION_KEY |
16 | 21 | from google.cloud.spanner_v1.metrics.spanner_metrics_tracer_factory import ( |
17 | 22 | SpannerMetricsTracerFactory, |
18 | 23 | ) |
| 24 | +from opentelemetry.sdk.resources import Resource |
| 25 | + |
| 26 | +pytest.importorskip("opentelemetry") |
19 | 27 |
|
20 | 28 |
|
21 | 29 | class TestSpannerMetricsTracerFactory: |
@@ -48,3 +56,42 @@ def test_get_location(self): |
48 | 56 | location = SpannerMetricsTracerFactory._get_location() |
49 | 57 | assert isinstance(location, str) |
50 | 58 | assert location # Simply asserting for non empty as this can change depending on the instance this test runs in. |
| 59 | + |
| 60 | + |
| 61 | +class TestSpannerMetricsTracerFactoryGetLocation(unittest.TestCase): |
| 62 | + @mock.patch( |
| 63 | + "opentelemetry.resourcedetector.gcp_resource_detector.GoogleCloudResourceDetector.detect" |
| 64 | + ) |
| 65 | + def test_get_location_with_region(self, mock_detect): |
| 66 | + """Test that _get_location returns the region when detected.""" |
| 67 | + mock_resource = Resource.create({GOOGLE_CLOUD_REGION_KEY: "us-central1"}) |
| 68 | + mock_detect.return_value = mock_resource |
| 69 | + |
| 70 | + location = SpannerMetricsTracerFactory._get_location() |
| 71 | + assert location == "us-central1" |
| 72 | + |
| 73 | + @mock.patch( |
| 74 | + "opentelemetry.resourcedetector.gcp_resource_detector.GoogleCloudResourceDetector.detect" |
| 75 | + ) |
| 76 | + def test_get_location_without_region(self, mock_detect): |
| 77 | + """Test that _get_location returns 'global' when no region is detected.""" |
| 78 | + mock_resource = Resource.create({}) # No region attribute |
| 79 | + mock_detect.return_value = mock_resource |
| 80 | + |
| 81 | + location = SpannerMetricsTracerFactory._get_location() |
| 82 | + assert location == "global" |
| 83 | + |
| 84 | + @mock.patch( |
| 85 | + "opentelemetry.resourcedetector.gcp_resource_detector.GoogleCloudResourceDetector.detect" |
| 86 | + ) |
| 87 | + def test_get_location_with_exception(self, mock_detect): |
| 88 | + """Test that _get_location returns 'global' and logs a warning on exception.""" |
| 89 | + mock_detect.side_effect = Exception("detector failed") |
| 90 | + |
| 91 | + with self.assertLogs( |
| 92 | + "google.cloud.spanner_v1.metrics.spanner_metrics_tracer_factory", |
| 93 | + level="WARNING", |
| 94 | + ) as log: |
| 95 | + location = SpannerMetricsTracerFactory._get_location() |
| 96 | + assert location == "global" |
| 97 | + self.assertIn("Failed to detect GCP resource location", log.output[0]) |
0 commit comments