forked from stripe/stripe-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClientTest.java
More file actions
326 lines (279 loc) · 11.7 KB
/
Copy pathHttpClientTest.java
File metadata and controls
326 lines (279 loc) · 11.7 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
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
package com.stripe.net;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.withSettings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.stripe.BaseStripeTest;
import com.stripe.Stripe;
import com.stripe.exception.ApiConnectionException;
import com.stripe.exception.StripeException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class HttpClientTest extends BaseStripeTest {
private HttpClient client;
private StripeRequest request;
private HttpHeaders emptyHeaders = HttpHeaders.of(Collections.emptyMap());
@BeforeEach
public void setUpFixtures() throws StripeException {
this.client =
Mockito.mock(
HttpClient.class,
withSettings().useConstructor().defaultAnswer(Mockito.CALLS_REAL_METHODS));
this.client.networkRetriesSleep = false;
this.request =
StripeRequest.create(
ApiResource.RequestMethod.GET,
"http://example.com/get",
null,
RequestOptions.builder().setApiKey("sk_test_123").setMaxNetworkRetries(2).build(),
ApiMode.V1);
}
@Test
public void testRequestWithRetriesConnectException() throws StripeException {
Mockito.when(this.client.request(this.request))
.thenThrow(new ApiConnectionException("foo", new ConnectException("timeout or something")))
.thenReturn(new StripeResponse(200, emptyHeaders, "{}"));
StripeResponse response = this.client.requestWithRetries(this.request);
assertNotNull(response);
assertEquals(200, response.code());
assertEquals(1, response.numRetries());
}
@Test
public void testRequestWithRetriesConnectExceptionRethrowAfterAllAttempts()
throws StripeException {
Mockito.when(this.client.request(this.request))
.thenThrow(new ApiConnectionException("1", new ConnectException("timeout 1")))
.thenThrow(new ApiConnectionException("2", new ConnectException("timeout 2")))
.thenThrow(new ApiConnectionException("3", new ConnectException("timeout 3")));
ApiConnectionException e =
assertThrows(
ApiConnectionException.class,
() -> {
this.client.requestWithRetries(this.request);
});
assertEquals("3", e.getMessage());
assertNotNull(e.getCause());
assertTrue(e.getCause() instanceof ConnectException);
assertEquals("timeout 3", e.getCause().getMessage());
}
@Test
public void testRequestWithRetriesSocketTimeoutException() throws StripeException {
Mockito.when(this.client.request(this.request))
.thenThrow(
new ApiConnectionException("foo", new SocketTimeoutException("timeout or something")))
.thenReturn(new StripeResponse(200, emptyHeaders, "{}"));
StripeResponse response = this.client.requestWithRetries(this.request);
assertNotNull(response);
assertEquals(200, response.code());
assertEquals(1, response.numRetries());
}
@Test
public void testRequestWithRetriesSocketTimeoutExceptionRethrowAfterAllAttempts()
throws StripeException {
Mockito.when(this.client.request(this.request))
.thenThrow(new ApiConnectionException("1", new SocketTimeoutException("timeout 1")))
.thenThrow(new ApiConnectionException("2", new SocketTimeoutException("timeout 2")))
.thenThrow(new ApiConnectionException("3", new SocketTimeoutException("timeout 3")));
ApiConnectionException e =
assertThrows(
ApiConnectionException.class,
() -> {
this.client.requestWithRetries(this.request);
});
assertEquals("3", e.getMessage());
assertNotNull(e.getCause());
assertTrue(e.getCause() instanceof SocketTimeoutException);
assertEquals("timeout 3", e.getCause().getMessage());
}
@Test
public void testRequestWithRetriesStripeShouldRetryTrue() throws StripeException {
Mockito.when(this.client.request(this.request))
.thenReturn(
new StripeResponse(
400,
HttpHeaders.of(ImmutableMap.of("Stripe-Should-Retry", ImmutableList.of("true"))),
"{}"))
.thenReturn(new StripeResponse(200, emptyHeaders, "{}"));
StripeResponse response = this.client.requestWithRetries(this.request);
assertNotNull(response);
assertEquals(200, response.code());
assertEquals(1, response.numRetries());
}
@Test
public void testRequestWithRetriesStripeShouldRetryFalse() throws StripeException {
Mockito.when(this.client.request(this.request))
.thenReturn(
new StripeResponse(
400,
HttpHeaders.of(ImmutableMap.of("Stripe-Should-Retry", ImmutableList.of("false"))),
"{}"));
StripeResponse response = this.client.requestWithRetries(this.request);
assertNotNull(response);
assertEquals(400, response.code());
assertEquals(0, response.numRetries());
}
@Test
public void testRequestWithRetriesConflict() throws StripeException {
Mockito.when(this.client.request(this.request))
.thenReturn(new StripeResponse(409, emptyHeaders, "{}"))
.thenReturn(new StripeResponse(200, emptyHeaders, "{}"));
StripeResponse response = this.client.requestWithRetries(this.request);
assertNotNull(response);
assertEquals(200, response.code());
assertEquals(1, response.numRetries());
}
@Test
public void testRequestWithRetriesConflictServiceUnavailable() throws StripeException {
Mockito.when(this.client.request(this.request))
.thenReturn(new StripeResponse(503, emptyHeaders, "{}"))
.thenReturn(new StripeResponse(200, emptyHeaders, "{}"));
StripeResponse response = this.client.requestWithRetries(this.request);
assertNotNull(response);
assertEquals(200, response.code());
assertEquals(1, response.numRetries());
}
@Test
public void testRequestWithRetriesConflictInternalServerError() throws StripeException {
Mockito.when(this.client.request(this.request))
.thenReturn(new StripeResponse(500, emptyHeaders, "{}"))
.thenReturn(new StripeResponse(200, emptyHeaders, "{}"));
StripeResponse response = this.client.requestWithRetries(this.request);
assertNotNull(response);
assertEquals(200, response.code());
assertEquals(1, response.numRetries());
}
@Test
public void testV1RequestSetsCorrectUserAgent() throws StripeException {
StripeRequest request =
StripeRequest.create(
ApiResource.RequestMethod.GET,
"http://example.com/get",
null,
RequestOptions.builder().setApiKey("sk_test_123").setMaxNetworkRetries(2).build(),
ApiMode.V1);
String userAgent = HttpClient.buildUserAgentString(request);
assertTrue(userAgent.startsWith(String.format("Stripe/v1 JavaBindings/%s", Stripe.VERSION)));
}
@Test
public void testV2RequestSetsCorrectUserAgent() throws StripeException {
StripeRequest request =
StripeRequest.create(
ApiResource.RequestMethod.GET,
"http://example.com/get",
null,
RequestOptions.builder().setApiKey("sk_test_123").setMaxNetworkRetries(2).build(),
ApiMode.V2);
String userAgent = HttpClient.buildUserAgentString(request);
assertTrue(userAgent.startsWith(String.format("Stripe/v2 JavaBindings/%s", Stripe.VERSION)));
}
@Test
public void testDetectAIAgent() {
String agent = HttpClient.detectAIAgent(key -> key.equals("CLAUDECODE") ? "1" : null);
assertEquals("claude_code", agent);
}
@Test
public void testDetectAIAgentNoEnv() {
String agent = HttpClient.detectAIAgent(key -> null);
assertEquals("", agent);
}
@Test
public void testDetectAIAgentFirstMatchWins() {
String agent =
HttpClient.detectAIAgent(
key -> {
if (key.equals("CURSOR_AGENT") || key.equals("OPENCODE")) return "1";
return null;
});
assertEquals("cursor", agent);
}
@Test
public void testBuildUserAgentStringWithAIAgent() throws StripeException {
StripeRequest request =
StripeRequest.create(
ApiResource.RequestMethod.GET,
"http://example.com/get",
null,
RequestOptions.builder().setApiKey("sk_test_123").build(),
ApiMode.V1);
String userAgent = HttpClient.buildUserAgentString(request, "cursor");
assertTrue(userAgent.contains("AIAgent/cursor"));
}
@Test
public void testBuildXStripeClientUserAgentStringWithAIAgent() {
String json = HttpClient.buildXStripeClientUserAgentString("cursor");
com.google.gson.JsonObject parsed =
com.google.gson.JsonParser.parseString(json).getAsJsonObject();
assertEquals("cursor", parsed.get("ai_agent").getAsString());
}
@Test
public void testBuildXStripeClientUserAgentStringOmitsPublisherAndOsKeys() {
String json = HttpClient.buildXStripeClientUserAgentString("");
com.google.gson.JsonObject parsed =
com.google.gson.JsonParser.parseString(json).getAsJsonObject();
assertTrue(!parsed.has("publisher"));
assertTrue(!parsed.has("os.name"));
assertTrue(!parsed.has("os.version"));
assertTrue(!parsed.has("os.arch"));
}
@Test
public void testBuildXStripeClientUserAgentStringPlatformWithTelemetry() {
boolean originalTelemetry = Stripe.enableTelemetry;
try {
Stripe.enableTelemetry = true;
String json = HttpClient.buildXStripeClientUserAgentString("");
com.google.gson.JsonObject parsed =
com.google.gson.JsonParser.parseString(json).getAsJsonObject();
assertTrue(parsed.has("platform"));
String platform = parsed.get("platform").getAsString();
assertTrue(platform.contains(System.getProperty("os.name")));
} finally {
Stripe.enableTelemetry = originalTelemetry;
}
}
@Test
public void testBuildXStripeClientUserAgentStringNoPlatformWithoutTelemetry() {
boolean originalTelemetry = Stripe.enableTelemetry;
try {
Stripe.enableTelemetry = false;
String json = HttpClient.buildXStripeClientUserAgentString("");
com.google.gson.JsonObject parsed =
com.google.gson.JsonParser.parseString(json).getAsJsonObject();
assertTrue(!parsed.has("platform"));
} finally {
Stripe.enableTelemetry = originalTelemetry;
}
}
@Test
public void testBuildXStripeClientUserAgentStringIncludesSource() {
String json = HttpClient.buildXStripeClientUserAgentString("");
com.google.gson.JsonObject parsed =
com.google.gson.JsonParser.parseString(json).getAsJsonObject();
// "source" should be present and be a 32-character lowercase MD5 hex digest
assertTrue(parsed.has("source"), "Expected 'source' field in X-Stripe-Client-User-Agent");
String source = parsed.get("source").getAsString();
assertTrue(
source.matches("[0-9a-f]{32}"),
"Expected 'source' to be a 32-character lowercase hex string, got: " + source);
}
@Test
public void testBuildXStripeClientUserAgentStringOmitsSourceWhenEmpty() throws Exception {
String savedHash = HttpClient.UNAME_HASH;
try {
HttpClient.UNAME_HASH = "";
String userAgentString = HttpClient.buildXStripeClientUserAgentString("");
com.google.gson.JsonObject userAgent =
com.google.gson.JsonParser.parseString(userAgentString).getAsJsonObject();
assertFalse(userAgent.has("source"));
} finally {
HttpClient.UNAME_HASH = savedHash;
}
}
}