| // Copyright 2021 Google LLC |
| // |
| // Licensed under the Apache License, Version 2.0 (the "License"); |
| // you may not use this file except in compliance with the License. |
| // You may obtain a copy of the License at |
| // |
| // http://www.apache.org/licenses/LICENSE-2.0 |
| // |
| // Unless required by applicable law or agreed to in writing, software |
| // distributed under the License is distributed on an "AS IS" BASIS, |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| // See the License for the specific language governing permissions and |
| // limitations under the License. |
| |
| package fakes |
| |
| import ( |
| "cloud.google.com/go/compute/metadata" |
| "fmt" |
| "testing" |
| ) |
| |
| // Tests that all metadata keys are parsed and applied correctly. |
| func TestMetadataKeysHandler(t *testing.T) { |
| tests := []struct { |
| // Name of the test case |
| name string |
| // Key:Value pairs present in metadata. |
| metadata map[string]string |
| // Expected metadataKeys to be returned |
| expectedMetadataKeys []string |
| }{ |
| { |
| "NoMetadataKeys", |
| map[string]string{}, |
| []string{""}, |
| }, |
| { |
| "UpdateStrategyPresent", |
| map[string]string{"update-strategy": "update-strategy-1"}, |
| []string{"update-strategy"}, |
| }, |
| { |
| "TwoKeysPresent", |
| map[string]string{"cos-update-strategy": "update-strategy-1", |
| "google-logging-enabled": "true"}, |
| []string{"cos-update-strategy", "google-logging-enabled"}, |
| }, |
| } |
| |
| for _, test := range tests { |
| t.Run(test.name, func(t *testing.T) { |
| fakeMetadata := NewMetadataServer() |
| fakeMetadata.Metadata = test.metadata |
| defer fakeMetadata.Server.Close() |
| if res, _ := metadata.InstanceAttributes(); len(res) != len(test.expectedMetadataKeys) { |
| fmt.Printf("%v", test.expectedMetadataKeys) |
| t.Errorf("FAILED '%s': got %v, expect %v", |
| test.name, res, test.expectedMetadataKeys) |
| } else { |
| for _, val := range res { |
| if metadataVal, _ := metadata.InstanceAttributeValue(val); metadataVal != test.metadata[val] { |
| t.Errorf("FAILED '%s': got %v, expect %v", |
| test.name, metadataVal, test.metadata[val]) |
| } |
| } |
| } |
| }) |
| } |
| } |