ProcessTest.php 48 KB

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