-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathProcessTest.php
1747 lines (1431 loc) · 52.9 KB
/
ProcessTest.php
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
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Process\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Exception\InvalidArgumentException;
use Symfony\Component\Process\Exception\LogicException;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Exception\ProcessSignaledException;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Exception\RuntimeException;
use Symfony\Component\Process\InputStream;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Pipes\PipesInterface;
use Symfony\Component\Process\Process;
/**
* @author Robert Schönthal <seroscho@googlemail.com>
*/
class ProcessTest extends TestCase
{
private static string $phpBin;
private static ?Process $process = null;
private static bool $sigchild;
public static function setUpBeforeClass(): void
{
$phpBin = new PhpExecutableFinder();
self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === \PHP_SAPI ? 'php' : $phpBin->find());
ob_start();
phpinfo(\INFO_GENERAL);
self::$sigchild = str_contains(ob_get_clean(), '--enable-sigchild');
}
protected function tearDown(): void
{
if (self::$process) {
self::$process->stop(0);
self::$process = null;
}
}
public function testInvalidCwd()
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessageMatches('/The provided cwd ".*" does not exist\./');
try {
// Check that it works fine if the CWD exists
$cmd = new Process(['echo', 'test'], __DIR__);
$cmd->run();
} catch (\Exception $e) {
$this->fail($e);
}
$cmd = new Process(['echo', 'test'], __DIR__.'/notfound/');
$cmd->run();
}
/**
* @dataProvider invalidProcessProvider
*/
public function testInvalidCommand(Process $process)
{
// An invalid command should not fail during start
$this->assertSame('\\' === \DIRECTORY_SEPARATOR ? 1 : 127, $process->run());
}
public static function invalidProcessProvider(): array
{
return [
[new Process(['invalid'])],
[Process::fromShellCommandline('invalid')],
];
}
/**
* @group transient-on-windows
*/
public function testThatProcessDoesNotThrowWarningDuringRun()
{
@trigger_error('Test Error', \E_USER_NOTICE);
$process = $this->getProcessForCode('sleep(3)');
$process->run();
$actualError = error_get_last();
$this->assertEquals('Test Error', $actualError['message']);
$this->assertEquals(\E_USER_NOTICE, $actualError['type']);
}
public function testNegativeTimeoutFromConstructor()
{
$this->expectException(InvalidArgumentException::class);
$this->getProcess('', null, null, null, -1);
}
public function testNegativeTimeoutFromSetter()
{
$this->expectException(InvalidArgumentException::class);
$p = $this->getProcess('');
$p->setTimeout(-1);
}
public function testFloatAndNullTimeout()
{
$p = $this->getProcess('');
$p->setTimeout(10);
$this->assertSame(10.0, $p->getTimeout());
$p->setTimeout(null);
$this->assertNull($p->getTimeout());
$p->setTimeout(0.0);
$this->assertNull($p->getTimeout());
}
/**
* @requires extension pcntl
*/
public function testStopWithTimeoutIsActuallyWorking()
{
$p = $this->getProcess([self::$phpBin, __DIR__.'/NonStopableProcess.php', 30]);
$p->start();
while ($p->isRunning() && !str_contains($p->getOutput(), 'received')) {
usleep(1000);
}
if (!$p->isRunning()) {
throw new \LogicException('Process is not running: '.$p->getErrorOutput());
}
$start = microtime(true);
$p->stop(0.1);
$p->wait();
$this->assertLessThan(15, microtime(true) - $start);
}
/**
* @group transient-on-windows
*/
public function testWaitUntilSpecificOutput()
{
$p = $this->getProcess([self::$phpBin, __DIR__.'/KillableProcessWithOutput.php']);
$p->start();
$start = microtime(true);
$completeOutput = '';
$result = $p->waitUntil(function ($type, $output) use (&$completeOutput) {
return str_contains($completeOutput .= $output, 'One more');
});
$this->assertTrue($result);
$this->assertLessThan(20, microtime(true) - $start);
$this->assertStringStartsWith("First iteration output\nSecond iteration output\nOne more", $completeOutput);
$p->stop();
}
public function testWaitUntilCanReturnFalse()
{
$p = $this->getProcess('echo foo');
$p->start();
$this->assertFalse($p->waitUntil(fn () => false));
}
public function testAllOutputIsActuallyReadOnTermination()
{
// this code will result in a maximum of 2 reads of 8192 bytes by calling
// start() and isRunning(). by the time getOutput() is called the process
// has terminated so the internal pipes array is already empty. normally
// the call to start() will not read any data as the process will not have
// generated output, but this is non-deterministic so we must count it as
// a possibility. therefore we need 2 * PipesInterface::CHUNK_SIZE plus
// another byte which will never be read.
$expectedOutputSize = PipesInterface::CHUNK_SIZE * 2 + 2;
$code = \sprintf('echo str_repeat(\'*\', %d);', $expectedOutputSize);
$p = $this->getProcessForCode($code);
$p->start();
// Don't call Process::run nor Process::wait to avoid any read of pipes
$h = new \ReflectionProperty($p, 'process');
$h = $h->getValue($p);
$s = @proc_get_status($h);
while (!empty($s['running'])) {
usleep(1000);
$s = proc_get_status($h);
}
$o = $p->getOutput();
$this->assertEquals($expectedOutputSize, \strlen($o));
}
public function testCallbacksAreExecutedWithStart()
{
$process = $this->getProcess('echo foo');
$process->start(function ($type, $buffer) use (&$data) {
$data .= $buffer;
});
$process->wait();
$this->assertSame('foo'.\PHP_EOL, $data);
}
public function testReadSupportIsDisabledWithoutCallback()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::wait".');
$process = $this->getProcess('echo foo');
// disabling output + not passing a callback to start() => read support disabled
$process->disableOutput();
$process->start();
$process->wait(function ($type, $buffer) use (&$data) {
$data .= $buffer;
});
}
/**
* tests results from sub processes.
*
* @dataProvider responsesCodeProvider
*/
public function testProcessResponses($expected, $getter, $code)
{
$p = $this->getProcessForCode($code);
$p->run();
$this->assertSame($expected, $p->$getter());
}
/**
* tests results from sub processes.
*
* @dataProvider pipesCodeProvider
*/
public function testProcessPipes($code, $size)
{
$expected = str_repeat(str_repeat('*', 1024), $size).'!';
$expectedLength = (1024 * $size) + 1;
$p = $this->getProcessForCode($code);
$p->setInput($expected);
$p->run();
$this->assertEquals($expectedLength, \strlen($p->getOutput()));
$this->assertEquals($expectedLength, \strlen($p->getErrorOutput()));
}
/**
* @dataProvider pipesCodeProvider
*/
public function testSetStreamAsInput($code, $size)
{
$expected = str_repeat(str_repeat('*', 1024), $size).'!';
$expectedLength = (1024 * $size) + 1;
$stream = fopen('php://temporary', 'w+');
fwrite($stream, $expected);
rewind($stream);
$p = $this->getProcessForCode($code);
$p->setInput($stream);
$p->run();
fclose($stream);
$this->assertEquals($expectedLength, \strlen($p->getOutput()));
$this->assertEquals($expectedLength, \strlen($p->getErrorOutput()));
}
public function testLiveStreamAsInput()
{
$stream = fopen('php://memory', 'r+');
fwrite($stream, 'hello');
rewind($stream);
$p = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
$p->setInput($stream);
$p->start(function ($type, $data) use ($stream) {
if ('hello' === $data) {
fclose($stream);
}
});
$p->wait();
$this->assertSame('hello', $p->getOutput());
}
public function testSetInputWhileRunningThrowsAnException()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Input cannot be set while the process is running.');
$process = $this->getProcessForCode('sleep(30);');
$process->start();
try {
$process->setInput('foobar');
$process->stop();
$this->fail('A LogicException should have been raised.');
} catch (LogicException $e) {
}
$process->stop();
throw $e;
}
/**
* @dataProvider provideInvalidInputValues
*/
public function testInvalidInput(array|object $value)
{
$process = $this->getProcess('foo');
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('"Symfony\Component\Process\Process::setInput" only accepts strings, Traversable objects or stream resources.');
$process->setInput($value);
}
public static function provideInvalidInputValues()
{
return [
[[]],
[new NonStringifiable()],
];
}
/**
* @dataProvider provideInputValues
*/
public function testValidInput(?string $expected, float|string|null $value)
{
$process = $this->getProcess('foo');
$process->setInput($value);
$this->assertSame($expected, $process->getInput());
}
public static function provideInputValues()
{
return [
[null, null],
['24.5', 24.5],
['input data', 'input data'],
];
}
public static function chainedCommandsOutputProvider()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
return [
["2 \r\n2\r\n", '&&', '2'],
];
}
return [
["1\n1\n", ';', '1'],
["2\n2\n", '&&', '2'],
];
}
/**
* @dataProvider chainedCommandsOutputProvider
*/
public function testChainedCommandsOutput($expected, $operator, $input)
{
$process = $this->getProcess(\sprintf('echo %s %s echo %s', $input, $operator, $input));
$process->run();
$this->assertEquals($expected, $process->getOutput());
}
public function testCallbackIsExecutedForOutput()
{
$p = $this->getProcessForCode('echo \'foo\';');
$called = false;
$p->run(function ($type, $buffer) use (&$called) {
$called = 'foo' === $buffer;
});
$this->assertTrue($called, 'The callback should be executed with the output');
}
public function testCallbackIsExecutedForOutputWheneverOutputIsDisabled()
{
$p = $this->getProcessForCode('echo \'foo\';');
$p->disableOutput();
$called = false;
$p->run(function ($type, $buffer) use (&$called) {
$called = 'foo' === $buffer;
});
$this->assertTrue($called, 'The callback should be executed with the output');
}
public function testGetErrorOutput()
{
$p = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }');
$p->run();
$this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches));
}
public function testFlushErrorOutput()
{
$p = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }');
$p->run();
$p->clearErrorOutput();
$this->assertEmpty($p->getErrorOutput());
}
/**
* @dataProvider provideIncrementalOutput
*/
public function testIncrementalOutput($getOutput, $getIncrementalOutput, $uri)
{
$lock = tempnam(sys_get_temp_dir(), __FUNCTION__);
$p = $this->getProcessForCode('file_put_contents($s = \''.$uri.'\', \'foo\'); flock(fopen('.var_export($lock, true).', \'r\'), LOCK_EX); file_put_contents($s, \'bar\');');
$h = fopen($lock, 'w');
flock($h, \LOCK_EX);
$p->start();
foreach (['foo', 'bar'] as $s) {
while (!str_contains($p->$getOutput(), $s)) {
usleep(1000);
}
$this->assertSame($s, $p->$getIncrementalOutput());
$this->assertSame('', $p->$getIncrementalOutput());
flock($h, \LOCK_UN);
}
fclose($h);
}
public static function provideIncrementalOutput()
{
return [
['getOutput', 'getIncrementalOutput', 'php://stdout'],
['getErrorOutput', 'getIncrementalErrorOutput', 'php://stderr'],
];
}
public function testGetOutput()
{
$p = $this->getProcessForCode('$n = 0; while ($n < 3) { echo \' foo \'; $n++; }');
$p->run();
$this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
}
public function testFlushOutput()
{
$p = $this->getProcessForCode('$n=0;while ($n<3) {echo \' foo \';$n++;}');
$p->run();
$p->clearOutput();
$this->assertEmpty($p->getOutput());
}
public function testZeroAsOutput()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
// see http://stackoverflow.com/questions/7105433/windows-batch-echo-without-new-line
$p = $this->getProcess('echo | set /p dummyName=0');
} else {
$p = $this->getProcess('printf 0');
}
$p->run();
$this->assertSame('0', $p->getOutput());
}
public function testExitCodeCommandFailed()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does not support POSIX exit code');
}
// such command run in bash return an exitcode 127
$process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
$process->run();
$this->assertGreaterThan(0, $process->getExitCode());
}
public function testTTYCommand()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does not have /dev/tty support');
}
if (!Process::isTtySupported()) {
$this->markTestSkipped('There is no TTY support');
}
$process = $this->getProcess('echo "foo" >> /dev/null && '.$this->getProcessForCode('usleep(100000);')->getCommandLine());
$process->setTty(true);
$process->start();
$this->assertTrue($process->isRunning());
$process->wait();
$this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
}
public function testTTYCommandExitCode()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does have /dev/tty support');
}
if (!Process::isTtySupported()) {
$this->markTestSkipped('There is no TTY support');
}
$process = $this->getProcess('echo "foo" >> /dev/null');
$process->setTty(true);
$process->run();
$this->assertTrue($process->isSuccessful());
}
public function testTTYInWindowsEnvironment()
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('TTY mode is not supported on Windows platform.');
if ('\\' !== \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('This test is for Windows platform only');
}
$process = $this->getProcess('echo "foo" >> /dev/null');
$process->setTty(false);
$process->setTty(true);
}
public function testExitCodeTextIsNullWhenExitCodeIsNull()
{
$process = $this->getProcess('');
$this->assertNull($process->getExitCodeText());
}
public function testStderrNotMixedWithStdout()
{
if (!Process::isPtySupported()) {
$this->markTestSkipped('PTY is not supported on this operating system.');
}
$process = $this->getProcess('echo "foo" && echo "bar" >&2');
$process->setPty(true);
$process->run();
$this->assertSame("foo\r\n", $process->getOutput());
$this->assertSame("bar\n", $process->getErrorOutput());
}
public function testPTYCommand()
{
if (!Process::isPtySupported()) {
$this->markTestSkipped('PTY is not supported on this operating system.');
}
$process = $this->getProcess('echo "foo"');
$process->setPty(true);
$process->run();
$this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
$this->assertEquals("foo\r\n", $process->getOutput());
}
public function testMustRun()
{
$process = $this->getProcess('echo foo');
$this->assertSame($process, $process->mustRun());
$this->assertEquals('foo'.\PHP_EOL, $process->getOutput());
}
public function testSuccessfulMustRunHasCorrectExitCode()
{
$process = $this->getProcess('echo foo')->mustRun();
$this->assertEquals(0, $process->getExitCode());
}
public function testMustRunThrowsException()
{
$process = $this->getProcess('exit 1');
$this->expectException(ProcessFailedException::class);
$process->mustRun();
}
public function testExitCodeText()
{
$process = $this->getProcess('');
$r = new \ReflectionObject($process);
$p = $r->getProperty('exitcode');
$p->setValue($process, 2);
$this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
}
public function testStartIsNonBlocking()
{
$process = $this->getProcessForCode('usleep(500000);');
$start = microtime(true);
$process->start();
$end = microtime(true);
$this->assertLessThan(0.4, $end - $start);
$process->stop();
}
public function testUpdateStatus()
{
$process = $this->getProcess('echo foo');
$process->run();
$this->assertGreaterThan(0, \strlen($process->getOutput()));
}
public function testGetExitCodeIsNullOnStart()
{
$process = $this->getProcessForCode('usleep(100000);');
$this->assertNull($process->getExitCode());
$process->start();
$this->assertNull($process->getExitCode());
$process->wait();
$this->assertEquals(0, $process->getExitCode());
}
public function testGetExitCodeIsNullOnWhenStartingAgain()
{
$process = $this->getProcessForCode('usleep(100000);');
$process->run();
$this->assertEquals(0, $process->getExitCode());
$process->start();
$this->assertNull($process->getExitCode());
$process->wait();
$this->assertEquals(0, $process->getExitCode());
}
public function testGetExitCode()
{
$process = $this->getProcess('echo foo');
$process->run();
$this->assertSame(0, $process->getExitCode());
}
public function testStatus()
{
$process = $this->getProcessForCode('usleep(100000);');
$this->assertFalse($process->isRunning());
$this->assertFalse($process->isStarted());
$this->assertFalse($process->isTerminated());
$this->assertSame(Process::STATUS_READY, $process->getStatus());
$process->start();
$this->assertTrue($process->isRunning());
$this->assertTrue($process->isStarted());
$this->assertFalse($process->isTerminated());
$this->assertSame(Process::STATUS_STARTED, $process->getStatus());
$process->wait();
$this->assertFalse($process->isRunning());
$this->assertTrue($process->isStarted());
$this->assertTrue($process->isTerminated());
$this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
}
public function testStop()
{
$process = $this->getProcessForCode('sleep(31);');
$process->start();
$this->assertTrue($process->isRunning());
$process->stop();
$this->assertFalse($process->isRunning());
}
public function testIsSuccessful()
{
$process = $this->getProcess('echo foo');
$process->run();
$this->assertTrue($process->isSuccessful());
}
public function testIsSuccessfulOnlyAfterTerminated()
{
$process = $this->getProcessForCode('usleep(100000);');
$process->start();
$this->assertFalse($process->isSuccessful());
$process->wait();
$this->assertTrue($process->isSuccessful());
}
public function testIsNotSuccessful()
{
$process = $this->getProcessForCode('throw new \Exception(\'BOUM\');');
$process->run();
$this->assertFalse($process->isSuccessful());
}
public function testProcessIsNotSignaled()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does not support POSIX signals');
}
$process = $this->getProcess('echo foo');
$process->run();
$this->assertFalse($process->hasBeenSignaled());
}
public function testProcessWithoutTermSignal()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does not support POSIX signals');
}
$process = $this->getProcess('echo foo');
$process->run();
$this->assertEquals(0, $process->getTermSignal());
}
public function testProcessIsSignaledIfStopped()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does not support POSIX signals');
}
if (\PHP_VERSION_ID < 80300 && isset($_SERVER['GITHUB_ACTIONS'])) {
$this->markTestSkipped('Transient on GHA with PHP < 8.3');
}
$process = $this->getProcessForCode('sleep(32);');
$process->start();
$process->stop();
$this->assertTrue($process->hasBeenSignaled());
$this->assertEquals(15, $process->getTermSignal()); // SIGTERM
}
public function testProcessThrowsExceptionWhenExternallySignaled()
{
$this->expectException(ProcessSignaledException::class);
$this->expectExceptionMessage('The process has been signaled with signal "9".');
if (!\function_exists('posix_kill')) {
$this->markTestSkipped('Function posix_kill is required.');
}
if (self::$sigchild) {
$this->markTestSkipped('PHP is compiled with --enable-sigchild.');
}
$process = $this->getProcessForCode('sleep(32.1);');
$process->start();
posix_kill($process->getPid(), 9); // SIGKILL
$process->wait();
}
public function testRestart()
{
$process1 = $this->getProcessForCode('echo getmypid();');
$process1->run();
$process2 = $process1->restart();
$process2->wait(); // wait for output
// Ensure that both processed finished and the output is numeric
$this->assertFalse($process1->isRunning());
$this->assertFalse($process2->isRunning());
$this->assertIsNumeric($process1->getOutput());
$this->assertIsNumeric($process2->getOutput());
// Ensure that restart returned a new process by check that the output is different
$this->assertNotEquals($process1->getOutput(), $process2->getOutput());
}
public function testRunProcessWithTimeout()
{
$this->expectException(ProcessTimedOutException::class);
$this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.');
$process = $this->getProcessForCode('sleep(30);');
$process->setTimeout(0.1);
$start = microtime(true);
try {
$process->run();
$this->fail('A RuntimeException should have been raised');
} catch (RuntimeException $e) {
}
$this->assertLessThan(15, microtime(true) - $start);
throw $e;
}
public function testIterateOverProcessWithTimeout()
{
$this->expectException(ProcessTimedOutException::class);
$this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.');
$process = $this->getProcessForCode('sleep(30);');
$process->setTimeout(0.1);
$start = microtime(true);
try {
$process->start();
foreach ($process as $buffer) {
}
$this->fail('A RuntimeException should have been raised');
} catch (RuntimeException $e) {
}
$this->assertLessThan(15, microtime(true) - $start);
throw $e;
}
public function testCheckTimeoutOnNonStartedProcess()
{
$process = $this->getProcess('echo foo');
$this->assertNull($process->checkTimeout());
}
public function testCheckTimeoutOnTerminatedProcess()
{
$process = $this->getProcess('echo foo');
$process->run();
$this->assertNull($process->checkTimeout());
}
public function testCheckTimeoutOnStartedProcess()
{
$this->expectException(ProcessTimedOutException::class);
$this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.');
$process = $this->getProcessForCode('sleep(33);');
$process->setTimeout(0.1);
$process->start();
$start = microtime(true);
try {
while ($process->isRunning()) {
$process->checkTimeout();
usleep(100000);
}
$this->fail('A ProcessTimedOutException should have been raised');
} catch (ProcessTimedOutException $e) {
}
$this->assertLessThan(15, microtime(true) - $start);
throw $e;
}
public function testIdleTimeout()
{
$process = $this->getProcessForCode('sleep(34);');
$process->setTimeout(60);
$process->setIdleTimeout(0.1);
try {
$process->run();
$this->fail('A timeout exception was expected.');
} catch (ProcessTimedOutException $e) {
$this->assertTrue($e->isIdleTimeout());
$this->assertFalse($e->isGeneralTimeout());
$this->assertEquals(0.1, $e->getExceededTimeout());
}
}
public function testIdleTimeoutNotExceededWhenOutputIsSent()
{
$process = $this->getProcessForCode('while (true) {echo \'foo \'; usleep(1000);}');
$process->setTimeout(1);
$process->start();
while (!str_contains($process->getOutput(), 'foo')) {
usleep(1000);
}
$process->setIdleTimeout(0.5);
try {
$process->wait();
$this->fail('A timeout exception was expected.');
} catch (ProcessTimedOutException $e) {
$this->assertTrue($e->isGeneralTimeout(), 'A general timeout is expected.');
$this->assertFalse($e->isIdleTimeout(), 'No idle timeout is expected.');
$this->assertEquals(1, $e->getExceededTimeout());
}
}
public function testStartAfterATimeout()
{
$this->expectException(ProcessTimedOutException::class);
$this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.');
$process = $this->getProcessForCode('sleep(35);');
$process->setTimeout(0.1);
try {
$process->run();
$this->fail('A ProcessTimedOutException should have been raised.');
} catch (ProcessTimedOutException $e) {
}
$this->assertFalse($process->isRunning());
$process->start();
$this->assertTrue($process->isRunning());
$process->stop(0);
throw $e;
}
public function testGetPid()
{
$process = $this->getProcessForCode('sleep(36);');
$process->start();
$this->assertGreaterThan(0, $process->getPid());
$process->stop(0);
}
public function testGetPidIsNullBeforeStart()
{
$process = $this->getProcess('foo');
$this->assertNull($process->getPid());
}
public function testGetPidIsNullAfterRun()
{
$process = $this->getProcess('echo foo');
$process->run();
$this->assertNull($process->getPid());
}
/**
* @requires extension pcntl
*/
public function testSignal()
{
$process = $this->getProcess([self::$phpBin, __DIR__.'/SignalListener.php']);
$process->start();
while (!str_contains($process->getOutput(), 'Caught')) {
usleep(1000);
}
$process->signal(\SIGUSR1);
$process->wait();
$this->assertEquals('Caught SIGUSR1', $process->getOutput());
}
/**
* @requires extension pcntl
*/
public function testExitCodeIsAvailableAfterSignal()
{
$process = $this->getProcess('sleep 4');
$process->start();
$process->signal(\SIGKILL);
while ($process->isRunning()) {
usleep(10000);
}
$this->assertFalse($process->isRunning());
$this->assertTrue($process->hasBeenSignaled());
$this->assertFalse($process->isSuccessful());
$this->assertEquals(137, $process->getExitCode());
}
public function testSignalProcessNotRunning()
{
$process = $this->getProcess('foo');
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot send signal on a non running process.');
$process->signal(1); // SIGHUP
}
/**
* @dataProvider provideMethodsThatNeedARunningProcess
*/