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

Side by Side Diff: go/src/infra/gae/libs/wrapper/time.go

Issue 1151473003: Better attempt at an appengine wrapper. (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@master
Patch Set: pointer! Created 5 years, 7 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 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 }
M-A Ruel 2015/05/25 17:14:52 I'd write the function as: if t == nil { return
iannucci 2015/05/26 18:25:06 cool done.
44 if t == nil {
45 f = nil
46 }
47 return SetTimeNowFactory(c, f)
48 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698