1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
|
package meilisearch
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// Mock structures for testing
type mockResponse struct {
Message string `json:"message"`
}
type mockJsonMarshaller struct {
valid bool
null bool
Foo string `json:"foo"`
Bar string `json:"bar"`
}
// failingEncoder is used to simulate encoder failure
type failingEncoder struct{}
func (fe failingEncoder) Encode(r io.Reader) (io.ReadCloser, error) {
return nil, errors.New("dummy encoding failure")
}
// Implement Decode method to satisfy the encoder interface, though it won't be used here
func (fe failingEncoder) Decode(b []byte, v interface{}) error {
return errors.New("dummy decode failure")
}
func TestExecuteRequest(t *testing.T) {
retryCount := 0
// Create a mock server
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet && r.URL.Path == "/test-get" {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"message":"get successful"}`))
} else if r.Method == http.MethodGet && r.URL.Path == "/test-get-encoding" {
encode := r.Header.Get("Accept-Encoding")
if len(encode) != 0 {
enc := newEncoding(ContentEncoding(encode), DefaultCompression)
d := &mockData{Name: "foo", Age: 30}
b, err := json.Marshal(d)
require.NoError(t, err)
res, err := enc.Encode(bytes.NewReader(b))
require.NoError(t, err)
defer func() {
_ = res.Close()
}()
compressedData, err := io.ReadAll(res)
require.NoError(t, err)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(compressedData)
return
}
_, _ = w.Write([]byte("invalid message"))
w.WriteHeader(http.StatusInternalServerError)
} else if r.Method == http.MethodPost && r.URL.Path == "/test-req-resp-encoding" {
accept := r.Header.Get("Accept-Encoding")
ce := r.Header.Get("Content-Encoding")
reqEnc := newEncoding(ContentEncoding(ce), DefaultCompression)
respEnc := newEncoding(ContentEncoding(accept), DefaultCompression)
req := new(mockData)
if len(ce) != 0 {
b, err := io.ReadAll(r.Body)
require.NoError(t, err)
err = reqEnc.Decode(b, req)
require.NoError(t, err)
}
if len(accept) != 0 {
d, err := json.Marshal(req)
require.NoError(t, err)
res, err := respEnc.Encode(bytes.NewReader(d))
require.NoError(t, err)
defer func() {
_ = res.Close()
}()
compressedData, err := io.ReadAll(res)
require.NoError(t, err)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(compressedData)
}
} else if r.Method == http.MethodPost && r.URL.Path == "/test-post" {
w.WriteHeader(http.StatusCreated)
msg := []byte(`{"message":"post successful"}`)
_, _ = w.Write(msg)
} else if r.Method == http.MethodGet && r.URL.Path == "/test-null-body" {
w.WriteHeader(http.StatusOK)
msg := []byte(`null`)
_, _ = w.Write(msg)
} else if r.Method == http.MethodPost && r.URL.Path == "/test-post-encoding" {
w.WriteHeader(http.StatusCreated)
msg := []byte(`{"message":"post successful"}`)
enc := r.Header.Get("Accept-Encoding")
if len(enc) != 0 {
e := newEncoding(ContentEncoding(enc), DefaultCompression)
res, err := e.Encode(bytes.NewReader(msg))
require.NoError(t, err)
defer func() {
_ = res.Close()
}()
compressedData, err := io.ReadAll(res)
require.NoError(t, err)
_, _ = w.Write(compressedData)
return
}
_, _ = w.Write(msg)
} else if r.URL.Path == "/test-bad-request" {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"message":"bad request"}`))
} else if r.URL.Path == "/invalid-response-body" {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"message":"bad response body"}`))
} else if r.URL.Path == "/io-reader" {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"message":"io reader"}`))
} else if r.URL.Path == "/failed-retry" {
w.WriteHeader(http.StatusBadGateway)
} else if r.URL.Path == "/success-retry" {
if retryCount == 2 {
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusBadGateway)
retryCount++
} else if r.URL.Path == "/dummy" {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusNotFound)
}
}))
defer ts.Close()
tests := []struct {
name string
internalReq *internalRequest
expectedResp interface{}
contentEncoding ContentEncoding
withTimeout bool
disableRetry bool
wantErr bool
}{
{
name: "Successful GET request",
internalReq: &internalRequest{
endpoint: "/test-get",
method: http.MethodGet,
withResponse: &mockResponse{},
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: &mockResponse{Message: "get successful"},
wantErr: false,
},
{
name: "Successful POST request",
internalReq: &internalRequest{
endpoint: "/test-post",
method: http.MethodPost,
withRequest: map[string]string{"key": "value"},
contentType: contentTypeJSON,
withResponse: &mockResponse{},
acceptedStatusCodes: []int{http.StatusCreated},
},
expectedResp: &mockResponse{Message: "post successful"},
wantErr: false,
},
{
name: "404 Not Found",
internalReq: &internalRequest{
endpoint: "/not-found",
method: http.MethodGet,
withResponse: &mockResponse{},
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: nil,
wantErr: true,
},
{
name: "Invalid URL",
internalReq: &internalRequest{
endpoint: "/invalid-url$%^*()*#",
method: http.MethodGet,
withResponse: &mockResponse{},
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: nil,
wantErr: true,
},
{
name: "Invalid response body",
internalReq: &internalRequest{
endpoint: "/invalid-response-body",
method: http.MethodGet,
withResponse: struct{}{},
acceptedStatusCodes: []int{http.StatusInternalServerError},
},
expectedResp: nil,
wantErr: true,
},
{
name: "Invalid request method",
internalReq: &internalRequest{
endpoint: "/invalid-request-method",
method: http.MethodGet,
withResponse: nil,
withRequest: struct{}{},
acceptedStatusCodes: []int{http.StatusBadRequest},
},
expectedResp: nil,
wantErr: true,
},
{
name: "Invalid request content type",
internalReq: &internalRequest{
endpoint: "/invalid-request-content-type",
method: http.MethodPost,
withResponse: nil,
contentType: "",
withRequest: struct{}{},
acceptedStatusCodes: []int{http.StatusBadRequest},
},
expectedResp: nil,
wantErr: true,
},
{
name: "Invalid json marshaler",
internalReq: &internalRequest{
endpoint: "/invalid-marshaler",
method: http.MethodPost,
withResponse: nil,
withRequest: &mockJsonMarshaller{
valid: false,
},
contentType: "application/json",
},
expectedResp: nil,
wantErr: true,
},
{
name: "Null data marshaler",
internalReq: &internalRequest{
endpoint: "/null-data-marshaler",
method: http.MethodPost,
withResponse: nil,
withRequest: &mockJsonMarshaller{
valid: true,
null: true,
},
contentType: "application/json",
},
expectedResp: nil,
wantErr: true,
},
{
name: "Test null body response",
internalReq: &internalRequest{
endpoint: "/test-null-body",
method: http.MethodGet,
withResponse: make([]byte, 0),
contentType: "application/json",
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: nil,
wantErr: false,
},
{
name: "400 Bad Request",
internalReq: &internalRequest{
endpoint: "/test-bad-request",
method: http.MethodGet,
withResponse: &mockResponse{},
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: nil,
wantErr: true,
},
{
name: "Test request encoding gzip",
internalReq: &internalRequest{
endpoint: "/test-post-encoding",
method: http.MethodPost,
withRequest: map[string]string{"key": "value"},
contentType: contentTypeJSON,
withResponse: &mockResponse{},
acceptedStatusCodes: []int{http.StatusCreated},
},
expectedResp: &mockResponse{Message: "post successful"},
contentEncoding: GzipEncoding,
wantErr: false,
},
{
name: "Test request encoding deflate",
internalReq: &internalRequest{
endpoint: "/test-post-encoding",
method: http.MethodPost,
withRequest: map[string]string{"key": "value"},
contentType: contentTypeJSON,
withResponse: &mockResponse{},
acceptedStatusCodes: []int{http.StatusCreated},
},
expectedResp: &mockResponse{Message: "post successful"},
contentEncoding: DeflateEncoding,
wantErr: false,
},
{
name: "Test request encoding brotli",
internalReq: &internalRequest{
endpoint: "/test-post-encoding",
method: http.MethodPost,
withRequest: map[string]string{"key": "value"},
contentType: contentTypeJSON,
withResponse: &mockResponse{},
acceptedStatusCodes: []int{http.StatusCreated},
},
expectedResp: &mockResponse{Message: "post successful"},
contentEncoding: BrotliEncoding,
wantErr: false,
},
{
name: "Test response decoding gzip",
internalReq: &internalRequest{
endpoint: "/test-get-encoding",
method: http.MethodGet,
withRequest: nil,
withResponse: &mockData{},
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: &mockData{Name: "foo", Age: 30},
contentEncoding: GzipEncoding,
wantErr: false,
},
{
name: "Test response decoding deflate",
internalReq: &internalRequest{
endpoint: "/test-get-encoding",
method: http.MethodGet,
withRequest: nil,
withResponse: &mockData{},
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: &mockData{Name: "foo", Age: 30},
contentEncoding: DeflateEncoding,
wantErr: false,
},
{
name: "Test response decoding brotli",
internalReq: &internalRequest{
endpoint: "/test-get-encoding",
method: http.MethodGet,
withRequest: nil,
withResponse: &mockData{},
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: &mockData{Name: "foo", Age: 30},
contentEncoding: BrotliEncoding,
wantErr: false,
},
{
name: "Test request and response encoding",
internalReq: &internalRequest{
endpoint: "/test-req-resp-encoding",
method: http.MethodPost,
contentType: contentTypeJSON,
withRequest: &mockData{Name: "foo", Age: 30},
withResponse: &mockData{},
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: &mockData{Name: "foo", Age: 30},
contentEncoding: GzipEncoding,
wantErr: false,
},
{
name: "Test successful retries",
internalReq: &internalRequest{
endpoint: "/success-retry",
method: http.MethodGet,
withResponse: nil,
withRequest: nil,
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: nil,
wantErr: false,
},
{
name: "Test failed retries",
internalReq: &internalRequest{
endpoint: "/failed-retry",
method: http.MethodGet,
withResponse: nil,
withRequest: nil,
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: nil,
wantErr: true,
},
{
name: "Test disable retries",
internalReq: &internalRequest{
endpoint: "/test-get",
method: http.MethodGet,
withResponse: nil,
withRequest: nil,
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: nil,
disableRetry: true,
wantErr: false,
},
{
name: "Test request timeout on retries",
internalReq: &internalRequest{
endpoint: "/failed-retry",
method: http.MethodGet,
withResponse: nil,
withRequest: nil,
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: nil,
withTimeout: true,
wantErr: true,
},
{
name: "Test request encoding with []byte encode failure",
internalReq: &internalRequest{
endpoint: "/dummy",
method: http.MethodPost,
withRequest: []byte("test data"),
contentType: "text/plain",
acceptedStatusCodes: []int{http.StatusOK},
},
expectedResp: nil,
contentEncoding: GzipEncoding,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := newClient(&http.Client{}, ts.URL, "testApiKey", &clientConfig{
contentEncoding: tt.contentEncoding,
encodingCompressionLevel: DefaultCompression,
maxRetries: 3,
disableRetry: tt.disableRetry,
retryOnStatus: map[int]bool{
502: true,
503: true,
504: true,
},
jsonMarshal: json.Marshal,
jsonUnmarshal: json.Unmarshal,
})
// For the specific test case, override the encoder to force an error
if tt.name == "Test request encoding with []byte encode failure" {
c.encoder = failingEncoder{}
}
ctx := context.Background()
if tt.withTimeout {
timeoutCtx, cancel := context.WithTimeout(ctx, 1*time.Second)
ctx = timeoutCtx
defer cancel()
}
err := c.executeRequest(ctx, tt.internalReq)
if tt.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
require.Equal(t, tt.expectedResp, tt.internalReq.withResponse)
}
})
}
}
func TestNewClientNilRetryOnStatus(t *testing.T) {
c := newClient(&http.Client{}, "", "", &clientConfig{
maxRetries: 3,
retryOnStatus: nil,
})
require.NotNil(t, c.retryOnStatus)
}
func (m mockJsonMarshaller) MarshalJSON() ([]byte, error) {
type Alias mockJsonMarshaller
if !m.valid {
return nil, errors.New("mockJsonMarshaller not valid")
}
if m.null {
return nil, nil
}
return json.Marshal(&struct {
Alias
}{
Alias: Alias(m),
})
}
|