ProcessTest.php 46 KB

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