-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenapi_serve_test.go
More file actions
97 lines (75 loc) · 2.43 KB
/
openapi_serve_test.go
File metadata and controls
97 lines (75 loc) · 2.43 KB
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
package api_test
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
"github.com/bjaus/api"
)
func TestServeSpecYAML(t *testing.T) {
t.Parallel()
r := api.New(api.WithTitle("YAML Test"), api.WithVersion("1.0.0"))
api.Get(r, "/health", func(_ context.Context, _ *api.Void) (*api.Void, error) {
return &api.Void{}, nil
})
r.ServeSpecYAML("/openapi.yaml")
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/openapi.yaml", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "application/yaml", resp.Header.Get("Content-Type"))
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var parsed map[string]any
require.NoError(t, yaml.Unmarshal(body, &parsed))
assert.Equal(t, "3.1.0", parsed["openapi"])
info, ok := parsed["info"].(map[string]any)
require.True(t, ok)
assert.Equal(t, "YAML Test", info["title"])
}
func TestWriteSpec(t *testing.T) {
t.Parallel()
r := api.New(api.WithTitle("Write Test"), api.WithVersion("2.0.0"))
api.Get(r, "/ping", func(_ context.Context, _ *api.Void) (*api.Void, error) {
return &api.Void{}, nil
})
var buf bytes.Buffer
err := r.WriteSpec(&buf)
require.NoError(t, err)
var spec map[string]any
require.NoError(t, json.Unmarshal(buf.Bytes(), &spec))
assert.Equal(t, "3.1.0", spec["openapi"])
info, ok := spec["info"].(map[string]any)
require.True(t, ok)
assert.Equal(t, "Write Test", info["title"])
assert.Equal(t, "2.0.0", info["version"])
assert.Contains(t, spec, "paths")
}
func TestWriteSpecYAML(t *testing.T) {
t.Parallel()
r := api.New(api.WithTitle("YAML Write"), api.WithVersion("3.0.0"))
api.Get(r, "/status", func(_ context.Context, _ *api.Void) (*api.Void, error) {
return &api.Void{}, nil
})
var buf bytes.Buffer
err := r.WriteSpecYAML(&buf)
require.NoError(t, err)
var spec map[string]any
require.NoError(t, yaml.Unmarshal(buf.Bytes(), &spec))
assert.Equal(t, "3.1.0", spec["openapi"])
info, ok := spec["info"].(map[string]any)
require.True(t, ok)
assert.Equal(t, "YAML Write", info["title"])
assert.Equal(t, "3.0.0", info["version"])
assert.Contains(t, spec, "paths")
}