| 1 | clock |
| 2 | ===== |
| 3 | |
| 4 | Clock is a small library for mocking time in Go. It provides an interface |
| 5 | around the standard library's [`time`][time] package so that the application |
| 6 | can use the realtime clock while tests can use the mock clock. |
| 7 | |
| 8 | [time]: http://golang.org/pkg/time/ |
| 9 | |
| 10 | |
| 11 | ## Usage |
| 12 | |
| 13 | ### Realtime Clock |
| 14 | |
| 15 | Your application can maintain a `Clock` variable that will allow realtime and |
| 16 | mock clocks to be interchangable. For example, if you had an `Application` type: |
| 17 | |
| 18 | ```go |
| 19 | import "github.com/benbjohnson/clock" |
| 20 | |
| 21 | type Application struct { |
| 22 | Clock clock.Clock |
| 23 | } |
| 24 | ``` |
| 25 | |
| 26 | You could initialize it to use the realtime clock like this: |
| 27 | |
| 28 | ```go |
| 29 | var app Application |
| 30 | app.Clock = clock.New() |
| 31 | ... |
| 32 | ``` |
| 33 | |
| 34 | Then all timers and time-related functionality should be performed from the |
| 35 | `Clock` variable. |
| 36 | |
| 37 | |
| 38 | ### Mocking time |
| 39 | |
| 40 | In your tests, you will want to use a `Mock` clock: |
| 41 | |
| 42 | ```go |
| 43 | import ( |
| 44 | "testing" |
| 45 | |
| 46 | "github.com/benbjohnson/clock" |
| 47 | ) |
| 48 | |
| 49 | func TestApplication_DoSomething(t *testing.T) { |
| 50 | mock := clock.NewMock() |
| 51 | app := Application{Clock: mock} |
| 52 | ... |
| 53 | } |
| 54 | ``` |
| 55 | |
| 56 | Now that you've initialized your application to use the mock clock, you can |
| 57 | adjust the time programmatically. The mock clock always starts from the Unix |
| 58 | epoch (midnight, Jan 1, 1970 UTC). |
| 59 | |
| 60 | |
| 61 | ### Controlling time |
| 62 | |
| 63 | The mock clock provides the same functions that the standard library's `time` |
| 64 | package provides. For example, to find the current time, you use the `Now()` |
| 65 | function: |
| 66 | |
| 67 | ```go |
| 68 | mock := clock.NewMock() |
| 69 | |
| 70 | // Find the current time. |
| 71 | mock.Now().UTC() // 1970-01-01 00:00:00 +0000 UTC |
| 72 | |
| 73 | // Move the clock forward. |
| 74 | mock.Add(2 * time.Hour) |
| 75 | |
| 76 | // Check the time again. It's 2 hours later! |
| 77 | mock.Now().UTC() // 1970-01-01 02:00:00 +0000 UTC |
| 78 | ``` |
| 79 | |
| 80 | Timers and Tickers are also controlled by this same mock clock. They will only |
| 81 | execute when the clock is moved forward: |
| 82 | |
| 83 | ``` |
| 84 | mock := clock.NewMock() |
| 85 | count := 0 |
| 86 | |
| 87 | // Kick off a timer to increment every 1 mock second. |
| 88 | go func() { |
| 89 | ticker := clock.Ticker(1 * time.Second) |
| 90 | for { |
| 91 | <-ticker.C |
| 92 | count++ |
| 93 | } |
| 94 | }() |
| 95 | runtime.Gosched() |
| 96 | |
| 97 | // Move the clock forward 10 second. |
| 98 | mock.Add(10 * time.Second) |
| 99 | |
| 100 | // This prints 10. |
| 101 | fmt.Println(count) |
| 102 | ``` |
| 103 | |
| 104 |