Skip to content

Allow mocking timeutil (#17354) #17356

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

Merged
merged 1 commit into from
Oct 18, 2021
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
7 changes: 7 additions & 0 deletions models/user_heatmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ package models
import (
"fmt"
"testing"
"time"

"code.gitea.io/gitea/modules/timeutil"

jsoniter "github.com/json-iterator/go"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -37,6 +40,10 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
// Prepare
assert.NoError(t, PrepareTestDatabase())

// Mock time
timeutil.Set(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC))
defer timeutil.Unset()

for i, tc := range testCases {
user := AssertExistsAndLoadBean(t, &User{ID: tc.userID}).(*User)

Expand Down
16 changes: 16 additions & 0 deletions modules/timeutil/timestamp.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,24 @@ import (
// TimeStamp defines a timestamp
type TimeStamp int64

// mock is NOT concurrency-safe!!
var mock time.Time

// Set sets the time to a mocked time.Time
func Set(now time.Time) {
mock = now
}

// Unset will unset the mocked time.Time
func Unset() {
mock = time.Time{}
}

// TimeStampNow returns now int64
func TimeStampNow() TimeStamp {
if !mock.IsZero() {
return TimeStamp(mock.Unix())
}
return TimeStamp(time.Now().Unix())
}

Expand Down