knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/observability/metrics/config_test.go (about) 1 /* 2 Copyright 2025 The Knative Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package metrics 18 19 import ( 20 "testing" 21 "time" 22 23 "github.com/google/go-cmp/cmp" 24 ) 25 26 func TestNewFromMap(t *testing.T) { 27 got, err := NewFromMap(nil) 28 want := DefaultConfig() 29 30 if err != nil { 31 t.Error("unexpected error:", err) 32 } 33 34 if diff := cmp.Diff(want, got); diff != "" { 35 t.Error("unexpected diff (-want +got): ", diff) 36 } 37 } 38 39 func TestNewFromMapBadInput(t *testing.T) { 40 cases := []struct { 41 name string 42 m map[string]string 43 }{{ 44 name: "unexpected endpoint set", 45 m: map[string]string{"metrics-endpoint": "https://blah.example.com"}, 46 }, { 47 name: "missing endpoint", 48 m: map[string]string{"metrics-protocol": "grpc"}, 49 }, { 50 name: "unsupported protocol", 51 m: map[string]string{"metrics-protocol": "bad-protocol"}, 52 }, { 53 name: "bad export interval - negative number", 54 m: map[string]string{"metrics-export-interval": "-1s"}, 55 }, { 56 name: "bad export interval - not an integer", 57 m: map[string]string{"metrics-export-interval": "bad-interval"}, 58 }} 59 60 for _, tc := range cases { 61 t.Run(tc.name, func(t *testing.T) { 62 if _, err := NewFromMap(tc.m); err == nil { 63 t.Error("expected an error") 64 } 65 }) 66 } 67 } 68 69 func TestNewFromMapWithPrefix(t *testing.T) { 70 got, err := NewFromMapWithPrefix("request-", map[string]string{ 71 "request-metrics-protocol": ProtocolGRPC, 72 "request-metrics-endpoint": "https://blah.example.com", 73 "request-metrics-export-interval": "15s", 74 }) 75 if err != nil { 76 t.Error("unexpected error", err) 77 } 78 79 want := Config{ 80 Protocol: ProtocolGRPC, 81 Endpoint: "https://blah.example.com", 82 ExportInterval: 15 * time.Second, 83 } 84 85 if diff := cmp.Diff(want, got); diff != "" { 86 t.Error("unexpected diff (-want +got): ", diff) 87 } 88 }