github.com/kiali/kiali@v1.84.0/business/testing.go (about) 1 package business 2 3 /* 4 This file contains helper methods for unit testing with the business package. 5 The utilities in this file are not meant to be used outside of unit tests. 6 */ 7 8 import ( 9 "testing" 10 11 "golang.org/x/exp/slices" 12 13 "github.com/kiali/kiali/config" 14 "github.com/kiali/kiali/kubernetes" 15 "github.com/kiali/kiali/kubernetes/cache" 16 "github.com/kiali/kiali/kubernetes/kubetest" 17 "github.com/kiali/kiali/prometheus" 18 ) 19 20 // SetWithBackends allows for specifying the ClientFactory and Prometheus clients to be used. 21 // Mock friendly. Used only with tests. 22 func setWithBackends(cf kubernetes.ClientFactory, prom prometheus.ClientInterface, cache cache.KialiCache, cpm ControlPlaneMonitor) { 23 clientFactory = cf 24 prometheusClient = prom 25 kialiCache = cache 26 poller = cpm 27 } 28 29 // SetupBusinessLayer mocks out some global variables in the business package 30 // such as the kiali cache and the prometheus client. 31 func SetupBusinessLayer(t *testing.T, k8s kubernetes.ClientInterface, config config.Config) cache.KialiCache { 32 t.Helper() 33 34 cf := kubetest.NewK8SClientFactoryMock(k8s) 35 36 cache := cache.NewTestingCacheWithFactory(t, cf, config) 37 38 originalClientFactory := clientFactory 39 originalPrometheusClient := prometheusClient 40 originalKialiCache := kialiCache 41 t.Cleanup(func() { 42 clientFactory = originalClientFactory 43 prometheusClient = originalPrometheusClient 44 kialiCache = originalKialiCache 45 }) 46 47 cpm := &FakeControlPlaneMonitor{} 48 49 setWithBackends(cf, nil, cache, cpm) 50 return cache 51 } 52 53 // WithProm is a testing func that lets you replace the global prom client var. 54 func WithProm(prom prometheus.ClientInterface) { 55 prometheusClient = prom 56 } 57 58 // WithKialiCache is a testing func that lets you replace the global cache var. 59 func WithKialiCache(cache cache.KialiCache) { 60 kialiCache = cache 61 } 62 63 // WithControlPlaneMonitor is a testing func that lets you replace the global cpm var. 64 func WithControlPlaneMonitor(cpm ControlPlaneMonitor) { 65 poller = cpm 66 } 67 68 // FindOrFail will find an element in a slice or fail the test. 69 func FindOrFail[T any](t *testing.T, s []T, f func(T) bool) T { 70 t.Helper() 71 idx := slices.IndexFunc(s, f) 72 if idx == -1 { 73 t.Fatal("Element not in slice") 74 } 75 return s[idx] 76 }