1/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package certificates
18
19import (
20	"context"
21	"testing"
22	"time"
23
24	certificates "k8s.io/api/certificates/v1"
25	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
26	"k8s.io/apimachinery/pkg/util/wait"
27	"k8s.io/client-go/informers"
28	"k8s.io/client-go/kubernetes/fake"
29	"k8s.io/kubernetes/pkg/controller"
30)
31
32// TODO flesh this out to cover things like not being able to find the csr in the cache, not
33// auto-approving, etc.
34func TestCertificateController(t *testing.T) {
35
36	csr := &certificates.CertificateSigningRequest{
37		ObjectMeta: metav1.ObjectMeta{
38			Name: "test-csr",
39		},
40	}
41
42	client := fake.NewSimpleClientset(csr)
43	informerFactory := informers.NewSharedInformerFactory(fake.NewSimpleClientset(csr), controller.NoResyncPeriodFunc())
44
45	handler := func(csr *certificates.CertificateSigningRequest) error {
46		csr.Status.Conditions = append(csr.Status.Conditions, certificates.CertificateSigningRequestCondition{
47			Type:    certificates.CertificateApproved,
48			Reason:  "test reason",
49			Message: "test message",
50		})
51		_, err := client.CertificatesV1().CertificateSigningRequests().UpdateApproval(context.TODO(), csr.Name, csr, metav1.UpdateOptions{})
52		if err != nil {
53			return err
54		}
55		return nil
56	}
57
58	controller := NewCertificateController(
59		"test",
60		client,
61		informerFactory.Certificates().V1().CertificateSigningRequests(),
62		handler,
63	)
64	controller.csrsSynced = func() bool { return true }
65
66	stopCh := make(chan struct{})
67	defer close(stopCh)
68	informerFactory.Start(stopCh)
69	informerFactory.WaitForCacheSync(stopCh)
70	wait.PollUntil(10*time.Millisecond, func() (bool, error) {
71		return controller.queue.Len() >= 1, nil
72	}, stopCh)
73
74	controller.processNextWorkItem()
75
76	actions := client.Actions()
77	if len(actions) != 1 {
78		t.Errorf("expected 1 actions")
79	}
80	if a := actions[0]; !a.Matches("update", "certificatesigningrequests") ||
81		a.GetSubresource() != "approval" {
82		t.Errorf("unexpected action: %#v", a)
83	}
84
85}
86