Skip to content

Commit

Permalink
lib/time: un-export the variable Now
Browse files Browse the repository at this point in the history
The original idea of providing Now is to mock the current time in
testing Scheduler.
Since this variable can be overridden by other packages, it is not safe
to export it, hence we un-export it here so it can be used internal only.
  • Loading branch information
shuLhan committed Dec 17, 2023
1 parent 74ab6e6 commit 876133e
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 14 deletions.
4 changes: 2 additions & 2 deletions lib/time/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ type Scheduler struct {
func NewScheduler(schedule string) (sch *Scheduler, err error) {
var (
logp = `NewScheduler`
now = Now().UTC()
now = timeNow().UTC()
)

sch, err = newScheduler(schedule, now)
Expand Down Expand Up @@ -574,7 +574,7 @@ func (sch *Scheduler) run() {
// receiving the event.
var now = sch.next

sch.calcNext(Now().UTC())
sch.calcNext(timeNow().UTC())
ticker.Reset(sch.nextDuration)

select {
Expand Down
12 changes: 5 additions & 7 deletions lib/time/scheduler_example_test.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
package time_test
package time

import (
"fmt"
"log"
"time"

libtime "github.com/shuLhan/share/lib/time"
)

func ExampleScheduler_Next() {
// Override Now for making this example works.
libtime.Now = func() time.Time {
// Override timeNow to make this example works.
timeNow = func() time.Time {
return time.Date(2013, time.January, 20, 14, 26, 59, 0, time.UTC)
}

var (
sch *libtime.Scheduler
sch *Scheduler
err error
)

sch, err = libtime.NewScheduler(`minutely`)
sch, err = NewScheduler(`minutely`)
if err != nil {
log.Fatal(err)
}
Expand Down
2 changes: 1 addition & 1 deletion lib/time/scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func TestNewScheduler(t *testing.T) {
err error
)

Now = func() (now time.Time) {
timeNow = func() (now time.Time) {
switch step {
case 0:
step++
Expand Down
8 changes: 4 additions & 4 deletions lib/time/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import (
"time"
)

// Now returns the current local time.
// Unlike standard library, this is a variable that can be override to mock
// the current time during testing.
var Now = func() time.Time {
// timeNow returns the current local time.
// This is a variable that can be override to mock the current time during
// testing.
var timeNow = func() time.Time {
return time.Now()
}

Expand Down

0 comments on commit 876133e

Please sign in to comment.