OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 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 wrapper |
| 6 |
| 7 import ( |
| 8 "time" |
| 9 |
| 10 "golang.org/x/net/context" |
| 11 ) |
| 12 |
| 13 // TimeNowFactory is the function signature for factory methods compatible with |
| 14 // SetTimeNowFactory. |
| 15 type TimeNowFactory func(context.Context) time.Time |
| 16 |
| 17 // GetTimeNow gets the current time.Time from the context. If the context has no |
| 18 // time factory set with SetTimeNowFactory, it returns time.Now(). |
| 19 func GetTimeNow(c context.Context) time.Time { |
| 20 obj := c.Value(timeNowKey) |
| 21 if obj == nil || obj.(TimeNowFactory) == nil { |
| 22 return time.Now() |
| 23 } |
| 24 return obj.(TimeNowFactory)(c) |
| 25 } |
| 26 |
| 27 // SetTimeNowFactory sets the function to produce time.Time instances, as |
| 28 // returned by the GetTimeNow method. |
| 29 func SetTimeNowFactory(c context.Context, tnf TimeNowFactory) context.Context { |
| 30 return context.WithValue(c, timeNowKey, tnf) |
| 31 } |
| 32 |
| 33 // SetTimeNow sets a pointer to the current time.Time object in the context. |
| 34 // Useful for testing with a quick mock. This is just a shorthand |
| 35 // SetTimeNowFactory invocation to set a factory which always returns the same |
| 36 // object. |
| 37 // |
| 38 // Note the pointer asymmetry with GetTimeNow. This is done intentionally to |
| 39 // allow you to modify the pointed-to-time to be able to manually monkey with |
| 40 // the clock in a test. Otherwise this would essentially freeze time in place. |
| 41 // If you pass 'nil', this will set the context back to returning time.Now(). |
| 42 func SetTimeNow(c context.Context, t *time.Time) context.Context { |
| 43 f := func(context.Context) time.Time { return *t } |
| 44 if t == nil { |
| 45 f = nil |
| 46 } |
| 47 return SetTimeNowFactory(c, f) |
| 48 } |
OLD | NEW |