From 166eefb2ed939b7babd008d7e8dc5b7a322e630d Mon Sep 17 00:00:00 2001 From: Quentin Smith Date: Tue, 24 Sep 2024 15:43:20 -0400 Subject: [PATCH] Improve test coverage by correctly simulating a non-GKE GCE VM --- detectors/gcp/detector_test.go | 14 ++++++++++++-- detectors/gcp/utils_test.go | 8 +++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/detectors/gcp/detector_test.go b/detectors/gcp/detector_test.go index 705bcf0c3..16a5f5e7e 100644 --- a/detectors/gcp/detector_test.go +++ b/detectors/gcp/detector_test.go @@ -43,7 +43,11 @@ func TestCloudPlatformAppEngineStandard(t *testing.T) { } func TestCloudPlatformGKE(t *testing.T) { - d := NewTestDetector(&FakeMetadataProvider{}, &FakeOSProvider{ + d := NewTestDetector(&FakeMetadataProvider{ + InstanceAttributes: map[string]string{ + clusterNameMetadataAttr: "cluster-name", + }, + }, &FakeOSProvider{ Vars: map[string]string{ k8sServiceHostEnv: "foo", }, @@ -53,12 +57,18 @@ func TestCloudPlatformGKE(t *testing.T) { } func TestCloudPlatformK8sNotGKE(t *testing.T) { - d := NewTestDetector(&FakeMetadataProvider{Err: fmt.Errorf("foo")}, &FakeOSProvider{ + d := NewTestDetector(&FakeMetadataProvider{}, &FakeOSProvider{ Vars: map[string]string{ k8sServiceHostEnv: "foo", }, }) platform := d.CloudPlatform() + assert.Equal(t, platform, GCE) +} + +func TestCloudPlatformUnknown(t *testing.T) { + d := NewTestDetector(&FakeMetadataProvider{Err: fmt.Errorf("no metadata server")}, &FakeOSProvider{}) + platform := d.CloudPlatform() assert.Equal(t, platform, UnknownPlatform) } diff --git a/detectors/gcp/utils_test.go b/detectors/gcp/utils_test.go index 212c44180..28417725f 100644 --- a/detectors/gcp/utils_test.go +++ b/detectors/gcp/utils_test.go @@ -14,6 +14,8 @@ package gcp +import "cloud.google.com/go/compute/metadata" + func NewTestDetector(metadata *FakeMetadataProvider, os *FakeOSProvider) *Detector { return &Detector{metadata: metadata, os: os} } @@ -69,7 +71,11 @@ func (f *FakeMetadataProvider) InstanceAttributeValue(s string) (string, error) if f.Err != nil { return "", f.Err } - return f.InstanceAttributes[s], nil + value, ok := f.InstanceAttributes[s] + if ok { + return value, nil + } + return "", metadata.NotDefinedError(s) } type FakeOSProvider struct {