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