ProcessTest.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Process\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Process\Exception\InvalidArgumentException;
  13. use Symfony\Component\Process\Exception\LogicException;
  14. use Symfony\Component\Process\Exception\ProcessFailedException;
  15. use Symfony\Component\Process\Exception\ProcessSignaledException;
  16. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  17. use Symfony\Component\Process\Exception\RuntimeException;
  18. use Symfony\Component\Process\InputStream;
  19. use Symfony\Component\Process\PhpExecutableFinder;
  20. use Symfony\Component\Process\Pipes\PipesInterface;
  21. use Symfony\Component\Process\Process;
  22. /**
  23. * @author Robert Schönthal <seroscho@googlemail.com>
  24. */
  25. class ProcessTest extends TestCase
  26. {
  27. private static $phpBin;
  28. private static $process;
  29. private static $sigchild;
  30. public static function setUpBeforeClass(): void
  31. {
  32. $phpBin = new PhpExecutableFinder();
  33. self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === \PHP_SAPI ? 'php' : $phpBin->find());
  34. ob_start();
  35. phpinfo(\INFO_GENERAL);
  36. self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  37. }
  38. protected function tearDown(): void
  39. {
  40. if (self::$process) {
  41. self::$process->stop(0);
  42. self::$process = null;
  43. }
  44. }
  45. public function testInvalidCwd()
  46. {
  47. $this->expectException(RuntimeException::class);
  48. $this->expectExceptionMessageMatches('/The provided cwd ".*" does not exist\./');
  49. try {
  50. // Check that it works fine if the CWD exists
  51. $cmd = new Process(['echo', 'test'], __DIR__);
  52. $cmd->run();
  53. } catch (\Exception $e) {
  54. $this->fail($e);
  55. }
  56. $cmd = new Process(['echo', 'test'], __DIR__.'/notfound/');
  57. $cmd->run();
  58. }
  59. public function testThatProcessDoesNotThrowWarningDuringRun()
  60. {
  61. if ('\\' === \DIRECTORY_SEPARATOR) {
  62. $this->markTestSkipped('This test is transient on Windows');
  63. }
  64. @trigger_error('Test Error', \E_USER_NOTICE);
  65. $process = $this->getProcessForCode('sleep(3)');
  66. $process->run();
  67. $actualError = error_get_last();
  68. $this->assertEquals('Test Error', $actualError['message']);
  69. $this->assertEquals(\E_USER_NOTICE, $actualError['type']);
  70. }
  71. public function testNegativeTimeoutFromConstructor()
  72. {
  73. $this->expectException(InvalidArgumentException::class);
  74. $this->getProcess('', null, null, null, -1);
  75. }
  76. public function testNegativeTimeoutFromSetter()
  77. {
  78. $this->expectException(InvalidArgumentException::class);
  79. $p = $this->getProcess('');
  80. $p->setTimeout(-1);
  81. }
  82. public function testFloatAndNullTimeout()
  83. {
  84. $p = $this->getProcess('');
  85. $p->setTimeout(10);
  86. $this->assertSame(10.0, $p->getTimeout());
  87. $p->setTimeout(null);
  88. $this->assertNull($p->getTimeout());
  89. $p->setTimeout(0.0);
  90. $this->assertNull($p->getTimeout());
  91. }
  92. /**
  93. * @requires extension pcntl
  94. */
  95. public function testStopWithTimeoutIsActuallyWorking()
  96. {
  97. $p = $this->getProcess([self::$phpBin, __DIR__.'/NonStopableProcess.php', 30]);
  98. $p->start();
  99. while ($p->isRunning() && false === strpos($p->getOutput(), 'received')) {
  100. usleep(1000);
  101. }
  102. if (!$p->isRunning()) {
  103. throw new \LogicException('Process is not running: '.$p->getErrorOutput());
  104. }
  105. $start = microtime(true);
  106. $p->stop(0.1);
  107. $p->wait();
  108. $this->assertLessThan(15, microtime(true) - $start);
  109. }
  110. public function testWaitUntilSpecificOutput()
  111. {
  112. if ('\\' === \DIRECTORY_SEPARATOR) {
  113. $this->markTestIncomplete('This test is too transient on Windows, help wanted to improve it');
  114. }
  115. $p = $this->getProcess([self::$phpBin, __DIR__.'/KillableProcessWithOutput.php']);
  116. $p->start();
  117. $start = microtime(true);
  118. $completeOutput = '';
  119. $result = $p->waitUntil(function ($type, $output) use (&$completeOutput) {
  120. return false !== strpos($completeOutput .= $output, 'One more');
  121. });
  122. $this->assertTrue($result);
  123. $this->assertLessThan(20, microtime(true) - $start);
  124. $this->assertStringStartsWith("First iteration output\nSecond iteration output\nOne more", $completeOutput);
  125. $p->stop();
  126. }
  127. public function testWaitUntilCanReturnFalse()
  128. {
  129. $p = $this->getProcess('echo foo');
  130. $p->start();
  131. $this->assertFalse($p->waitUntil(function () { return false; }));
  132. }
  133. public function testAllOutputIsActuallyReadOnTermination()
  134. {
  135. // this code will result in a maximum of 2 reads of 8192 bytes by calling
  136. // start() and isRunning(). by the time getOutput() is called the process
  137. // has terminated so the internal pipes array is already empty. normally
  138. // the call to start() will not read any data as the process will not have
  139. // generated output, but this is non-deterministic so we must count it as
  140. // a possibility. therefore we need 2 * PipesInterface::CHUNK_SIZE plus
  141. // another byte which will never be read.
  142. $expectedOutputSize = PipesInterface::CHUNK_SIZE * 2 + 2;
  143. $code = sprintf('echo str_repeat(\'*\', %d);', $expectedOutputSize);
  144. $p = $this->getProcessForCode($code);
  145. $p->start();
  146. // Don't call Process::run nor Process::wait to avoid any read of pipes
  147. $h = new \ReflectionProperty($p, 'process');
  148. $h->setAccessible(true);
  149. $h = $h->getValue($p);
  150. $s = @proc_get_status($h);
  151. while (!empty($s['running'])) {
  152. usleep(1000);
  153. $s = proc_get_status($h);
  154. }
  155. $o = $p->getOutput();
  156. $this->assertEquals($expectedOutputSize, \strlen($o));
  157. }
  158. public function testCallbacksAreExecutedWithStart()
  159. {
  160. $process = $this->getProcess('echo foo');
  161. $process->start(function ($type, $buffer) use (&$data) {
  162. $data .= $buffer;
  163. });
  164. $process->wait();
  165. $this->assertSame('foo'.\PHP_EOL, $data);
  166. }
  167. /**
  168. * tests results from sub processes.
  169. *
  170. * @dataProvider responsesCodeProvider
  171. */
  172. public function testProcessResponses($expected, $getter, $code)
  173. {
  174. $p = $this->getProcessForCode($code);
  175. $p->run();
  176. $this->assertSame($expected, $p->$getter());
  177. }
  178. /**
  179. * tests results from sub processes.
  180. *
  181. * @dataProvider pipesCodeProvider
  182. */
  183. public function testProcessPipes($code, $size)
  184. {
  185. $expected = str_repeat(str_repeat('*', 1024), $size).'!';
  186. $expectedLength = (1024 * $size) + 1;
  187. $p = $this->getProcessForCode($code);
  188. $p->setInput($expected);
  189. $p->run();
  190. $this->assertEquals($expectedLength, \strlen($p->getOutput()));
  191. $this->assertEquals($expectedLength, \strlen($p->getErrorOutput()));
  192. }
  193. /**
  194. * @dataProvider pipesCodeProvider
  195. */
  196. public function testSetStreamAsInput($code, $size)
  197. {
  198. $expected = str_repeat(str_repeat('*', 1024), $size).'!';
  199. $expectedLength = (1024 * $size) + 1;
  200. $stream = fopen('php://temporary', 'w+');
  201. fwrite($stream, $expected);
  202. rewind($stream);
  203. $p = $this->getProcessForCode($code);
  204. $p->setInput($stream);
  205. $p->run();
  206. fclose($stream);
  207. $this->assertEquals($expectedLength, \strlen($p->getOutput()));
  208. $this->assertEquals($expectedLength, \strlen($p->getErrorOutput()));
  209. }
  210. public function testLiveStreamAsInput()
  211. {
  212. $stream = fopen('php://memory', 'r+');
  213. fwrite($stream, 'hello');
  214. rewind($stream);
  215. $p = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
  216. $p->setInput($stream);
  217. $p->start(function ($type, $data) use ($stream) {
  218. if ('hello' === $data) {
  219. fclose($stream);
  220. }
  221. });
  222. $p->wait();
  223. $this->assertSame('hello', $p->getOutput());
  224. }
  225. public function testSetInputWhileRunningThrowsAnException()
  226. {
  227. $this->expectException(LogicException::class);
  228. $this->expectExceptionMessage('Input can not be set while the process is running.');
  229. $process = $this->getProcessForCode('sleep(30);');
  230. $process->start();
  231. try {
  232. $process->setInput('foobar');
  233. $process->stop();
  234. $this->fail('A LogicException should have been raised.');
  235. } catch (LogicException $e) {
  236. }
  237. $process->stop();
  238. throw $e;
  239. }
  240. /**
  241. * @dataProvider provideInvalidInputValues
  242. */
  243. public function testInvalidInput($value)
  244. {
  245. $this->expectException(InvalidArgumentException::class);
  246. $this->expectExceptionMessage('"Symfony\Component\Process\Process::setInput" only accepts strings, Traversable objects or stream resources.');
  247. $process = $this->getProcess('foo');
  248. $process->setInput($value);
  249. }
  250. public function provideInvalidInputValues()
  251. {
  252. return [
  253. [[]],
  254. [new NonStringifiable()],
  255. ];
  256. }
  257. /**
  258. * @dataProvider provideInputValues
  259. */
  260. public function testValidInput($expected, $value)
  261. {
  262. $process = $this->getProcess('foo');
  263. $process->setInput($value);
  264. $this->assertSame($expected, $process->getInput());
  265. }
  266. public function provideInputValues()
  267. {
  268. return [
  269. [null, null],
  270. ['24.5', 24.5],
  271. ['input data', 'input data'],
  272. ];
  273. }
  274. public function chainedCommandsOutputProvider()
  275. {
  276. if ('\\' === \DIRECTORY_SEPARATOR) {
  277. return [
  278. ["2 \r\n2\r\n", '&&', '2'],
  279. ];
  280. }
  281. return [
  282. ["1\n1\n", ';', '1'],
  283. ["2\n2\n", '&&', '2'],
  284. ];
  285. }
  286. /**
  287. * @dataProvider chainedCommandsOutputProvider
  288. */
  289. public function testChainedCommandsOutput($expected, $operator, $input)
  290. {
  291. $process = $this->getProcess(sprintf('echo %s %s echo %s', $input, $operator, $input));
  292. $process->run();
  293. $this->assertEquals($expected, $process->getOutput());
  294. }
  295. public function testCallbackIsExecutedForOutput()
  296. {
  297. $p = $this->getProcessForCode('echo \'foo\';');
  298. $called = false;
  299. $p->run(function ($type, $buffer) use (&$called) {
  300. $called = 'foo' === $buffer;
  301. });
  302. $this->assertTrue($called, 'The callback should be executed with the output');
  303. }
  304. public function testCallbackIsExecutedForOutputWheneverOutputIsDisabled()
  305. {
  306. $p = $this->getProcessForCode('echo \'foo\';');
  307. $p->disableOutput();
  308. $called = false;
  309. $p->run(function ($type, $buffer) use (&$called) {
  310. $called = 'foo' === $buffer;
  311. });
  312. $this->assertTrue($called, 'The callback should be executed with the output');
  313. }
  314. public function testGetErrorOutput()
  315. {
  316. $p = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }');
  317. $p->run();
  318. $this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches));
  319. }
  320. public function testFlushErrorOutput()
  321. {
  322. $p = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }');
  323. $p->run();
  324. $p->clearErrorOutput();
  325. $this->assertEmpty($p->getErrorOutput());
  326. }
  327. /**
  328. * @dataProvider provideIncrementalOutput
  329. */
  330. public function testIncrementalOutput($getOutput, $getIncrementalOutput, $uri)
  331. {
  332. $lock = tempnam(sys_get_temp_dir(), __FUNCTION__);
  333. $p = $this->getProcessForCode('file_put_contents($s = \''.$uri.'\', \'foo\'); flock(fopen('.var_export($lock, true).', \'r\'), LOCK_EX); file_put_contents($s, \'bar\');');
  334. $h = fopen($lock, 'w');
  335. flock($h, \LOCK_EX);
  336. $p->start();
  337. foreach (['foo', 'bar'] as $s) {
  338. while (false === strpos($p->$getOutput(), $s)) {
  339. usleep(1000);
  340. }
  341. $this->assertSame($s, $p->$getIncrementalOutput());
  342. $this->assertSame('', $p->$getIncrementalOutput());
  343. flock($h, \LOCK_UN);
  344. }
  345. fclose($h);
  346. }
  347. public function provideIncrementalOutput()
  348. {
  349. return [
  350. ['getOutput', 'getIncrementalOutput', 'php://stdout'],
  351. ['getErrorOutput', 'getIncrementalErrorOutput', 'php://stderr'],
  352. ];
  353. }
  354. public function testGetOutput()
  355. {
  356. $p = $this->getProcessForCode('$n = 0; while ($n < 3) { echo \' foo \'; $n++; }');
  357. $p->run();
  358. $this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
  359. }
  360. public function testFlushOutput()
  361. {
  362. $p = $this->getProcessForCode('$n=0;while ($n<3) {echo \' foo \';$n++;}');
  363. $p->run();
  364. $p->clearOutput();
  365. $this->assertEmpty($p->getOutput());
  366. }
  367. public function testZeroAsOutput()
  368. {
  369. if ('\\' === \DIRECTORY_SEPARATOR) {
  370. // see http://stackoverflow.com/questions/7105433/windows-batch-echo-without-new-line
  371. $p = $this->getProcess('echo | set /p dummyName=0');
  372. } else {
  373. $p = $this->getProcess('printf 0');
  374. }
  375. $p->run();
  376. $this->assertSame('0', $p->getOutput());
  377. }
  378. public function testExitCodeCommandFailed()
  379. {
  380. if ('\\' === \DIRECTORY_SEPARATOR) {
  381. $this->markTestSkipped('Windows does not support POSIX exit code');
  382. }
  383. // such command run in bash return an exitcode 127
  384. $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
  385. $process->run();
  386. $this->assertGreaterThan(0, $process->getExitCode());
  387. }
  388. public function testTTYCommand()
  389. {
  390. if ('\\' === \DIRECTORY_SEPARATOR) {
  391. $this->markTestSkipped('Windows does not have /dev/tty support');
  392. }
  393. if (!Process::isTtySupported()) {
  394. $this->markTestSkipped('There is no TTY support');
  395. }
  396. $process = $this->getProcess('echo "foo" >> /dev/null && '.$this->getProcessForCode('usleep(100000);')->getCommandLine());
  397. $process->setTty(true);
  398. $process->start();
  399. $this->assertTrue($process->isRunning());
  400. $process->wait();
  401. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  402. }
  403. public function testTTYCommandExitCode()
  404. {
  405. if ('\\' === \DIRECTORY_SEPARATOR) {
  406. $this->markTestSkipped('Windows does have /dev/tty support');
  407. }
  408. if (!Process::isTtySupported()) {
  409. $this->markTestSkipped('There is no TTY support');
  410. }
  411. $process = $this->getProcess('echo "foo" >> /dev/null');
  412. $process->setTty(true);
  413. $process->run();
  414. $this->assertTrue($process->isSuccessful());
  415. }
  416. public function testTTYInWindowsEnvironment()
  417. {
  418. $this->expectException(RuntimeException::class);
  419. $this->expectExceptionMessage('TTY mode is not supported on Windows platform.');
  420. if ('\\' !== \DIRECTORY_SEPARATOR) {
  421. $this->markTestSkipped('This test is for Windows platform only');
  422. }
  423. $process = $this->getProcess('echo "foo" >> /dev/null');
  424. $process->setTty(false);
  425. $process->setTty(true);
  426. }
  427. public function testExitCodeTextIsNullWhenExitCodeIsNull()
  428. {
  429. $process = $this->getProcess('');
  430. $this->assertNull($process->getExitCodeText());
  431. }
  432. public function testPTYCommand()
  433. {
  434. if (!Process::isPtySupported()) {
  435. $this->markTestSkipped('PTY is not supported on this operating system.');
  436. }
  437. $process = $this->getProcess('echo "foo"');
  438. $process->setPty(true);
  439. $process->run();
  440. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  441. $this->assertEquals("foo\r\n", $process->getOutput());
  442. }
  443. public function testMustRun()
  444. {
  445. $process = $this->getProcess('echo foo');
  446. $this->assertSame($process, $process->mustRun());
  447. $this->assertEquals('foo'.\PHP_EOL, $process->getOutput());
  448. }
  449. public function testSuccessfulMustRunHasCorrectExitCode()
  450. {
  451. $process = $this->getProcess('echo foo')->mustRun();
  452. $this->assertEquals(0, $process->getExitCode());
  453. }
  454. public function testMustRunThrowsException()
  455. {
  456. $this->expectException(ProcessFailedException::class);
  457. $process = $this->getProcess('exit 1');
  458. $process->mustRun();
  459. }
  460. public function testExitCodeText()
  461. {
  462. $process = $this->getProcess('');
  463. $r = new \ReflectionObject($process);
  464. $p = $r->getProperty('exitcode');
  465. $p->setAccessible(true);
  466. $p->setValue($process, 2);
  467. $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
  468. }
  469. public function testStartIsNonBlocking()
  470. {
  471. $process = $this->getProcessForCode('usleep(500000);');
  472. $start = microtime(true);
  473. $process->start();
  474. $end = microtime(true);
  475. $this->assertLessThan(0.4, $end - $start);
  476. $process->stop();
  477. }
  478. public function testUpdateStatus()
  479. {
  480. $process = $this->getProcess('echo foo');
  481. $process->run();
  482. $this->assertGreaterThan(0, \strlen($process->getOutput()));
  483. }
  484. public function testGetExitCodeIsNullOnStart()
  485. {
  486. $process = $this->getProcessForCode('usleep(100000);');
  487. $this->assertNull($process->getExitCode());
  488. $process->start();
  489. $this->assertNull($process->getExitCode());
  490. $process->wait();
  491. $this->assertEquals(0, $process->getExitCode());
  492. }
  493. public function testGetExitCodeIsNullOnWhenStartingAgain()
  494. {
  495. $process = $this->getProcessForCode('usleep(100000);');
  496. $process->run();
  497. $this->assertEquals(0, $process->getExitCode());
  498. $process->start();
  499. $this->assertNull($process->getExitCode());
  500. $process->wait();
  501. $this->assertEquals(0, $process->getExitCode());
  502. }
  503. public function testGetExitCode()
  504. {
  505. $process = $this->getProcess('echo foo');
  506. $process->run();
  507. $this->assertSame(0, $process->getExitCode());
  508. }
  509. public function testStatus()
  510. {
  511. $process = $this->getProcessForCode('usleep(100000);');
  512. $this->assertFalse($process->isRunning());
  513. $this->assertFalse($process->isStarted());
  514. $this->assertFalse($process->isTerminated());
  515. $this->assertSame(Process::STATUS_READY, $process->getStatus());
  516. $process->start();
  517. $this->assertTrue($process->isRunning());
  518. $this->assertTrue($process->isStarted());
  519. $this->assertFalse($process->isTerminated());
  520. $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
  521. $process->wait();
  522. $this->assertFalse($process->isRunning());
  523. $this->assertTrue($process->isStarted());
  524. $this->assertTrue($process->isTerminated());
  525. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  526. }
  527. public function testStop()
  528. {
  529. $process = $this->getProcessForCode('sleep(31);');
  530. $process->start();
  531. $this->assertTrue($process->isRunning());
  532. $process->stop();
  533. $this->assertFalse($process->isRunning());
  534. }
  535. public function testIsSuccessful()
  536. {
  537. $process = $this->getProcess('echo foo');
  538. $process->run();
  539. $this->assertTrue($process->isSuccessful());
  540. }
  541. public function testIsSuccessfulOnlyAfterTerminated()
  542. {
  543. $process = $this->getProcessForCode('usleep(100000);');
  544. $process->start();
  545. $this->assertFalse($process->isSuccessful());
  546. $process->wait();
  547. $this->assertTrue($process->isSuccessful());
  548. }
  549. public function testIsNotSuccessful()
  550. {
  551. $process = $this->getProcessForCode('throw new \Exception(\'BOUM\');');
  552. $process->run();
  553. $this->assertFalse($process->isSuccessful());
  554. }
  555. public function testProcessIsNotSignaled()
  556. {
  557. if ('\\' === \DIRECTORY_SEPARATOR) {
  558. $this->markTestSkipped('Windows does not support POSIX signals');
  559. }
  560. $process = $this->getProcess('echo foo');
  561. $process->run();
  562. $this->assertFalse($process->hasBeenSignaled());
  563. }
  564. public function testProcessWithoutTermSignal()
  565. {
  566. if ('\\' === \DIRECTORY_SEPARATOR) {
  567. $this->markTestSkipped('Windows does not support POSIX signals');
  568. }
  569. $process = $this->getProcess('echo foo');
  570. $process->run();
  571. $this->assertEquals(0, $process->getTermSignal());
  572. }
  573. public function testProcessIsSignaledIfStopped()
  574. {
  575. if ('\\' === \DIRECTORY_SEPARATOR) {
  576. $this->markTestSkipped('Windows does not support POSIX signals');
  577. }
  578. $process = $this->getProcessForCode('sleep(32);');
  579. $process->start();
  580. $process->stop();
  581. $this->assertTrue($process->hasBeenSignaled());
  582. $this->assertEquals(15, $process->getTermSignal()); // SIGTERM
  583. }
  584. public function testProcessThrowsExceptionWhenExternallySignaled()
  585. {
  586. $this->expectException(ProcessSignaledException::class);
  587. $this->expectExceptionMessage('The process has been signaled with signal "9".');
  588. if (!\function_exists('posix_kill')) {
  589. $this->markTestSkipped('Function posix_kill is required.');
  590. }
  591. if (self::$sigchild) {
  592. $this->markTestSkipped('PHP is compiled with --enable-sigchild.');
  593. }
  594. $process = $this->getProcessForCode('sleep(32.1);');
  595. $process->start();
  596. posix_kill($process->getPid(), 9); // SIGKILL
  597. $process->wait();
  598. }
  599. public function testRestart()
  600. {
  601. $process1 = $this->getProcessForCode('echo getmypid();');
  602. $process1->run();
  603. $process2 = $process1->restart();
  604. $process2->wait(); // wait for output
  605. // Ensure that both processed finished and the output is numeric
  606. $this->assertFalse($process1->isRunning());
  607. $this->assertFalse($process2->isRunning());
  608. $this->assertIsNumeric($process1->getOutput());
  609. $this->assertIsNumeric($process2->getOutput());
  610. // Ensure that restart returned a new process by check that the output is different
  611. $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
  612. }
  613. public function testRunProcessWithTimeout()
  614. {
  615. $this->expectException(ProcessTimedOutException::class);
  616. $this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.');
  617. $process = $this->getProcessForCode('sleep(30);');
  618. $process->setTimeout(0.1);
  619. $start = microtime(true);
  620. try {
  621. $process->run();
  622. $this->fail('A RuntimeException should have been raised');
  623. } catch (RuntimeException $e) {
  624. }
  625. $this->assertLessThan(15, microtime(true) - $start);
  626. throw $e;
  627. }
  628. public function testIterateOverProcessWithTimeout()
  629. {
  630. $this->expectException(ProcessTimedOutException::class);
  631. $this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.');
  632. $process = $this->getProcessForCode('sleep(30);');
  633. $process->setTimeout(0.1);
  634. $start = microtime(true);
  635. try {
  636. $process->start();
  637. foreach ($process as $buffer);
  638. $this->fail('A RuntimeException should have been raised');
  639. } catch (RuntimeException $e) {
  640. }
  641. $this->assertLessThan(15, microtime(true) - $start);
  642. throw $e;
  643. }
  644. public function testCheckTimeoutOnNonStartedProcess()
  645. {
  646. $process = $this->getProcess('echo foo');
  647. $this->assertNull($process->checkTimeout());
  648. }
  649. public function testCheckTimeoutOnTerminatedProcess()
  650. {
  651. $process = $this->getProcess('echo foo');
  652. $process->run();
  653. $this->assertNull($process->checkTimeout());
  654. }
  655. public function testCheckTimeoutOnStartedProcess()
  656. {
  657. $this->expectException(ProcessTimedOutException::class);
  658. $this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.');
  659. $process = $this->getProcessForCode('sleep(33);');
  660. $process->setTimeout(0.1);
  661. $process->start();
  662. $start = microtime(true);
  663. try {
  664. while ($process->isRunning()) {
  665. $process->checkTimeout();
  666. usleep(100000);
  667. }
  668. $this->fail('A ProcessTimedOutException should have been raised');
  669. } catch (ProcessTimedOutException $e) {
  670. }
  671. $this->assertLessThan(15, microtime(true) - $start);
  672. throw $e;
  673. }
  674. public function testIdleTimeout()
  675. {
  676. $process = $this->getProcessForCode('sleep(34);');
  677. $process->setTimeout(60);
  678. $process->setIdleTimeout(0.1);
  679. try {
  680. $process->run();
  681. $this->fail('A timeout exception was expected.');
  682. } catch (ProcessTimedOutException $e) {
  683. $this->assertTrue($e->isIdleTimeout());
  684. $this->assertFalse($e->isGeneralTimeout());
  685. $this->assertEquals(0.1, $e->getExceededTimeout());
  686. }
  687. }
  688. public function testIdleTimeoutNotExceededWhenOutputIsSent()
  689. {
  690. $process = $this->getProcessForCode('while (true) {echo \'foo \'; usleep(1000);}');
  691. $process->setTimeout(1);
  692. $process->start();
  693. while (false === strpos($process->getOutput(), 'foo')) {
  694. usleep(1000);
  695. }
  696. $process->setIdleTimeout(0.5);
  697. try {
  698. $process->wait();
  699. $this->fail('A timeout exception was expected.');
  700. } catch (ProcessTimedOutException $e) {
  701. $this->assertTrue($e->isGeneralTimeout(), 'A general timeout is expected.');
  702. $this->assertFalse($e->isIdleTimeout(), 'No idle timeout is expected.');
  703. $this->assertEquals(1, $e->getExceededTimeout());
  704. }
  705. }
  706. public function testStartAfterATimeout()
  707. {
  708. $this->expectException(ProcessTimedOutException::class);
  709. $this->expectExceptionMessage('exceeded the timeout of 0.1 seconds.');
  710. $process = $this->getProcessForCode('sleep(35);');
  711. $process->setTimeout(0.1);
  712. try {
  713. $process->run();
  714. $this->fail('A ProcessTimedOutException should have been raised.');
  715. } catch (ProcessTimedOutException $e) {
  716. }
  717. $this->assertFalse($process->isRunning());
  718. $process->start();
  719. $this->assertTrue($process->isRunning());
  720. $process->stop(0);
  721. throw $e;
  722. }
  723. public function testGetPid()
  724. {
  725. $process = $this->getProcessForCode('sleep(36);');
  726. $process->start();
  727. $this->assertGreaterThan(0, $process->getPid());
  728. $process->stop(0);
  729. }
  730. public function testGetPidIsNullBeforeStart()
  731. {
  732. $process = $this->getProcess('foo');
  733. $this->assertNull($process->getPid());
  734. }
  735. public function testGetPidIsNullAfterRun()
  736. {
  737. $process = $this->getProcess('echo foo');
  738. $process->run();
  739. $this->assertNull($process->getPid());
  740. }
  741. /**
  742. * @requires extension pcntl
  743. */
  744. public function testSignal()
  745. {
  746. $process = $this->getProcess([self::$phpBin, __DIR__.'/SignalListener.php']);
  747. $process->start();
  748. while (false === strpos($process->getOutput(), 'Caught')) {
  749. usleep(1000);
  750. }
  751. $process->signal(\SIGUSR1);
  752. $process->wait();
  753. $this->assertEquals('Caught SIGUSR1', $process->getOutput());
  754. }
  755. /**
  756. * @requires extension pcntl
  757. */
  758. public function testExitCodeIsAvailableAfterSignal()
  759. {
  760. $process = $this->getProcess('sleep 4');
  761. $process->start();
  762. $process->signal(\SIGKILL);
  763. while ($process->isRunning()) {
  764. usleep(10000);
  765. }
  766. $this->assertFalse($process->isRunning());
  767. $this->assertTrue($process->hasBeenSignaled());
  768. $this->assertFalse($process->isSuccessful());
  769. $this->assertEquals(137, $process->getExitCode());
  770. }
  771. public function testSignalProcessNotRunning()
  772. {
  773. $this->expectException(LogicException::class);
  774. $this->expectExceptionMessage('Can not send signal on a non running process.');
  775. $process = $this->getProcess('foo');
  776. $process->signal(1); // SIGHUP
  777. }
  778. /**
  779. * @dataProvider provideMethodsThatNeedARunningProcess
  780. */
  781. public function testMethodsThatNeedARunningProcess($method)
  782. {
  783. $process = $this->getProcess('foo');
  784. $this->expectException(LogicException::class);
  785. $this->expectExceptionMessage(sprintf('Process must be started before calling "%s()".', $method));
  786. $process->{$method}();
  787. }
  788. public function provideMethodsThatNeedARunningProcess()
  789. {
  790. return [
  791. ['getOutput'],
  792. ['getIncrementalOutput'],
  793. ['getErrorOutput'],
  794. ['getIncrementalErrorOutput'],
  795. ['wait'],
  796. ];
  797. }
  798. /**
  799. * @dataProvider provideMethodsThatNeedATerminatedProcess
  800. */
  801. public function testMethodsThatNeedATerminatedProcess($method)
  802. {
  803. $this->expectException(LogicException::class);
  804. $this->expectExceptionMessage('Process must be terminated before calling');
  805. $process = $this->getProcessForCode('sleep(37);');
  806. $process->start();
  807. try {
  808. $process->{$method}();
  809. $process->stop(0);
  810. $this->fail('A LogicException must have been thrown');
  811. } catch (\Exception $e) {
  812. }
  813. $process->stop(0);
  814. throw $e;
  815. }
  816. public function provideMethodsThatNeedATerminatedProcess()
  817. {
  818. return [
  819. ['hasBeenSignaled'],
  820. ['getTermSignal'],
  821. ['hasBeenStopped'],
  822. ['getStopSignal'],
  823. ];
  824. }
  825. public function testWrongSignal()
  826. {
  827. if ('\\' === \DIRECTORY_SEPARATOR) {
  828. $this->markTestSkipped('POSIX signals do not work on Windows');
  829. }
  830. $this->expectException(RuntimeException::class);
  831. $process = $this->getProcessForCode('sleep(38);');
  832. $process->start();
  833. try {
  834. $process->signal(-4);
  835. $this->fail('A RuntimeException must have been thrown');
  836. } finally {
  837. $process->stop(0);
  838. }
  839. }
  840. public function testDisableOutputDisablesTheOutput()
  841. {
  842. $p = $this->getProcess('foo');
  843. $this->assertFalse($p->isOutputDisabled());
  844. $p->disableOutput();
  845. $this->assertTrue($p->isOutputDisabled());
  846. $p->enableOutput();
  847. $this->assertFalse($p->isOutputDisabled());
  848. }
  849. public function testDisableOutputWhileRunningThrowsException()
  850. {
  851. $this->expectException(RuntimeException::class);
  852. $this->expectExceptionMessage('Disabling output while the process is running is not possible.');
  853. $p = $this->getProcessForCode('sleep(39);');
  854. $p->start();
  855. $p->disableOutput();
  856. }
  857. public function testEnableOutputWhileRunningThrowsException()
  858. {
  859. $this->expectException(RuntimeException::class);
  860. $this->expectExceptionMessage('Enabling output while the process is running is not possible.');
  861. $p = $this->getProcessForCode('sleep(40);');
  862. $p->disableOutput();
  863. $p->start();
  864. $p->enableOutput();
  865. }
  866. public function testEnableOrDisableOutputAfterRunDoesNotThrowException()
  867. {
  868. $p = $this->getProcess('echo foo');
  869. $p->disableOutput();
  870. $p->run();
  871. $p->enableOutput();
  872. $p->disableOutput();
  873. $this->assertTrue($p->isOutputDisabled());
  874. }
  875. public function testDisableOutputWhileIdleTimeoutIsSet()
  876. {
  877. $this->expectException(LogicException::class);
  878. $this->expectExceptionMessage('Output can not be disabled while an idle timeout is set.');
  879. $process = $this->getProcess('foo');
  880. $process->setIdleTimeout(1);
  881. $process->disableOutput();
  882. }
  883. public function testSetIdleTimeoutWhileOutputIsDisabled()
  884. {
  885. $this->expectException(LogicException::class);
  886. $this->expectExceptionMessage('timeout can not be set while the output is disabled.');
  887. $process = $this->getProcess('foo');
  888. $process->disableOutput();
  889. $process->setIdleTimeout(1);
  890. }
  891. public function testSetNullIdleTimeoutWhileOutputIsDisabled()
  892. {
  893. $process = $this->getProcess('foo');
  894. $process->disableOutput();
  895. $this->assertSame($process, $process->setIdleTimeout(null));
  896. }
  897. /**
  898. * @dataProvider provideOutputFetchingMethods
  899. */
  900. public function testGetOutputWhileDisabled($fetchMethod)
  901. {
  902. $this->expectException(LogicException::class);
  903. $this->expectExceptionMessage('Output has been disabled.');
  904. $p = $this->getProcessForCode('sleep(41);');
  905. $p->disableOutput();
  906. $p->start();
  907. $p->{$fetchMethod}();
  908. }
  909. public function provideOutputFetchingMethods()
  910. {
  911. return [
  912. ['getOutput'],
  913. ['getIncrementalOutput'],
  914. ['getErrorOutput'],
  915. ['getIncrementalErrorOutput'],
  916. ];
  917. }
  918. public function testStopTerminatesProcessCleanly()
  919. {
  920. $process = $this->getProcessForCode('echo 123; sleep(42);');
  921. $process->run(function () use ($process) {
  922. $process->stop();
  923. });
  924. $this->assertTrue(true, 'A call to stop() is not expected to cause wait() to throw a RuntimeException');
  925. }
  926. public function testKillSignalTerminatesProcessCleanly()
  927. {
  928. $process = $this->getProcessForCode('echo 123; sleep(43);');
  929. $process->run(function () use ($process) {
  930. $process->signal(9); // SIGKILL
  931. });
  932. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  933. }
  934. public function testTermSignalTerminatesProcessCleanly()
  935. {
  936. $process = $this->getProcessForCode('echo 123; sleep(44);');
  937. $process->run(function () use ($process) {
  938. $process->signal(15); // SIGTERM
  939. });
  940. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  941. }
  942. public function responsesCodeProvider()
  943. {
  944. return [
  945. //expected output / getter / code to execute
  946. // [1,'getExitCode','exit(1);'],
  947. // [true,'isSuccessful','exit();'],
  948. ['output', 'getOutput', 'echo \'output\';'],
  949. ];
  950. }
  951. public function pipesCodeProvider()
  952. {
  953. $variations = [
  954. 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
  955. 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
  956. ];
  957. if ('\\' === \DIRECTORY_SEPARATOR) {
  958. // Avoid XL buffers on Windows because of https://bugs.php.net/65650
  959. $sizes = [1, 2, 4, 8];
  960. } else {
  961. $sizes = [1, 16, 64, 1024, 4096];
  962. }
  963. $codes = [];
  964. foreach ($sizes as $size) {
  965. foreach ($variations as $code) {
  966. $codes[] = [$code, $size];
  967. }
  968. }
  969. return $codes;
  970. }
  971. /**
  972. * @dataProvider provideVariousIncrementals
  973. */
  974. public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method)
  975. {
  976. $process = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }', null, null, null, null);
  977. $process->start();
  978. $result = '';
  979. $limit = microtime(true) + 3;
  980. $expected = '012';
  981. while ($result !== $expected && microtime(true) < $limit) {
  982. $result .= $process->$method();
  983. }
  984. $this->assertSame($expected, $result);
  985. $process->stop();
  986. }
  987. public function provideVariousIncrementals()
  988. {
  989. return [
  990. ['php://stdout', 'getIncrementalOutput'],
  991. ['php://stderr', 'getIncrementalErrorOutput'],
  992. ];
  993. }
  994. public function testIteratorInput()
  995. {
  996. $input = function () {
  997. yield 'ping';
  998. yield 'pong';
  999. };
  1000. $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);', null, null, $input());
  1001. $process->run();
  1002. $this->assertSame('pingpong', $process->getOutput());
  1003. }
  1004. public function testSimpleInputStream()
  1005. {
  1006. $input = new InputStream();
  1007. $process = $this->getProcessForCode('echo \'ping\'; echo fread(STDIN, 4); echo fread(STDIN, 4);');
  1008. $process->setInput($input);
  1009. $process->start(function ($type, $data) use ($input) {
  1010. if ('ping' === $data) {
  1011. $input->write('pang');
  1012. } elseif (!$input->isClosed()) {
  1013. $input->write('pong');
  1014. $input->close();
  1015. }
  1016. });
  1017. $process->wait();
  1018. $this->assertSame('pingpangpong', $process->getOutput());
  1019. }
  1020. public function testInputStreamWithCallable()
  1021. {
  1022. $i = 0;
  1023. $stream = fopen('php://memory', 'w+');
  1024. $stream = function () use ($stream, &$i) {
  1025. if ($i < 3) {
  1026. rewind($stream);
  1027. fwrite($stream, ++$i);
  1028. rewind($stream);
  1029. return $stream;
  1030. }
  1031. return null;
  1032. };
  1033. $input = new InputStream();
  1034. $input->onEmpty($stream);
  1035. $input->write($stream());
  1036. $process = $this->getProcessForCode('echo fread(STDIN, 3);');
  1037. $process->setInput($input);
  1038. $process->start(function ($type, $data) use ($input) {
  1039. $input->close();
  1040. });
  1041. $process->wait();
  1042. $this->assertSame('123', $process->getOutput());
  1043. }
  1044. public function testInputStreamWithGenerator()
  1045. {
  1046. $input = new InputStream();
  1047. $input->onEmpty(function ($input) {
  1048. yield 'pong';
  1049. $input->close();
  1050. });
  1051. $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
  1052. $process->setInput($input);
  1053. $process->start();
  1054. $input->write('ping');
  1055. $process->wait();
  1056. $this->assertSame('pingpong', $process->getOutput());
  1057. }
  1058. public function testInputStreamOnEmpty()
  1059. {
  1060. $i = 0;
  1061. $input = new InputStream();
  1062. $input->onEmpty(function () use (&$i) { ++$i; });
  1063. $process = $this->getProcessForCode('echo 123; echo fread(STDIN, 1); echo 456;');
  1064. $process->setInput($input);
  1065. $process->start(function ($type, $data) use ($input) {
  1066. if ('123' === $data) {
  1067. $input->close();
  1068. }
  1069. });
  1070. $process->wait();
  1071. $this->assertSame(0, $i, 'InputStream->onEmpty callback should be called only when the input *becomes* empty');
  1072. $this->assertSame('123456', $process->getOutput());
  1073. }
  1074. public function testIteratorOutput()
  1075. {
  1076. $input = new InputStream();
  1077. $process = $this->getProcessForCode('fwrite(STDOUT, 123); fwrite(STDERR, 234); flush(); usleep(10000); fwrite(STDOUT, fread(STDIN, 3)); fwrite(STDERR, 456);');
  1078. $process->setInput($input);
  1079. $process->start();
  1080. $output = [];
  1081. foreach ($process as $type => $data) {
  1082. $output[] = [$type, $data];
  1083. break;
  1084. }
  1085. $expectedOutput = [
  1086. [$process::OUT, '123'],
  1087. ];
  1088. $this->assertSame($expectedOutput, $output);
  1089. $input->write(345);
  1090. foreach ($process as $type => $data) {
  1091. $output[] = [$type, $data];
  1092. }
  1093. $this->assertSame('', $process->getOutput());
  1094. $this->assertFalse($process->isRunning());
  1095. $expectedOutput = [
  1096. [$process::OUT, '123'],
  1097. [$process::ERR, '234'],
  1098. [$process::OUT, '345'],
  1099. [$process::ERR, '456'],
  1100. ];
  1101. $this->assertSame($expectedOutput, $output);
  1102. }
  1103. public function testNonBlockingNorClearingIteratorOutput()
  1104. {
  1105. $input = new InputStream();
  1106. $process = $this->getProcessForCode('fwrite(STDOUT, fread(STDIN, 3));');
  1107. $process->setInput($input);
  1108. $process->start();
  1109. $output = [];
  1110. foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
  1111. $output[] = [$type, $data];
  1112. break;
  1113. }
  1114. $expectedOutput = [
  1115. [$process::OUT, ''],
  1116. ];
  1117. $this->assertSame($expectedOutput, $output);
  1118. $input->write(123);
  1119. foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
  1120. if ('' !== $data) {
  1121. $output[] = [$type, $data];
  1122. }
  1123. }
  1124. $this->assertSame('123', $process->getOutput());
  1125. $this->assertFalse($process->isRunning());
  1126. $expectedOutput = [
  1127. [$process::OUT, ''],
  1128. [$process::OUT, '123'],
  1129. ];
  1130. $this->assertSame($expectedOutput, $output);
  1131. }
  1132. public function testChainedProcesses()
  1133. {
  1134. $p1 = $this->getProcessForCode('fwrite(STDERR, 123); fwrite(STDOUT, 456);');
  1135. $p2 = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
  1136. $p2->setInput($p1);
  1137. $p1->start();
  1138. $p2->run();
  1139. $this->assertSame('123', $p1->getErrorOutput());
  1140. $this->assertSame('', $p1->getOutput());
  1141. $this->assertSame('', $p2->getErrorOutput());
  1142. $this->assertSame('456', $p2->getOutput());
  1143. }
  1144. public function testSetBadEnv()
  1145. {
  1146. $process = $this->getProcess('echo hello');
  1147. $process->setEnv(['bad%%' => '123']);
  1148. $process->run();
  1149. $this->assertSame('hello'.\PHP_EOL, $process->getOutput());
  1150. $this->assertSame('', $process->getErrorOutput());
  1151. }
  1152. public function testEnvBackupDoesNotDeleteExistingVars()
  1153. {
  1154. putenv('existing_var=foo');
  1155. $_ENV['existing_var'] = 'foo';
  1156. $process = $this->getProcess('php -r "echo getenv(\'new_test_var\');"');
  1157. $process->setEnv(['existing_var' => 'bar', 'new_test_var' => 'foo']);
  1158. $process->run();
  1159. $this->assertSame('foo', $process->getOutput());
  1160. $this->assertSame('foo', getenv('existing_var'));
  1161. $this->assertFalse(getenv('new_test_var'));
  1162. putenv('existing_var');
  1163. unset($_ENV['existing_var']);
  1164. }
  1165. public function testEnvIsInherited()
  1166. {
  1167. $process = $this->getProcessForCode('echo serialize($_SERVER);', null, ['BAR' => 'BAZ', 'EMPTY' => '']);
  1168. putenv('FOO=BAR');
  1169. $_ENV['FOO'] = 'BAR';
  1170. $process->run();
  1171. $expected = ['BAR' => 'BAZ', 'EMPTY' => '', 'FOO' => 'BAR'];
  1172. $env = array_intersect_key(unserialize($process->getOutput()), $expected);
  1173. $this->assertEquals($expected, $env);
  1174. putenv('FOO');
  1175. unset($_ENV['FOO']);
  1176. }
  1177. public function testGetCommandLine()
  1178. {
  1179. $p = new Process(['/usr/bin/php']);
  1180. $expected = '\\' === \DIRECTORY_SEPARATOR ? '"/usr/bin/php"' : "'/usr/bin/php'";
  1181. $this->assertSame($expected, $p->getCommandLine());
  1182. }
  1183. /**
  1184. * @dataProvider provideEscapeArgument
  1185. */
  1186. public function testEscapeArgument($arg)
  1187. {
  1188. $p = new Process([self::$phpBin, '-r', 'echo $argv[1];', $arg]);
  1189. $p->run();
  1190. $this->assertSame((string) $arg, $p->getOutput());
  1191. }
  1192. public function testRawCommandLine()
  1193. {
  1194. $p = Process::fromShellCommandline(sprintf('"%s" -r %s "a" "" "b"', self::$phpBin, escapeshellarg('print_r($argv);')));
  1195. $p->run();
  1196. $expected = "Array\n(\n [0] => -\n [1] => a\n [2] => \n [3] => b\n)\n";
  1197. $this->assertSame($expected, str_replace('Standard input code', '-', $p->getOutput()));
  1198. }
  1199. public function provideEscapeArgument()
  1200. {
  1201. yield ['a"b%c%'];
  1202. yield ['a"b^c^'];
  1203. yield ["a\nb'c"];
  1204. yield ['a^b c!'];
  1205. yield ["a!b\tc"];
  1206. yield ['a\\\\"\\"'];
  1207. yield ['éÉèÈàÀöä'];
  1208. yield [null];
  1209. yield [1];
  1210. yield [1.1];
  1211. }
  1212. public function testPreparedCommand()
  1213. {
  1214. $p = Process::fromShellCommandline('echo "${:abc}"DEF');
  1215. $p->run(null, ['abc' => 'ABC']);
  1216. $this->assertSame('ABCDEF', rtrim($p->getOutput()));
  1217. }
  1218. public function testPreparedCommandMulti()
  1219. {
  1220. $p = Process::fromShellCommandline('echo "${:abc}""${:def}"');
  1221. $p->run(null, ['abc' => 'ABC', 'def' => 'DEF']);
  1222. $this->assertSame('ABCDEF', rtrim($p->getOutput()));
  1223. }
  1224. public function testPreparedCommandWithQuoteInIt()
  1225. {
  1226. $p = Process::fromShellCommandline('php -r "${:code}" "${:def}"');
  1227. $p->run(null, ['code' => 'echo $argv[1];', 'def' => '"DEF"']);
  1228. $this->assertSame('"DEF"', rtrim($p->getOutput()));
  1229. }
  1230. public function testPreparedCommandWithMissingValue()
  1231. {
  1232. $this->expectException(InvalidArgumentException::class);
  1233. $this->expectExceptionMessage('Command line is missing a value for parameter "abc": echo "${:abc}"');
  1234. $p = Process::fromShellCommandline('echo "${:abc}"');
  1235. $p->run(null, ['bcd' => 'BCD']);
  1236. }
  1237. public function testPreparedCommandWithNoValues()
  1238. {
  1239. $this->expectException(InvalidArgumentException::class);
  1240. $this->expectExceptionMessage('Command line is missing a value for parameter "abc": echo "${:abc}"');
  1241. $p = Process::fromShellCommandline('echo "${:abc}"');
  1242. $p->run(null, []);
  1243. }
  1244. public function testEnvArgument()
  1245. {
  1246. $env = ['FOO' => 'Foo', 'BAR' => 'Bar'];
  1247. $cmd = '\\' === \DIRECTORY_SEPARATOR ? 'echo !FOO! !BAR! !BAZ!' : 'echo $FOO $BAR $BAZ';
  1248. $p = Process::fromShellCommandline($cmd, null, $env);
  1249. $p->run(null, ['BAR' => 'baR', 'BAZ' => 'baZ']);
  1250. $this->assertSame('Foo baR baZ', rtrim($p->getOutput()));
  1251. $this->assertSame($env, $p->getEnv());
  1252. }
  1253. public function testWaitStoppedDeadProcess()
  1254. {
  1255. $process = $this->getProcess(self::$phpBin.' '.__DIR__.'/ErrorProcessInitiator.php -e '.self::$phpBin);
  1256. $process->start();
  1257. $process->setTimeout(2);
  1258. $process->wait();
  1259. $this->assertFalse($process->isRunning());
  1260. }
  1261. /**
  1262. * @param string|array $commandline
  1263. * @param mixed $input
  1264. */
  1265. private function getProcess($commandline, string $cwd = null, array $env = null, $input = null, ?int $timeout = 60): Process
  1266. {
  1267. if (\is_string($commandline)) {
  1268. $process = Process::fromShellCommandline($commandline, $cwd, $env, $input, $timeout);
  1269. } else {
  1270. $process = new Process($commandline, $cwd, $env, $input, $timeout);
  1271. }
  1272. if (self::$process) {
  1273. self::$process->stop(0);
  1274. }
  1275. return self::$process = $process;
  1276. }
  1277. private function getProcessForCode(string $code, string $cwd = null, array $env = null, $input = null, ?int $timeout = 60): Process
  1278. {
  1279. return $this->getProcess([self::$phpBin, '-r', $code], $cwd, $env, $input, $timeout);
  1280. }
  1281. }
  1282. class NonStringifiable
  1283. {
  1284. }