78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
package rest
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestInstanceIDPrefersEnvironment(t *testing.T) {
|
|
t.Setenv(instanceIDEnv, "api-7")
|
|
|
|
assert.Equal(t, "api-7", InstanceID())
|
|
}
|
|
|
|
func TestInstanceIDFallsBackToHostname(t *testing.T) {
|
|
t.Setenv(instanceIDEnv, "")
|
|
|
|
host, err := os.Hostname()
|
|
require.NoError(t, err)
|
|
|
|
assert.Equal(t, host, InstanceID())
|
|
}
|
|
|
|
func TestInstanceIDMiddleware(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
handler http.HandlerFunc
|
|
wantID string
|
|
wantCode int
|
|
}{
|
|
{
|
|
name: "handler response",
|
|
handler: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusCreated) },
|
|
wantID: "api-1",
|
|
wantCode: http.StatusCreated,
|
|
},
|
|
{
|
|
name: "response without explicit status",
|
|
handler: func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) },
|
|
wantID: "api-1",
|
|
wantCode: http.StatusOK,
|
|
},
|
|
{
|
|
name: "error produced outside a handler",
|
|
handler: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusMethodNotAllowed) },
|
|
wantID: "api-1",
|
|
wantCode: http.StatusMethodNotAllowed,
|
|
},
|
|
{
|
|
name: "header set by the transport is not overwritten",
|
|
handler: func(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set(instanceIDHeader, "explicit")
|
|
w.WriteHeader(http.StatusOK)
|
|
},
|
|
wantID: "explicit",
|
|
wantCode: http.StatusOK,
|
|
},
|
|
}
|
|
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
recorder := httptest.NewRecorder()
|
|
|
|
instanceIDMiddleware("api-1", test.handler).ServeHTTP(
|
|
recorder,
|
|
httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil),
|
|
)
|
|
|
|
assert.Equal(t, test.wantID, recorder.Header().Get(instanceIDHeader))
|
|
assert.Equal(t, test.wantCode, recorder.Code)
|
|
})
|
|
}
|
|
}
|