kubectl-persistent-logger/logs/watcher_test.go

71 lines
1.8 KiB
Go

package logs_test
import (
"bytes"
"context"
"testing"
"time"
"git.netflux.io/rob/kubectl-persistent-logger/logs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
testclient "k8s.io/client-go/kubernetes/fake"
k8stest "k8s.io/client-go/testing"
)
func TestWatcher(t *testing.T) {
clientset := testclient.NewSimpleClientset(
&appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "mydeployment",
Namespace: "default",
},
Spec: appsv1.DeploymentSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{"mylabelname": "mylabelvalue"},
},
},
},
)
k8swatcher := watch.NewFake()
clientset.PrependWatchReactor("pods", k8stest.DefaultWatchReactor(k8swatcher, nil))
pods := []*corev1.Pod{
{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"},
Status: corev1.PodStatus{Phase: corev1.PodRunning},
},
{
ObjectMeta: metav1.ObjectMeta{Name: "bar", Namespace: "default"},
Status: corev1.PodStatus{Phase: corev1.PodRunning},
},
{
ObjectMeta: metav1.ObjectMeta{Name: "baz", Namespace: "default"},
Status: corev1.PodStatus{Phase: corev1.PodPending},
},
}
go func() {
defer k8swatcher.Stop()
for _, pod := range pods {
time.Sleep(time.Millisecond * 300)
k8swatcher.Add(pod)
}
}()
client := logs.KubernetesClient{Interface: clientset}
var buf bytes.Buffer
watcher := logs.NewWatcher("mydeployment", client, &buf)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err := watcher.Watch(ctx)
require.EqualError(t, err, context.DeadlineExceeded.Error())
assert.Equal(t, "[foo] fake logs\n[bar] fake logs\n", buf.String())
}