This repository has been archived by the owner on Jun 16, 2023. It is now read-only.
forked from Mirantis/virtlet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.go
331 lines (279 loc) · 8.21 KB
/
data.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
Copyright 2017 Mirantis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gm
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"github.com/davecgh/go-spew/spew"
"github.com/ghodss/yaml"
"github.com/golang/glog"
)
const (
jsonDataIndent = " "
)
// Verifier describes a type that can verify its contents
// against a Golden Master data file and also generate
// the contents of such file
type Verifier interface {
// Suffix returns the suffix for the file name of the Golden Master
// data file for this value.
Suffix() string
// Marshal generates the contents of the Golden Master data file.
Marshal() ([]byte, error)
// Verify returns true if the contents can be considered
// the same as the value of the Verifier. It should not return
// an error if content is invalid.
Verify(content []byte) (bool, error)
}
type textVerifier string
var _ Verifier = textVerifier("")
func (v textVerifier) Suffix() string {
return ".txt"
}
func (v textVerifier) Verify(content []byte) (bool, error) {
return string(v) == string(content), nil
}
func (v textVerifier) Marshal() ([]byte, error) {
return []byte(v), nil
}
type JSONVerifier struct {
data interface{}
}
var _ Verifier = JSONVerifier{}
func NewJSONVerifier(data interface{}) JSONVerifier {
return JSONVerifier{data}
}
func (v JSONVerifier) Suffix() string {
return ".json"
}
func (v JSONVerifier) Verify(content []byte) (bool, error) {
var curData interface{}
if err := json.Unmarshal(content, &curData); err != nil {
glog.Warningf("Failed to unmarshal to JSON: %v:\n%s", err, content)
return false, nil
}
out, err := json.Marshal(v.data)
if err != nil {
return false, fmt.Errorf("failed to marshal data: %v. Input:\n%s",
err, spew.Sdump(v))
}
var newData interface{}
if err := json.Unmarshal(out, &newData); err != nil {
return false, fmt.Errorf("failed to unmarshal back marshalled value: %v. JSON:\n%s\nOriginal data:\n%s",
err, string(out), spew.Sdump(v))
}
return reflect.DeepEqual(curData, newData), nil
}
func (v JSONVerifier) Marshal() ([]byte, error) {
switch d := v.data.(type) {
case []byte:
return d, nil
case string:
return []byte(d), nil
default:
out, err := json.MarshalIndent(v.data, "", jsonDataIndent)
if err != nil {
return nil, fmt.Errorf("failed to marshal json data: %v. Input:\n%s",
err, spew.Sdump(v.data))
}
return out, nil
}
}
// YamlVerifier verifies the data using YAML representation.
type YamlVerifier struct {
data interface{}
}
var _ Verifier = YamlVerifier{}
// NewYamlVerifier makes a YamlVerifier with the specified content.
func NewYamlVerifier(data interface{}) YamlVerifier {
return YamlVerifier{data}
}
// Suffix implements Suffix method of the Verifier interface.
func (v YamlVerifier) Suffix() string {
return ".yaml"
}
func marshalMultiple(data []interface{}) ([]byte, error) {
var out bytes.Buffer
for _, v := range data {
bs, err := yaml.Marshal(v)
if err != nil {
return nil, err
}
fmt.Fprintf(&out, "---\n%s", bs)
}
return out.Bytes(), nil
}
func unmarshalMultiple(in []byte) ([]interface{}, error) {
var r []interface{}
for _, part := range bytes.Split(in, []byte("---\n")) {
if len(bytes.TrimSpace(part)) == 0 {
continue
}
var data interface{}
if err := yaml.Unmarshal(part, &data); err != nil {
return nil, err
}
r = append(r, data)
}
return r, nil
}
func (v YamlVerifier) verifyMultiple(content []byte) (bool, error) {
curData, err := unmarshalMultiple(content)
if err != nil {
glog.Warningf("Failed to unmarshal to YAML: %v:\n%s", err, content)
return false, nil
}
out, err := v.Marshal()
if err != nil {
return false, err
}
newData, err := unmarshalMultiple(out)
if err != nil {
return false, fmt.Errorf("failed to unmarshal back marshalled value: %v. YAML:\n%s\nOriginal data:\n%s",
err, string(out), content)
}
return reflect.DeepEqual(curData, newData), nil
}
// Verify implements Verify method of the Verifier interface.
func (v YamlVerifier) Verify(content []byte) (bool, error) {
switch v.data.(type) {
case []byte:
return v.verifyMultiple(content)
case string:
return v.verifyMultiple(content)
}
var curData interface{}
if err := yaml.Unmarshal(content, &curData); err != nil {
glog.Warningf("Failed to unmarshal to YAML: %v:\n%s", err, content)
return false, nil
}
out, err := v.Marshal()
if err != nil {
return false, err
}
var newData interface{}
if err := yaml.Unmarshal(out, &newData); err != nil {
return false, fmt.Errorf("failed to unmarshal back marshalled value: %v. YAML:\n%s\nOriginal data:\n%s",
err, string(out), spew.Sdump(v))
}
return reflect.DeepEqual(curData, newData), nil
}
// Marshal implements Marshal method of the Verifier interface.
func (v YamlVerifier) Marshal() ([]byte, error) {
switch d := v.data.(type) {
case []byte:
return d, nil
case string:
return []byte(d), nil
default:
out, err := yaml.Marshal(v.data)
if err != nil {
return nil, fmt.Errorf("failed to marshal yaml data: %v. Input:\n%s",
err, spew.Sdump(v.data))
}
return out, nil
}
}
// Replacement specifies a replacement for SubstVerifier.
type Replacement struct {
Old string
New string
}
// SubstVerifier wraps another verifier and replaces the specified
// substrings in the data it generates.
type SubstVerifier struct {
next Verifier
replacements []Replacement
}
var _ Verifier = SubstVerifier{}
// NewSubstVerifier makes a SubstVerifier that wraps another verifier
// and does the specified replacements.
func NewSubstVerifier(next Verifier, replacements []Replacement) SubstVerifier {
return SubstVerifier{next, replacements}
}
// Suffix implements Suffix method of the Verifier interface.
func (v SubstVerifier) Suffix() string {
return v.next.Suffix()
}
// Verify implements Verify method of the Verifier interface.
func (v SubstVerifier) Verify(content []byte) (bool, error) {
return v.next.Verify(content)
}
// Marshal implements Marshal method of the Verifier interface.
func (v SubstVerifier) Marshal() ([]byte, error) {
d, err := v.next.Marshal()
if err != nil {
return nil, err
}
for _, rep := range v.replacements {
d = bytes.Replace(d, []byte(rep.Old), []byte(rep.New), -1)
}
return d, nil
}
func getVerifier(data interface{}) Verifier {
switch v := data.(type) {
case Verifier:
return v
case string:
return textVerifier(v)
case []byte:
return textVerifier(string(v))
default:
return NewJSONVerifier(v)
}
}
var badFilenameCharRx = regexp.MustCompile(`[^\w-]`)
// GetFilenameForTest converts a Go test name to filename
func GetFilenameForTest(testName string, v interface{}) (string, error) {
suffix := ".out" + getVerifier(v).Suffix()
filename := strings.Replace(testName, "/", "__", -1)
filename = badFilenameCharRx.ReplaceAllString(filename, "_") + suffix
wd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("can't get current directory: %v", err)
}
return filepath.Join(wd, filename), nil
}
// WriteDataFile serializes the specified value into a data file
func WriteDataFile(filename string, v interface{}) error {
out, err := getVerifier(v).Marshal()
if err != nil {
return fmt.Errorf("error generating the data for %q: %v", filename, err)
}
if err := ioutil.WriteFile(filename, out, 0777); err != nil {
return fmt.Errorf("error writing %q: %v", filename, err)
}
return nil
}
// DataFileDiffers compares the specified value against the stored data file
func DataFileDiffers(filename string, v interface{}) (bool, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
if os.IsNotExist(err) {
return true, nil
}
return false, fmt.Errorf("error reading %q: %v", filename, err)
}
ok, err := getVerifier(v).Verify(content)
if err != nil {
return false, fmt.Errorf("error parsing %q: %v", filename, err)
}
return !ok, nil
}