-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathflashduty_test.go
More file actions
222 lines (206 loc) · 7.82 KB
/
Copy pathflashduty_test.go
File metadata and controls
222 lines (206 loc) · 7.82 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
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
package flashduty
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// noopLogger keeps test output clean.
type noopLogger struct{}
func (noopLogger) Debug(string, ...any) {}
func (noopLogger) Info(string, ...any) {}
func (noopLogger) Warn(string, ...any) {}
func (noopLogger) Error(string, ...any) {}
func newTestClient(t *testing.T, handler http.HandlerFunc) *Client {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
c, err := NewClient("KEY", WithBaseURL(srv.URL), WithLogger(noopLogger{}))
if err != nil {
t.Fatal(err)
}
return c
}
func TestNewRequestBuildsPostWithAppKeyAndJSON(t *testing.T) {
c, _ := NewClient("KEY", WithBaseURL("https://api.flashcat.cloud"), WithLogger(noopLogger{}))
req, err := c.newRequest(context.Background(), http.MethodPost, "/incident/list", map[string]any{"p": 1})
if err != nil {
t.Fatal(err)
}
if req.Method != http.MethodPost {
t.Fatalf("method = %s", req.Method)
}
if got := req.URL.Query().Get("app_key"); got != "KEY" {
t.Fatalf("app_key = %q", got)
}
if req.URL.Path != "/incident/list" {
t.Fatalf("path = %s", req.URL.Path)
}
if ct := req.Header.Get("Content-Type"); ct != "application/json" {
t.Fatalf("content-type = %s", ct)
}
body, _ := io.ReadAll(req.Body)
if !strings.Contains(string(body), `"p":1`) {
t.Fatalf("body = %s", body)
}
}
// TestOptionalObjectRequestFieldOmitsWhenUnset guards against a codegen
// regression: encoding/json's `,omitempty` never drops a bare struct value
// (only false/0/""/nil-slice/nil-map/nil-pointer count as "empty"), so an
// unset optional object request field used to always be sent as `{}`. For
// CreateSilenceRuleRequest.TimeFilter this made a recurring-only silence rule
// (TimeFilters set, TimeFilter unset) impossible: the server's binding
// validates StartTime/EndTime with `gt=0` whenever "time_filter" is present
// in the payload at all. The generator now emits `,omitzero` for optional
// struct-typed request fields, which correctly drops the zero value.
func TestOptionalObjectRequestFieldOmitsWhenUnset(t *testing.T) {
c, _ := NewClient("KEY", WithBaseURL("https://api.flashcat.cloud"), WithLogger(noopLogger{}))
req, err := c.newRequest(context.Background(), http.MethodPost, "/silence-rule/create", &CreateSilenceRuleRequest{
RuleName: "recurring only",
TimeFilters: []CreateSilenceRuleRequestTimeFiltersItem{
{Start: "09:00", End: "18:00"},
},
})
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(req.Body)
if strings.Contains(string(body), `"time_filter"`) {
t.Fatalf("unset TimeFilter must be omitted from the wire, got body = %s", body)
}
if !strings.Contains(string(body), `"time_filters"`) {
t.Fatalf("TimeFilters must be present, got body = %s", body)
}
req, err = c.newRequest(context.Background(), http.MethodPost, "/silence-rule/create", &CreateSilenceRuleRequest{
RuleName: "one-off only",
TimeFilter: CreateSilenceRuleRequestTimeFilter{StartTime: 1000, EndTime: 2000},
})
if err != nil {
t.Fatal(err)
}
body, _ = io.ReadAll(req.Body)
if !strings.Contains(string(body), `"time_filter"`) {
t.Fatalf("set TimeFilter must be present on the wire, got body = %s", body)
}
}
func TestNewRequestAppliesHookAndHeaders(t *testing.T) {
c, _ := NewClient("KEY",
WithRequestHeaders(map[string][]string{"X-Static": {"s"}}),
WithRequestHook(func(r *http.Request) { r.Header.Set("X-Hook", "h") }),
WithLogger(noopLogger{}),
)
req, _ := c.newRequest(context.Background(), http.MethodPost, "/x", nil)
if req.Header.Get("X-Static") != "s" || req.Header.Get("X-Hook") != "h" {
t.Fatalf("headers not applied: %+v", req.Header)
}
}
func TestDoDecodesDataAndPagination(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Flashcat-Request-Id", "RID1")
_, _ = io.WriteString(w, `{"request_id":"RID1","data":{"total":2,"has_next_page":true,"search_after_ctx":"cur","items":[{"incident_id":"i1"}]}}`)
})
var out struct {
Items []struct {
IncidentID string `json:"incident_id"`
} `json:"items"`
}
resp, err := c.do(context.Background(), "/incident/list", map[string]any{}, &out)
if err != nil {
t.Fatal(err)
}
if resp.RequestID != "RID1" || resp.Total != 2 || !resp.HasNextPage || resp.SearchAfterCtx != "cur" {
t.Fatalf("response meta = %+v", resp)
}
if len(out.Items) != 1 || out.Items[0].IncidentID != "i1" {
t.Fatalf("data not decoded: %+v", out)
}
}
func TestDoMapsEnvelopeError(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, `{"request_id":"RID2","error":{"code":"incident_not_found","message":"nope"}}`)
})
_, err := c.do(context.Background(), "/incident/info", map[string]any{}, nil)
var apiErr *ErrorResponse
if !errors.As(err, &apiErr) || apiErr.Code != "incident_not_found" || apiErr.RequestID != "RID2" {
t.Fatalf("expected mapped ErrorResponse, got %v", err)
}
}
func TestDoMapsNon2xx(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
_, _ = io.WriteString(w, `{"error":{"code":"internal","message":"boom"}}`)
})
_, err := c.do(context.Background(), "/x", map[string]any{}, nil)
var apiErr *ErrorResponse
if !errors.As(err, &apiErr) || apiErr.Response.StatusCode != 500 {
t.Fatalf("expected 500 ErrorResponse, got %v", err)
}
}
func TestDoEmptyBodySuccess(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, `{"request_id":"RID3"}`)
})
resp, err := c.do(context.Background(), "/incident/ack", map[string]any{}, nil)
if err != nil || resp.RequestID != "RID3" {
t.Fatalf("empty-data success failed: err=%v resp=%+v", err, resp)
}
}
func TestDoTreatsOKCodeAsSuccess(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
// Some success envelopes carry error.code "OK" rather than a null error.
_, _ = io.WriteString(w, `{"request_id":"RID","error":{"code":"OK","message":""},"data":{"items":[{"incident_id":"i1"}]}}`)
})
var out struct {
Items []struct {
IncidentID string `json:"incident_id"`
} `json:"items"`
}
resp, err := c.do(context.Background(), "/incident/list", map[string]any{}, &out)
if err != nil {
t.Fatalf("OK code must be treated as success, got %v", err)
}
if len(out.Items) != 1 || out.Items[0].IncidentID != "i1" || resp.RequestID != "RID" {
t.Fatalf("data not decoded on OK envelope: out=%+v resp=%+v", out, resp)
}
}
func TestDoExposesNonJSONBodyAsRaw(t *testing.T) {
const csv = "id,title\n1,boom\n2,bam\n"
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = io.WriteString(w, csv)
})
resp, err := c.do(context.Background(), "/insight/incident/export", map[string]any{}, nil)
if err != nil {
t.Fatalf("non-JSON success body must not error, got %v", err)
}
if string(resp.Raw) != csv {
t.Fatalf("Response.Raw = %q, want the CSV body", resp.Raw)
}
}
func TestDoReturnsRateLimitErrorOn429(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", "30")
w.Header().Set("X-RateLimit-Remaining", "0")
w.WriteHeader(429)
_, _ = io.WriteString(w, `{"error":{"code":"rate_limited","message":"slow down"}}`)
})
resp, err := c.do(context.Background(), "/incident/list", map[string]any{}, nil)
var rl *RateLimitError
if !errors.As(err, &rl) {
t.Fatalf("expected *RateLimitError, got %T: %v", err, err)
}
if rl.RetryAfter != 30*time.Second {
t.Fatalf("RetryAfter = %s, want 30s", rl.RetryAfter)
}
var generic *ErrorResponse
if !errors.As(err, &generic) || generic.Code != "rate_limited" {
t.Fatalf("RateLimitError must unwrap to *ErrorResponse")
}
if resp.RateLimit.RetryAfter != 30*time.Second || resp.RateLimit.Remaining != 0 {
t.Fatalf("Response.RateLimit not populated: %+v", resp.RateLimit)
}
}