ProcessTest.php 47 KB

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