Debian Codegraph @

testing/integration/ntfy/utils_test.go

raw
1 package ntfy_test
2
3 import (
4 "bytes"
5 "io"
6 "net/http"
7 "net/url"
8 "strings"
9 "testing"
10
11 "github.com/stretchr/testify/mock"
12
13 "github.com/nicholas-fedor/shoutrrr/pkg/services/push/ntfy"
14 "github.com/nicholas-fedor/shoutrrr/pkg/types"
15 )
16
17 // MockHTTPClient is a testify mock that implements the types.HTTPClient interface.
18 type MockHTTPClient struct {
19 mock.Mock
20 }
21
22 // mockLogger is a simple logger implementation for testing.
23 type mockLogger struct{}
24
25 func (m *mockLogger) Print(_ ...any) {}
26 func (m *mockLogger) Printf(_ string, _ ...any) {}
27 func (m *mockLogger) Println(_ ...any) {}
28
29 // createTestService creates an ntfy service instance configured for testing.
30 func createTestService(
31 t *testing.T,
32 serviceURL string,
33 httpClients ...types.HTTPClient,
34 ) *ntfy.Service {
35 t.Helper()
36
37 service := &ntfy.Service{}
38
39 parsedURL, err := url.Parse(serviceURL)
40 if err != nil {
41 t.Fatalf("failed to parse service URL: %v", err)
42 }
43
44 err = service.Initialize(parsedURL, &mockLogger{})
45 if err != nil {
46 t.Fatalf("failed to initialize service: %v", err)
47 }
48
49 // Override the HTTPClient if provided (after Initialize sets the default)
50 if len(httpClients) > 0 && httpClients[0] != nil {
51 service.SetHTTPClient(httpClients[0])
52 }
53
54 return service
55 }
56
57 // createTestParams creates test parameters with the given key-value pairs.
58 func createTestParams(pairs ...string) *types.Params {
59 params := make(types.Params)
60
61 for i := 0; i < len(pairs); i += 2 {
62 if i+1 < len(pairs) {
63 params[pairs[i]] = pairs[i+1]
64 }
65 }
66
67 return &params
68 }
69
70 // createTestServiceWithMock creates an ntfy service instance configured for testing,
71 // along with a MockHTTPClient that is already configured on the service and seeded
72 // with a default successful 200 OK Do expectation.
73 func createTestServiceWithMock(
74 t *testing.T,
75 serviceURL string,
76 ) (*ntfy.Service, *MockHTTPClient) {
77 t.Helper()
78
79 mockClient := &MockHTTPClient{}
80 service := createTestService(t, serviceURL, mockClient)
81
82 mockClient.On("Do", mock.Anything).
83 Return(createMockResponse(http.StatusOK, `{"code":200,"error":"OK"}`), nil).
84 Once()
85
86 return service, mockClient
87 }
88
89 func (m *MockHTTPClient) Do(req *http.Request) (*http.Response, error) {
90 if req.Body != nil {
91 body, err := io.ReadAll(req.Body)
92 if err == nil {
93 req.Body = io.NopCloser(bytes.NewReader(body))
94 }
95 }
96
97 args := m.Called(req)
98
99 if args.Get(0) == nil {
100 return nil, args.Error(1)
101 }
102
103 return args.Get(0).(*http.Response), args.Error(1)
104 }
105
106 // createMockResponse creates a mock HTTP response with the given status code and body.
107 func createMockResponse(statusCode int, body string) *http.Response {
108 resp := &http.Response{
109 StatusCode: statusCode,
110 Body: io.NopCloser(strings.NewReader(body)),
111 Header: make(http.Header),
112 }
113
114 return resp
115 }
116
117 // findMatchingRequest iterates over mock Do calls and returns the first request
118 // that matches the given predicate, or nil if no match is found.
119 func findMatchingRequest(
120 mockClient *MockHTTPClient,
121 predicate func(*http.Request) bool,
122 ) *http.Request {
123 for i := range mockClient.Calls {
124 call := &mockClient.Calls[i]
125 if call.Method == "Do" {
126 req := call.Arguments[0].(*http.Request)
127 if predicate(req) {
128 return req
129 }
130 }
131 }
132
133 return nil
134 }
135
136 // assertRequestContains asserts that the HTTP request body contains the expected content.
137 func assertRequestContains(t *testing.T, mockClient *MockHTTPClient, expectedContent string) {
138 t.Helper()
139
140 req := findMatchingRequest(mockClient, func(req *http.Request) bool {
141 body, err := io.ReadAll(req.Body)
142 if err != nil {
143 return false
144 }
145
146 req.Body = io.NopCloser(bytes.NewReader(body))
147
148 return strings.Contains(string(body), expectedContent)
149 })
150
151 if req == nil {
152 t.Errorf("Expected request body to contain %q, but no matching call found", expectedContent)
153 }
154 }
155
156 // assertRequestHeaderContains asserts that at least one HTTP request contains the expected header value.
157 func assertRequestHeaderContains(
158 t *testing.T,
159 mockClient *MockHTTPClient,
160 headerName,
161 expectedValue string,
162 ) {
163 t.Helper()
164
165 req := findMatchingRequest(mockClient, func(req *http.Request) bool {
166 if values := req.Header.Values(headerName); len(values) > 0 {
167 for _, v := range values {
168 if strings.Contains(v, expectedValue) {
169 return true
170 }
171 }
172 }
173
174 return false
175 })
176
177 if req == nil {
178 t.Errorf("Expected request header %q to contain %q, but no matching call found", headerName, expectedValue)
179 }
180 }
181
182 // assertRequestMade asserts that an HTTP POST request was made to the expected URL.
183 func assertRequestMade(
184 t *testing.T,
185 mockClient *MockHTTPClient,
186 expectedURL string,
187 ) {
188 t.Helper()
189
190 req := findMatchingRequest(mockClient, func(req *http.Request) bool {
191 return req.Method == http.MethodPost && req.URL.String() == expectedURL
192 })
193
194 if req == nil {
195 t.Errorf("Expected POST request to %s, but no matching call found", expectedURL)
196 }
197 }
198
199 // assertRequestMatches asserts that at least one HTTP request matches the given predicate.
200 func assertRequestMatches(
201 t *testing.T,
202 mockClient *MockHTTPClient,
203 predicate func(*http.Request) bool,
204 description string,
205 ) {
206 t.Helper()
207
208 req := findMatchingRequest(mockClient, predicate)
209
210 if req == nil {
211 t.Errorf("Expected request to match %s, but no matching call found", description)
212 }
213 }