TestFakeClient demonstrates how to use a fake client with SharedInformerFactory in tests.
(t *testing.T)
| 31 | |
| 32 | // TestFakeClient demonstrates how to use a fake client with SharedInformerFactory in tests. |
| 33 | func 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 | } |
nothing calls this directly
no test coverage detected