forked from go-bdd/gobdd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
88 lines (70 loc) · 1.89 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package gobdd
import (
"encoding/json"
"fmt"
)
// Holds data from previously executed steps
type Context struct {
values map[interface{}]interface{}
}
// Creates a new (empty) context struct
func NewContext() Context {
return Context{
values: map[interface{}]interface{}{},
}
}
// Clone creates a copy of the context
func (ctx Context) Clone() Context {
c := Context{
values: map[interface{}]interface{}{},
}
for k, v := range ctx.values {
c.Set(k, v)
}
return c
}
// Sets the value under the key
func (ctx Context) Set(key interface{}, value interface{}) {
ctx.values[key] = value
}
// Returns the data under the key.
// If couldn't find anything but the default value is provided, returns the default value.
// Otherwise, it returns an error.
func (ctx Context) Get(key interface{}, defaultValue ...interface{}) (interface{}, error) {
if _, ok := ctx.values[key]; !ok {
if len(defaultValue) == 1 {
return defaultValue[0], nil
}
return nil, fmt.Errorf("the key %+v does not exist", key)
}
return ctx.values[key], nil
}
// GetAs copies data from tke key to the dest.
// Supports maps, slices and structs.
func (ctx Context) GetAs(key interface{}, dest interface{}) error {
if _, ok := ctx.values[key]; !ok {
return fmt.Errorf("the key %+v does not exist", key)
}
d, err := json.Marshal(ctx.values[key])
if err != nil {
return err
}
return json.Unmarshal(d, dest)
}
// It is a shortcut for getting the value already casted as error.
func (ctx Context) GetError(key interface{}, defaultValue ...error) (error, error) {
if _, ok := ctx.values[key]; !ok {
if len(defaultValue) == 1 {
return defaultValue[0], nil
}
return nil, fmt.Errorf("the key %+v does not exist", key)
}
if ctx.values[key] == nil {
return nil, nil
}
value, ok := ctx.values[key].(error)
if !ok {
return nil, fmt.Errorf("the expected value is not error (%T)", key)
}
return value, nil
}