Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
84 lines
2.4 KiB
Go
84 lines
2.4 KiB
Go
package adminhandler
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
type fakeCacheBumper struct {
|
|
calls int
|
|
err error
|
|
contexts []context.Context
|
|
}
|
|
|
|
func (f *fakeCacheBumper) Bump(ctx context.Context) error {
|
|
f.calls++
|
|
f.contexts = append(f.contexts, ctx)
|
|
return f.err
|
|
}
|
|
|
|
func TestInvalidateCache(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
method string
|
|
status int
|
|
write bool
|
|
want int
|
|
}{
|
|
{name: "successful write", method: http.MethodPost, status: http.StatusCreated, write: true, want: 1},
|
|
{name: "implicit success", method: http.MethodPost, status: http.StatusOK, want: 1},
|
|
{name: "client error", method: http.MethodPost, status: http.StatusBadRequest, write: true},
|
|
{name: "server error", method: http.MethodPost, status: http.StatusInternalServerError, write: true},
|
|
{name: "get", method: http.MethodGet, status: http.StatusCreated, write: true},
|
|
{name: "head", method: http.MethodHead, status: http.StatusCreated, write: true},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
bumper := &fakeCacheBumper{}
|
|
h := New(nil, nil, "/ping", nil).WithCache(bumper)
|
|
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
if tt.write {
|
|
w.WriteHeader(tt.status)
|
|
}
|
|
})
|
|
handler := h.invalidateCache(next)
|
|
req := httptest.NewRequest(tt.method, "/", nil)
|
|
recorder := httptest.NewRecorder()
|
|
handler.ServeHTTP(recorder, req)
|
|
if bumper.calls != tt.want {
|
|
t.Fatalf("Bump calls = %d, want %d", bumper.calls, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestInvalidateCacheDoesNotFailResponseAndUsesUncancelledContext(t *testing.T) {
|
|
bumper := &fakeCacheBumper{err: errors.New("redis unavailable")}
|
|
h := New(nil, nil, "/ping", nil).WithCache(bumper)
|
|
handler := h.invalidateCache(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
w.WriteHeader(http.StatusCreated)
|
|
}))
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
req := httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx)
|
|
recorder := httptest.NewRecorder()
|
|
|
|
handler.ServeHTTP(recorder, req)
|
|
|
|
if recorder.Code != http.StatusCreated {
|
|
t.Fatalf("response status = %d, want %d", recorder.Code, http.StatusCreated)
|
|
}
|
|
if bumper.calls != 1 {
|
|
t.Fatalf("Bump calls = %d, want 1", bumper.calls)
|
|
}
|
|
select {
|
|
case <-bumper.contexts[0].Done():
|
|
t.Fatal("Bump context was canceled")
|
|
default:
|
|
}
|
|
}
|