-
Notifications
You must be signed in to change notification settings - Fork 272
/
php.spec.ts
1134 lines (1036 loc) · 32.6 KB
/
php.spec.ts
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { getPHPLoaderModule, NodePHP } from '..';
import { vi } from 'vitest';
import {
loadPHPRuntime,
SupportedPHPVersions,
__private__dont__use,
} from '@php-wasm/universal';
import { existsSync, rmSync, readFileSync } from 'fs';
const testDirPath = '/__test987654321';
const testFilePath = '/__test987654321.txt';
describe.each(SupportedPHPVersions)('PHP %s', (phpVersion) => {
let php: NodePHP;
beforeEach(async () => {
php = await NodePHP.load(phpVersion as any);
php.setPhpIniEntry('disable_functions', '');
});
describe('exec()', () => {
it('echo', async () => {
const result = await php.run({
code: `<?php
echo 'stdout: ' . exec("echo WordPress");
`,
});
expect(result.text).toEqual('stdout: WordPress');
});
});
describe('popen()', () => {
it('popen("echo", "r")', async () => {
const result = await php.run({
code: `<?php
$fp = popen("echo WordPress", "r");
echo 'stdout: ' . fread($fp, 1024);
fclose($fp);
`,
});
expect(result.text).toEqual('stdout: WordPress\n');
});
it('popen("cat", "w")', async () => {
const result = await php.run({
code: `<?php
$path = __DIR__;
$fp = popen("cat > out", "w");
fwrite($fp, "WordPress\n");
fclose($fp);
// Yields back to JS event loop to give the child process a chance
// to process the input.
sleep(1);
$fp = popen("cat out", "r");
echo 'stdout: ' . fread($fp, 1024);
fclose($fp);
`,
});
expect(result.text).toEqual('stdout: WordPress\n');
});
});
describe('proc_open()', () => {
it('echo – stdin=file (empty), stdout=file, stderr=file', async () => {
const result = await php.run({
code: `<?php
file_put_contents('/tmp/process_in', '');
$res = proc_open(
"echo WordPress",
array(
array("file","/tmp/process_in", "r"),
array("file","/tmp/process_out", "w"),
array("file","/tmp/process_err", "w"),
),
$pipes
);
// Yields back to JS event loop to capture and process the
// child_process output. This is fine. Regular PHP scripts
// typically wait for the child process to finish.
sleep(1);
$stdout = file_get_contents("/tmp/process_out");
$stderr = file_get_contents("/tmp/process_err");
echo 'stdout: ' . $stdout . "";
echo 'stderr: ' . $stderr . PHP_EOL;
`,
});
expect(result.text).toEqual('stdout: WordPress\nstderr: \n');
});
it('echo – stdin=file (empty), stdout=pipe, stderr=pipe', async () => {
const result = await php.run({
code: `<?php
file_put_contents('/tmp/process_in', '');
$res = proc_open(
"echo WordPress",
array(
array("file","/tmp/process_in", "r"),
array("pipe","w"),
array("pipe","w"),
),
$pipes
);
// stream_get_contents yields back to JS event loop internally.
sleep(1);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
proc_close($res);
echo 'stdout: ' . $stdout . "";
echo 'stderr: ' . $stderr . PHP_EOL;
`,
});
expect(result.text).toEqual('stdout: WordPress\nstderr: \n');
});
// This test fails
if (!['7.0', '7.1', '7.2', '7.3'].includes(phpVersion)) {
/*
There is a race condition in this variant of the test which
causes the following failure (but only sometimes):
src/test/php.spec.ts > PHP 8.2 > proc_open() > cat – stdin=pipe, stdout=file, stderr=file
→ expected 'stdout: \nordPressstderr: \n' to deeply equal 'stdout: WordPress\nstderr: \n'
*/
it.skip('cat – stdin=pipe, stdout=file, stderr=file', async () => {
const result = await php.run({
code: `<?php
$res = proc_open(
"cat",
array(
array("pipe","r"),
array("file","/tmp/process_out", "w"),
array("file","/tmp/process_err", "w"),
),
$pipes
);
fwrite($pipes[0], 'WordPress\n');
// Yields back to JS event loop to capture and process the
// child_process output. This is fine. Regular PHP scripts
// typically wait for the child process to finish.
sleep(1);
$stdout = file_get_contents("/tmp/process_out");
$stderr = file_get_contents("/tmp/process_err");
proc_close($res);
echo 'stdout: ' . $stdout . "";
echo 'stderr: ' . $stderr . PHP_EOL;
`,
});
expect(result.text).toEqual('stdout: WordPress\nstderr: \n');
});
}
it('cat – stdin=file, stdout=file, stderr=file', async () => {
const result = await php.run({
code: `<?php
file_put_contents('/tmp/process_in', 'WordPress\n');
$res = proc_open(
"cat",
array(
array("file","/tmp/process_in", "r"),
array("file","/tmp/process_out", "w"),
array("file","/tmp/process_err", "w"),
),
$pipes
);
// Yields back to JS event loop to capture and process the
// child_process output. This is fine. Regular PHP scripts
// typically wait for the child process to finish.
sleep(1);
$stdout = file_get_contents("/tmp/process_out");
$stderr = file_get_contents("/tmp/process_err");
proc_close($res);
echo 'stdout: ' . $stdout . "";
echo 'stderr: ' . $stderr . PHP_EOL;
`,
});
expect(result.text).toEqual('stdout: WordPress\nstderr: \n');
});
it('Uses the specified spawn handler', async () => {
let spawnHandlerCalled = false;
php.setSpawnHandler(() => {
spawnHandlerCalled = true;
return {
stdout: {
on: () => {},
},
stderr: {
on: () => {},
},
stdin: {
write: () => {},
},
on: () => {},
kill: () => {},
} as any;
});
await php.run({
code: `<?php
$res = proc_open(
"echo 'Hello World!'",
array(
array("pipe","r"),
array("pipe","w"),
array("pipe","w"),
),
$pipes
);
proc_close($res);
`,
});
expect(spawnHandlerCalled).toEqual(true);
});
});
describe('Filesystem', () => {
// Unit tests for the filesystem methods of the
// PHP runtime.
it('writeFile() should create a file when it does not exist', () => {
php.writeFile(testFilePath, 'Hello World!');
expect(php.fileExists(testFilePath)).toEqual(true);
});
it('writeFile() should throw a useful error when parent directory does not exist', () => {
expect(() => {
php.writeFile('/a/b/c/d/e/f', 'Hello World!');
}).toThrowError(
'Could not write to "/a/b/c/d/e/f": There is no such file or directory OR the parent directory does not exist.'
);
});
it('writeFile() should throw a useful error when the specified path is a directory', () => {
php.mkdir('/dir');
expect(() => {
php.writeFile('/dir', 'Hello World!');
}).toThrowError(
new Error(
`Could not write to "/dir": There is a directory under that path.`
)
);
});
it('writeFile() should overwrite a file when it exists', () => {
php.writeFile(testFilePath, 'Hello World!');
php.writeFile(testFilePath, 'New contents');
expect(php.readFileAsText(testFilePath)).toEqual('New contents');
});
it('readFileAsText() should read a file as text', () => {
php.writeFile(testFilePath, 'Hello World!');
expect(php.readFileAsText(testFilePath)).toEqual('Hello World!');
});
it('readFileAsBuffer() should read a file as buffer', () => {
php.writeFile(testFilePath, 'Hello World!');
expect(php.readFileAsBuffer(testFilePath)).toEqual(
new TextEncoder().encode('Hello World!')
);
});
it('unlink() should delete a file', () => {
php.writeFile(testFilePath, 'Hello World!');
expect(php.fileExists(testFilePath)).toEqual(true);
php.unlink(testFilePath);
expect(php.fileExists(testFilePath)).toEqual(false);
});
it('mv() should move a file', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/2.txt';
php.writeFile(file1, '1');
php.mv(file1, file2);
expect(php.fileExists(file1)).toEqual(false);
expect(php.fileExists(file2)).toEqual(true);
expect(php.readFileAsText(file2)).toEqual('1');
});
it('mv() should replace target file if it exists', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/2.txt';
php.writeFile(file1, '1');
php.writeFile(file2, '2');
php.mv(file1, file2);
expect(php.fileExists(file1)).toEqual(false);
expect(php.fileExists(file2)).toEqual(true);
expect(php.readFileAsText(file2)).toEqual('1');
});
it('mv() should throw a useful error when source file does not exist', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/2.txt';
expect(() => {
php.mv(file1, file2);
}).toThrowError(
`Could not move "${testDirPath}/1.txt": There is no such file or directory OR the parent directory does not exist.`
);
});
it('mv() should throw a useful error when target directory does not exist', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/nowhere/2.txt';
php.writeFile(file1, '1');
expect(() => {
php.mv(file1, file2);
}).toThrowError(
`Could not move "${testDirPath}/1.txt": There is no such file or directory OR the parent directory does not exist.`
);
});
it('cp() should copy a file', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/2.txt';
php.writeFile(file1, '1');
php.cp(file1, file2);
expect(php.fileExists(file1)).toEqual(true);
expect(php.fileExists(file2)).toEqual(true);
expect(php.readFileAsText(file2)).toEqual('1');
});
it('cp() should copy a directory', () => {
const testDirPath1 = testDirPath;
const testDirPath2 = '/__test987654322';
php.mkdir(testDirPath1);
php.writeFile(testDirPath1 + '/1.txt', '1');
php.writeFile(testDirPath1 + '/2.txt', '2');
php.cp(testDirPath1, testDirPath2, { recursive: true });
expect(php.fileExists(testDirPath2 + '/1.txt')).toEqual(true);
expect(php.fileExists(testDirPath2 + '/2.txt')).toEqual(true);
expect(php.readFileAsText(testDirPath2 + '/1.txt')).toEqual('1');
expect(php.readFileAsText(testDirPath2 + '/2.txt')).toEqual('2');
});
it('cp() should copy a file into a directory', () => {
const testDirPath1 = testDirPath;
const testDirPath2 = '/__test987654322';
php.mkdir(testDirPath1);
php.mkdir(testDirPath2);
php.writeFile(testDirPath1 + '/1.txt', '1');
php.cp(testDirPath1 + '/1.txt', testDirPath2);
expect(php.fileExists(testDirPath2 + '/1.txt')).toEqual(true);
expect(php.readFileAsText(testDirPath2 + '/1.txt')).toEqual('1');
});
it('cp() should replace target file if it exists', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/2.txt';
php.writeFile(file1, '1');
php.writeFile(file2, '2');
php.cp(file1, file2);
expect(php.fileExists(file1)).toEqual(true);
expect(php.fileExists(file2)).toEqual(true);
expect(php.readFileAsText(file2)).toEqual('1');
});
it('cp() should throw a useful error when source file does not exist', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/2.txt';
expect(() => {
php.cp(file1, file2);
}).toThrowError(
`Could not copy "${testDirPath}/1.txt": There is no such file or directory OR the parent directory does not exist.`
);
});
it('cp() should throw a useful error when target directory does not exist', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/nowhere/2.txt';
php.writeFile(file1, '1');
expect(() => {
php.cp(file1, file2);
}).toThrowError(
`Could not copy "${testDirPath}/1.txt": There is no such file or directory OR the parent directory does not exist.`
);
});
it('mkdir() should create a directory', () => {
php.mkdir(testDirPath);
expect(php.fileExists(testDirPath)).toEqual(true);
});
it('mkdir() should create all nested directories', () => {
php.mkdir(testDirPath + '/nested/doubly/triply');
expect(php.isDir(testDirPath + '/nested/doubly/triply')).toEqual(
true
);
});
it('unlink() should throw a useful error when parent directory does not exist', () => {
expect(() => {
php.unlink('/a/b/c/d/e/f');
}).toThrowError(
'Could not unlink "/a/b/c/d/e/f": There is no such file or directory OR the parent directory does not exist.'
);
});
it('isDir() should correctly distinguish between a file and a directory', () => {
php.mkdir(testDirPath);
expect(php.fileExists(testDirPath)).toEqual(true);
expect(php.isDir(testDirPath)).toEqual(true);
php.writeFile(testFilePath, 'Hello World!');
expect(php.fileExists(testFilePath)).toEqual(true);
expect(php.isDir(testFilePath)).toEqual(false);
});
it('listFiles() should return a list of files in a directory', () => {
php.mkdir(testDirPath);
php.writeFile(testDirPath + '/test.txt', 'Hello World!');
php.writeFile(testDirPath + '/test2.txt', 'Hello World!');
expect(php.listFiles(testDirPath)).toEqual([
'test.txt',
'test2.txt',
]);
});
it('listFiles() option prependPath should prepend given path to all files returned', () => {
php.mkdir(testDirPath);
php.writeFile(testDirPath + '/test.txt', 'Hello World!');
php.writeFile(testDirPath + '/test2.txt', 'Hello World!');
expect(php.listFiles(testDirPath, { prependPath: true })).toEqual([
testDirPath + '/test.txt',
testDirPath + '/test2.txt',
]);
});
});
describe('Stdio', () => {
it('should output strings (1)', async () => {
expect(
await php.run({ code: '<?php echo "Hello world!";' })
).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new TextEncoder().encode('Hello world!'),
errors: '',
exitCode: 0,
});
});
it('should output strings (2) ', async () => {
expect(
await php.run({ code: '<?php echo "Hello world!\nI am PHP";' })
).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new TextEncoder().encode('Hello world!\nI am PHP'),
errors: '',
exitCode: 0,
});
});
it('should output bytes ', async () => {
const results = await php.run({
code: '<?php echo chr(1).chr(0).chr(1).chr(0).chr(2); ',
});
expect(results).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new Uint8Array([1, 0, 1, 0, 2]),
errors: '',
exitCode: 0,
});
});
it('should output strings when .run() is called twice', async () => {
expect(
await php.run({ code: '<?php echo "Hello world!";' })
).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new TextEncoder().encode('Hello world!'),
errors: '',
exitCode: 0,
});
expect(
await php.run({ code: '<?php echo "Ehlo world!";' })
).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new TextEncoder().encode('Ehlo world!'),
errors: '',
exitCode: 0,
});
});
it('should capture error data from stderr', async () => {
const code = `<?php
$stdErr = fopen('php://stderr', 'w');
fwrite($stdErr, "Hello from stderr!");
`;
expect(await php.run({ code })).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new TextEncoder().encode(''),
errors: 'Hello from stderr!',
exitCode: 0,
});
});
it('should provide response text through .text', async () => {
const code = `<?php
echo "Hello world!";
`;
const response = await php.run({ code });
expect(response.text).toEqual('Hello world!');
});
it('should provide response JSON through .json', async () => {
const code = `<?php
echo json_encode(["hello" => "world"]);
`;
const response = await php.run({ code });
expect(response.json).toEqual({ hello: 'world' });
});
});
describe('Startup sequence – basics', () => {
/**
* This test ensures that the PHP runtime can be loaded twice.
*
* It protects from a regression that happened in the past
* after making the Emscripten module's main function the
* default export. Turns out, the generated Emscripten code
* replaces the default export with an instantiated module upon
* the first call.
*/
it('Should spawn two PHP runtimes', async () => {
const phpLoaderModule1 = await getPHPLoaderModule(
phpVersion as any
);
const runtimeId1 = await loadPHPRuntime(phpLoaderModule1);
const phpLoaderModule2 = await getPHPLoaderModule(
phpVersion as any
);
const runtimeId2 = await loadPHPRuntime(phpLoaderModule2);
expect(runtimeId1).not.toEqual(runtimeId2);
});
});
describe('Startup sequence', () => {
const testScriptPath = '/test.php';
afterEach(() => {
if (existsSync(testScriptPath)) {
rmSync(testScriptPath);
}
});
/**
* Issue https://github.com/WordPress/wordpress-playground/issues/169
*/
it('Should work with long POST body', () => {
php.writeFile(testScriptPath, '<?php echo "Hello world!"; ?>');
const body =
readFileSync(
new URL('./test-data/long-post-body.txt', import.meta.url)
.pathname,
'utf8'
) + '';
// 0x4000 is SAPI_POST_BLOCK_SIZE
expect(body.length).toBeGreaterThan(0x4000);
expect(async () => {
await php.run({
code: 'echo "A";',
relativeUri: '/test.php?a=b',
body,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
}).not.toThrowError();
});
it('Should run a script when no code snippet is provided', async () => {
php.writeFile(testScriptPath, `<?php echo "Hello world!"; ?>\n`);
const response = await php.run({
scriptPath: testScriptPath,
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual('Hello world!');
});
it('Should run a code snippet when provided, even if scriptPath is set', async () => {
php.writeFile(testScriptPath, '<?php echo "Hello world!"; ?>');
const response = await php.run({
scriptPath: testScriptPath,
code: '<?php echo "Hello from a code snippet!";',
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual('Hello from a code snippet!');
});
it('Should have access to raw request data via the php://input stream', async () => {
const response = await php.run({
method: 'POST',
body: '{"foo": "bar"}',
code: `<?php echo file_get_contents('php://input');`,
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual('{"foo": "bar"}');
});
it('Should set $_SERVER entries for provided headers', async () => {
const response = await php.run({
code: `<?php echo json_encode($_SERVER);`,
method: 'POST',
body: 'foo=bar',
headers: {
'Content-Type': 'text/plain',
'Content-Length': '15',
'User-agent': 'my-user-agent',
'custom-header': 'custom value',
'x-test': 'x custom value',
},
});
const json = response.json;
expect(json).toHaveProperty('HTTP_USER_AGENT', 'my-user-agent');
expect(json).toHaveProperty('HTTP_CUSTOM_HEADER', 'custom value');
expect(json).toHaveProperty('HTTP_X_TEST', 'x custom value');
/*
* The following headers should be set without the HTTP_ prefix,
* as PHP follows the following convention:
* https://www.ietf.org/rfc/rfc3875
*/
expect(json).toHaveProperty('CONTENT_TYPE', 'text/plain');
expect(json).toHaveProperty('CONTENT_LENGTH', '15');
});
it('Should expose urlencoded POST data in $_POST', async () => {
const response = await php.run({
code: `<?php echo json_encode($_POST);`,
method: 'POST',
body: 'foo=bar',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual('{"foo":"bar"}');
});
it('Should expose urlencoded POST arrays in $_POST', async () => {
const response = await php.run({
code: `<?php echo json_encode($_POST);`,
method: 'POST',
body: 'foo[]=bar1&foo[]=bar2&indexed[key]=value',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual(
'{"foo":["bar1","bar2"],"indexed":{"key":"value"}}'
);
});
it('Should expose multipart POST data in $_POST', async () => {
const response = await php.run({
code: `<?php echo json_encode($_POST);`,
method: 'POST',
body: `--boundary
Content-Disposition: form-data; name="foo"
bar`,
headers: {
'Content-Type': 'multipart/form-data; boundary=boundary',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual('{"foo":"bar"}');
});
it('Should expose multipart POST files in $_FILES', async () => {
const response = await php.run({
code: `<?php echo json_encode(array(
"files" => $_FILES,
"is_uploaded" => is_uploaded_file($_FILES["myFile"]["tmp_name"])
));`,
method: 'POST',
body: `--boundary
Content-Disposition: form-data; name="myFile"; filename="text.txt"
Content-Type: text/plain
bar
--boundary--`,
headers: {
'Content-Type': 'multipart/form-data; boundary=boundary',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
const expectedResult = {
files: {
myFile: {
name: 'text.txt',
type: 'text/plain',
tmp_name: expect.any(String),
error: 0,
size: 3,
},
},
is_uploaded: true,
};
if (Number(phpVersion) > 8) {
(expectedResult.files.myFile as any).full_path = 'text.txt';
}
expect(JSON.parse(bodyText)).toEqual(expectedResult);
});
it('Should expose uploaded files in $_FILES', async () => {
const response = await php.run({
code: `<?php echo json_encode(array(
"files" => $_FILES,
"is_uploaded" => is_uploaded_file($_FILES["myFile"]["tmp_name"])
));`,
method: 'POST',
fileInfos: [
{
name: 'text.txt',
key: 'myFile',
data: new TextEncoder().encode('bar'),
type: 'text/plain',
},
],
headers: {
'Content-Type': 'multipart/form-data; boundary=boundary',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(JSON.parse(bodyText)).toEqual({
files: {
myFile: {
name: 'text.txt',
type: 'text/plain',
tmp_name: expect.any(String),
error: '0',
size: '3',
},
},
is_uploaded: true,
});
});
it('Should expose both the multipart/form-data request body AND uploaded files in $_FILES', async () => {
const response = await php.run({
code: `<?php echo json_encode(array(
"files" => $_FILES,
"is_uploaded1" => is_uploaded_file($_FILES["myFile1"]["tmp_name"]),
"is_uploaded2" => is_uploaded_file($_FILES["myFile2"]["tmp_name"])
));`,
relativeUri: '/',
method: 'POST',
body: `--boundary
Content-Disposition: form-data; name="myFile1"; filename="from_body.txt"
Content-Type: text/plain
bar1
--boundary--`,
fileInfos: [
{
name: 'from_files.txt',
key: 'myFile2',
data: new TextEncoder().encode('bar2'),
type: 'application/json',
},
],
headers: {
'Content-Type': 'multipart/form-data; boundary=boundary',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
const expectedResult = {
files: {
myFile1: {
name: 'from_body.txt',
type: 'text/plain',
tmp_name: expect.any(String),
error: 0,
size: 4,
},
myFile2: {
name: 'from_files.txt',
type: 'application/json',
tmp_name: expect.any(String),
error: '0',
size: '4',
},
},
is_uploaded1: true,
is_uploaded2: true,
};
if (Number(phpVersion) > 8) {
(expectedResult.files.myFile1 as any).full_path =
'from_body.txt';
}
expect(JSON.parse(bodyText)).toEqual(expectedResult);
});
it('Should provide the correct $_SERVER information', async () => {
php.writeFile(
testScriptPath,
'<?php echo json_encode($_SERVER); ?>'
);
const response = await php.run({
scriptPath: testScriptPath,
relativeUri: '/test.php?a=b',
method: 'POST',
body: `--boundary
Content-Disposition: form-data; name="myFile1"; filename="from_body.txt"
Content-Type: text/plain
bar1
--boundary--`,
fileInfos: [
{
name: 'from_files.txt',
key: 'myFile2',
data: new TextEncoder().encode('bar2'),
type: 'application/json',
},
],
headers: {
'Content-Type': 'multipart/form-data; boundary=boundary',
Host: 'https://example.com:1235',
'X-is-ajax': 'true',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
const $_SERVER = JSON.parse(bodyText);
expect($_SERVER).toHaveProperty('REQUEST_URI', '/test.php?a=b');
expect($_SERVER).toHaveProperty('REQUEST_METHOD', 'POST');
expect($_SERVER).toHaveProperty(
'CONTENT_TYPE',
'multipart/form-data; boundary=boundary'
);
expect($_SERVER).toHaveProperty(
'HTTP_HOST',
'https://example.com:1235'
);
expect($_SERVER).toHaveProperty(
'SERVER_NAME',
'https://example.com:1235'
);
expect($_SERVER).toHaveProperty('HTTP_X_IS_AJAX', 'true');
expect($_SERVER).toHaveProperty('SERVER_PORT', '1235');
});
});
/**
* libsqlite3 path needs to be explicitly provided in Dockerfile
* for PHP < 7.4 – let's make sure it works
*/
describe('PDO SQLite support', () => {
it('Should be able to create a database', async () => {
const response = await php.run({
code: `<?php
$db = new PDO('sqlite::memory:');
$db->exec('CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)');
$db->exec('INSERT INTO test (name) VALUES ("This is a test")');
$result = $db->query('SELECT name FROM test');
$rows = $result->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($rows);
?>`,
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(JSON.parse(bodyText)).toEqual(['This is a test']);
});
it('Should support modern libsqlite (ON CONFLICT)', async () => {
const response = await php.run({
code: `<?php
$db = new PDO('sqlite::memory:');
$db->exec('CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)');
$db->exec('CREATE UNIQUE INDEX test_name ON test (name)');
$db->exec('INSERT INTO test (name) VALUES ("This is a test")');
$db->exec('INSERT INTO test (name) VALUES ("This is a test") ON CONFLICT DO NOTHING');
$result = $db->query('SELECT name FROM test');
$rows = $result->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($rows);
?>`,
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(JSON.parse(bodyText)).toEqual(['This is a test']);
});
});
/**
* hash extension needs to be explicitly enabled in Dockerfile
* for PHP < 7.3 – let's make sure it works
*/
describe('Hash extension support', () => {
it('Should be able to hash a string', async () => {
const response = await php.run({
code: `<?php
echo json_encode([
'md5' => md5('test'),
'sha1' => sha1('test'),
'hash' => hash('sha256', 'test'),
]);
?>`,
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(JSON.parse(bodyText)).toEqual({
md5: '098f6bcd4621d373cade4e832627b4f6',
sha1: 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3',
hash: '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08',
});
});
});
describe('onMessage', () => {
it('should pass messages to JS', async () => {
let messageReceived = '';
php.onMessage((message) => {
messageReceived = message;
});
const out = await php.run({
code: `<?php
post_message_to_js('world');
`,
});
expect(out.errors).toBe('');
expect(messageReceived).toBe('world');
});
it('should return sync messages from JS', async () => {
php.onMessage(async (message) => message + '!');
const out = await php.run({
code: `<?php echo post_message_to_js('a');`,
});
expect(out.errors).toBe('');
expect(out.text).toBe('a!');
});
it('should return async messages from JS', async () => {
php.onMessage(async (message) => {
// Simulate getting data asynchronously.
return await new Promise<string>((resolve) =>
setTimeout(() => resolve(message + '!'), 100)
);
});
const out = await php.run({
code: `<?php echo post_message_to_js('a');`,
});
expect(out.errors).toBe('');
expect(out.text).toBe('a!');
});
it('should return null when JS message handler throws an error', async () => {
php.onMessage(async () => {
// Simulate getting data asynchronously.
return await new Promise<string>((resolve, reject) =>
setTimeout(() => reject('Failure!'), 100)
);
});
const out = await php.run({
code: `<?php var_dump(post_message_to_js('a'));`,
});
expect(out.errors).toBe('');
expect(out.text).toBe('NULL\n');
});
});
describe('CLI', () => {
let consoleLogMock: any;
let consoleErrorMock: any;
beforeEach(() => {
consoleLogMock = vi
.spyOn(console, 'log')
.mockImplementation(() => {});
consoleErrorMock = vi
.spyOn(console, 'error')
.mockImplementation(() => {});
});
afterAll(() => {
consoleLogMock.mockReset();
consoleErrorMock.mockReset();
});
it('should not log an error message on exit status 0', async () => {
await php.cli(['php', '-r', '$tmp = "Hello";']);
expect(consoleLogMock).not.toHaveBeenCalled();
expect(consoleErrorMock).not.toHaveBeenCalled();
});