Skip to content

Commit c59afa7

Browse files
authored
Allow mocking timeutil (#17354)
Signed-off-by: jolheiser <[email protected]>
1 parent f0376b7 commit c59afa7

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

models/user_heatmap_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ package models
77
import (
88
"fmt"
99
"testing"
10+
"time"
1011

1112
"code.gitea.io/gitea/models/db"
1213
"code.gitea.io/gitea/modules/json"
14+
"code.gitea.io/gitea/modules/timeutil"
1315

1416
"github.com/stretchr/testify/assert"
1517
)
@@ -39,6 +41,10 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
3941
// Prepare
4042
assert.NoError(t, db.PrepareTestDatabase())
4143

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

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)