k8s.io/kubernetes@v1.29.3/pkg/controller/certificates/rootcacertpublisher/metrics_test.go (about) 1 /* 2 Copyright 2020 The Kubernetes 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 rootcacertpublisher 18 19 import ( 20 "errors" 21 "strings" 22 "testing" 23 "time" 24 25 corev1 "k8s.io/api/core/v1" 26 apierrors "k8s.io/apimachinery/pkg/api/errors" 27 "k8s.io/component-base/metrics/legacyregistry" 28 "k8s.io/component-base/metrics/testutil" 29 ) 30 31 func TestSyncCounter(t *testing.T) { 32 testCases := []struct { 33 desc string 34 err error 35 metrics []string 36 want string 37 }{ 38 { 39 desc: "nil error", 40 err: nil, 41 metrics: []string{ 42 "root_ca_cert_publisher_sync_total", 43 }, 44 want: ` 45 # HELP root_ca_cert_publisher_sync_total [ALPHA] Number of namespace syncs happened in root ca cert publisher. 46 # TYPE root_ca_cert_publisher_sync_total counter 47 root_ca_cert_publisher_sync_total{code="200"} 1 48 `, 49 }, 50 { 51 desc: "kube api error", 52 err: apierrors.NewNotFound(corev1.Resource("configmap"), "test-configmap"), 53 metrics: []string{ 54 "root_ca_cert_publisher_sync_total", 55 }, 56 want: ` 57 # HELP root_ca_cert_publisher_sync_total [ALPHA] Number of namespace syncs happened in root ca cert publisher. 58 # TYPE root_ca_cert_publisher_sync_total counter 59 root_ca_cert_publisher_sync_total{code="404"} 1 60 `, 61 }, 62 { 63 desc: "kube api error without code", 64 err: &apierrors.StatusError{}, 65 metrics: []string{ 66 "root_ca_cert_publisher_sync_total", 67 }, 68 want: ` 69 # HELP root_ca_cert_publisher_sync_total [ALPHA] Number of namespace syncs happened in root ca cert publisher. 70 # TYPE root_ca_cert_publisher_sync_total counter 71 root_ca_cert_publisher_sync_total{code="500"} 1 72 `, 73 }, 74 { 75 desc: "general error", 76 err: errors.New("test"), 77 metrics: []string{ 78 "root_ca_cert_publisher_sync_total", 79 }, 80 want: ` 81 # HELP root_ca_cert_publisher_sync_total [ALPHA] Number of namespace syncs happened in root ca cert publisher. 82 # TYPE root_ca_cert_publisher_sync_total counter 83 root_ca_cert_publisher_sync_total{code="500"} 1 84 `, 85 }, 86 } 87 88 for _, tc := range testCases { 89 t.Run(tc.desc, func(t *testing.T) { 90 recordMetrics(time.Now(), tc.err) 91 defer syncCounter.Reset() 92 if err := testutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(tc.want), tc.metrics...); err != nil { 93 t.Fatal(err) 94 } 95 }) 96 } 97 }