Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add clock #6

Merged
merged 1 commit into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions utils/clock/clock.go
Original file line number Diff line number Diff line change
@@ -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
}
66 changes: 66 additions & 0 deletions utils/clock/clock_test.go
Original file line number Diff line number Diff line change
@@ -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))
}
Loading