-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
runner_test.go
107 lines (91 loc) · 2.49 KB
/
runner_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
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
package apigen_test
import (
"bytes"
"context"
"flag"
"io/ioutil"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/ktr0731/apigen"
"github.com/ktr0731/apigen/curl"
)
var update = flag.Bool("update", false, "update golden files")
func TestGenerate(t *testing.T) {
t.Parallel()
def := &apigen.Definition{
Services: map[string][]*apigen.Method{
"Dummy": {
{
Name: "CreatePost",
Request: curl.ParseCommand(`curl 'https://jsonplaceholder.typicode.com/posts' --data-binary '{"title":"foo","body":"bar","userId":1}'`),
},
{
Name: "ListPosts",
Request: curl.ParseCommand(`curl https://jsonplaceholder.typicode.com/posts`),
},
{
Name: "GetPost",
Request: curl.ParseCommand(`curl https://jsonplaceholder.typicode.com/posts?id=1`),
},
{
Name: "ListComments",
Request: curl.ParseCommand(`curl https://jsonplaceholder.typicode.com/posts/1/comments`),
ParamHint: "/posts/{postID}/comments",
},
{
Name: "UpdatePost",
Request: curl.ParseCommand(`curl 'https://jsonplaceholder.typicode.com/posts/1' -X 'PUT' --data-binary '{"title":"foo","body":"bar","userId":1}'`),
ParamHint: "/posts/{postID}",
},
{
Name: "DeletePost",
Request: curl.ParseCommand(`curl 'https://jsonplaceholder.typicode.com/posts/1' -X 'DELETE'`),
ParamHint: "/posts/{postID}",
},
},
},
}
var w bytes.Buffer
if err := apigen.Generate(context.Background(), def, apigen.WithWriter(&w)); err != nil {
t.Fatalf("should not return an error, but got '%s'", err)
}
assertWithGolden(t, w.String())
}
func assertWithGolden(t *testing.T, actual string) {
t.Helper()
name := t.Name()
r := strings.NewReplacer(
"/", "-",
" ", "_",
"=", "-",
"'", "",
`"`, "",
",", "",
)
normalizeFilename := func(name string) string {
fname := r.Replace(strings.ToLower(name)) + ".golden"
return filepath.Join("testdata", fname)
}
fname := normalizeFilename(name)
if *update {
if err := ioutil.WriteFile(fname, []byte(actual), 0600); err != nil {
t.Fatalf("failed to update the golden file: %s", err)
}
return
}
// Load the golden file.
b, err := ioutil.ReadFile(fname)
if err != nil {
t.Fatalf("failed to load a golden file: %s", err)
}
expected := string(b)
if runtime.GOOS == "windows" {
expected = strings.ReplaceAll(expected, "\r\n", "\n")
}
if diff := cmp.Diff(expected, actual); diff != "" {
t.Errorf("wrong result: \n%s", diff)
}
}