-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntegrationPropertyTest.java
More file actions
488 lines (419 loc) · 19.8 KB
/
IntegrationPropertyTest.java
File metadata and controls
488 lines (419 loc) · 19.8 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
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
package com.github.mrbox.easyhttp.client.httpclient;
import com.github.mrbox.easyhttp.client.apache.PoolingHttpClientExecutor;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.mrbox.easyhttp.config.HttpConfig;
import com.github.mrbox.easyhttp.core.HttpMethod;
import com.github.mrbox.easyhttp.core.HttpRequest;
import com.github.mrbox.easyhttp.core.HttpResponse;
import com.github.mrbox.easyhttp.core.RequestBodyType;
import net.jqwik.api.*;
import net.jqwik.api.constraints.IntRange;
import net.jqwik.api.constraints.NotBlank;
import net.jqwik.api.constraints.Size;
import net.jqwik.api.lifecycle.AfterProperty;
import net.jqwik.api.lifecycle.BeforeProperty;
import net.jqwik.api.lifecycle.BeforeTry;
import java.time.Duration;
import java.util.Arrays;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.*;
/**
* 集成属性测试
* <p>使用 WireMock 模拟 HTTP 服务器进行端到端测试
*
* @author Zwk
*/
public class IntegrationPropertyTest {
private WireMockServer wireMockServer;
private PoolingHttpClientExecutor executor;
@BeforeProperty
void setUp() {
wireMockServer = new WireMockServer(WireMockConfiguration.options().dynamicPort());
wireMockServer.start();
WireMock.configureFor("localhost", wireMockServer.port());
HttpConfig config = HttpConfig.builder()
.connectTimeout(Duration.ofSeconds(5))
.readTimeout(Duration.ofSeconds(10))
.build();
executor = new PoolingHttpClientExecutor(config);
}
@AfterProperty
void tearDown() {
if (executor != null) {
executor.close();
}
if (wireMockServer != null) {
wireMockServer.stop();
}
}
@BeforeTry
void resetStubs() {
// Reset WireMock stubs before each try
if (wireMockServer != null) {
wireMockServer.resetAll();
}
}
/**
* Feature: http-executor-enhancement, Property 13: Backward Compatibility
* Validates: Requirements 6.1, 6.2, 6.4
*
* For any HttpRequest built using only the original API (url, method, headers, body),
* the execution behavior SHALL be identical to the original implementation.
*/
@Property(tries = 100)
void backwardCompatibility_getRequest(@ForAll @NotBlank @Size(max = 100) String responseBody) {
// Setup mock server
wireMockServer.stubFor(get(urlEqualTo("/test"))
.willReturn(aResponse()
.withStatus(200)
.withBody(responseBody)));
// Build request using original API only
HttpRequest request = HttpRequest.builder()
.url(baseUrl() + "/test")
.method(HttpMethod.GET)
.build();
// Verify original behavior
assertEquals("Should default to NONE body type", RequestBodyType.NONE, request.getBodyType());
assertTrue("QueryParams should be empty", request.getQueryParams().isEmpty());
assertTrue("FormParams should be empty", request.getFormParams().isEmpty());
assertNull("MultipartBody should be null", request.getMultipartBody());
// Execute and verify response
HttpResponse response = executor.execute(request);
assertEquals("Status should be 200", 200, response.getStatusCode());
assertEquals("Body should match", responseBody, response.getBodyAsString());
assertNotNull("BodyBytes should not be null", response.getBodyAsBytes());
}
@Provide
Arbitrary<String> asciiStrings() {
return Arbitraries.strings()
.alpha()
.numeric()
.withChars(' ', '-', '_', '.', ',', '!', '?')
.ofMinLength(1)
.ofMaxLength(100);
}
@Property(tries = 100)
void backwardCompatibility_postWithBody(
@ForAll("asciiStrings") String requestBody,
@ForAll("asciiStrings") String responseBody) {
// Setup mock server - match any POST to /test
wireMockServer.stubFor(post(urlEqualTo("/test"))
.willReturn(aResponse()
.withStatus(201)
.withBody(responseBody)));
// Build request using original API only
HttpRequest request = HttpRequest.builder()
.url(baseUrl() + "/test")
.method(HttpMethod.POST)
.header("Content-Type", "application/json")
.body(requestBody)
.build();
// Verify original behavior
assertEquals("Should be RAW body type", RequestBodyType.RAW, request.getBodyType());
assertEquals("Body should be set", requestBody, request.getBody());
// Execute and verify response
HttpResponse response = executor.execute(request);
assertEquals("Status should be 201", 201, response.getStatusCode());
assertEquals("Body should match", responseBody, response.getBodyAsString());
}
@Property(tries = 100)
void backwardCompatibility_withHeaders(
@ForAll("asciiStrings") String headerValue,
@ForAll("asciiStrings") String responseBody) {
// Setup mock server - match any GET to /test with the header
wireMockServer.stubFor(get(urlEqualTo("/test"))
.withHeader("X-Custom-Header", matching(".*"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("X-Response-Header", "test-value")
.withBody(responseBody)));
// Build request using original API only
HttpRequest request = HttpRequest.builder()
.url(baseUrl() + "/test")
.method(HttpMethod.GET)
.header("X-Custom-Header", headerValue)
.build();
// Execute and verify response
HttpResponse response = executor.execute(request);
assertEquals("Status should be 200", 200, response.getStatusCode());
assertEquals("Body should match", responseBody, response.getBodyAsString());
assertEquals("Response header should be present", "test-value", response.getHeaders().get("X-Response-Header"));
}
/**
* Feature: http-executor-enhancement, Property 9: Byte Response Round-Trip
* Validates: Requirements 4.2
*
* For any HTTP response with binary content,
* HttpResponse.getBodyAsBytes() SHALL return the exact bytes received from the server.
*/
@Property(tries = 100)
void byteResponseRoundTrip(@ForAll @Size(min = 1, max = 1000) byte[] binaryContent) {
// Setup mock server with binary response
wireMockServer.stubFor(get(urlEqualTo("/binary"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/octet-stream")
.withBody(binaryContent)));
// Build request
HttpRequest request = HttpRequest.builder()
.url(baseUrl() + "/binary")
.method(HttpMethod.GET)
.build();
// Execute and verify response
HttpResponse response = executor.execute(request);
assertEquals("Status should be 200", 200, response.getStatusCode());
assertNotNull("BodyBytes should not be null", response.getBodyAsBytes());
assertTrue("Bytes should match exactly", Arrays.equals(binaryContent, response.getBodyAsBytes()));
}
@Property(tries = 100)
void byteResponseIdempotence(@ForAll @Size(min = 1, max = 500) byte[] binaryContent) {
// Setup mock server
wireMockServer.stubFor(get(urlEqualTo("/binary"))
.willReturn(aResponse()
.withStatus(200)
.withBody(binaryContent)));
// Build request
HttpRequest request = HttpRequest.builder()
.url(baseUrl() + "/binary")
.method(HttpMethod.GET)
.build();
// Execute
HttpResponse response = executor.execute(request);
// Multiple calls should return same cached value
byte[] firstCall = response.getBodyAsBytes();
byte[] secondCall = response.getBodyAsBytes();
byte[] thirdCall = response.getBodyAsBytes();
assertSame("Multiple calls should return same array instance", firstCall, secondCall);
assertSame("Multiple calls should return same array instance", secondCall, thirdCall);
assertTrue("Content should match original", Arrays.equals(binaryContent, firstCall));
}
private String baseUrl() {
return "http://localhost:" + wireMockServer.port();
}
// ==================== Proxy Configuration Tests ====================
/**
* Test proxy configuration with different hosts and ports
* Validates: Proxy configuration functionality
*/
@Property(tries = 20)
void proxyConfiguration_basic(@ForAll @NotBlank @Size(max = 50) String proxyHost,
@ForAll @IntRange(min = 1, max = 65535) int proxyPort) {
// Just test that the config can be created without throwing exceptions
// We can't actually test the proxy functionality without a real proxy server
try {
HttpConfig config = HttpConfig.builder()
.proxyConfig(new HttpConfig.ProxyConfig(proxyHost, proxyPort))
.build();
assertTrue("Config should have proxy config", config.hasProxyConfig());
assertEquals("Proxy host should match", proxyHost, config.getProxyConfig().getHost());
assertEquals("Proxy port should match", proxyPort, config.getProxyConfig().getPort());
} catch (Exception e) {
fail("Proxy configuration should not throw exception: " + e.getMessage());
}
}
/**
* Test proxy configuration with authentication
* Validates: Proxy authentication functionality
*/
@Property(tries = 20)
void proxyConfiguration_withAuth(@ForAll @NotBlank @Size(max = 20) String proxyHost,
@ForAll @IntRange(min = 1, max = 65535) int proxyPort,
@ForAll @NotBlank @Size(max = 20) String username,
@ForAll @NotBlank @Size(max = 20) String password) {
try {
HttpConfig config = HttpConfig.builder()
.proxyConfig(new HttpConfig.ProxyConfig(proxyHost, proxyPort, username, password))
.build();
assertTrue("Config should have proxy config", config.hasProxyConfig());
assertEquals("Proxy host should match", proxyHost, config.getProxyConfig().getHost());
assertEquals("Proxy port should match", proxyPort, config.getProxyConfig().getPort());
assertTrue("Config should have authentication", config.getProxyConfig().hasAuthentication());
assertEquals("Username should match", username, config.getProxyConfig().getUsername());
assertEquals("Password should match", password, config.getProxyConfig().getPassword());
} catch (Exception e) {
fail("Proxy configuration with auth should not throw exception: " + e.getMessage());
}
}
/**
* Test proxy configuration with scheme
* Validates: Proxy scheme functionality
*/
@Property(tries = 10)
void proxyConfiguration_withScheme(@ForAll @NotBlank @Size(max = 10) String proxyHost,
@ForAll @IntRange(min = 1, max = 65535) int proxyPort,
@ForAll @Size(max = 10) String scheme) {
try {
// Use only valid schemes for testing
String validScheme = scheme.replaceAll("[^a-zA-Z]", "").toLowerCase();
if (validScheme.isEmpty()) {
validScheme = "http";
}
HttpConfig config = HttpConfig.builder()
.proxyConfig(new HttpConfig.ProxyConfig(proxyHost, proxyPort, validScheme))
.build();
assertTrue("Config should have proxy config", config.hasProxyConfig());
assertEquals("Proxy host should match", proxyHost, config.getProxyConfig().getHost());
assertEquals("Proxy port should match", proxyPort, config.getProxyConfig().getPort());
assertEquals("Proxy scheme should match", validScheme, config.getProxyConfig().getScheme());
} catch (Exception e) {
fail("Proxy configuration with scheme should not throw exception: " + e.getMessage());
}
}
/**
* Test proxy configuration using ProxyConfig object directly
* Validates: Direct ProxyConfig instantiation
*/
@Property(tries = 20)
void proxyConfiguration_directProxyConfig(@ForAll @NotBlank @Size(max = 50) String proxyHost,
@ForAll @IntRange(min = 1, max = 65535) int proxyPort,
@ForAll @NotBlank @Size(max = 20) String username,
@ForAll @NotBlank @Size(max = 20) String password,
@ForAll @Size(max = 10) String scheme) {
try {
String validScheme = scheme.replaceAll("[^a-zA-Z]", "").toLowerCase();
if (validScheme.isEmpty()) {
validScheme = "http";
}
HttpConfig.ProxyConfig proxyConfig = new HttpConfig.ProxyConfig(
proxyHost, proxyPort, username, password, validScheme);
HttpConfig config = HttpConfig.builder()
.proxyConfig(proxyConfig)
.build();
assertTrue("Config should have proxy config", config.hasProxyConfig());
assertEquals("Proxy host should match", proxyHost, config.getProxyConfig().getHost());
assertEquals("Proxy port should match", proxyPort, config.getProxyConfig().getPort());
assertEquals("Proxy scheme should match", validScheme, config.getProxyConfig().getScheme());
assertTrue("Config should have authentication", config.getProxyConfig().hasAuthentication());
assertEquals("Username should match", username, config.getProxyConfig().getUsername());
assertEquals("Password should match", password, config.getProxyConfig().getPassword());
} catch (Exception e) {
fail("Direct proxy config should not throw exception: " + e.getMessage());
}
}
// ==================== File Download Integration Tests ====================
/**
* Test executeAndSaveTo() method
* Validates: Requirements 4.3
*/
@Property(tries = 50)
void fileDownload_executeAndSaveTo(@ForAll @Size(min = 1, max = 5000) byte[] content) throws Exception {
// Setup mock server
wireMockServer.stubFor(get(urlEqualTo("/download"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/octet-stream")
.withHeader("Content-Length", String.valueOf(content.length))
.withBody(content)));
// Create temp file
java.io.File tempFile = java.io.File.createTempFile("download-test-", ".bin");
tempFile.deleteOnExit();
try {
// Build request
HttpRequest request = HttpRequest.builder()
.url(baseUrl() + "/download")
.method(HttpMethod.GET)
.build();
// Execute download
HttpResponse response = executor.executeAndSaveTo(request, tempFile);
// Verify response
assertEquals("Status should be 200", 200, response.getStatusCode());
// Verify file content
assertTrue("File should exist", tempFile.exists());
byte[] fileContent = java.nio.file.Files.readAllBytes(tempFile.toPath());
assertTrue("File content should match", Arrays.equals(content, fileContent));
} finally {
tempFile.delete();
}
}
/**
* Test directory auto-creation
* Validates: Requirements 4.6
*/
@Property(tries = 20)
void fileDownload_autoCreateDirectory(@ForAll @Size(min = 1, max = 1000) byte[] content) throws Exception {
// Setup mock server
wireMockServer.stubFor(get(urlEqualTo("/download"))
.willReturn(aResponse()
.withStatus(200)
.withBody(content)));
// Create temp directory path that doesn't exist
java.io.File tempDir = new java.io.File(System.getProperty("java.io.tmpdir"),
"download-test-" + System.nanoTime() + "/subdir/nested");
java.io.File tempFile = new java.io.File(tempDir, "test.bin");
try {
assertFalse("Directory should not exist initially", tempDir.exists());
// Build request
HttpRequest request = HttpRequest.builder()
.url(baseUrl() + "/download")
.method(HttpMethod.GET)
.build();
// Execute download
HttpResponse response = executor.executeAndSaveTo(request, tempFile);
// Verify directory was created
assertTrue("Directory should be created", tempDir.exists());
assertTrue("File should exist", tempFile.exists());
// Verify content
byte[] fileContent = java.nio.file.Files.readAllBytes(tempFile.toPath());
assertTrue("File content should match", Arrays.equals(content, fileContent));
} finally {
// Cleanup
if (tempFile.exists()) tempFile.delete();
deleteDirectory(tempDir);
}
}
/**
* Test executeAndWriteTo() method
* Validates: Requirements 4.4
*/
@Property(tries = 50)
void fileDownload_executeAndWriteTo(@ForAll @Size(min = 1, max = 5000) byte[] content) throws Exception {
// Setup mock server
wireMockServer.stubFor(get(urlEqualTo("/download"))
.willReturn(aResponse()
.withStatus(200)
.withBody(content)));
// Build request
HttpRequest request = HttpRequest.builder()
.url(baseUrl() + "/download")
.method(HttpMethod.GET)
.build();
// Execute with ByteArrayOutputStream
java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream();
HttpResponse response = executor.executeAndWriteTo(request, outputStream);
// Verify response
assertEquals("Status should be 200", 200, response.getStatusCode());
// Verify content
byte[] receivedContent = outputStream.toByteArray();
assertTrue("Content should match", Arrays.equals(content, receivedContent));
}
/**
* Helper method to delete directory recursively
*/
private void deleteDirectory(java.io.File dir) {
if (dir == null || !dir.exists()) return;
java.io.File[] files = dir.listFiles();
if (files != null) {
for (java.io.File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
file.delete();
}
}
}
dir.delete();
// Also try to delete parent directories up to temp dir
java.io.File parent = dir.getParentFile();
String tempDir = System.getProperty("java.io.tmpdir");
while (parent != null && !parent.getAbsolutePath().equals(tempDir)) {
if (parent.list() != null && parent.list().length == 0) {
parent.delete();
parent = parent.getParentFile();
} else {
break;
}
}
}
}