Skip to content
This repository was archived by the owner on Sep 29, 2024. It is now read-only.

Commit 4ba97de

Browse files
authored
Merge pull request #428 from manapoints/fix-timestamp-test
Add TimestampFromClock(); add Clock interface for mocking time.Now()
2 parents cf54d38 + e62a288 commit 4ba97de

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

engineio/base/util.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,23 @@ import "time"
44

55
var chars = []byte("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_")
66

7+
type clock interface {
8+
Now() time.Time
9+
}
10+
11+
type timeClock struct{}
12+
13+
func (timeClock) Now() time.Time {
14+
return time.Now()
15+
}
16+
717
// Timestamp returns a string based on different nano time.
818
func Timestamp() string {
9-
now := time.Now().UnixNano()
19+
return TimestampFromClock(timeClock{})
20+
}
21+
22+
func TimestampFromClock(c clock) string {
23+
now := c.Now().UnixNano()
1024
ret := make([]byte, 0, 16)
1125
for now > 0 {
1226
ret = append(ret, chars[int(now%int64(len(chars)))])

engineio/base/util_test.go

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,23 @@
11
package base
22

33
import (
4-
"testing"
5-
64
"github.com/stretchr/testify/assert"
5+
"testing"
6+
"time"
77
)
88

9-
func TestTimestamp(t *testing.T) {
9+
type testClock struct {
10+
now time.Time
11+
}
12+
13+
func (c testClock) Now() time.Time {
14+
return c.now
15+
}
16+
17+
func TestTimestampFromClock(t *testing.T) {
1018
should := assert.New(t)
11-
t1 := Timestamp()
12-
t2 := Timestamp()
19+
t1 := TimestampFromClock(testClock{time.Unix(0, 1000)})
20+
t2 := TimestampFromClock(testClock{time.Unix(0, 2000)})
1321
should.NotEmpty(t1)
1422
should.NotEmpty(t2)
1523
should.NotEqual(t1, t2)

0 commit comments

Comments
 (0)