Skip to content

Commit

Permalink
feat: add timez.Now() func (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
ginokent authored Aug 24, 2023
2 parents 3fb6c4f + 72df7bd commit 05589b7
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
48 changes: 48 additions & 0 deletions time/time.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package timez

import (
"context"
"sync"
"time"
)

type ctxKeyNow struct{}

func Now(ctx context.Context) time.Time {
nowFuncRWMu.RLock()
defer nowFuncRWMu.RUnlock()
return nowFunc(ctx)
}

//nolint:gochecknoglobals
var (
nowFunc = DefaultNowFunc
nowFuncRWMu sync.RWMutex
)

type NowFunc = func(ctx context.Context) time.Time

func DefaultNowFunc(ctx context.Context) time.Time {
if now, ok := FromContext(ctx); ok {
return now
}

return time.Now()
}

func SetNowFunc(now NowFunc) (backup NowFunc) {
nowFuncRWMu.Lock()
defer nowFuncRWMu.Unlock()
backup = nowFunc
nowFunc = now
return backup
}

func WithContext(ctx context.Context, now time.Time) context.Context {
return context.WithValue(ctx, ctxKeyNow{}, now)
}

func FromContext(ctx context.Context) (time.Time, bool) {
now, ok := ctx.Value(ctxKeyNow{}).(time.Time)
return now, ok
}
37 changes: 37 additions & 0 deletions time/time_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package timez_test

import (
"context"
"testing"
"time"

timez "github.com/kunitsucom/util.go/time"
)

func TestNow(t *testing.T) {
t.Parallel()
t.Run("success,", func(t *testing.T) {
t.Parallel()

ctx := context.Background()
constant := time.Date(2023, 8, 24, 21, 32, 0, 0, time.UTC)
ctx = timez.WithContext(ctx, constant)

actual := timez.Now(ctx)
if constant != actual {
t.Errorf("❌: constant(%v) != actual(%v)", constant, actual)
}

backup := timez.SetNowFunc(func(_ context.Context) time.Time { return time.Now() })
current := timez.Now(context.Background())
if current.After(constant) {
t.Errorf("❌: current(%v) after constant(%v)", current, constant)
}

timez.SetNowFunc(backup)
current2 := timez.Now(context.Background())
if !current2.After(current) {
t.Errorf("❌: current2(%v) after current(%v)", current2, current)
}
})
}

0 comments on commit 05589b7

Please sign in to comment.