|
| 1 | +/* |
| 2 | +Copyright 2024. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package api |
| 18 | + |
| 19 | +import ( |
| 20 | + "encoding/json" |
| 21 | + "net/http" |
| 22 | + "net/http/httptest" |
| 23 | + "strconv" |
| 24 | + |
| 25 | + . "github.com/onsi/ginkgo/v2" |
| 26 | + . "github.com/onsi/gomega" |
| 27 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 28 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 29 | + "k8s.io/apimachinery/pkg/runtime/schema" |
| 30 | + "k8s.io/apimachinery/pkg/util/validation/field" |
| 31 | +) |
| 32 | + |
| 33 | +var _ = Describe("Error Response Functions", func() { |
| 34 | + |
| 35 | + // Shared constants (used across multiple Describe blocks or in BeforeEach) |
| 36 | + const ( |
| 37 | + testRequestPath = "/test" |
| 38 | + testRequestMethod = "GET" |
| 39 | + |
| 40 | + // Used in both failedValidationResponse and Error response structure |
| 41 | + testFieldName = "name" |
| 42 | + testNameRequiredMsg = "name is required" |
| 43 | + ) |
| 44 | + |
| 45 | + var ( |
| 46 | + app *App |
| 47 | + w *httptest.ResponseRecorder |
| 48 | + r *http.Request |
| 49 | + ) |
| 50 | + |
| 51 | + BeforeEach(func() { |
| 52 | + app = &App{} |
| 53 | + w = httptest.NewRecorder() |
| 54 | + r = httptest.NewRequest(testRequestMethod, testRequestPath, http.NoBody) |
| 55 | + }) |
| 56 | + |
| 57 | + Describe("conflictResponse", func() { |
| 58 | + const ( |
| 59 | + httpStatusCodeConflict = http.StatusConflict |
| 60 | + |
| 61 | + testGroupResourceGroup = "test" |
| 62 | + testGroupResourceResource = "tests" |
| 63 | + testResourceName = "test-name" |
| 64 | + testConflictMsg = "WorkspaceKind is used by 5 workspace(s)" |
| 65 | + ) |
| 66 | + |
| 67 | + var httpStatusCodeConflictStr = strconv.Itoa(http.StatusConflict) |
| 68 | + |
| 69 | + type testCase struct { |
| 70 | + description string |
| 71 | + err error |
| 72 | + k8sCauses []metav1.StatusCause |
| 73 | + } |
| 74 | + |
| 75 | + conflictErr := apierrors.NewConflict( |
| 76 | + schema.GroupResource{Group: testGroupResourceGroup, Resource: testGroupResourceResource}, |
| 77 | + testResourceName, |
| 78 | + nil, |
| 79 | + ) |
| 80 | + |
| 81 | + testCases := []testCase{ |
| 82 | + { |
| 83 | + description: "should return 409 with k8s causes", |
| 84 | + err: conflictErr, |
| 85 | + k8sCauses: []metav1.StatusCause{{Type: metav1.CauseTypeFieldValueInvalid, Message: testConflictMsg}}, |
| 86 | + }, |
| 87 | + { |
| 88 | + description: "should return 409 with error message when no k8s causes", |
| 89 | + err: conflictErr, |
| 90 | + k8sCauses: nil, |
| 91 | + }, |
| 92 | + { |
| 93 | + description: "should return 409 with empty conflict causes array", |
| 94 | + err: conflictErr, |
| 95 | + k8sCauses: []metav1.StatusCause{}, |
| 96 | + }, |
| 97 | + } |
| 98 | + |
| 99 | + buildExpectedConflictResponse := func(err error, k8sCauses []metav1.StatusCause, codeStr string) ErrorResponse { |
| 100 | + expectedConflictCauses := make([]ConflictError, len(k8sCauses)) |
| 101 | + for i, cause := range k8sCauses { |
| 102 | + expectedConflictCauses[i] = ConflictError{ |
| 103 | + Origin: OriginKubernetes, |
| 104 | + Message: cause.Message, |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + // Determine message: if we have k8s causes, use generic message; otherwise use error message |
| 109 | + var expectedMessage string |
| 110 | + if len(k8sCauses) > 0 { |
| 111 | + expectedMessage = errMsgKubernetesConflict |
| 112 | + } else { |
| 113 | + expectedMessage = err.Error() |
| 114 | + } |
| 115 | + |
| 116 | + // Empty slices become nil after JSON unmarshaling |
| 117 | + var expectedConflictCausesForComparison []ConflictError |
| 118 | + if len(expectedConflictCauses) > 0 { |
| 119 | + expectedConflictCausesForComparison = expectedConflictCauses |
| 120 | + } else { |
| 121 | + expectedConflictCausesForComparison = nil |
| 122 | + } |
| 123 | + |
| 124 | + return ErrorResponse{ |
| 125 | + Code: codeStr, |
| 126 | + Message: expectedMessage, |
| 127 | + Cause: &ErrorCause{ |
| 128 | + ConflictCauses: expectedConflictCausesForComparison, |
| 129 | + }, |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + for _, tc := range testCases { |
| 134 | + It(tc.description, func() { |
| 135 | + app.conflictResponse(w, r, tc.err, tc.k8sCauses) |
| 136 | + |
| 137 | + Expect(w.Code).To(Equal(httpStatusCodeConflict)) |
| 138 | + |
| 139 | + var envelope ErrorEnvelope |
| 140 | + unmarshalErr := json.Unmarshal(w.Body.Bytes(), &envelope) |
| 141 | + Expect(unmarshalErr).NotTo(HaveOccurred()) |
| 142 | + Expect(envelope.Error).NotTo(BeNil()) |
| 143 | + |
| 144 | + expectedErrorResponse := buildExpectedConflictResponse(tc.err, tc.k8sCauses, httpStatusCodeConflictStr) |
| 145 | + Expect(envelope.Error.ErrorResponse).To(Equal(expectedErrorResponse)) |
| 146 | + }) |
| 147 | + } |
| 148 | + }) |
| 149 | + |
| 150 | + Describe("failedValidationResponse", func() { |
| 151 | + const ( |
| 152 | + httpStatusCodeUnprocessableEntity = http.StatusUnprocessableEntity |
| 153 | + |
| 154 | + testFieldKind = "kind" |
| 155 | + testFieldSpecName = "spec.name" |
| 156 | + testFieldSpecKind = "spec.kind" |
| 157 | + testInvalidKind = "invalid-kind" |
| 158 | + testKindInvalidMsg = "kind is invalid" |
| 159 | + ) |
| 160 | + |
| 161 | + var httpStatusCodeUnprocessableEntityStr = strconv.Itoa(http.StatusUnprocessableEntity) |
| 162 | + |
| 163 | + type testCase struct { |
| 164 | + description string |
| 165 | + msg string |
| 166 | + valErrs field.ErrorList |
| 167 | + k8sCauses []metav1.StatusCause |
| 168 | + } |
| 169 | + |
| 170 | + buildExpectedValidationResponse := func(msg string, valErrs field.ErrorList, k8sCauses []metav1.StatusCause, codeStr string) ErrorResponse { |
| 171 | + valErrsConverted := make([]ValidationError, len(valErrs)) |
| 172 | + for i, err := range valErrs { |
| 173 | + valErrsConverted[i] = ValidationError{ |
| 174 | + Origin: OriginInternal, |
| 175 | + Type: err.Type, |
| 176 | + Field: err.Field, |
| 177 | + Message: err.ErrorBody(), |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + k8sCausesConverted := make([]ValidationError, len(k8sCauses)) |
| 182 | + for i, cause := range k8sCauses { |
| 183 | + k8sCausesConverted[i] = ValidationError{ |
| 184 | + Origin: OriginKubernetes, |
| 185 | + Type: field.ErrorType(cause.Type), |
| 186 | + Field: cause.Field, |
| 187 | + Message: cause.Message, |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + expectedValidationErrors := make([]ValidationError, len(valErrsConverted)+len(k8sCausesConverted)) |
| 192 | + copy(expectedValidationErrors, valErrsConverted) |
| 193 | + copy(expectedValidationErrors[len(valErrsConverted):], k8sCausesConverted) |
| 194 | + |
| 195 | + var expectedValidationErrorsForComparison []ValidationError |
| 196 | + if len(expectedValidationErrors) > 0 { |
| 197 | + expectedValidationErrorsForComparison = expectedValidationErrors |
| 198 | + } else { |
| 199 | + expectedValidationErrorsForComparison = nil |
| 200 | + } |
| 201 | + |
| 202 | + return ErrorResponse{ |
| 203 | + Code: codeStr, |
| 204 | + Message: msg, |
| 205 | + Cause: &ErrorCause{ |
| 206 | + ValidationErrors: expectedValidationErrorsForComparison, |
| 207 | + }, |
| 208 | + } |
| 209 | + } |
| 210 | + |
| 211 | + testCases := []testCase{ |
| 212 | + { |
| 213 | + description: "should return 422 with internal validation errors", |
| 214 | + msg: errMsgRequestBodyInvalid, |
| 215 | + valErrs: field.ErrorList{ |
| 216 | + field.Required(field.NewPath(testFieldName), ""), |
| 217 | + field.Invalid(field.NewPath(testFieldKind), testInvalidKind, testKindInvalidMsg), |
| 218 | + }, |
| 219 | + k8sCauses: nil, |
| 220 | + }, |
| 221 | + { |
| 222 | + description: "should return 422 with k8s validation errors", |
| 223 | + msg: errMsgKubernetesValidation, |
| 224 | + valErrs: nil, |
| 225 | + k8sCauses: []metav1.StatusCause{ |
| 226 | + { |
| 227 | + Type: metav1.CauseTypeFieldValueRequired, |
| 228 | + Field: testFieldSpecName, |
| 229 | + Message: testNameRequiredMsg, |
| 230 | + }, |
| 231 | + { |
| 232 | + Type: metav1.CauseTypeFieldValueInvalid, |
| 233 | + Field: testFieldSpecKind, |
| 234 | + Message: testKindInvalidMsg, |
| 235 | + }, |
| 236 | + }, |
| 237 | + }, |
| 238 | + { |
| 239 | + description: "should return 422 with both internal and k8s validation errors", |
| 240 | + msg: errMsgRequestBodyInvalid, |
| 241 | + valErrs: field.ErrorList{ |
| 242 | + field.Required(field.NewPath(testFieldName), ""), |
| 243 | + }, |
| 244 | + k8sCauses: []metav1.StatusCause{ |
| 245 | + { |
| 246 | + Type: metav1.CauseTypeFieldValueInvalid, |
| 247 | + Field: testFieldSpecKind, |
| 248 | + Message: testKindInvalidMsg, |
| 249 | + }, |
| 250 | + }, |
| 251 | + }, |
| 252 | + { |
| 253 | + description: "should return 422 with empty validation errors", |
| 254 | + msg: errMsgRequestBodyInvalid, |
| 255 | + valErrs: nil, |
| 256 | + k8sCauses: nil, |
| 257 | + }, |
| 258 | + } |
| 259 | + |
| 260 | + for _, tc := range testCases { |
| 261 | + It(tc.description, func() { |
| 262 | + app.failedValidationResponse(w, r, tc.msg, tc.valErrs, tc.k8sCauses) |
| 263 | + |
| 264 | + Expect(w.Code).To(Equal(httpStatusCodeUnprocessableEntity)) |
| 265 | + |
| 266 | + var envelope ErrorEnvelope |
| 267 | + err := json.Unmarshal(w.Body.Bytes(), &envelope) |
| 268 | + Expect(err).NotTo(HaveOccurred()) |
| 269 | + Expect(envelope.Error).NotTo(BeNil()) |
| 270 | + |
| 271 | + expectedErrorResponse := buildExpectedValidationResponse(tc.msg, tc.valErrs, tc.k8sCauses, httpStatusCodeUnprocessableEntityStr) |
| 272 | + Expect(envelope.Error.ErrorResponse).To(Equal(expectedErrorResponse)) |
| 273 | + }) |
| 274 | + } |
| 275 | + }) |
| 276 | +}) |
0 commit comments