| 1 |
/* |
| 2 |
Copyright 2022 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 metrics |
| 18 |
|
| 19 |
import ( |
| 20 |
"math" |
| 21 |
"testing" |
| 22 |
"time" |
| 23 |
|
| 24 |
"k8s.io/component-base/metrics/legacyregistry" |
| 25 |
) |
| 26 |
|
| 27 |
func TestObserveCompilation(t *testing.T) { |
| 28 |
defer legacyregistry.Reset() |
| 29 |
Metrics.ObserveCompilation(2 * time.Second) |
| 30 |
c, s := gatherHistogram(t, "apiserver_cel_compilation_duration_seconds") |
| 31 |
if c != 1 { |
| 32 |
t.Errorf("unexpected count: %v", c) |
| 33 |
} |
| 34 |
if math.Abs(s-2.0) > 1e-7 { |
| 35 |
t.Fatalf("incorrect sum: %v", s) |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
func TestObserveEvaluation(t *testing.T) { |
| 40 |
defer legacyregistry.Reset() |
| 41 |
Metrics.ObserveEvaluation(2 * time.Second) |
| 42 |
c, s := gatherHistogram(t, "apiserver_cel_evaluation_duration_seconds") |
| 43 |
if c != 1 { |
| 44 |
t.Errorf("unexpected count: %v", c) |
| 45 |
} |
| 46 |
if math.Abs(s-2.0) > 1e-7 { |
| 47 |
t.Fatalf("incorrect sum: %v", s) |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
func gatherHistogram(t *testing.T, name string) (count uint64, sum float64) { |
| 52 |
metrics, err := legacyregistry.DefaultGatherer.Gather() |
| 53 |
if err != nil { |
| 54 |
t.Fatalf("Failed to gather metrics: %s", err) |
| 55 |
} |
| 56 |
for _, mf := range metrics { |
| 57 |
if mf.GetName() == name { |
| 58 |
for _, m := range mf.GetMetric() { |
| 59 |
h := m.GetHistogram() |
| 60 |
count += h.GetSampleCount() |
| 61 |
sum += h.GetSampleSum() |
| 62 |
} |
| 63 |
return |
| 64 |
} |
| 65 |
} |
| 66 |
t.Fatalf("metric not found: %v", name) |
| 67 |
return 0, 0 |
| 68 |
} |