Matt Rosencrantz | 1932912 | 2015-01-23 22:18:49 -0800 | [diff] [blame] | 1 | // fake implements a fake runtime. The fake runtime is useful in tests when you |
| 2 | // want to mock out important components. |
| 3 | // TODO(mattr): Make a more complete, but still fake, implementation. |
| 4 | package fake |
| 5 | |
| 6 | import ( |
| 7 | "v.io/core/veyron2" |
| 8 | "v.io/core/veyron2/context" |
| 9 | "v.io/core/veyron2/security" |
| 10 | "v.io/core/veyron2/vlog" |
| 11 | |
| 12 | tsecurity "v.io/core/veyron/lib/testutil/security" |
| 13 | ) |
| 14 | |
| 15 | type contextKey int |
| 16 | |
| 17 | const ( |
| 18 | clientKey = contextKey(iota) |
| 19 | principalKey |
| 20 | loggerKey |
| 21 | backgroundKey |
| 22 | ) |
| 23 | |
| 24 | type Runtime struct{} |
| 25 | |
| 26 | func Init(ctx *context.T) (*Runtime, *context.T, veyron2.Shutdown, error) { |
| 27 | ctx = context.WithValue(ctx, principalKey, tsecurity.NewPrincipal()) |
| 28 | return &Runtime{}, ctx, func() {}, nil |
| 29 | } |
| 30 | |
| 31 | func (r *Runtime) SetPrincipal(ctx *context.T, principal security.Principal) (*context.T, error) { |
| 32 | return context.WithValue(ctx, principalKey, principal), nil |
| 33 | } |
| 34 | |
| 35 | func (r *Runtime) GetPrincipal(ctx *context.T) security.Principal { |
| 36 | p, _ := ctx.Value(principalKey).(security.Principal) |
| 37 | return p |
| 38 | } |
| 39 | |
| 40 | func (r *Runtime) SetNewLogger(ctx *context.T, name string, opts ...vlog.LoggingOpts) (*context.T, vlog.Logger, error) { |
| 41 | logger, err := vlog.NewLogger(name, opts...) |
| 42 | if err != nil { |
| 43 | return context.WithValue(ctx, loggerKey, logger), logger, nil |
| 44 | } |
| 45 | return ctx, nil, err |
| 46 | } |
| 47 | |
| 48 | func (r *Runtime) GetLogger(ctx *context.T) vlog.Logger { |
| 49 | l, _ := ctx.Value(loggerKey).(vlog.Logger) |
| 50 | return l |
| 51 | } |
| 52 | |
Matt Rosencrantz | 1932912 | 2015-01-23 22:18:49 -0800 | [diff] [blame] | 53 | func (r *Runtime) GetAppCycle(ctx *context.T) veyron2.AppCycle { |
| 54 | panic("unimplemented") |
| 55 | } |
| 56 | |
| 57 | func (r *Runtime) SetBackgroundContext(ctx *context.T) *context.T { |
| 58 | // Note we add an extra context with a nil value here. |
| 59 | // This prevents users from travelling back through the |
| 60 | // chain of background contexts. |
| 61 | ctx = context.WithValue(ctx, backgroundKey, nil) |
| 62 | return context.WithValue(ctx, backgroundKey, ctx) |
| 63 | } |
| 64 | |
| 65 | func (r *Runtime) GetBackgroundContext(ctx *context.T) *context.T { |
| 66 | bctx, _ := ctx.Value(backgroundKey).(*context.T) |
| 67 | if bctx == nil { |
| 68 | // There should always be a background context. If we don't find |
| 69 | // it, that means that the user passed us the background context |
| 70 | // in hopes of following the chain. Instead we just give them |
| 71 | // back what they sent in, which is correct. |
| 72 | return ctx |
| 73 | } |
| 74 | return bctx |
| 75 | } |