ProcessTest.php 48 KB

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