Skip to content

Commit eb748ff

Browse files
authored
Allow mocking timeutil (go-gitea#17354) (go-gitea#17356)
Signed-off-by: jolheiser <[email protected]>
1 parent c577019 commit eb748ff

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

models/user_heatmap_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ package models
77
import (
88
"fmt"
99
"testing"
10+
"time"
11+
12+
"code.gitea.io/gitea/modules/timeutil"
1013

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

43+
// Mock time
44+
timeutil.Set(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC))
45+
defer timeutil.Unset()
46+
4047
for i, tc := range testCases {
4148
user := AssertExistsAndLoadBean(t, &User{ID: tc.userID}).(*User)
4249

modules/timeutil/timestamp.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,24 @@ import (
1313
// TimeStamp defines a timestamp
1414
type TimeStamp int64
1515

16+
// mock is NOT concurrency-safe!!
17+
var mock time.Time
18+
19+
// Set sets the time to a mocked time.Time
20+
func Set(now time.Time) {
21+
mock = now
22+
}
23+
24+
// Unset will unset the mocked time.Time
25+
func Unset() {
26+
mock = time.Time{}
27+
}
28+
1629
// TimeStampNow returns now int64
1730
func TimeStampNow() TimeStamp {
31+
if !mock.IsZero() {
32+
return TimeStamp(mock.Unix())
33+
}
1834
return TimeStamp(time.Now().Unix())
1935
}
2036

0 commit comments

Comments
 (0)