|
| 1 | +package eppoclient |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "net/http/httptest" |
| 6 | + "testing" |
| 7 | +) |
| 8 | + |
| 9 | +func TestHttpClientGet(t *testing.T) { |
| 10 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 11 | + switch r.URL.Path { |
| 12 | + case "/test": |
| 13 | + w.WriteHeader(http.StatusOK) |
| 14 | + _, _ = w.Write([]byte(`OK`)) |
| 15 | + case "/unauthorized": |
| 16 | + w.WriteHeader(http.StatusUnauthorized) |
| 17 | + _, _ = w.Write([]byte(`Unauthorized`)) |
| 18 | + case "/internal-error": |
| 19 | + w.WriteHeader(http.StatusInternalServerError) |
| 20 | + _, _ = w.Write([]byte(`Internal Server Error`)) |
| 21 | + case "/bad-response": |
| 22 | + w.WriteHeader(http.StatusOK) |
| 23 | + if hijacker, ok := w.(http.Hijacker); ok { |
| 24 | + conn, _, _ := hijacker.Hijack() |
| 25 | + conn.Close() // Close the connection to simulate an unreadable body |
| 26 | + } |
| 27 | + } |
| 28 | + })) |
| 29 | + defer server.Close() |
| 30 | + |
| 31 | + client := &http.Client{} |
| 32 | + hc := newHttpClient(server.URL, client, SDKParams{ |
| 33 | + apiKey: "testApiKey", |
| 34 | + sdkName: "testSdkName", |
| 35 | + sdkVersion: "testSdkVersion", |
| 36 | + }) |
| 37 | + |
| 38 | + tests := []struct { |
| 39 | + name string |
| 40 | + resource string |
| 41 | + expectedError string |
| 42 | + expectedResult string |
| 43 | + }{ |
| 44 | + { |
| 45 | + name: "api returns http 200", |
| 46 | + resource: "/test", |
| 47 | + expectedResult: "OK", |
| 48 | + }, |
| 49 | + { |
| 50 | + name: "api returns 401 unauthorized error", |
| 51 | + resource: "/unauthorized", |
| 52 | + expectedError: "unauthorized access", |
| 53 | + }, |
| 54 | + { |
| 55 | + name: "api returns an 500 error", |
| 56 | + resource: "/internal-error", |
| 57 | + expectedError: "server error: 500", |
| 58 | + }, |
| 59 | + { |
| 60 | + name: "api returns unreadable body", |
| 61 | + resource: "/bad-response", |
| 62 | + expectedError: "server error: unreadable body", |
| 63 | + }, |
| 64 | + } |
| 65 | + |
| 66 | + for _, tc := range tests { |
| 67 | + t.Run(tc.name, func(t *testing.T) { |
| 68 | + result, err := hc.get(tc.resource) |
| 69 | + if err != nil { |
| 70 | + if err.Error() != tc.expectedError { |
| 71 | + t.Errorf("Expected error %v, got %v", tc.expectedError, err) |
| 72 | + } |
| 73 | + if result != "" { // Check if result is not an empty string when an error is expected |
| 74 | + t.Errorf("Expected result to be an empty string when there is an error, got %v", result) |
| 75 | + } |
| 76 | + } else { |
| 77 | + if tc.expectedError != "" { |
| 78 | + t.Errorf("Expected error %v, got nil", tc.expectedError) |
| 79 | + } |
| 80 | + if result != tc.expectedResult { |
| 81 | + t.Errorf("Expected result %v, got %v", tc.expectedResult, result) |
| 82 | + } |
| 83 | + } |
| 84 | + }) |
| 85 | + } |
| 86 | +} |
0 commit comments