ProcessTest.php 47 KB

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