MCPcopy
hub / github.com/kubernetes/client-go / TestFakeClient

Function TestFakeClient

examples/fake-client/main_test.go:33–73  ·  view source on GitHub ↗

TestFakeClient demonstrates how to use a fake client with SharedInformerFactory in tests.

(t *testing.T)

Source from the content-addressed store, hash-verified

31
32// TestFakeClient demonstrates how to use a fake client with SharedInformerFactory in tests.
33func TestFakeClient(t *testing.T) {
34 ctx, cancel := context.WithCancel(context.Background())
35 defer cancel()
36
37 // Create the fake client.
38 client := fake.NewSimpleClientset()
39
40 // We will create an informer that writes added pods to a channel.
41 pods := make(chan *v1.Pod, 1)
42 informers := informers.NewSharedInformerFactory(client, 0)
43 podInformer := informers.Core().V1().Pods().Informer()
44 podInformer.AddEventHandler(&cache.ResourceEventHandlerFuncs{
45 AddFunc: func(obj interface{}) {
46 pod := obj.(*v1.Pod)
47 t.Logf("pod added: %s/%s", pod.Namespace, pod.Name)
48 pods <- pod
49 },
50 })
51
52 // Make sure informers are running.
53 informers.Start(ctx.Done())
54
55 // This is not required in tests, but it serves as a proof-of-concept by
56 // ensuring that the informer goroutine have warmed up and called List before
57 // we send any events to it.
58 cache.WaitForCacheSync(ctx.Done(), podInformer.HasSynced)
59
60 // Inject an event into the fake client.
61 p := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "my-pod"}}
62 _, err := client.CoreV1().Pods("test-ns").Create(p)
63 if err != nil {
64 t.Fatalf("error injecting pod add: %v", err)
65 }
66
67 select {
68 case pod := <-pods:
69 t.Logf("Got pod from channel: %s/%s", pod.Namespace, pod.Name)
70 case <-time.After(wait.ForeverTestTimeout):
71 t.Error("Informer did not get the added pod")
72 }
73}

Callers

nothing calls this directly

Calls 13

CoreMethod · 0.95
StartMethod · 0.95
NewSimpleClientsetFunction · 0.92
WaitForCacheSyncFunction · 0.92
InformerMethod · 0.65
PodsMethod · 0.65
V1Method · 0.65
AddEventHandlerMethod · 0.65
LogfMethod · 0.65
DoneMethod · 0.65
CreateMethod · 0.65
CoreV1Method · 0.65

Tested by

no test coverage detected