-
Notifications
You must be signed in to change notification settings - Fork 5
/
parser_test.go
76 lines (66 loc) · 1.54 KB
/
parser_test.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
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"regexp"
"testing"
)
const testSchemaFile = "testdata/nvd/nvd_cve_feed_json_1.0.schema"
func TestParseSchema(t *testing.T) {
_, err := ParseSchema(testSchemaFile)
if err != nil {
t.Fatal(err)
}
}
type genFunc func(w io.Writer, jsonSchema string) error
var goldenCmdRegexp = regexp.MustCompile("// Command: .*\n")
func testGenEqualGolden(t *testing.T, f genFunc, file string) {
var b bytes.Buffer
err := f(&b, testSchemaFile)
if err != nil {
t.Fatal(err)
}
want, err := ioutil.ReadFile(file)
if err != nil {
t.Fatal(err)
}
// remove the command from generated code; won't ever match
want = goldenCmdRegexp.ReplaceAll(want, nil)
have := goldenCmdRegexp.ReplaceAll(b.Bytes(), nil)
if !bytes.Equal(want, have) {
t.Error("golden file (a) != generated file (b)")
err = printDiff("gen", "tmp", want, have)
if err != nil {
t.Fatal(err)
}
}
}
// printDiff is a helper function used by tests.
func printDiff(prefix, ext string, a, b []byte) error {
files := []struct {
Name string
Data []byte
}{
{Name: prefix + "-a." + ext, Data: a},
{Name: prefix + "-b." + ext, Data: b},
}
for _, f := range files {
defer os.Remove(f.Name)
if err := ioutil.WriteFile(f.Name, f.Data, 0600); err != nil {
return err
}
}
var stdout, stderr bytes.Buffer
cmd := exec.Command("diff", "-u", files[0].Name, files[1].Name)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return fmt.Errorf("%v: %s", err, stdout.String())
}
return nil
}