-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathendpoint_fetch_test.go
More file actions
90 lines (79 loc) · 2.35 KB
/
Copy pathendpoint_fetch_test.go
File metadata and controls
90 lines (79 loc) · 2.35 KB
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//go:build unit
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestFetchFromEndpoint tests the fetchFromEndpoint helper with various HTTP
// response scenarios.
func TestFetchFromEndpoint(t *testing.T) {
t.Parallel()
tests := []struct {
name string
statusCode int
responseBody string
expectErr bool
errContains string
expectedBody string
}{
{
name: "successful fetch returns body",
statusCode: http.StatusOK,
responseBody: `{"token":"secret-value"}`,
expectErr: false,
expectedBody: `{"token":"secret-value"}`,
},
{
name: "non-200 response returns error with status code and body",
statusCode: http.StatusNotFound,
responseBody: `{"code":"NotFound","message":"not found"}`,
expectErr: true,
errContains: "HTTP 404",
},
{
name: "internal server error returns error with status code and body",
statusCode: http.StatusInternalServerError,
responseBody: `{"code":"InternalServerError","message":"error"}`,
expectErr: true,
errContains: "HTTP 500",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(tc.statusCode)
_, _ = fmt.Fprint(w, tc.responseBody)
}))
defer server.Close()
body, err := fetchFromEndpoint(server.URL)
if tc.expectErr {
require.Error(t, err)
assert.Contains(t, err.Error(), tc.errContains)
assert.Contains(t, err.Error(), server.URL)
// Verify the error includes the response body snippet for debugging.
if tc.responseBody != "" {
assert.Contains(t, err.Error(), tc.responseBody)
}
} else {
require.NoError(t, err)
assert.Equal(t, tc.expectedBody, string(body))
}
})
}
}
// TestFetchFromEndpointNetworkError tests that a network error returns a
// descriptive error including the URL.
func TestFetchFromEndpointNetworkError(t *testing.T) {
t.Parallel()
body, err := fetchFromEndpoint("http://127.0.0.1:0/nonexistent")
require.Error(t, err)
assert.Nil(t, body)
assert.Contains(t, err.Error(), "failed to fetch from")
}