Skip to content

Commit

Permalink
squashme: assorted minor readability improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Craig Furman committed Feb 27, 2023
1 parent 6d18896 commit 2b6358e
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 101 deletions.
4 changes: 2 additions & 2 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ type ScanType struct {
}

type Scan struct {
Types []ScanType
Types []ScanType `json:"types"`
// RequeueAfter defines the duration after which an object is requeued when we've visited it.
// Note that due to the event handlers, objects that are being changed will be requeued earlier
// in such cases.
RequeueAfter metav1.Duration
RequeueAfter metav1.Duration `json:"requeueAfter"`
}

// Read reads the config file from the specificied flag "-config" and returns a
Expand Down
198 changes: 99 additions & 99 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,13 @@ import (

"github.com/snyk/kubernetes-scanner/internal/config"
"github.com/snyk/kubernetes-scanner/internal/test"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"

corev1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
)

const (
Expand All @@ -29,12 +28,105 @@ type testObjects struct {
types []config.ScanType
}

func TestController(t *testing.T) {
if testing.Short() {
t.Skip("not running controller tests that spawn API server")
}

ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()

restCfg := test.SetupEnv(t)

c, err := client.New(restCfg, client.Options{Scheme: scheme.Scheme})
if err != nil {
t.Fatalf("could not create client: %v", err)
}
k8sClient := testClient{c}

testObjects := newTestObjects()

cfg := &config.Config{
Scheme: scheme.Scheme,
RestConfig: restCfg,
Scanning: config.Scan{
Types: testObjects.types,
RequeueAfter: metav1.Duration{Duration: time.Second},
},
}
if err := cfg.Validate(); err != nil {
t.Fatalf("error validating config: %v", err)
}

if err := waitForAPI(ctx, c); err != nil {
t.Fatalf("error waiting for API: %v", err)
}

// creating existing resources first to prove that the reconciler also reconciles already
// existing objects.
const initialResources = 1
for _, res := range testObjects.objects[:initialResources] {
if err := k8sClient.Create(ctx, res); err != nil {
t.Fatalf("could not create initial resource: %v", err)
}
}

fb := newFakeBackend()
mgr, err := setupController(cfg, fb)
if err != nil {
t.Fatalf("could not setup controller: %v", err)
}

ctx, cancel = context.WithCancel(ctx)
const timeout = 1500 * time.Millisecond
go func() {
// cancel the context, which is important to stop the manager, once the resources are
// deleted.
defer cancel()
c := time.After(timeout)
// create the rest of the resources which need to be reconciled.
for _, res := range testObjects.objects[initialResources:] {
if err := k8sClient.Create(ctx, res); err != nil {
t.Errorf("could not create resource: %v", err)
}
}

// TODO race against timeout with select in order to speed up the happy path
<-c
if err := deleteResources(ctx, k8sClient, testObjects.objects); err != nil {
t.Errorf("could not delete resources: %v", err)
}
// we need to give the reconciler a bit of time in order to actually record all deletion
// events, before we stop it
time.Sleep(100 * time.Millisecond)
}()

go func() {
// stop our backend to end event collection once the manager has stopped as well.
defer fb.stop()
// mgr.Start returns once ctx is done.
if err := mgr.Start(ctx); err != nil {
t.Errorf("could not start manager: %v", err)
}
}()

events := fb.collectEvents()
// e.g. a requeueAfter of 1s, timeout of 1.5 seconds means we expect 2 reconciliations each;
// the first one immediately after create, and the next one a second later.
numReconciliationLoops := int(timeout/cfg.Scanning.RequeueAfter.Duration) + 1
for _, obj := range testObjects.objects {
if err := checkObject(obj, numReconciliationLoops, events); err != nil {
t.Errorf("%v", err)
}
}
}

func newTestObjects() testObjects {
return testObjects{
objects: []client.Object{
&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Name: "a-pod",
Namespace: "default",
},
TypeMeta: metav1.TypeMeta{
Expand All @@ -50,7 +142,7 @@ func newTestObjects() testObjects {
},
&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "bar",
Name: "pod-with-finalizer",
Namespace: "default",
Finalizers: []string{"yes.com/hello"},
Labels: map[string]string{hasFinalizerLabel: "true"},
Expand All @@ -68,7 +160,7 @@ func newTestObjects() testObjects {
},
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "baz",
Name: "a-secret",
Namespace: "default",
},
TypeMeta: metav1.TypeMeta{
Expand All @@ -79,7 +171,7 @@ func newTestObjects() testObjects {
},
&corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "cm",
Name: "object-we-dont-expect-to-scan",
Namespace: "default",
Labels: map[string]string{expectNoReconcilesLabel: "true"},
},
Expand Down Expand Up @@ -196,98 +288,6 @@ func (r resourceIdentifier) String() string {
)
}

func TestController(t *testing.T) {
if testing.Short() {
t.Skip("not running controller tests that spawn API server")
}

ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()

restCfg := test.SetupEnv(t)

c, err := client.New(restCfg, client.Options{Scheme: scheme.Scheme})
if err != nil {
t.Fatalf("could not create client: %v", err)
}
k8sClient := testClient{c}

testObjects := newTestObjects()

cfg := &config.Config{
Scheme: scheme.Scheme,
RestConfig: restCfg,
Scanning: config.Scan{
Types: testObjects.types,
RequeueAfter: metav1.Duration{Duration: time.Second},
},
}
if err := cfg.Validate(); err != nil {
t.Fatalf("error validating config: %v", err)
}

if err := waitForAPI(ctx, c); err != nil {
t.Fatalf("error waiting for API: %v", err)
}

// creating existing resources first to prove that the reconciler also reconciles already
// existing objects.
const initialResources = 1
for _, res := range testObjects.objects[:initialResources] {
if err := k8sClient.Create(ctx, res); err != nil {
t.Fatalf("could not create initial resource: %v", err)
}
}

fb := newFakeBackend()
mgr, err := setupController(cfg, fb)
if err != nil {
t.Fatalf("could not setup controller: %v", err)
}

ctx, cancel = context.WithCancel(ctx)
const timeout = 1500 * time.Millisecond
go func() {
// cancel the context, which is important to stop the manager, once the resources are
// deleted.
defer cancel()
c := time.After(timeout)
// create the rest of the resources which need to be reconciled.
for _, res := range testObjects.objects[initialResources:] {
if err := k8sClient.Create(ctx, res); err != nil {
t.Errorf("could not create resource: %v", err)
}
}

<-c
if err := deleteResources(ctx, k8sClient, testObjects.objects); err != nil {
t.Errorf("could not delete resources: %v", err)
}
// we need to give the reconciler a bit of time in order to actually record all deletion
// events, before we stop it
time.Sleep(100 * time.Millisecond)
}()

go func() {
// stop our backend to end event collection once the manager has stopped as well.
defer fb.stop()
// mgr.Start returns once ctx is done.
if err := mgr.Start(ctx); err != nil {
t.Errorf("could not start manager: %v", err)
}
}()

events := fb.collectEvents()
// e.g. a requeueAfter of 1s, timeout of 1.5 seconds means we expect 2 reconciliations each;
// the first one immediately after create, and the next one a second later.
numReconciliationLoops := int(timeout/cfg.Scanning.RequeueAfter.Duration) + 1
for _, obj := range testObjects.objects {
if err := checkObject(obj, numReconciliationLoops, events); err != nil {
t.Errorf("%v", err)
}
}
}

// checkObject checks that the given object has the correct amount of expectedReconciliations
// tracked in the events.
func checkObject(obj client.Object, expectedReconciliations int, events reconciliationEvents) error {
Expand Down

0 comments on commit 2b6358e

Please sign in to comment.