Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(16)

Side by Side Diff: go/src/infra/libs/clock/testclock/testclock.go

Issue 1154213012: Add context-aware "time" library wrapper. (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@master
Patch Set: Refactored into sub-packages. Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright (c) 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 package testclock
6
7 import (
8 "time"
9
10 "golang.org/x/net/context"
11 "infra/libs/clock"
12 )
13
14 // TestClock is a Clock interface with additional methods to help instrument it.
15 type TestClock interface {
16 clock.Clock
17 SetNow(time.Time)
18 SetTimerFactory(TimerFactory)
19 }
20
21 // testClock is a test-oriented implementation of the 'Clock' interface.
22 //
23 // This implementation's Clock responses are configurable by modifying its membe r
24 // variables. Time-based events are explicitly triggered by sending on a Timer
25 // instance's channel.
26 type testClock struct {
iannucci 2015/06/02 22:19:03 mutex for protecting now/timeC/tf
dnj 2015/06/03 00:25:28 Done.
27 now time.Time // The current clock time.
28 timeC chan time.Time // Channel to unblock sleeping and After.
29 tf TimerFactory // Timer generator function. Must be set to use New Timer() and After().
30 }
31
32 // testClock implements clock.TestClock.
33 var _ TestClock = (*testClock)(nil)
34
35 // New returns a TestClock instance set at the specified time.
36 func New(now time.Time, tf TimerFactory) TestClock {
37 return &testClock{
38 now: now,
39 tf: tf,
iannucci 2015/06/02 22:19:03 timeC?
dnj 2015/06/03 00:25:28 Acknowledged.
40 }
41 }
42
43 func (c *testClock) Now() time.Time {
44 return c.now
45 }
46
47 func (c *testClock) Sleep(time.Duration) {
48 if c.timeC != nil {
49 // Wait for sleep signal; update current time.
50 c.now = <-c.timeC
51 }
52 }
53
54 func (c *testClock) NewTimer() clock.Timer {
55 if c.tf == nil {
56 panic("No test timer generator is configured.")
57 }
58 return c.tf()
59 }
60
61 func (c *testClock) After(d time.Duration) <-chan time.Time {
62 t := c.NewTimer()
63 t.Reset(d)
64 return t.GetC()
65 }
66
67 func (c *testClock) SetNow(t time.Time) {
68 c.now = t
69 }
70
71 func (c *testClock) SetTimerFactory(tf TimerFactory) {
72 c.tf = tf
73 }
74
75 // Set creates a new Context using the supplied clock instance.
76 func Set(ctx context.Context, now time.Time, tf TimerFactory) context.Context {
77 return clock.SetClock(ctx, New(now, tf))
78 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698