diff --git a/utils/clock/clock.go b/utils/clock/clock.go new file mode 100644 index 0000000..555b5c4 --- /dev/null +++ b/utils/clock/clock.go @@ -0,0 +1,54 @@ +package clock + +import ( + "sync" + "time" +) + +const ( + BangkokTZ = "Asia/Bangkok" + + DateTimeFormat = "2006-01-02 15:04:05" + DateFormat = "2006-01-02" +) + +var ( + instance = time.Now + lock = sync.Mutex{} +) + +// NowBKK returns current time in BKK timezone +func NowBKK() time.Time { + loc, _ := time.LoadLocation(BangkokTZ) + return Now().In(loc) +} + +// Now returns current time +func Now() time.Time { + return instance() +} + +// ToString returns date time in string format +func ToString(n time.Time) string { + return n.Format(DateTimeFormat) +} + +// ToDateString returns date in string format +func ToDateString(n time.Time) string { + return n.Format(DateFormat) +} + +// Freeze sets the instance of time +func Freeze(fn func() time.Time) { + lock.Lock() + defer lock.Unlock() + instance = fn +} + +// UnFreeze removes all applied time +func UnFreeze() { + lock.Lock() + defer lock.Unlock() + + instance = time.Now +} diff --git a/utils/clock/clock_test.go b/utils/clock/clock_test.go new file mode 100644 index 0000000..6850764 --- /dev/null +++ b/utils/clock/clock_test.go @@ -0,0 +1,66 @@ +package clock_test + +import ( + "github.com/hokkung/go-groceries/utils/clock" + "github.com/stretchr/testify/assert" + "testing" + "time" +) + +var mockInstance = func() time.Time { + return time.Date(2024, 01, 01, 10, 0, 0, 0, time.UTC) +} + +func TestMain(m *testing.M) { + clock.Freeze(mockInstance) + m.Run() + clock.UnFreeze() +} + +func TestNow(t *testing.T) { + exp := mockInstance() + act := clock.Now() + + assert.Equal(t, exp, act) +} + +func TestNowBKK(t *testing.T) { + loc, _ := time.LoadLocation(clock.BangkokTZ) + exp := mockInstance().In(loc) + + act := clock.NowBKK() + + assert.Equal(t, exp, act) +} + +func TestToString(t *testing.T) { + tt := mockInstance() + exp := "2024-01-01 10:00:00" + + act := clock.ToString(tt) + + assert.Equal(t, exp, act) +} + +func TestToDateString(t *testing.T) { + tt := mockInstance() + exp := "2024-01-01" + + act := clock.ToDateString(tt) + + assert.Equal(t, exp, act) +} + +func TestUnFreeze(t *testing.T) { + exp := mockInstance() + + act := clock.Now() + + assert.Equal(t, exp, act) + + clock.UnFreeze() + + act2 := clock.Now() + + assert.True(t, act.Before(act2)) +}