| 1 |
// Copyright 2019 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package httpvar |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"net/http" |
| 22 |
"net/http/httptest" |
| 23 |
"net/url" |
| 24 |
"strconv" |
| 25 |
"strings" |
| 26 |
"testing" |
| 27 |
"time" |
| 28 |
|
| 29 |
"github.com/google/go-cmp/cmp" |
| 30 |
"gocloud.dev/internal/gcerr" |
| 31 |
"gocloud.dev/runtimevar" |
| 32 |
"gocloud.dev/runtimevar/driver" |
| 33 |
"gocloud.dev/runtimevar/drivertest" |
| 34 |
) |
| 35 |
|
| 36 |
type harness struct { |
| 37 |
mockServer *mockServer |
| 38 |
} |
| 39 |
|
| 40 |
func (h *harness) MakeWatcher(ctx context.Context, name string, decoder *runtimevar.Decoder) (driver.Watcher, error) { |
| 41 |
endpointURL, err := url.Parse(h.mockServer.baseURL + "/" + name) |
| 42 |
if err != nil { |
| 43 |
return nil, err |
| 44 |
} |
| 45 |
return newWatcher(http.DefaultClient, endpointURL, decoder, nil), nil |
| 46 |
} |
| 47 |
|
| 48 |
func (h *harness) CreateVariable(ctx context.Context, name string, val []byte) error { |
| 49 |
h.mockServer.SetResponse(name, string(val)) |
| 50 |
return nil |
| 51 |
} |
| 52 |
|
| 53 |
func (h *harness) UpdateVariable(ctx context.Context, name string, val []byte) error { |
| 54 |
h.mockServer.SetResponse(name, string(val)) |
| 55 |
return nil |
| 56 |
} |
| 57 |
|
| 58 |
func (h *harness) DeleteVariable(ctx context.Context, name string) error { |
| 59 |
h.mockServer.DeleteResponse(name) |
| 60 |
return nil |
| 61 |
} |
| 62 |
|
| 63 |
func (h *harness) Close() { |
| 64 |
h.mockServer.close() |
| 65 |
} |
| 66 |
|
| 67 |
func (h *harness) Mutable() bool { |
| 68 |
return true |
| 69 |
} |
| 70 |
|
| 71 |
func newHarness(t *testing.T) (drivertest.Harness, error) { |
| 72 |
t.Helper() |
| 73 |
|
| 74 |
return &harness{ |
| 75 |
mockServer: newMockServer(), |
| 76 |
}, nil |
| 77 |
} |
| 78 |
|
| 79 |
func TestConformance(t *testing.T) { |
| 80 |
drivertest.RunConformanceTests(t, newHarness, []drivertest.AsTest{verifyAs{}}) |
| 81 |
} |
| 82 |
|
| 83 |
type verifyAs struct{} |
| 84 |
|
| 85 |
func (verifyAs) Name() string { |
| 86 |
return "verify As" |
| 87 |
} |
| 88 |
|
| 89 |
func (verifyAs) SnapshotCheck(s *runtimevar.Snapshot) error { |
| 90 |
var resp *http.Response |
| 91 |
if !s.As(&resp) { |
| 92 |
return errors.New("Snapshot.As failed") |
| 93 |
} |
| 94 |
|
| 95 |
s2 := state{raw: nil} |
| 96 |
if s2.As(nil) { |
| 97 |
return errors.New("Snapshot.As was expected to fail") |
| 98 |
} |
| 99 |
return nil |
| 100 |
} |
| 101 |
|
| 102 |
func (verifyAs) ErrorCheck(v *runtimevar.Variable, err error) error { |
| 103 |
var e RequestError |
| 104 |
if !v.ErrorAs(err, &e) { |
| 105 |
return errors.New("ErrorAs expected to succeed with *httpvar.RequestError") |
| 106 |
} |
| 107 |
if !strings.Contains(e.Error(), strconv.Itoa(e.Response.StatusCode)) { |
| 108 |
return errors.New("should contain url and status code") |
| 109 |
} |
| 110 |
|
| 111 |
var e2 url.Error |
| 112 |
urlError := &url.Error{URL: "http://example.com", Op: "GET", Err: errors.New("example error")} |
| 113 |
if !v.ErrorAs(urlError, &e2) { |
| 114 |
return errors.New("ErrorAs expected to succeed with *url.Error") |
| 115 |
} |
| 116 |
|
| 117 |
var e3 RequestError |
| 118 |
if v.ErrorAs(errors.New("example error"), &e3) { |
| 119 |
return errors.New("ErrorAs was expected to fail") |
| 120 |
} |
| 121 |
return nil |
| 122 |
} |
| 123 |
|
| 124 |
// httpvar-specific tests. |
| 125 |
|
| 126 |
func TestOpenVariable(t *testing.T) { |
| 127 |
tests := []struct { |
| 128 |
URL string |
| 129 |
WantErr bool |
| 130 |
}{ |
| 131 |
{"http://example.com/config", false}, |
| 132 |
{"%gh&%ij", true}, |
| 133 |
} |
| 134 |
|
| 135 |
for _, test := range tests { |
| 136 |
v, err := OpenVariable(http.DefaultClient, test.URL, runtimevar.StringDecoder, nil) |
| 137 |
if (err != nil) != test.WantErr { |
| 138 |
t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr) |
| 139 |
} |
| 140 |
if v != nil { |
| 141 |
v.Close() |
| 142 |
} |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
func TestEquivalentError(t *testing.T) { |
| 147 |
notFoundErr := newRequestError(&http.Response{StatusCode: http.StatusNotFound}) |
| 148 |
badGatewayErr := newRequestError(&http.Response{StatusCode: http.StatusBadGateway}) |
| 149 |
tests := []struct { |
| 150 |
Err1, Err2 error |
| 151 |
Want bool |
| 152 |
}{ |
| 153 |
{Err1: errors.New("error one"), Err2: errors.New("error one"), Want: true}, |
| 154 |
{Err1: errors.New("error one"), Err2: errors.New("error two"), Want: false}, |
| 155 |
{Err1: errors.New("error one"), Err2: notFoundErr, Want: false}, |
| 156 |
{Err1: notFoundErr, Err2: notFoundErr, Want: true}, |
| 157 |
{Err1: notFoundErr, Err2: badGatewayErr, Want: false}, |
| 158 |
} |
| 159 |
|
| 160 |
for _, test := range tests { |
| 161 |
got := equivalentError(test.Err1, test.Err2) |
| 162 |
if got != test.Want { |
| 163 |
t.Errorf("%v vs %v: got %v want %v", test.Err1, test.Err2, got, test.Want) |
| 164 |
} |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
func TestWatcher_ErrorCode(t *testing.T) { |
| 169 |
tests := []struct { |
| 170 |
Err *RequestError |
| 171 |
GCErr gcerr.ErrorCode |
| 172 |
}{ |
| 173 |
{Err: newRequestError(&http.Response{StatusCode: http.StatusBadRequest}), GCErr: gcerr.InvalidArgument}, |
| 174 |
{Err: newRequestError(&http.Response{StatusCode: http.StatusNotFound}), GCErr: gcerr.NotFound}, |
| 175 |
{Err: newRequestError(&http.Response{StatusCode: http.StatusUnauthorized}), GCErr: gcerr.PermissionDenied}, |
| 176 |
{Err: newRequestError(&http.Response{StatusCode: http.StatusGatewayTimeout}), GCErr: gcerr.DeadlineExceeded}, |
| 177 |
{Err: newRequestError(&http.Response{StatusCode: http.StatusRequestTimeout}), GCErr: gcerr.DeadlineExceeded}, |
| 178 |
{Err: newRequestError(&http.Response{StatusCode: http.StatusInternalServerError}), GCErr: gcerr.Internal}, |
| 179 |
{Err: newRequestError(&http.Response{StatusCode: http.StatusServiceUnavailable}), GCErr: gcerr.Internal}, |
| 180 |
{Err: newRequestError(&http.Response{StatusCode: http.StatusBadGateway}), GCErr: gcerr.Internal}, |
| 181 |
} |
| 182 |
|
| 183 |
endpointURL, err := url.Parse("http://example.com") |
| 184 |
if err != nil { |
| 185 |
t.Fatal(err) |
| 186 |
} |
| 187 |
|
| 188 |
watcher := newWatcher(http.DefaultClient, endpointURL, runtimevar.StringDecoder, nil) |
| 189 |
defer watcher.Close() |
| 190 |
for _, test := range tests { |
| 191 |
actualGCErr := watcher.ErrorCode(test.Err) |
| 192 |
if test.GCErr != actualGCErr { |
| 193 |
t.Errorf("expected gcerr.ErrorCode to be %d, got %d", test.GCErr, actualGCErr) |
| 194 |
} |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
func TestWatcher_WatchVariable(t *testing.T) { |
| 199 |
t.Run("client returns an error", func(t *testing.T) { |
| 200 |
endpointURL, err := url.Parse("http://example.com") |
| 201 |
if err != nil { |
| 202 |
t.Fatal(err) |
| 203 |
} |
| 204 |
|
| 205 |
// In order to force httpClient.Get to return an error, we pass custom *http.Client |
| 206 |
// with every short timeout, so that request will timed out and return an error. |
| 207 |
httpClient := &http.Client{ |
| 208 |
Timeout: time.Duration(1 * time.Millisecond), |
| 209 |
} |
| 210 |
watcher := newWatcher(httpClient, endpointURL, runtimevar.StringDecoder, nil) |
| 211 |
defer watcher.Close() |
| 212 |
state, _ := watcher.WatchVariable(context.Background(), &state{}) |
| 213 |
|
| 214 |
val, err := state.Value() |
| 215 |
if err == nil { |
| 216 |
t.Errorf("expected error got nil") |
| 217 |
} |
| 218 |
if val != nil { |
| 219 |
t.Errorf("expected state value to be nil, got %v", val) |
| 220 |
} |
| 221 |
}) |
| 222 |
} |
| 223 |
|
| 224 |
func TestWithAuth(t *testing.T) { |
| 225 |
const ( |
| 226 |
authUser = "test_user" |
| 227 |
authPwd = "test_pwd" |
| 228 |
value = "hello world" |
| 229 |
) |
| 230 |
h, err := newHarness(t) |
| 231 |
if err != nil { |
| 232 |
t.Fatal(err) |
| 233 |
} |
| 234 |
defer h.Close() |
| 235 |
mockServer := h.(*harness).mockServer |
| 236 |
testURL := mockServer.baseURL + "/string-var?decoder=string" |
| 237 |
mockServer.authUser = authUser |
| 238 |
mockServer.authPwd = authPwd |
| 239 |
|
| 240 |
ctx := context.Background() |
| 241 |
if err := h.CreateVariable(ctx, "string-var", []byte(value)); err != nil { |
| 242 |
t.Fatal(err) |
| 243 |
} |
| 244 |
|
| 245 |
tests := []struct { |
| 246 |
AuthUser string |
| 247 |
AuthPwd string |
| 248 |
WantErr bool |
| 249 |
}{ |
| 250 |
// No auth provided, fails. |
| 251 |
{"", "", true}, |
| 252 |
// Invalid user, fails. |
| 253 |
{"wronguser", authPwd, true}, |
| 254 |
// Invalid password, fails. |
| 255 |
{authUser, "wrongpassword", true}, |
| 256 |
// Auth good, works. |
| 257 |
{authUser, authPwd, false}, |
| 258 |
} |
| 259 |
|
| 260 |
for _, test := range tests { |
| 261 |
name := fmt.Sprintf("user=%s,pwd=%s", test.AuthUser, test.AuthPwd) |
| 262 |
t.Run(name, func(t *testing.T) { |
| 263 |
t.Setenv("HTTPVAR_AUTH_USERNAME", test.AuthUser) |
| 264 |
t.Setenv("HTTPVAR_AUTH_PASSWORD", test.AuthPwd) |
| 265 |
|
| 266 |
v, err := runtimevar.OpenVariable(ctx, testURL) |
| 267 |
if err != nil { |
| 268 |
t.Fatalf("failed OpenVariable: %v", err) |
| 269 |
} |
| 270 |
defer v.Close() |
| 271 |
snapshot, err := v.Watch(ctx) |
| 272 |
if (err != nil) != test.WantErr { |
| 273 |
t.Errorf("got Watch error %v, want error %v", err, test.WantErr) |
| 274 |
} |
| 275 |
if err != nil { |
| 276 |
return |
| 277 |
} |
| 278 |
if !cmp.Equal(snapshot.Value, value) { |
| 279 |
t.Errorf("got snapshot value\n%v\n want\n%v", snapshot.Value, value) |
| 280 |
} |
| 281 |
}) |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
func TestOpenVariableURL(t *testing.T) { |
| 286 |
h, err := newHarness(t) |
| 287 |
if err != nil { |
| 288 |
t.Fatal(err) |
| 289 |
} |
| 290 |
defer h.Close() |
| 291 |
baseURL := h.(*harness).mockServer.baseURL |
| 292 |
|
| 293 |
ctx := context.Background() |
| 294 |
if err := h.CreateVariable(ctx, "string-var", []byte("hello world")); err != nil { |
| 295 |
t.Fatal(err) |
| 296 |
} |
| 297 |
if err := h.CreateVariable(ctx, "json-var", []byte(`{"Foo": "Bar"}`)); err != nil { |
| 298 |
t.Fatal(err) |
| 299 |
} |
| 300 |
|
| 301 |
tests := []struct { |
| 302 |
URL string |
| 303 |
WantErr bool |
| 304 |
WantWatchErr bool |
| 305 |
Want any |
| 306 |
}{ |
| 307 |
// Nonexistentvar does not exist, so we get an error from Watch. |
| 308 |
{baseURL + "/nonexistentvar", false, true, nil}, |
| 309 |
// Invalid decoder arg. |
| 310 |
{baseURL + "/string-var?decoder=notadecoder", true, false, nil}, |
| 311 |
// Working example with string decoder. |
| 312 |
{baseURL + "/string-var?decoder=string", false, false, "hello world"}, |
| 313 |
// Working example with default decoder. |
| 314 |
{baseURL + "/string-var", false, false, []byte("hello world")}, |
| 315 |
// Working example with JSON decoder. |
| 316 |
{baseURL + "/json-var?decoder=jsonmap", false, false, &map[string]any{"Foo": "Bar"}}, |
| 317 |
// Setting wait. |
| 318 |
{baseURL + "/string-var?decoder=string&wait=1m", false, false, "hello world"}, |
| 319 |
// Invalid wait. |
| 320 |
{baseURL + "/string-var?decoder=string&wait=xx", true, false, nil}, |
| 321 |
} |
| 322 |
|
| 323 |
for _, test := range tests { |
| 324 |
t.Run(test.URL, func(t *testing.T) { |
| 325 |
v, err := runtimevar.OpenVariable(ctx, test.URL) |
| 326 |
if (err != nil) != test.WantErr { |
| 327 |
t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr) |
| 328 |
} |
| 329 |
if err != nil { |
| 330 |
return |
| 331 |
} |
| 332 |
defer v.Close() |
| 333 |
snapshot, err := v.Watch(ctx) |
| 334 |
if (err != nil) != test.WantWatchErr { |
| 335 |
t.Errorf("%s: got Watch error %v, want error %v", test.URL, err, test.WantWatchErr) |
| 336 |
} |
| 337 |
if err != nil { |
| 338 |
return |
| 339 |
} |
| 340 |
if !cmp.Equal(snapshot.Value, test.Want) { |
| 341 |
t.Errorf("%s: got snapshot value\n%v\n want\n%v", test.URL, snapshot.Value, test.Want) |
| 342 |
} |
| 343 |
}) |
| 344 |
} |
| 345 |
} |
| 346 |
|
| 347 |
type mockServer struct { |
| 348 |
baseURL string |
| 349 |
close func() |
| 350 |
responses map[string]any |
| 351 |
authUser string |
| 352 |
authPwd string |
| 353 |
} |
| 354 |
|
| 355 |
func (m *mockServer) SetResponse(name string, response any) { |
| 356 |
m.responses[name] = response |
| 357 |
} |
| 358 |
|
| 359 |
func (m *mockServer) DeleteResponse(name string) { |
| 360 |
delete(m.responses, name) |
| 361 |
} |
| 362 |
|
| 363 |
func newMockServer() *mockServer { |
| 364 |
mock := &mockServer{responses: map[string]any{}} |
| 365 |
|
| 366 |
mux := http.NewServeMux() |
| 367 |
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 368 |
if mock.authUser != "" { |
| 369 |
user, pwd, ok := r.BasicAuth() |
| 370 |
if !ok || user != mock.authUser || pwd != mock.authPwd { |
| 371 |
w.WriteHeader(http.StatusUnauthorized) |
| 372 |
return |
| 373 |
} |
| 374 |
} |
| 375 |
resp := mock.responses[strings.TrimPrefix(r.URL.String(), "/")] |
| 376 |
if resp == nil { |
| 377 |
w.WriteHeader(http.StatusNotFound) |
| 378 |
return |
| 379 |
} |
| 380 |
fmt.Fprint(w, resp) |
| 381 |
}) |
| 382 |
|
| 383 |
server := httptest.NewServer(mux) |
| 384 |
mock.baseURL = server.URL |
| 385 |
mock.close = server.Close |
| 386 |
return mock |
| 387 |
} |