Refactor successApi in acceptance tests
In 6ad0543b, customHandler
type for acceptance tests has been introduced. It allows to customize the behaviour of the function and handle requests base on the URL. It also allows refactoring the function itself because most of the handlers are used in a single tests. I believe the final implementation may seem like:
func successAPI(t *testing.T, handlers ...customHandler) http.Handler {
t.Helper()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Logf("gitlab-api-mock: received request: %s %s", r.Method, r.RequestURI)
w.Header().Set("Content-Type", "application/json")
url := r.URL.EscapedPath()
for _, handler := range handlers {
if url == handler.url {
handler.caller(w, r)
return
}
}
switch url {
case "/api/v4/internal/authorized_keys":
fmt.Fprintf(w, `{"id":1, "key":"%s"}`, r.FormValue("key"))
case "/api/v4/internal/allowed":
response := buildAllowedResponse(t, "responses/allowed_without_console_messages.json")
_, err := fmt.Fprint(w, response)
require.NoError(t, err)
default:
t.Logf("Unexpected request to successAPI: %s", r.URL.EscapedPath())
t.FailNow()
}
})
}
While all other cases are passed as params wherever needed like:
handler := customHandler{
url: "/api/v4/internal/discover",
caller: func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, `{"id": 1000, "name": "Test User", "username": "test-user"}`)
},
}
client := runSSHD(t, successAPI(t, handler))