File: clock_test.go

package info (click to toggle)
golang-github-bep-clock 0.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 92 kB
  • sloc: makefile: 2
file content (87 lines) | stat: -rw-r--r-- 2,143 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package clock

import (
	"testing"
	"time"

	qt "github.com/frankban/quicktest"
	"github.com/google/go-cmp/cmp"
)

const timeLayout = "2006-01-02-15:04:05"

var durationEq = qt.CmpEquals(
	cmp.Comparer(func(x, y time.Duration) bool {
		return x.Truncate(1*time.Second) == y.Truncate(1*time.Second)
	}),
)

func TestClock(t *testing.T) {
	c := qt.New(t)

	c.Run("Past", func(c *qt.C) {
		c.Parallel()

		start, _ := time.Parse(timeLayout, "2019-10-11-02:50:01")
		clock := Start(start)

		c.Assert(toString(clock.Now()), qt.Equals, "2019-10-11-02:50:01")
		time.Sleep(1 * time.Second)
		c.Assert(toString(clock.Now()), qt.Equals, "2019-10-11-02:50:02")
	})

	c.Run("Future", func(c *qt.C) {
		c.Parallel()

		start, _ := time.Parse(timeLayout, "2053-10-11-02:50:01")
		clock := Start(start)

		c.Assert(toString(clock.Now()), qt.Equals, "2053-10-11-02:50:01")
		time.Sleep(1 * time.Second)
		c.Assert(toString(clock.Now()), qt.Equals, "2053-10-11-02:50:02")
	})

	c.Run("Offset", func(c *qt.C) {
		c.Parallel()

		clock := Start(time.Now().Add(5010 * time.Millisecond))
		c.Assert(clock.Offset(), durationEq, time.Duration(5*time.Second))

	})

	c.Run("Since", func(c *qt.C) {
		c.Parallel()

		start, _ := time.Parse(timeLayout, "2019-10-11-02:50:01")
		clock := Start(start)

		time.Sleep(1 * time.Second)
		c.Assert(clock.Since(start), durationEq, time.Duration(1*time.Second))
	})

	c.Run("Until", func(c *qt.C) {
		c.Parallel()

		start, _ := time.Parse(timeLayout, "2019-10-11-02:50:01")
		clock := Start(start)
		then := clock.Now().Add(3010 * time.Millisecond)
		c.Assert(clock.Until(then), durationEq, time.Duration(3*time.Second))
	})

}

func TestSystemClock(t *testing.T) {
	t.Parallel()

	c := qt.New(t)

	c.Assert(toString(System().Now()), qt.Equals, toString(time.Now()))
	c.Assert(System().Since(time.Now().Add(-10*time.Hour)), durationEq, time.Since(time.Now().Add(-10*time.Hour)))
	c.Assert(System().Until(time.Now().Add(10*time.Hour)), durationEq, time.Until(time.Now().Add(10*time.Hour)))
	c.Assert(System().Offset(), qt.Equals, time.Duration(0))

}

func toString(t time.Time) string {
	return t.UTC().Format(timeLayout)
}