Skip to content

Commit a48a5bb

Browse files
committed
#150 Added a fake Clock that allows for testing crontab ScheduledScans
fakeClock can fake the passing of time Signed-off-by: Ilyes Ben Dlala <ilyes.bendlala@iteratec.com>
1 parent e903e5d commit a48a5bb

4 files changed

Lines changed: 46 additions & 8 deletions

File tree

‎operator/controllers/execution/scheduledscan_controller.go‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,21 @@ type ScheduledScanReconciler struct {
3434
client.Client
3535
Log logr.Logger
3636
Scheme *runtime.Scheme
37+
Clock
38+
}
39+
40+
/*
41+
We'll mock out the clock to make it easier to jump around in time while testing,
42+
the "real" clock just calls `time.Now`.
43+
*/
44+
type realClock struct{}
45+
46+
func (_ realClock) Now() time.Time { return time.Now() }
47+
48+
// clock knows how to get the current time.
49+
// It can be used to fake out timing for testing.
50+
type Clock interface {
51+
Now() time.Time
3752
}
3853

3954
// +kubebuilder:rbac:groups=execution.securecodebox.io,resources=scheduledscans,verbs=get;list;watch;create;update;patch;delete
@@ -101,14 +116,14 @@ func (r *ScheduledScanReconciler) Reconcile(ctx context.Context, req ctrl.Reques
101116
}
102117

103118
// Calculate the next schedule
104-
nextSchedule, err := getNextSchedule(scheduledScan, time.Now())
119+
nextSchedule, err := getNextSchedule(r, scheduledScan, r.Clock.Now())
105120
if err != nil {
106121
log.Error(err, "Unable to calculate next schedule")
107122
return ctrl.Result{}, err
108123
}
109124

110125
// check if it is time to start the next Scan
111-
if !time.Now().Before(nextSchedule) {
126+
if !r.Clock.Now().Before(nextSchedule) {
112127
if scheduledScan.Spec.RetriggerOnScanTypeChange == true {
113128
// generate hash for current state of the configured ScanType
114129
var scanType executionv1.ScanType
@@ -156,13 +171,13 @@ func (r *ScheduledScanReconciler) Reconcile(ctx context.Context, req ctrl.Reques
156171
}
157172

158173
// Recalculate next schedule
159-
nextSchedule = time.Now().Add(scheduledScan.Spec.Interval.Duration)
174+
nextSchedule = r.Clock.Now().Add(scheduledScan.Spec.Interval.Duration)
160175
}
161176

162-
return ctrl.Result{RequeueAfter: nextSchedule.Sub(time.Now())}, nil
177+
return ctrl.Result{RequeueAfter: nextSchedule.Sub(r.Clock.Now())}, nil
163178
}
164179

165-
func getNextSchedule(scheduledScan executionv1.ScheduledScan, now time.Time) (next time.Time, err error) {
180+
func getNextSchedule(r *ScheduledScanReconciler, scheduledScan executionv1.ScheduledScan, now time.Time) (next time.Time, err error) {
166181
// check if the Cron schedule is set
167182
if scheduledScan.Spec.Schedule != "" {
168183
sched, err := cron.ParseStandard(scheduledScan.Spec.Schedule)
@@ -189,7 +204,7 @@ func getNextSchedule(scheduledScan executionv1.ScheduledScan, now time.Time) (ne
189204
if scheduledScan.Status.LastScheduleTime != nil {
190205
nextSchedule = scheduledScan.Status.LastScheduleTime.Add(scheduledScan.Spec.Interval.Duration)
191206
} else {
192-
nextSchedule = time.Now().Add(-1 * time.Second)
207+
nextSchedule = r.Clock.Now().Add(-1 * time.Second)
193208
}
194209
return nextSchedule, nil
195210
}
@@ -246,6 +261,10 @@ func (r *ScheduledScanReconciler) deleteOldScans(scans []executionv1.Scan, maxCo
246261

247262
// SetupWithManager sets up the controller and initializes every thing it needs
248263
func (r *ScheduledScanReconciler) SetupWithManager(mgr ctrl.Manager) error {
264+
// set up a real clock, since we're not in a test
265+
if r.Clock == nil {
266+
r.Clock = realClock{}
267+
}
249268
ctx := context.Background()
250269
if err := mgr.GetFieldIndexer().IndexField(ctx, &executionv1.Scan{}, ownerKey, func(rawObj client.Object) []string {
251270
// grab the job object, extract the owner...

‎operator/controllers/execution/scheduledscan_controller_test.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package controllers
55

66
import (
77
"context"
8+
"time"
89

910
. "github.com/onsi/ginkgo"
1011
. "github.com/onsi/gomega"
@@ -52,6 +53,7 @@ var _ = Describe("ScheduledScan controller", func() {
5253
},
5354
}
5455
It("Should drop all annotations not prefixed with \"*.securecodebox.io/*\"", func() {
56+
FakeClock.Reset() // making sure the clock is reset before we start
5557
for _, test := range tests {
5658
scheduledScan := executionv1.ScheduledScan{
5759
ObjectMeta: metav1.ObjectMeta{
@@ -66,6 +68,7 @@ var _ = Describe("ScheduledScan controller", func() {
6668
})
6769
Context("A Scan is triggred due to a Scheduled Scan with Interval in Spec", func() {
6870
It("The ScheduledScan's Finding Summary shoud be updated of with the results of the successful Scan", func() {
71+
FakeClock.Reset() // making sure the clock is reset before we start
6972
ctx := context.Background()
7073
namespace := "scantype-multiple-scheduled-scan-triggerd-test"
7174

@@ -107,6 +110,7 @@ var _ = Describe("ScheduledScan controller", func() {
107110

108111
Context("A Scan is triggred due to a Scheduled Scan with Schedule in Spec", func() {
109112
It("The ScheduledScan's Finding Summary shoud be updated of with the results of the successful Scan", func() {
113+
FakeClock.Reset() // making sure the clock is reset before we start
110114
ctx := context.Background()
111115
namespace := "scantype-multiple-scheduled-scan-triggerd-test-schedule"
112116

@@ -115,11 +119,13 @@ var _ = Describe("ScheduledScan controller", func() {
115119
scheduledScan := createScheduledScanWithSchedule(ctx, namespace, true)
116120

117121
var scanlist executionv1.ScanList
122+
// Fake a minute passing
123+
FakeClock.TimeTravel(1 * time.Minute)
118124
// ensure that the ScheduledScan has been triggered
119125
waitForScheduledScanToBeTriggered(ctx, namespace)
120126
k8sClient.List(ctx, &scanlist, client.InNamespace(namespace))
121127

122-
Expect(scheduledScan.Spec.Schedule).Should(Equal("* * * * *"))
128+
Expect(scheduledScan.Spec.Schedule).Should(Equal("*/1 * * * *"))
123129
Expect(scanlist.Items).Should(HaveLen(1))
124130

125131
scan := scanlist.Items[0]

‎operator/controllers/execution/suite_test.go‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"context"
99
"path/filepath"
1010
"testing"
11+
"time"
1112

1213
. "github.com/onsi/ginkgo"
1314
. "github.com/onsi/gomega"
@@ -36,6 +37,16 @@ var testEnv *envtest.Environment
3637
var ctx context.Context
3738
var cancel context.CancelFunc
3839

40+
type fakeClock struct {
41+
timeToAdd time.Duration
42+
}
43+
44+
func (f fakeClock) Now() time.Time { return time.Now().Add(f.timeToAdd) }
45+
func (f fakeClock) TimeTravel(d time.Duration) { f.timeToAdd += d }
46+
func (f fakeClock) Reset() { f.timeToAdd = 0 }
47+
48+
var FakeClock = &fakeClock{timeToAdd: 0}
49+
3950
func TestAPIs(t *testing.T) {
4051
RegisterFailHandler(Fail)
4152

@@ -83,6 +94,7 @@ var _ = BeforeSuite(func() {
8394
Client: k8sManager.GetClient(),
8495
Scheme: k8sManager.GetScheme(),
8596
Log: ctrl.Log.WithName("controllers").WithName("ScheduledScanController"),
97+
Clock: FakeClock,
8698
}).SetupWithManager(k8sManager)
8799
Expect(err).ToNot(HaveOccurred())
88100

‎operator/controllers/execution/test_utils_test.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,8 @@ func createScheduledScanWithSchedule(ctx context.Context, namespace string, retr
9797
Namespace: namespace,
9898
},
9999
Spec: executionv1.ScheduledScanSpec{
100-
Schedule: "* * * * *",
100+
Schedule: "*/1 * * * *",
101+
Interval: metav1.Duration{Duration: 42 * time.Hour},
101102
RetriggerOnScanTypeChange: retriggerOnScanTypeChange,
102103
ScanSpec: &executionv1.ScanSpec{
103104
ScanType: "nmap",

0 commit comments

Comments
 (0)