-
Notifications
You must be signed in to change notification settings - Fork 0
/
snapshotter.go
85 lines (73 loc) · 2.01 KB
/
snapshotter.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
package testgraphql
import (
"context"
"fmt"
"reflect"
"testing"
"github.com/base-go/go/snapshotter"
"github.com/base-go/baseql/graphql"
"github.com/base-go/baseql/internal"
"github.com/stretchr/testify/require"
)
type Snapshotter struct {
*snapshotter.Snapshotter
t *testing.T
schema *graphql.Schema
}
func NewSnapshotter(t *testing.T, schema *graphql.Schema) *Snapshotter {
return &Snapshotter{
t: t,
Snapshotter: snapshotter.New(t),
schema: schema,
}
}
type Option func(*instanceOption)
// Don't fail on error, snapshot it instead.
func RecordError(o *instanceOption) { o.recordError = true }
type instanceOption struct{ recordError bool }
func applyOpts(opts []Option) instanceOption {
var option instanceOption
for _, opt := range opts {
opt(&option)
}
return option
}
func (s *Snapshotter) SnapshotQuery(name, query string, opts ...Option) {
opt := applyOpts(opts)
q := graphql.MustParse(query, nil)
err := graphql.PrepareQuery(context.Background(), s.schema.Query, q.SelectionSet)
if err != nil && opt.recordError {
s.Snapshot(name, struct{ Error string }{err.Error()})
return
}
require.NoError(s.t, err)
var lastOutput interface{}
var lastErr error
runOnce := false
for _, executorAndName := range GetExecutors() {
output, err := executorAndName.Executor.Execute(context.Background(), s.schema.Query, nil, q)
if err != nil && opt.recordError {
s.Snapshot(fmt.Sprintf("%s%s", executorAndName.Name, name), struct{ Error string }{err.Error()})
} else {
require.NoError(s.t, err)
s.Snapshot(fmt.Sprintf("%s%s", executorAndName.Name, name), output)
}
if !runOnce {
lastOutput = output
lastErr = err
runOnce = true
continue
}
if err != nil {
require.NotNil(s.t, lastErr)
require.Equal(s.t, lastErr.Error(), err.Error())
continue
}
require.Nil(s.t, lastErr)
require.True(
s.t,
reflect.DeepEqual(internal.AsJSON(lastOutput), internal.AsJSON(output)),
"Snapshots for %q do no match between different executors", name,
)
}
}