Repository navigation
Expand file tree
/
Copy pathtest-integration.php
More file actions
479 lines (402 loc) · 15.7 KB
/
Copy pathtest-integration.php
File metadata and controls
479 lines (402 loc) · 15.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
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
<?php
/**
* ENTERPRISE INTEGRATION TEST
*
* Tests REAL database operations with SQLite in-memory.
* Verifies connection pooling, auto-release, circuit breaker, performance.
*
* ⚠️ CRITICAL: These tests prove the package works as advertised!
*/
require __DIR__ . '/vendor/autoload.php';
use Senza1dio\DatabasePool\Config\PoolConfig;
use Senza1dio\DatabasePool\DatabasePool;
use Senza1dio\DatabasePool\Exceptions\PoolExhaustedException;
use Senza1dio\DatabasePool\Exceptions\CircuitBreakerOpenException;
echo "🔥 ADOS DatabasePool - REAL INTEGRATION TEST\n";
echo str_repeat('=', 70) . "\n\n";
$testsPassed = 0;
$testsFailed = 0;
function test_pass(string $name): void {
global $testsPassed;
$testsPassed++;
echo "✅ PASSED: {$name}\n";
}
function test_fail(string $name, string $reason): void {
global $testsFailed;
$testsFailed++;
echo "❌ FAILED: {$name}\n";
echo " Reason: {$reason}\n";
}
// =============================================================================
// TEST 1: SQLite In-Memory Connection Pool
// =============================================================================
echo "\n[TEST 1] SQLite in-memory connection...\n";
try {
$config = (new PoolConfig())
->setDriver('sqlite')
->setDatabase(':memory:')
->setPoolSize(5, 10);
$pool = new DatabasePool($config);
$pdo = $pool->getConnection();
// Create test table
$pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');
$pdo->exec("INSERT INTO users (name, email) VALUES ('Alice', 'alice@test.com')");
$pdo->exec("INSERT INTO users (name, email) VALUES ('Bob', 'bob@test.com')");
// Verify data
$stmt = $pdo->query('SELECT COUNT(*) FROM users');
$count = $stmt->fetchColumn();
if ($count == 2) {
test_pass('SQLite connection + queries work');
} else {
test_fail('SQLite queries', "Expected 2 rows, got {$count}");
}
} catch (Exception $e) {
test_fail('SQLite connection', $e->getMessage());
}
// =============================================================================
// TEST 2: Connection Reuse (Pool Hit)
// =============================================================================
echo "\n[TEST 2] Connection pooling (reuse)...\n";
try {
$config = (new PoolConfig())
->setDriver('sqlite')
->setDatabase(':memory:')
->setPoolSize(2, 5);
$pool = new DatabasePool($config);
// Get connection, use it, let it auto-release
$pdo1 = $pool->getConnection();
$pdo1->exec('CREATE TABLE IF NOT EXISTS test (id INTEGER)');
$conn1Id = spl_object_hash($pdo1);
// Explicit unset to trigger __destruct()
unset($pdo1);
// Force garbage collection to ensure __destruct() called
gc_collect_cycles();
// Small delay to ensure release processed
usleep(10000); // 10ms
// Get connection again - should reuse from pool
$pdo2 = $pool->getConnection();
$conn2Id = spl_object_hash($pdo2);
$stats = $pool->getStats();
// Check pool stats
if ($stats['pool_hits'] > 0 && $stats['active_connections'] > 0) {
test_pass('Connection reused from pool (pool_hits=' . $stats['pool_hits'] . ')');
} else {
test_fail('Connection reuse', 'Pool hits: ' . $stats['pool_hits'] . ', Active: ' . $stats['active_connections']);
}
} catch (Exception $e) {
test_fail('Connection reuse', $e->getMessage());
}
// =============================================================================
// TEST 3: AutoReleasePDO (Automatic Release)
// =============================================================================
echo "\n[TEST 3] AutoReleasePDO (automatic release)...\n";
try {
$config = (new PoolConfig())
->setDriver('sqlite')
->setDatabase(':memory:')
->setPoolSize(1, 2);
$pool = new DatabasePool($config);
// Use connection
$pdo = $pool->getConnection();
$pdo->exec('CREATE TABLE test2 (id INTEGER)');
// Explicit unset + garbage collection
unset($pdo);
gc_collect_cycles();
usleep(10000); // 10ms delay
$stats = $pool->getStats();
// After release, idle connections should increase
if ($stats['idle_connections'] > 0) {
test_pass('AutoReleasePDO released connection (idle=' . $stats['idle_connections'] . ')');
} else {
test_fail('AutoReleasePDO', 'No idle connections after scope exit');
}
} catch (Exception $e) {
test_fail('AutoReleasePDO', $e->getMessage());
}
// =============================================================================
// TEST 4: Pool Exhaustion (maxConnections reached)
// =============================================================================
echo "\n[TEST 4] Pool exhaustion (maxConnections limit)...\n";
try {
$config = (new PoolConfig())
->setDriver('sqlite')
->setDatabase(':memory:')
->setPoolSize(1, 2) // Max 2 connections
->setConnectionTimeout(1); // 1 second timeout
$pool = new DatabasePool($config);
// Hold connections without releasing
$conn1 = $pool->getConnection();
$conn2 = $pool->getConnection();
// Try to get 3rd connection - should fail or timeout
$exhausted = false;
try {
$conn3 = $pool->getConnection(); // Should throw PoolExhaustedException
} catch (PoolExhaustedException $e) {
$exhausted = true;
}
if ($exhausted) {
test_pass('Pool exhaustion detected correctly');
} else {
test_fail('Pool exhaustion', 'Did not throw PoolExhaustedException');
}
} catch (Exception $e) {
test_fail('Pool exhaustion', $e->getMessage());
}
// =============================================================================
// TEST 5: Circuit Breaker (Failure Detection)
// =============================================================================
echo "\n[TEST 5] Circuit breaker (failure handling)...\n";
try {
$config = (new PoolConfig())
->setDriver('sqlite')
->setDatabase('/invalid/path/database.db') // Invalid path to trigger errors
->setCircuitBreaker(threshold: 2, timeout: 2); // Open after 2 failures
$pool = new DatabasePool($config);
$failures = 0;
$circuitOpened = false;
// Trigger failures
for ($i = 0; $i < 5; $i++) {
try {
$pdo = $pool->getConnection();
} catch (CircuitBreakerOpenException $e) {
$circuitOpened = true;
break;
} catch (Exception $e) {
$failures++;
}
}
if ($circuitOpened) {
test_pass('Circuit breaker opened after failures');
} else {
test_fail('Circuit breaker', "Expected circuit to open, got {$failures} failures");
}
} catch (Exception $e) {
// Circuit breaker might throw on construction if driver validation fails
if (strpos($e->getMessage(), 'Circuit breaker') !== false) {
test_pass('Circuit breaker opened (constructor level)');
} else {
test_fail('Circuit breaker', $e->getMessage());
}
}
// =============================================================================
// TEST 6: Prepared Statements (Real Queries)
// =============================================================================
echo "\n[TEST 6] Prepared statements (parameterized queries)...\n";
try {
$config = (new PoolConfig())
->setDriver('sqlite')
->setDatabase(':memory:')
->setPoolSize(5, 10);
$pool = new DatabasePool($config);
$pdo = $pool->getConnection();
$pdo->exec('CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL)');
// Insert with prepared statement
$stmt = $pdo->prepare('INSERT INTO products (name, price) VALUES (?, ?)');
$stmt->execute(['Laptop', 999.99]);
$stmt->execute(['Mouse', 29.99]);
$stmt->execute(['Keyboard', 79.99]);
// Query with prepared statement
$stmt = $pdo->prepare('SELECT * FROM products WHERE price > ?');
$stmt->execute([50.0]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($results) == 2) {
test_pass('Prepared statements work correctly');
} else {
test_fail('Prepared statements', 'Expected 2 results, got ' . count($results));
}
} catch (Exception $e) {
test_fail('Prepared statements', $e->getMessage());
}
// =============================================================================
// TEST 7: Concurrent Connections (Simulated)
// =============================================================================
echo "\n[TEST 7] Concurrent connections (10 operations)...\n";
try {
$config = (new PoolConfig())
->setDriver('sqlite')
->setDatabase(':memory:')
->setPoolSize(5, 10);
$pool = new DatabasePool($config);
// Initialize table
$pdo = $pool->getConnection();
$pdo->exec('CREATE TABLE concurrent_test (id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT)');
unset($pdo); // Release
usleep(10000);
// Simulate concurrent operations
$operations = 10;
for ($i = 0; $i < $operations; $i++) {
$pdo = $pool->getConnection();
$stmt = $pdo->prepare('INSERT INTO concurrent_test (value) VALUES (?)');
$stmt->execute(["value_{$i}"]);
unset($pdo); // Release after each operation
usleep(1000); // 1ms delay
}
// Verify all inserts
$pdo = $pool->getConnection();
$stmt = $pdo->query('SELECT COUNT(*) FROM concurrent_test');
$count = $stmt->fetchColumn();
if ($count == $operations) {
test_pass('Concurrent operations completed successfully');
} else {
test_fail('Concurrent operations', "Expected {$operations} rows, got {$count}");
}
} catch (Exception $e) {
test_fail('Concurrent operations', $e->getMessage());
}
// =============================================================================
// TEST 8: Performance (Pool vs No Pool)
// =============================================================================
echo "\n[TEST 8] Performance benchmark (100 queries)...\n";
try {
// With pool
$config = (new PoolConfig())
->setDriver('sqlite')
->setDatabase(':memory:')
->setPoolSize(5, 10);
$pool = new DatabasePool($config);
$pdo = $pool->getConnection();
$pdo->exec('CREATE TABLE perf_test (id INTEGER PRIMARY KEY, value TEXT)');
unset($pdo);
usleep(10000);
$startPool = microtime(true);
for ($i = 0; $i < 100; $i++) {
$pdo = $pool->getConnection();
$stmt = $pdo->prepare('INSERT INTO perf_test (value) VALUES (?)');
$stmt->execute(["test_{$i}"]);
unset($pdo);
}
$timePool = microtime(true) - $startPool;
// Without pool (new PDO each time)
$startNative = microtime(true);
for ($i = 0; $i < 100; $i++) {
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE IF NOT EXISTS perf_test2 (id INTEGER PRIMARY KEY, value TEXT)');
$stmt = $pdo->prepare('INSERT INTO perf_test2 (value) VALUES (?)');
$stmt->execute(["test_{$i}"]);
unset($pdo);
}
$timeNative = microtime(true) - $startNative;
$improvement = round($timeNative / $timePool, 2);
echo " Pool time: " . round($timePool * 1000, 2) . "ms\n";
echo " Native time: " . round($timeNative * 1000, 2) . "ms\n";
echo " Improvement: {$improvement}x faster\n";
if ($improvement > 1.0) {
test_pass("Pool is {$improvement}x faster than native PDO");
} else {
test_fail('Performance', "Pool should be faster (got {$improvement}x)");
}
} catch (Exception $e) {
test_fail('Performance benchmark', $e->getMessage());
}
// =============================================================================
// TEST 9: Memory Leak Test (1000 connections)
// =============================================================================
echo "\n[TEST 9] Memory leak test (1000 operations)...\n";
try {
$config = (new PoolConfig())
->setDriver('sqlite')
->setDatabase(':memory:')
->setPoolSize(10, 20);
$pool = new DatabasePool($config);
$pdo = $pool->getConnection();
$pdo->exec('CREATE TABLE leak_test (id INTEGER PRIMARY KEY, value TEXT)');
unset($pdo);
usleep(10000);
$memStart = memory_get_usage(true);
for ($i = 0; $i < 1000; $i++) {
$pdo = $pool->getConnection();
$stmt = $pdo->prepare('INSERT INTO leak_test (value) VALUES (?)');
$stmt->execute(["value_{$i}"]);
unset($pdo); // Force release
}
// Force garbage collection
gc_collect_cycles();
$memEnd = memory_get_usage(true);
$memDiff = ($memEnd - $memStart) / 1024 / 1024; // MB
echo " Memory start: " . round($memStart / 1024 / 1024, 2) . " MB\n";
echo " Memory end: " . round($memEnd / 1024 / 1024, 2) . " MB\n";
echo " Memory diff: " . round($memDiff, 2) . " MB\n";
// Memory growth should be reasonable (<10MB for 1000 operations)
if ($memDiff < 10) {
test_pass('No significant memory leak detected');
} else {
test_fail('Memory leak', "Memory grew by {$memDiff} MB (suspicious)");
}
} catch (Exception $e) {
test_fail('Memory leak test', $e->getMessage());
}
// =============================================================================
// TEST 10: Stats & Monitoring
// =============================================================================
echo "\n[TEST 10] Stats & monitoring...\n";
try {
$config = (new PoolConfig())
->setDriver('sqlite')
->setDatabase(':memory:')
->setPoolSize(5, 10);
$pool = new DatabasePool($config);
// Perform operations
for ($i = 0; $i < 10; $i++) {
$pdo = $pool->getConnection();
if ($i === 0) {
$pdo->exec('CREATE TABLE stats_test (id INTEGER)');
}
$pdo->exec('INSERT INTO stats_test (id) VALUES (' . $i . ')');
unset($pdo);
usleep(1000);
}
$stats = $pool->getStats();
$requiredKeys = [
'total_connections',
'active_connections',
'idle_connections',
'total_queries',
'pool_hits',
'pool_misses',
'circuit_breaker_state',
];
$allKeysPresent = true;
foreach ($requiredKeys as $key) {
if (!isset($stats[$key])) {
$allKeysPresent = false;
break;
}
}
if ($allKeysPresent) {
test_pass('Stats tracking works correctly');
echo " Total connections: " . $stats['total_connections'] . "\n";
echo " Active connections: " . $stats['active_connections'] . "\n";
echo " Idle connections: " . $stats['idle_connections'] . "\n";
echo " Total queries: " . $stats['total_queries'] . "\n";
echo " Pool hits: " . $stats['pool_hits'] . "\n";
echo " Pool misses: " . $stats['pool_misses'] . "\n";
} else {
test_fail('Stats tracking', 'Missing required stats keys');
}
} catch (Exception $e) {
test_fail('Stats & monitoring', $e->getMessage());
}
// =============================================================================
// FINAL SUMMARY
// =============================================================================
echo "\n" . str_repeat('=', 70) . "\n";
echo "📊 FINAL RESULTS:\n";
echo " ✅ Tests passed: {$testsPassed}\n";
echo " ❌ Tests failed: {$testsFailed}\n";
if ($testsFailed === 0) {
echo "\n🎉 ALL INTEGRATION TESTS PASSED!\n";
echo "✅ Package is PRODUCTION-READY\n";
echo "✅ Connection pooling WORKS\n";
echo "✅ Performance improvements VERIFIED\n";
echo "✅ Memory management SAFE\n";
echo "✅ Circuit breaker FUNCTIONAL\n";
echo "✅ AutoRelease WORKING\n";
echo str_repeat('=', 70) . "\n";
exit(0);
} else {
echo "\n❌ SOME TESTS FAILED!\n";
echo "⚠️ Package NOT ready for production\n";
echo "⚠️ Fix issues before publishing\n";
echo str_repeat('=', 70) . "\n";
exit(1);
}