11/*
2- Copyright 2019 the original author or authors.
2+ Copyright 2025 the original author or authors.
33
44Licensed under the Apache License, Version 2.0 (the "License");
55you may not use this file except in compliance with the License.
@@ -19,48 +19,57 @@ package testing
1919import (
2020 "context"
2121 "testing"
22+ "time"
2223
2324 "k8s.io/apimachinery/pkg/runtime"
2425 "reconciler.io/runtime/reconcilers"
26+ rtime "reconciler.io/runtime/time"
2527 "sigs.k8s.io/controller-runtime/pkg/reconcile"
2628)
2729
28- func TestReconcilerTestCase_Run (t * testing.T ) {
30+ func TestReconcilerTestCase_Now (t * testing.T ) {
31+ start := time .Now ()
32+
2933 type testCase struct {
30- name string
31- verify func ( * testing. T , * ReconcilerTestCase , * testCase )
32- verifyRan bool
34+ name string
35+ rtc * ReconcilerTestCase
36+ verify func ( * testing. T , context. Context )
3337 }
3438 tests := []* testCase {
3539 {
3640 name : "Now defaults to time.Now()" ,
37- verify : func (t * testing.T , rtc * ReconcilerTestCase , tc * testCase ) {
38- tc .verifyRan = true
39- if rtc .Now .IsZero () {
41+ rtc : & ReconcilerTestCase {},
42+ verify : func (t * testing.T , ctx context.Context ) {
43+ now := rtime .RetrieveNow (ctx )
44+ // compare with a range to allow for time skew
45+ // test must complete within 1 hour of wall clock time
46+ if now .Before (start .Add (- 1 * time .Second )) || now .After (start .Add (time .Hour )) {
4047 t .Error ("expected test case to be initialized with time.Now()" )
4148 }
42-
49+ },
50+ },
51+ {
52+ name : "Now is set explicitly" ,
53+ rtc : & ReconcilerTestCase {
54+ Now : time .UnixMilli (1000 ),
55+ },
56+ verify : func (t * testing.T , ctx context.Context ) {
57+ now := rtime .RetrieveNow (ctx )
58+ if ! now .Equal (time .UnixMilli (1000 )) {
59+ t .Error ("expected time to be initialized from the test case" )
60+ }
4361 },
4462 },
4563 }
4664 for _ , tc := range tests {
4765 t .Run (tc .name , func (t * testing.T ) {
48- rtc := & ReconcilerTestCase {}
49- if tc .verify != nil {
50- rtc .Prepare = func (t * testing.T , ctx context.Context , rtc * ReconcilerTestCase ) (context.Context , error ) {
51- tc .verify (t , rtc , tc )
52- return ctx , nil
53- }
54- }
55- rtc .Run (t , runtime .NewScheme (), func (t * testing.T , rtc * ReconcilerTestCase , c reconcilers.Config ) reconcile.Reconciler {
66+ tc .rtc .ExpectedResult = reconcile.Result {RequeueAfter : time .Second }
67+ tc .rtc .Run (t , runtime .NewScheme (), func (t * testing.T , rtc * ReconcilerTestCase , c reconcilers.Config ) reconcile.Reconciler {
5668 return reconcile .Func (func (ctx context.Context , o reconcile.Request ) (reconcile.Result , error ) {
57- return reconcile.Result {}, nil
69+ tc .verify (t , ctx )
70+ return reconcile.Result {RequeueAfter : time .Second }, nil
5871 })
5972 })
60-
61- if ! tc .verifyRan {
62- t .Fatal ("expected verify to have run" )
63- }
6473 })
6574 }
6675}
0 commit comments