Repository navigation
Expand file tree
/
Copy pathtests.php
More file actions
822 lines (644 loc) · 26.8 KB
/
Copy pathtests.php
File metadata and controls
822 lines (644 loc) · 26.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
<?php
/**
* Seed-PHP Test Suite
* Run: php tests.php
* Vanilla PHP. No external test framework. Unit tests run in-process; HTTP tests
* spin up a temporary server using tests/app.php as the router.
*/
error_reporting(E_ALL & ~E_DEPRECATED & ~E_WARNING);
ini_set('display_errors', '1');
$composerAutoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($composerAutoload)) {
require_once $composerAutoload;
}
require_once __DIR__ . '/loader.php';
$TEST_PORT = 8090;
$TEST_HOST = 'localhost';
$BASE = "http://{$TEST_HOST}:{$TEST_PORT}";
$SERVER_LOG = sys_get_temp_dir() . '/seedphp_test_server.log';
$passed = 0;
$failed = 0;
$skipped = 0;
$serverProc = null;
$pipes = [];
function colorGreen(string $s): string { return "\033[32m" . $s . "\033[0m"; }
function colorRed(string $s): string { return "\033[31m" . $s . "\033[0m"; }
function colorYellow(string $s): string { return "\033[33m" . $s . "\033[0m"; }
function colorBold(string $s): string { return "\033[1m" . $s . "\033[0m"; }
function group(string $name): void
{
echo "\n" . colorBold('### ' . $name . ' ###') . "\n";
}
function pass(string $msg): void
{
global $passed;
$passed++;
echo ' ' . colorGreen('PASS') . ' ' . $msg . "\n";
}
function fail(string $msg, $expected = null, $actual = null): void
{
global $failed;
$failed++;
echo ' ' . colorRed('FAIL') . ' ' . $msg . "\n";
if (func_num_args() > 1) {
echo ' ' . colorRed('expected: ' . var_export($expected, true)) . "\n";
echo ' ' . colorRed('actual: ' . var_export($actual, true)) . "\n";
}
}
function skip(string $msg): void
{
global $skipped;
$skipped++;
echo ' ' . colorYellow('SKIP') . ' ' . $msg . "\n";
}
function assert_true($value, string $msg): void
{
if ($value === true) {
pass($msg);
return;
}
fail($msg, true, $value);
}
function assert_eq($expected, $actual, string $msg): void
{
if ($expected === $actual) {
pass($msg);
return;
}
fail($msg, $expected, $actual);
}
function assert_contains(string $needle, string $haystack, string $msg): void
{
if (strpos($haystack, $needle) !== false) {
pass($msg);
return;
}
fail($msg, "contains: {$needle}", $haystack);
}
/**
* Extract unique PHP diagnostic lines (Deprecated/Warning/Notice) from output.
* PHP prints each diagnostic twice, once as "PHP Deprecated: ..." on stderr and
* once as "Deprecated: ..." on stdout, so the lines are normalized and deduped.
*/
function diagnostics(array $lines): array
{
$found = [];
foreach ($lines as $line) {
if (!preg_match('/(Deprecated|Warning|Notice):/', $line)) {
continue;
}
$normalized = preg_replace('/\s+/', ' ', preg_replace('/^PHP /', '', trim($line)));
$found[$normalized] = true;
}
return array_keys($found);
}
/**
* Runs PHP code in a subprocess with E_ALL and returns [exit status, output lines].
* The snippet receives $app (a booted SeedPHP\Core) plus the library autoloader.
*/
function run_php_subprocess(array $snippet): array
{
$script = tempnam(sys_get_temp_dir(), 'seedphp_diagnostics_') . '.php';
$code = implode("\n", array_merge(
[
'<?php',
'error_reporting(E_ALL);',
'ini_set("display_errors", "1");',
'$autoload = ' . var_export(__DIR__ . '/vendor/autoload.php', true) . ';',
'if (file_exists($autoload)) { require $autoload; }',
'require ' . var_export(__DIR__ . '/loader.php', true) . ';',
'$app = SeedPHP\\App::getInstance();',
],
$snippet
));
file_put_contents($script, $code);
$output = [];
$status = 0;
exec(
PHP_BINARY . ' -d error_reporting=E_ALL -d display_errors=1 '
. escapeshellarg($script) . ' 2>&1',
$output,
$status
);
@unlink($script);
return [$status, $output];
}
function assert_no_diagnostics(string $msg, array $snippet): void
{
list($status, $output) = run_php_subprocess($snippet);
$found = diagnostics($output);
if ($found === [] && $status === 0) {
pass($msg);
return;
}
$actual = $found;
if ($actual === []) {
$actual = ['no diagnostics, but exit status ' . $status . ': ' . trim(implode("\n", $output))];
}
fail($msg, 'no diagnostics and a clean exit', $actual);
}
function assert_throws(string $class, callable $fn, string $msg): void
{
try {
$fn();
} catch (\Throwable $e) {
if ($e instanceof $class) {
pass($msg);
return;
}
fail($msg, $class, get_class($e));
return;
}
fail($msg, $class, 'no exception thrown');
}
function http_request(string $method, string $path, ?array $body = null, ?string $cookie = null): array
{
global $BASE;
$ch = curl_init();
$options = [
CURLOPT_URL => $BASE . $path,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => $method,
];
if ($cookie !== null) {
$options[CURLOPT_COOKIEFILE] = $cookie;
$options[CURLOPT_COOKIEJAR] = $cookie;
}
if ($body !== null) {
$options[CURLOPT_POSTFIELDS] = json_encode($body);
$options[CURLOPT_HTTPHEADER] = ['Content-Type: application/json'];
}
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = (int) curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr((string) $response, 0, $headerSize);
$rawBody = substr((string) $response, $headerSize);
return [
'status' => $status,
'headers' => $headers,
'body' => $rawBody,
'json' => json_decode($rawBody, true),
];
}
function start_server(string $host, int $port, string $logFile): array
{
$command = sprintf(
'php -S %s:%d %s',
$host,
$port,
escapeshellarg(__DIR__ . '/tests/app.php')
);
$descriptors = [
['pipe', 'r'],
['file', $logFile, 'a'],
['file', $logFile, 'a'],
];
$proc = proc_open($command, $descriptors, $pipes);
if (!is_resource($proc)) {
return [null, []];
}
for ($i = 0; $i < 50; $i++) {
$sock = @fsockopen($host, $port, $errno, $errstr, 0.1);
if ($sock) {
fclose($sock);
return [$proc, $pipes];
}
usleep(100000);
}
return [$proc, $pipes];
}
echo colorBold('Seed-PHP Test Suite') . "\n";
echo str_repeat('=', 80) . "\n";
group('Autoloader');
assert_true(class_exists('SeedPHP\\App'), 'loads SeedPHP\\App');
assert_true(class_exists('SeedPHP\\Core'), 'loads SeedPHP\\Core');
assert_true(class_exists('SeedPHP\\Router'), 'loads SeedPHP\\Router');
assert_true(class_exists('SeedPHP\\Helper\\Http'), 'loads SeedPHP\\Helper\\Http');
assert_true(class_exists('SeedPHP\\Helper\\Database'), 'loads SeedPHP\\Helper\\Database');
assert_true(class_exists('SeedPHP\\Helper\\Curl'), 'loads SeedPHP\\Helper\\Curl');
assert_true(class_exists('SeedPHP\\Helper\\RateLimit'), 'loads SeedPHP\\Helper\\RateLimit');
assert_true(class_exists('SeedPHP\\Helper\\Logger'), 'loads SeedPHP\\Helper\\Logger');
assert_throws(Exception::class, function () {
class_exists('SeedPHP\\ThisDoesNotExist');
}, 'throws for a missing class');
group('App singleton');
$app = SeedPHP\App::getInstance();
assert_true($app === SeedPHP\App::getInstance(), 'getInstance() returns the same instance');
assert_true($app instanceof SeedPHP\Core, 'getInstance() returns the Core engine');
assert_true(method_exists($app, 'route'), 'exposes route()');
assert_true(method_exists($app, 'run'), 'exposes run()');
assert_true(method_exists($app, 'load'), 'exposes load()');
$app->load('logger', ['driver' => 'sqlite', 'base' => ':memory:'], 'logalias');
assert_true($app->logalias instanceof SeedPHP\Helper\Logger, 'load() registers the helper under its alias');
assert_eq('logalias', $app->logger, 'load() maps the original helper name to the alias');
group('Http helper');
$status = SeedPHP\Helper\Http::getHTTPStatus(200);
assert_eq(200, $status['code'], 'getHTTPStatus(200) code');
assert_eq('OK', $status['message'], 'getHTTPStatus(200) message');
$status = SeedPHP\Helper\Http::getHTTPStatus(404);
assert_eq('Not Found', $status['message'], 'getHTTPStatus(404) message');
assert_throws(ErrorException::class, function () {
SeedPHP\Helper\Http::getHTTPStatus(599);
}, 'getHTTPStatus() throws on an unknown code');
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['SERVER_PORT'] = 80;
unset($_SERVER['HTTPS']);
assert_eq('http://localhost', SeedPHP\Helper\Http::getBaseUrl(), 'getBaseUrl() detects http');
$_SERVER['HTTPS'] = 'on';
assert_eq('https://localhost', SeedPHP\Helper\Http::getBaseUrl(), 'getBaseUrl() detects https');
$_SERVER['REMOTE_ADDR'] = '203.0.113.9';
unset(
$_SERVER['HTTP_CLIENT_IP'],
$_SERVER['HTTP_CF_CONNECTING_IP'],
$_SERVER['HTTP_X_FORWARDED'],
$_SERVER['HTTP_X_FORWARDED_FOR'],
$_SERVER['HTTP_FORWARDED'],
$_SERVER['HTTP_FORWARDED_FOR']
);
assert_eq('203.0.113.9', SeedPHP\Helper\Http::getClientIP(), 'getClientIP() falls back to REMOTE_ADDR');
group('Router response');
assert_true($app->route('GET /unit-test', function () {}) === $app, 'route() is chainable');
ob_start();
$app->response(200, ['foo' => 'bar']);
$out = ob_get_clean();
assert_contains('"status":200', $out, 'response() json status');
assert_contains('"message":"OK"', $out, 'response() json message');
assert_contains('"foo":"bar"', $out, 'response() json payload');
ob_start();
$app->response(404, ['message' => 'nope']);
$out = ob_get_clean();
assert_contains('"error":true', $out, 'response() flags errors');
ob_start();
$app->response(200, ['message' => 'ok'], 'xml');
$out = ob_get_clean();
assert_contains('<status>200</status>', $out, 'response() xml status');
assert_contains('<message>ok</message>', $out, 'response() xml message');
ob_start();
$returned = $app->response(200, ['a' => 1], false);
$out = ob_get_clean();
assert_eq('', $out, 'response() with output=false does not echo');
assert_true(is_array($returned), 'response() with output=false returns the array');
$_GET['_router_status'] = 'code';
ob_start();
$app->response(200, ['a' => 1]);
$out = ob_get_clean();
unset($_GET['_router_status']);
assert_contains('"code":200', $out, 'response() honours _router_status');
group('Database helper (sqlite)');
$db = new SeedPHP\Helper\Database(['driver' => 'sqlite']);
$db->setDNS('sqlite::memory:');
assert_true($db->connect() === $db, 'connect() is chainable');
assert_true($db->getLink() instanceof PDO, 'getLink() returns a PDO');
assert_eq(1, $db->exec('create table items (id integer primary key autoincrement, name text)'), 'exec() returns 1 for DDL');
assert_eq(1, $db->insert('items', ['name' => 'alpha']), 'insert() returns 1');
$db->insert('items', ['name' => 'beta']);
assert_eq(2, $db->insertedId(), 'insertedId() returns the last id');
$rows = $db->fetch('items', ['*'], [], 10, 0, ['id' => 'ASC']);
assert_eq(2, count($rows), 'fetch() returns both rows');
assert_eq('alpha', $rows[0]['name'], 'fetch() keeps insertion order');
$bound = $db->exec('select * from items where id = :id', ['id' => 1]);
assert_eq('alpha', $bound[0]['name'], 'exec() binds named parameters');
$db->update('items', ['name' => 'gamma'], ['id' => 1]);
$rows = $db->fetch('items', ['*'], ['id' => 1]);
assert_eq('gamma', $rows[0]['name'], 'update() changes a row');
$db->delete('items', ['id' => 2]);
assert_eq(1, count($db->fetch('items')), 'delete() removes a row');
assert_eq(0, $db->resultCount(), 'resultCount() is 0 after a non-select');
$db->transaction('begin');
$db->insert('items', ['name' => 'delta']);
$db->transaction('commit');
assert_eq(2, count($db->fetch('items')), 'transaction commit persists');
$db->disconnect();
assert_throws(ErrorException::class, function () {
(new SeedPHP\Helper\Database())->exec('select 1');
}, 'exec() without a connection throws');
group('Curl helper');
$curl = new SeedPHP\Helper\Curl();
assert_true($curl->create('http://localhost') === $curl, 'create() is chainable');
assert_true($curl->option(CURLOPT_TIMEOUT, 5) === $curl, 'option() is chainable');
assert_true($curl->data(['a' => 1]) === $curl, 'data() is chainable');
$noSessionCurl = new SeedPHP\Helper\Curl();
$noSessionResult = 'threw';
try {
$noSessionResult = $noSessionCurl->execute();
} catch (\Throwable $e) {
$noSessionResult = get_class($e) . ': ' . $e->getMessage();
}
assert_eq(false, $noSessionResult, 'execute() without create() returns false');
$proxyCurl = new SeedPHP\Helper\Curl();
$proxyCurl->create('http://127.0.0.1:1/');
$proxyError = null;
try {
$proxyCurl->proxy('http://127.0.0.1:8080', 'user', 'pass');
$proxyCurl->execute();
} catch (\Throwable $e) {
$proxyError = get_class($e) . ': ' . $e->getMessage();
}
assert_eq(null, $proxyError, 'proxy() does not set an invalid cURL option');
group('Logger helper');
$loggerDb = tempnam(sys_get_temp_dir(), 'seedphp_logger_');
register_shutdown_function(function () use ($loggerDb) {
@unlink($loggerDb);
});
$loggerSetup = new SeedPHP\Helper\Database(['driver' => 'sqlite', 'base' => $loggerDb]);
$loggerSetup->connect();
$loggerSetup->exec('create table log_usage (id integer primary key autoincrement, endpoint text, resource text, request_ip text, request_header text, request_data text, response_data text, response_code integer)');
$loggerSetup->disconnect();
$logger = new SeedPHP\Helper\Logger(['driver' => 'sqlite', 'base' => $loggerDb]);
assert_true($logger instanceof SeedPHP\Helper\Logger, 'instantiates with config');
$logger
->endpoint('/logger-test')
->resource('items')
->requestIP('203.0.113.9')
->requestHeader(['X-Test' => 'yes'])
->requestData(['a' => 1])
->responseData(['ok' => true])
->responseCode(200);
assert_eq(1, $logger->log(), 'log() inserts a row');
$loggerCheck = new SeedPHP\Helper\Database(['driver' => 'sqlite', 'base' => $loggerDb]);
$loggerCheck->connect();
$rows = $loggerCheck->fetch('log_usage', ['*'], ['id' => 1]);
assert_eq(1, count($rows), 'log() persists the entry');
assert_eq('/logger-test', $rows[0]['endpoint'], 'log() stores the endpoint');
$loggerCheck->disconnect();
@unlink($loggerDb);
group('Mysql helper (removed)');
assert_throws(Exception::class, function () {
class_exists('SeedPHP\\Helper\\Mysql');
}, 'Mysql helper class is no longer available');
group('Mailgun helper');
$mailgun = new SeedPHP\Helper\Mailgun(['apiKey' => 'key', 'domain' => 'example.test']);
assert_true($mailgun instanceof SeedPHP\Helper\Mailgun, 'instantiates with config');
if (class_exists('Twig\\Environment')) {
$rendered = $mailgun->parse('Hello {{ name }}', ['name' => 'World'], 'twig', 'string');
assert_eq('Hello World', trim($rendered), 'parse() renders a Twig string template');
$scalarVarsError = null;
try {
$mailgun->parse('Hello', 'not-an-array', 'twig', 'string');
} catch (\Throwable $e) {
$scalarVarsError = get_class($e) . ': ' . $e->getMessage();
}
assert_eq(null, $scalarVarsError, 'parse() accepts a non-array $vars with a Twig string template');
} else {
skip('Mailgun::parse() needs Twig (vendor not installed)');
}
if (class_exists('Parsedown')) {
$rendered = $mailgun->parse('# Title', [], 'markdown', 'string');
assert_contains('<h1>Title</h1>', $rendered, 'parse() renders Markdown');
} else {
skip('Mailgun::parse() needs Parsedown (vendor not installed)');
}
group('PHP 8 fatal and type errors');
$emptyLoadResult = null;
$emptyLoadError = null;
try {
$emptyLoadResult = $app->load('', []);
} catch (\Throwable $e) {
$emptyLoadError = get_class($e) . ': ' . $e->getMessage();
}
assert_eq(null, $emptyLoadError, 'load() with an empty component does not throw');
assert_true($emptyLoadResult === $app, 'load() with an empty component is chainable');
assert_throws(ErrorException::class, function () {
SeedPHP\Helper\Http::getHTTPStatus('abc');
}, 'getHTTPStatus() accepts a non-integer code');
assert_throws(ErrorException::class, function () {
SeedPHP\Helper\Http::getHTTPStatus(null);
}, 'getHTTPStatus() accepts a null code');
$unlinked = new SeedPHP\Helper\Database(['driver' => 'sqlite']);
$unlinkedLink = 'threw';
$unlinkedId = 'threw';
try {
$unlinkedLink = $unlinked->getLink();
$unlinkedId = $unlinked->insertedId();
} catch (\Throwable $e) {
$unlinkedLink = get_class($e) . ': ' . $e->getMessage();
$unlinkedId = $unlinkedLink;
}
assert_eq(null, $unlinkedLink, 'getLink() returns null before connecting');
assert_eq(0, $unlinkedId, 'insertedId() returns 0 before connecting');
$chained = new SeedPHP\Helper\Database(['driver' => 'sqlite']);
$chained->setDNS('sqlite::memory:');
$chained->connect();
$chainedRef = new ReflectionClass($chained);
$chainedDriver = $chainedRef->getProperty('_driver');
$chainedDriver->setAccessible(true);
$chainedDriver->setValue($chained, 'mysql');
$chainedCount = $chainedRef->getProperty('_transactions');
$chainedCount->setAccessible(true);
$chainedCount->setValue($chained, 2);
$chainedError = null;
try {
$chained->transaction('rollback');
} catch (\Error $e) {
$chainedError = $e->getMessage();
} catch (\Throwable $e) {
}
assert_eq(null, $chainedError, 'chained rollback does not read a non-static property');
$chained->disconnect();
group('Composer platform');
$composerManifest = json_decode((string) file_get_contents(__DIR__ . '/composer.json'), true);
$composerRequire = $composerManifest['require'] ?? [];
assert_eq('^8.1', $composerRequire['php'] ?? null, 'composer.json requires PHP ^8.1');
$expectedExtensions = ['ext-curl', 'ext-pdo', 'ext-json', 'ext-mbstring', 'ext-ctype'];
$missingExtensions = array_values(
array_diff($expectedExtensions, array_keys($composerRequire))
);
assert_eq([], $missingExtensions, 'composer.json declares the extensions the code uses');
assert_true(
!isset($composerManifest['config']['platform']['php']),
'composer.json does not pin the platform PHP version'
);
assert_eq('^3.0', $composerRequire['twig/twig'] ?? null, 'composer.json requires Twig ^3.0');
group('PHP 8 deprecations');
$lintTargets = array_merge(
[
__DIR__ . '/App.php',
__DIR__ . '/Core.php',
__DIR__ . '/Router.php',
__DIR__ . '/loader.php',
__DIR__ . '/index.php',
],
glob(__DIR__ . '/helper/*.php') ?: []
);
$lintProblems = [];
foreach ($lintTargets as $lintTarget) {
$lintOutput = [];
$lintStatus = 0;
exec(PHP_BINARY . ' -l ' . escapeshellarg($lintTarget) . ' 2>&1', $lintOutput, $lintStatus);
if ($lintStatus !== 0) {
$lintProblems[] = basename($lintTarget) . ': syntax error: ' . trim(implode("\n", $lintOutput));
continue;
}
foreach (diagnostics($lintOutput) as $lintDiagnostic) {
$lintProblems[] = basename($lintTarget) . ': ' . $lintDiagnostic;
}
}
assert_eq([], $lintProblems, 'php -l reports no compile-time deprecations');
$serverKeys = [
'$_SERVER["REMOTE_ADDR"] = "203.0.113.9";',
'unset($_SERVER["HTTP_X_FORWARDED_FOR"], $_SERVER["SERVER_PORT"],',
' $_SERVER["SERVER_NAME"], $_SERVER["SCRIPT_NAME"]);',
];
assert_no_diagnostics('booting and loading helpers is clean', [
'$app->load("database", ["driver" => "sqlite", "base" => ":memory:"], "db");',
'echo "runtime OK\n";',
]);
assert_no_diagnostics('reading the client IP and the base URL is clean', array_merge($serverKeys, [
'SeedPHP\\Helper\\Http::getClientIP();',
'SeedPHP\\Helper\\Http::getBaseUrl();',
]));
assert_no_diagnostics('building the request without SCRIPT_NAME is clean', array_merge($serverKeys, [
'$_SERVER["REQUEST_URI"] = "/sample/42";',
'(new ReflectionMethod($app, "buildRequest"))->invoke($app);',
]));
assert_no_diagnostics('rendering XML with null, object and attribute values is clean', [
'ob_start();',
'$app->response(200, [',
' "nil" => null,',
' "obj" => (object) ["x" => 1],',
' "node bare" => ["k" => "v"],',
' "node quoted=\"q\"" => ["k" => "v"],',
'], "xml");',
'ob_end_clean();',
]);
assert_no_diagnostics('replacing a template variable with a null value is clean', [
'$mailgun = new SeedPHP\\Helper\\Mailgun(["apiKey" => "key", "domain" => "example.test"]);',
'$mailgun->parse("Hello {name}", ["name" => null], "string", "string");',
]);
assert_no_diagnostics('rate limiting a partial session shape is clean', array_merge($serverKeys, [
'$rateLimit = new SeedPHP\\Helper\\RateLimit(["limit_per_second" => 2]);',
'$_SESSION["rate-limit"]["203.0.113.9"] = ["last-call" => date("Y-m-d H:i:s")];',
'$rateLimit->test();',
'$rateLimit->test();',
]));
assert_no_diagnostics('a failing cURL request is clean', [
'$curl = new SeedPHP\\Helper\\Curl();',
'$curl->create("http://127.0.0.1:1/");',
'$curl->execute();',
]);
$deprecatedCurlClose = 'curl_' . 'close(';
$curlCloseSources = [];
foreach (array_merge($lintTargets, [__DIR__ . '/tests.php', __DIR__ . '/tests/app.php']) as $sourceFile) {
if (strpos((string) file_get_contents($sourceFile), $deprecatedCurlClose) !== false) {
$curlCloseSources[] = basename($sourceFile);
}
}
assert_eq([], $curlCloseSources, 'no file calls curl_close, deprecated in PHP 8.5');
$removedRawPostIni = 'always_populate_raw_' . 'post_data';
$rawPostIniSources = [];
foreach (array_merge($lintTargets, [__DIR__ . '/tests.php', __DIR__ . '/tests/app.php']) as $sourceFile) {
if (strpos((string) file_get_contents($sourceFile), $removedRawPostIni) !== false) {
$rawPostIniSources[] = basename($sourceFile);
}
}
assert_eq([], $rawPostIniSources, 'no file reads the always_populate_raw_post ini setting, removed in PHP 7.0');
group('HTTP routing (live server)');
$portBusy = @fsockopen($TEST_HOST, $TEST_PORT, $errno, $errstr, 0.2);
if ($portBusy) {
fclose($portBusy);
fail("port {$TEST_PORT} is already in use");
} else {
@unlink($SERVER_LOG);
list($serverProc, $pipes) = start_server($TEST_HOST, $TEST_PORT, $SERVER_LOG);
register_shutdown_function(function () use (&$serverProc) {
if (is_resource($serverProc)) {
proc_terminate($serverProc);
proc_close($serverProc);
}
});
$ready = @fsockopen($TEST_HOST, $TEST_PORT, $errno, $errstr, 0.2);
if ($ready) {
fclose($ready);
} else {
fail("test server did not start on port {$TEST_PORT}");
}
if ($ready) {
$r = http_request('GET', '/');
assert_eq(200, $r['status'], 'GET / returns 200');
assert_eq('root', $r['body'], 'GET / echoes the handler output');
$r = http_request('GET', '/json');
assert_eq(200, $r['status'], 'GET /json returns 200');
assert_eq(200, $r['json']['status'], 'GET /json status field');
assert_eq('bar', $r['json']['data']['foo'], 'GET /json data payload');
$r = http_request('GET', '/xml');
assert_contains('<response>', $r['body'], 'GET /xml returns XML');
assert_contains('<status>200</status>', $r['body'], 'GET /xml status node');
$r = http_request('GET', '/error');
assert_eq(404, $r['status'], 'GET /error returns 404');
assert_true($r['json']['error'] === true, 'GET /error flags the error');
$r = http_request('GET', '/hooks');
assert_eq('before|main|after', $r['body'], 'before and after hooks run in order');
$r = http_request('GET', '/sample/123');
assert_eq('123', $r['json']['id'], 'numeric path segment becomes the id');
$r = http_request('POST', '/methods');
assert_eq('POST', $r['json']['method'], 'POST method is routed');
$r = http_request('GET', '/methods');
assert_eq('GET', $r['json']['method'], 'GET method is routed');
$r = http_request('OPTIONS', '/json');
assert_eq(200, $r['status'], 'OPTIONS is accepted');
$r = http_request('POST', '/post', ['name' => 'seed']);
assert_eq(200, $r['status'], 'POST /post returns 200');
assert_eq('seed', $r['json']['all']['name'], 'post() decodes a JSON body when $_POST is empty');
assert_eq('seed', $r['json']['one'], 'post(key) returns the matching value');
assert_eq(false, $r['json']['missing'], 'post(key) returns false when the key is missing');
$r = http_request('GET', '/nope');
assert_eq(501, $r['status'], 'unknown route returns 501');
group('Curl helper (live server)');
$curl = new SeedPHP\Helper\Curl();
$curl->create($BASE . '/json', [CURLOPT_VERBOSE => false]);
$result = $curl->execute();
assert_true(is_object($result), 'Curl::execute() decodes the JSON response');
assert_eq('bar', $result->data->foo, 'Curl::execute() returns the payload');
$curl = new SeedPHP\Helper\Curl();
$result = $curl->get($BASE . '/json', [CURLOPT_VERBOSE => false]);
assert_eq(200, $result->status, 'Curl::get() returns the response status');
$curl = new SeedPHP\Helper\Curl();
$result = $curl->post($BASE . '/methods', [CURLOPT_VERBOSE => false]);
assert_eq('POST', $result->method, 'Curl::post() uses the POST method');
group('Mailgun helper (live server)');
$mailgun = new SeedPHP\Helper\Mailgun(['apiKey' => 'key', 'domain' => 'example.test']);
$reflection = new ReflectionClass(SeedPHP\Helper\Mailgun::class);
$apiBase = $reflection->getProperty('_apiBase');
$apiBase->setAccessible(true);
$apiBase->setValue($mailgun, $BASE);
$domain = $reflection->getProperty('_domain');
$domain->setAccessible(true);
$domain->setValue($mailgun, '');
$mailgun
->setFrom('from@example.test', 'From')
->setTo('to@example.test', 'To')
->setSubject('Hello')
->setMessage('<b>Body</b>');
$result = $mailgun->send();
assert_eq('stubbed-message', $result['id'], 'send() posts to the API and returns the JSON');
assert_eq('Queued', $result['message'], 'send() reads the API message');
$cookie = tempnam(sys_get_temp_dir(), 'seedphp_cookie_');
$r = http_request('GET', '/ratelimit', null, $cookie);
assert_eq(200, $r['status'], 'ratelimit allows the first call');
$banned = false;
for ($i = 0; $i < 6; $i++) {
$r = http_request('GET', '/ratelimit', null, $cookie);
if ($r['status'] === 429) {
$banned = true;
break;
}
}
assert_true($banned, 'ratelimit bans after repeated calls');
@unlink($cookie);
}
if (is_resource($serverProc)) {
proc_terminate($serverProc);
proc_close($serverProc);
$serverProc = null;
}
}
echo "\n" . colorBold(str_repeat('=', 80)) . "\n";
$total = $passed + $failed + $skipped;
$summary = sprintf('%d PASSED. %d FAILED. %d SKIP.', $passed, $failed, $skipped);
echo ($failed === 0 ? colorGreen($summary) : colorRed($summary)) . "\n";
echo colorBold(sprintf('TOTAL: %d TEST CASES.', $total)) . "\n";
echo colorBold(str_repeat('=', 80)) . "\n";
exit($failed > 0 ? 1 : 0);