Allow mocking timeutil (#17354)

Signed-off-by: jolheiser <john.olheiser@gmail.com>
tokarchuk/v1.17
John Olheiser 3 years ago committed by GitHub
parent f0376b7e02
commit c59afa752d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 6
      models/user_heatmap_test.go
  2. 16
      modules/timeutil/timestamp.go

@ -7,9 +7,11 @@ package models
import ( import (
"fmt" "fmt"
"testing" "testing"
"time"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -39,6 +41,10 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
// Prepare // Prepare
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
// Mock time
timeutil.Set(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC))
defer timeutil.Unset()
for i, tc := range testCases { for i, tc := range testCases {
user := db.AssertExistsAndLoadBean(t, &User{ID: tc.userID}).(*User) user := db.AssertExistsAndLoadBean(t, &User{ID: tc.userID}).(*User)

@ -13,8 +13,24 @@ import (
// TimeStamp defines a timestamp // TimeStamp defines a timestamp
type TimeStamp int64 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 // TimeStampNow returns now int64
func TimeStampNow() TimeStamp { func TimeStampNow() TimeStamp {
if !mock.IsZero() {
return TimeStamp(mock.Unix())
}
return TimeStamp(time.Now().Unix()) return TimeStamp(time.Now().Unix())
} }

Loading…
Cancel
Save