|
| 1 | +package servicecacertpublisher |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "strings" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | + |
| 9 | + corev1 "k8s.io/api/core/v1" |
| 10 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 11 | + "k8s.io/component-base/metrics/legacyregistry" |
| 12 | + "k8s.io/component-base/metrics/testutil" |
| 13 | +) |
| 14 | + |
| 15 | +func TestSyncCounter(t *testing.T) { |
| 16 | + testCases := []struct { |
| 17 | + desc string |
| 18 | + err error |
| 19 | + metrics []string |
| 20 | + want string |
| 21 | + }{ |
| 22 | + { |
| 23 | + desc: "nil error", |
| 24 | + err: nil, |
| 25 | + metrics: []string{ |
| 26 | + "service_ca_cert_publisher_sync_total", |
| 27 | + }, |
| 28 | + want: ` |
| 29 | +# HELP service_ca_cert_publisher_sync_total [ALPHA] Number of namespace syncs happened in service ca cert publisher. |
| 30 | +# TYPE service_ca_cert_publisher_sync_total counter |
| 31 | +service_ca_cert_publisher_sync_total{code="200"} 1 |
| 32 | + `, |
| 33 | + }, |
| 34 | + { |
| 35 | + desc: "kube api error", |
| 36 | + err: apierrors.NewNotFound(corev1.Resource("configmap"), "test-configmap"), |
| 37 | + metrics: []string{ |
| 38 | + "service_ca_cert_publisher_sync_total", |
| 39 | + }, |
| 40 | + want: ` |
| 41 | +# HELP service_ca_cert_publisher_sync_total [ALPHA] Number of namespace syncs happened in service ca cert publisher. |
| 42 | +# TYPE service_ca_cert_publisher_sync_total counter |
| 43 | +service_ca_cert_publisher_sync_total{code="404"} 1 |
| 44 | + `, |
| 45 | + }, |
| 46 | + { |
| 47 | + desc: "kube api error without code", |
| 48 | + err: &apierrors.StatusError{}, |
| 49 | + metrics: []string{ |
| 50 | + "service_ca_cert_publisher_sync_total", |
| 51 | + }, |
| 52 | + want: ` |
| 53 | +# HELP service_ca_cert_publisher_sync_total [ALPHA] Number of namespace syncs happened in service ca cert publisher. |
| 54 | +# TYPE service_ca_cert_publisher_sync_total counter |
| 55 | +service_ca_cert_publisher_sync_total{code="500"} 1 |
| 56 | + `, |
| 57 | + }, |
| 58 | + { |
| 59 | + desc: "general error", |
| 60 | + err: errors.New("test"), |
| 61 | + metrics: []string{ |
| 62 | + "service_ca_cert_publisher_sync_total", |
| 63 | + }, |
| 64 | + want: ` |
| 65 | +# HELP service_ca_cert_publisher_sync_total [ALPHA] Number of namespace syncs happened in service ca cert publisher. |
| 66 | +# TYPE service_ca_cert_publisher_sync_total counter |
| 67 | +service_ca_cert_publisher_sync_total{code="500"} 1 |
| 68 | + `, |
| 69 | + }, |
| 70 | + } |
| 71 | + |
| 72 | + for _, tc := range testCases { |
| 73 | + t.Run(tc.desc, func(t *testing.T) { |
| 74 | + recordMetrics(time.Now(), "test-ns", tc.err) |
| 75 | + defer syncCounter.Reset() |
| 76 | + if err := testutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(tc.want), tc.metrics...); err != nil { |
| 77 | + t.Fatal(err) |
| 78 | + } |
| 79 | + }) |
| 80 | + } |
| 81 | +} |
0 commit comments