Skip to content

Instantly share code, notes, and snippets.

@dtaniwaki
Last active March 12, 2020 12:04
Show Gist options
  • Save dtaniwaki/3e460579005a1051927b3dba86816ad6 to your computer and use it in GitHub Desktop.
Save dtaniwaki/3e460579005a1051927b3dba86816ad6 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"testing"
"time"
"github.com/ghodss/yaml"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
samplecontroller "k8s.io/sample-controller/pkg/apis/samplecontroller/v1alpha1"
"k8s.io/sample-controller/pkg/generated/clientset/versioned/fake"
informers "k8s.io/sample-controller/pkg/generated/informers/externalversions"
)
var (
noResyncPeriodFunc = func() time.Duration { return 0 }
)
var testFooYaml = `
apiVersion: samplecontroller/v1alpha1
kind: Foo
metadata:
name: test-foo
spec:
`
func TestListAndGet(t *testing.T) {
clientset := fake.NewSimpleClientset()
informerFactory := informers.NewSharedInformerFactory(clientset, noResyncPeriodFunc())
informer := informerFactory.Samplecontroller().V1alpha1().Foos()
ctx := context.Background()
go informer.Informer().Run(ctx.Done())
if !cache.WaitForCacheSync(ctx.Done(), informer.Informer().HasSynced) {
t.Fatal("Timed out waiting for caches to sync")
}
testFoo := unmarshalFoo(testFooYaml)
_, err := clientset.SamplecontrollerV1alpha1().Foos("").Create(ctx, testFoo, metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
expectedFooNames := []string{"test-foo"}
fooNames := []string{}
foosList, err := clientset.SamplecontrollerV1alpha1().Foos("").List(ctx, metav1.ListOptions{})
if err != nil {
t.Fatal(err)
}
for _, foo := range foosList.Items {
fooNames = append(fooNames, foo.Name)
}
if compareStringSlices(fooNames, expectedFooNames) {
t.Errorf("%v is not %v", fooNames, expectedFooNames)
}
_, err = clientset.SamplecontrollerV1alpha1().Foos("").Get(ctx, "test-foo", metav1.GetOptions{})
if err != nil {
t.Fatal(err)
}
fooNames = []string{}
foos, err := informer.Lister().Foos("").List(labels.Everything())
if err != nil {
t.Fatal(err)
}
for _, foo := range foos {
fooNames = append(fooNames, foo.Name)
}
if compareStringSlices(fooNames, expectedFooNames) {
t.Errorf("%v is not %v", fooNames, expectedFooNames)
}
_, err = informer.Lister().Foos("").Get("test-foo")
if err != nil {
t.Fatal(err)
}
}
func compareStringSlices(a, b []string) bool {
m1, _ := yaml.Marshal(a)
m2, _ := yaml.Marshal(b)
return string(m1) != string(m2)
}
func unmarshalFoo(yamlStr string) *samplecontroller.Foo {
var foo samplecontroller.Foo
err := yaml.Unmarshal([]byte(yamlStr), &foo)
if err != nil {
panic(err)
}
return &foo
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment