ProcessTest.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  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. }