Repository: prometheus/prometheus
File: web/api/v1/api_test.go (Go)

Code before:

	api.ClearCodecs()
	api.InstallCodec(&testCodec{contentType: MIMEType{"application", "default-format"}, canEncode: false})

	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		api.respond(w, r, "test", nil, "")
	}))
	defer s.Close()

	req, err := http.NewRequest(http.MethodGet, s.URL, nil)
	require.NoError(t, err)

	resp, err := http.DefaultClient.Do(req)
	require.NoError(t, err)

	body, err := io.ReadAll(resp.Body)
	defer resp.Body.Close()
	require.NoError(t, err)

	require.Equal(t, http.StatusNotAcceptable, resp.StatusCode)
	require.Equal(t, "application/json", resp.Header.Get("Content-Type"))
	require.JSONEq(t, `{"status":"error","errorType":"not_acceptable","error":"cannot encode response as application/default-format"}`, string(body))
}

func TestRespondError(t *testing.T) {
	type test struct {
		errType             errorType
		err                 error
		resCode             int
		msg                 string
		errTypeToStatusCode ErrorTypeToStatusCode
	}

	tests := map[string]test{
		"timeout should return 503 (ServiceUnavailable)": {
			errType: ErrorTimeout,
			err:     errors.New("message"),
			resCode: http.StatusServiceUnavailable,
			msg:     "message",
		},
		"execution error without override should return 422 (UnprocessableEntity)": {
			errType: ErrorExec,
			err:     errors.New("message"),
			resCode: http.StatusUnprocessableEntity,
			msg:     "message",
		},
		"errorTypeToStatusCode override works as expected": {
			errType: ErrorExec,
			err:     errors.New("message"),
			errTypeToStatusCode: map[errorType]func(error) int{
				ErrorExec: func(_ error) int {

Review comment (refactor):
thanks, I think we can simplify it a little bit
```diff
diff --git a/web/api/v1/api_test.go b/web/api/v1/api_test.go
index 18305ff3d..8e926c9e6 100644
--- a/web/api/v1/api_test.go
+++ b/web/api/v1/api_test.go
@@ -4125,48 +4125,37 @@ func TestRespondSuccess_DefaultCodecCannotEncodeResponse(t *testing.T) {
 func TestRespondError(t *testing.T) {
        type test struct {
                errType             errorType
-               err                 error
                resCode             int
-               msg                 string
                errTypeToStatusCode ErrorTypeToStatusCode
        }
 
        tests := map[string]test{
                "timeout should return 503 (ServiceUnavailable)": {
                        errType: ErrorTimeout,
-                       err:     errors.New("message"),
                        resCode: http.StatusServiceUnavailable,
-                       msg:     "message",
                },
                "execution error without override should return 422 (UnprocessableEntity)": {
                        errType: ErrorExec,
-                       err:     errors.New("message"),
                        resCode: http.StatusUnprocessableEntity,
-                       msg:     "message",
                },
                "errorTypeToStatusCode override works as expected": {
                        errType: ErrorExec,
-                       err:     errors.New("message"),
                        errTypeToStatusCode: map[errorType]func(error) int{
                                ErrorExec: func(_ error) int {
                                        return http.StatusTooManyRequests
                                },
                        },
                        resCode: http.StatusTooManyRequests,
-                       msg:     "message",
                },
        }
 
        for name, tc := range tests {
                t.Run(name, func(t *testing.T) {
                        s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
-                               api := API{}
-                               err := tc.err
-                               api.errorTypeToStatusCode = map[errorType]func(error) int{}
-                               for errType, handler := range tc.errTypeToStatusCode {
-                                       api.errorTypeToStatusCode[errType] = handler
+                               api := API{
+                                       errorTypeToStatusCode: tc.errTypeToStatusCode,
                                }
-                               api.respondError(w, &apiError{tc.errType, err}, "test")
+                               api.respondError(w, &apiError{tc.errType, errors.New("message")}, "test")
                        }))
                        defer s.Close()
 
@@ -4179,7 +4168,7 @@ func TestRespondError(t *testing.T) {
                        require.Equal(t, want, have, "Return code %d expected in error response but got %d", want, have)
                        h := resp.Header.Get("Content-Type")
                        require.Equal(t, "application/json", h, "Expected Content-Type %q but got %q", "application/json", h)
-                       require.JSONEq(t, fmt.Sprintf(`{"status": "error", "data": "test", "errorType": "%s", "error": "%s"}`, tc.errType, tc.msg), string(body))
+                       require.JSONEq(t, fmt.Sprintf(`{"status": "error", "data": "test", "errorType": "%s", "error": "message"}`, tc.errType), string(body))
                })
        }
 }
```

Code after:
	}
}

func TestRespondSuccess_DefaultCodecCannotEncodeResponse(t *testing.T) {
	api := API{
		logger: promslog.NewNopLogger(),
	}

	api.ClearCodecs()
	api.InstallCodec(&testCodec{contentType: MIMEType{"application", "default-format"}, canEncode: false})

	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		api.respond(w, r, "test", nil, "")
	}))
	defer s.Close()

	req, err := http.NewRequest(http.MethodGet, s.URL, nil)
	require.NoError(t, err)

	resp, err := http.DefaultClient.Do(req)
	require.NoError(t, err)

	body, err := io.ReadAll(resp.Body)
	defer resp.Body.Close()
	require.NoError(t, err)

	require.Equal(t, http.StatusNotAcceptable, resp.StatusCode)
	require.Equal(t, "application/json", resp.Header.Get("Content-Type"))
	require.JSONEq(t, `{"status":"error","errorType":"not_acceptable","error":"cannot encode response as application/default-format"}`, string(body))
}

func TestServeTSDBBlocks(t *testing.T) {
	blockMeta := tsdb.BlockMeta{
		ULID:    ulid.MustNew(ulid.Now(), nil),
		MinTime: 0,
		MaxTime: 1000,
		Stats: tsdb.BlockStats{
			NumSeries: 10,
		},
	}

	db := &fakeDB{
		blockMetas: []tsdb.BlockMeta{blockMeta},
	}

	api := &API{
		db: db,
	}

	req := httptest.NewRequest(http.MethodGet, "/api/v1/status/tsdb/blocks", nil)
	w := httptest.NewRecorder()