ProcessTest.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  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 = 'foo' === $buffer;
  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 = 'foo' === $buffer;
  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. /**
  354. * @group tty
  355. */
  356. public function testTTYCommand()
  357. {
  358. if ('\\' === DIRECTORY_SEPARATOR) {
  359. $this->markTestSkipped('Windows does not have /dev/tty support');
  360. }
  361. $process = $this->getProcess('echo "foo" >> /dev/null && '.$this->getProcessForCode('usleep(100000);')->getCommandLine());
  362. $process->setTty(true);
  363. $process->start();
  364. $this->assertTrue($process->isRunning());
  365. $process->wait();
  366. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  367. }
  368. /**
  369. * @group tty
  370. */
  371. public function testTTYCommandExitCode()
  372. {
  373. if ('\\' === DIRECTORY_SEPARATOR) {
  374. $this->markTestSkipped('Windows does have /dev/tty support');
  375. }
  376. $this->skipIfNotEnhancedSigchild();
  377. $process = $this->getProcess('echo "foo" >> /dev/null');
  378. $process->setTty(true);
  379. $process->run();
  380. $this->assertTrue($process->isSuccessful());
  381. }
  382. /**
  383. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  384. * @expectedExceptionMessage TTY mode is not supported on Windows platform.
  385. */
  386. public function testTTYInWindowsEnvironment()
  387. {
  388. if ('\\' !== DIRECTORY_SEPARATOR) {
  389. $this->markTestSkipped('This test is for Windows platform only');
  390. }
  391. $process = $this->getProcess('echo "foo" >> /dev/null');
  392. $process->setTty(false);
  393. $process->setTty(true);
  394. }
  395. public function testExitCodeTextIsNullWhenExitCodeIsNull()
  396. {
  397. $this->skipIfNotEnhancedSigchild();
  398. $process = $this->getProcess('');
  399. $this->assertNull($process->getExitCodeText());
  400. }
  401. public function testPTYCommand()
  402. {
  403. if (!Process::isPtySupported()) {
  404. $this->markTestSkipped('PTY is not supported on this operating system.');
  405. }
  406. $process = $this->getProcess('echo "foo"');
  407. $process->setPty(true);
  408. $process->run();
  409. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  410. $this->assertEquals("foo\r\n", $process->getOutput());
  411. }
  412. public function testMustRun()
  413. {
  414. $this->skipIfNotEnhancedSigchild();
  415. $process = $this->getProcess('echo foo');
  416. $this->assertSame($process, $process->mustRun());
  417. $this->assertEquals('foo'.PHP_EOL, $process->getOutput());
  418. }
  419. public function testSuccessfulMustRunHasCorrectExitCode()
  420. {
  421. $this->skipIfNotEnhancedSigchild();
  422. $process = $this->getProcess('echo foo')->mustRun();
  423. $this->assertEquals(0, $process->getExitCode());
  424. }
  425. /**
  426. * @expectedException \Symfony\Component\Process\Exception\ProcessFailedException
  427. */
  428. public function testMustRunThrowsException()
  429. {
  430. $this->skipIfNotEnhancedSigchild();
  431. $process = $this->getProcess('exit 1');
  432. $process->mustRun();
  433. }
  434. public function testExitCodeText()
  435. {
  436. $this->skipIfNotEnhancedSigchild();
  437. $process = $this->getProcess('');
  438. $r = new \ReflectionObject($process);
  439. $p = $r->getProperty('exitcode');
  440. $p->setAccessible(true);
  441. $p->setValue($process, 2);
  442. $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
  443. }
  444. public function testStartIsNonBlocking()
  445. {
  446. $process = $this->getProcessForCode('usleep(500000);');
  447. $start = microtime(true);
  448. $process->start();
  449. $end = microtime(true);
  450. $this->assertLessThan(0.4, $end - $start);
  451. $process->stop();
  452. }
  453. public function testUpdateStatus()
  454. {
  455. $process = $this->getProcess('echo foo');
  456. $process->run();
  457. $this->assertGreaterThan(0, strlen($process->getOutput()));
  458. }
  459. public function testGetExitCodeIsNullOnStart()
  460. {
  461. $this->skipIfNotEnhancedSigchild();
  462. $process = $this->getProcessForCode('usleep(100000);');
  463. $this->assertNull($process->getExitCode());
  464. $process->start();
  465. $this->assertNull($process->getExitCode());
  466. $process->wait();
  467. $this->assertEquals(0, $process->getExitCode());
  468. }
  469. public function testGetExitCodeIsNullOnWhenStartingAgain()
  470. {
  471. $this->skipIfNotEnhancedSigchild();
  472. $process = $this->getProcessForCode('usleep(100000);');
  473. $process->run();
  474. $this->assertEquals(0, $process->getExitCode());
  475. $process->start();
  476. $this->assertNull($process->getExitCode());
  477. $process->wait();
  478. $this->assertEquals(0, $process->getExitCode());
  479. }
  480. public function testGetExitCode()
  481. {
  482. $this->skipIfNotEnhancedSigchild();
  483. $process = $this->getProcess('echo foo');
  484. $process->run();
  485. $this->assertSame(0, $process->getExitCode());
  486. }
  487. public function testStatus()
  488. {
  489. $process = $this->getProcessForCode('usleep(100000);');
  490. $this->assertFalse($process->isRunning());
  491. $this->assertFalse($process->isStarted());
  492. $this->assertFalse($process->isTerminated());
  493. $this->assertSame(Process::STATUS_READY, $process->getStatus());
  494. $process->start();
  495. $this->assertTrue($process->isRunning());
  496. $this->assertTrue($process->isStarted());
  497. $this->assertFalse($process->isTerminated());
  498. $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
  499. $process->wait();
  500. $this->assertFalse($process->isRunning());
  501. $this->assertTrue($process->isStarted());
  502. $this->assertTrue($process->isTerminated());
  503. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  504. }
  505. public function testStop()
  506. {
  507. $process = $this->getProcessForCode('sleep(31);');
  508. $process->start();
  509. $this->assertTrue($process->isRunning());
  510. $process->stop();
  511. $this->assertFalse($process->isRunning());
  512. }
  513. public function testIsSuccessful()
  514. {
  515. $this->skipIfNotEnhancedSigchild();
  516. $process = $this->getProcess('echo foo');
  517. $process->run();
  518. $this->assertTrue($process->isSuccessful());
  519. }
  520. public function testIsSuccessfulOnlyAfterTerminated()
  521. {
  522. $this->skipIfNotEnhancedSigchild();
  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. $this->skipIfNotEnhancedSigchild();
  532. $process = $this->getProcessForCode('throw new \Exception(\'BOUM\');');
  533. $process->run();
  534. $this->assertFalse($process->isSuccessful());
  535. }
  536. public function testProcessIsNotSignaled()
  537. {
  538. if ('\\' === DIRECTORY_SEPARATOR) {
  539. $this->markTestSkipped('Windows does not support POSIX signals');
  540. }
  541. $this->skipIfNotEnhancedSigchild();
  542. $process = $this->getProcess('echo foo');
  543. $process->run();
  544. $this->assertFalse($process->hasBeenSignaled());
  545. }
  546. public function testProcessWithoutTermSignal()
  547. {
  548. if ('\\' === DIRECTORY_SEPARATOR) {
  549. $this->markTestSkipped('Windows does not support POSIX signals');
  550. }
  551. $this->skipIfNotEnhancedSigchild();
  552. $process = $this->getProcess('echo foo');
  553. $process->run();
  554. $this->assertEquals(0, $process->getTermSignal());
  555. }
  556. public function testProcessIsSignaledIfStopped()
  557. {
  558. if ('\\' === DIRECTORY_SEPARATOR) {
  559. $this->markTestSkipped('Windows does not support POSIX signals');
  560. }
  561. $this->skipIfNotEnhancedSigchild();
  562. $process = $this->getProcessForCode('sleep(32);');
  563. $process->start();
  564. $process->stop();
  565. $this->assertTrue($process->hasBeenSignaled());
  566. $this->assertEquals(15, $process->getTermSignal()); // SIGTERM
  567. }
  568. /**
  569. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  570. * @expectedExceptionMessage The process has been signaled
  571. */
  572. public function testProcessThrowsExceptionWhenExternallySignaled()
  573. {
  574. if (!function_exists('posix_kill')) {
  575. $this->markTestSkipped('Function posix_kill is required.');
  576. }
  577. $this->skipIfNotEnhancedSigchild(false);
  578. $process = $this->getProcessForCode('sleep(32.1);');
  579. $process->start();
  580. posix_kill($process->getPid(), 9); // SIGKILL
  581. $process->wait();
  582. }
  583. public function testRestart()
  584. {
  585. $process1 = $this->getProcessForCode('echo getmypid();');
  586. $process1->run();
  587. $process2 = $process1->restart();
  588. $process2->wait(); // wait for output
  589. // Ensure that both processed finished and the output is numeric
  590. $this->assertFalse($process1->isRunning());
  591. $this->assertFalse($process2->isRunning());
  592. $this->assertInternalType('numeric', $process1->getOutput());
  593. $this->assertInternalType('numeric', $process2->getOutput());
  594. // Ensure that restart returned a new process by check that the output is different
  595. $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
  596. }
  597. /**
  598. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  599. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  600. */
  601. public function testRunProcessWithTimeout()
  602. {
  603. $process = $this->getProcessForCode('sleep(30);');
  604. $process->setTimeout(0.1);
  605. $start = microtime(true);
  606. try {
  607. $process->run();
  608. $this->fail('A RuntimeException should have been raised');
  609. } catch (RuntimeException $e) {
  610. }
  611. $this->assertLessThan(15, microtime(true) - $start);
  612. throw $e;
  613. }
  614. /**
  615. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  616. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  617. */
  618. public function testIterateOverProcessWithTimeout()
  619. {
  620. $process = $this->getProcessForCode('sleep(30);');
  621. $process->setTimeout(0.1);
  622. $start = microtime(true);
  623. try {
  624. $process->start();
  625. foreach ($process as $buffer);
  626. $this->fail('A RuntimeException should have been raised');
  627. } catch (RuntimeException $e) {
  628. }
  629. $this->assertLessThan(15, microtime(true) - $start);
  630. throw $e;
  631. }
  632. public function testCheckTimeoutOnNonStartedProcess()
  633. {
  634. $process = $this->getProcess('echo foo');
  635. $this->assertNull($process->checkTimeout());
  636. }
  637. public function testCheckTimeoutOnTerminatedProcess()
  638. {
  639. $process = $this->getProcess('echo foo');
  640. $process->run();
  641. $this->assertNull($process->checkTimeout());
  642. }
  643. /**
  644. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  645. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  646. */
  647. public function testCheckTimeoutOnStartedProcess()
  648. {
  649. $process = $this->getProcessForCode('sleep(33);');
  650. $process->setTimeout(0.1);
  651. $process->start();
  652. $start = microtime(true);
  653. try {
  654. while ($process->isRunning()) {
  655. $process->checkTimeout();
  656. usleep(100000);
  657. }
  658. $this->fail('A ProcessTimedOutException should have been raised');
  659. } catch (ProcessTimedOutException $e) {
  660. }
  661. $this->assertLessThan(15, microtime(true) - $start);
  662. throw $e;
  663. }
  664. public function testIdleTimeout()
  665. {
  666. $process = $this->getProcessForCode('sleep(34);');
  667. $process->setTimeout(60);
  668. $process->setIdleTimeout(0.1);
  669. try {
  670. $process->run();
  671. $this->fail('A timeout exception was expected.');
  672. } catch (ProcessTimedOutException $e) {
  673. $this->assertTrue($e->isIdleTimeout());
  674. $this->assertFalse($e->isGeneralTimeout());
  675. $this->assertEquals(0.1, $e->getExceededTimeout());
  676. }
  677. }
  678. public function testIdleTimeoutNotExceededWhenOutputIsSent()
  679. {
  680. $process = $this->getProcessForCode('while (true) {echo \'foo \'; usleep(1000);}');
  681. $process->setTimeout(1);
  682. $process->start();
  683. while (false === strpos($process->getOutput(), 'foo')) {
  684. usleep(1000);
  685. }
  686. $process->setIdleTimeout(0.5);
  687. try {
  688. $process->wait();
  689. $this->fail('A timeout exception was expected.');
  690. } catch (ProcessTimedOutException $e) {
  691. $this->assertTrue($e->isGeneralTimeout(), 'A general timeout is expected.');
  692. $this->assertFalse($e->isIdleTimeout(), 'No idle timeout is expected.');
  693. $this->assertEquals(1, $e->getExceededTimeout());
  694. }
  695. }
  696. /**
  697. * @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
  698. * @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
  699. */
  700. public function testStartAfterATimeout()
  701. {
  702. $process = $this->getProcessForCode('sleep(35);');
  703. $process->setTimeout(0.1);
  704. try {
  705. $process->run();
  706. $this->fail('A ProcessTimedOutException should have been raised.');
  707. } catch (ProcessTimedOutException $e) {
  708. }
  709. $this->assertFalse($process->isRunning());
  710. $process->start();
  711. $this->assertTrue($process->isRunning());
  712. $process->stop(0);
  713. throw $e;
  714. }
  715. public function testGetPid()
  716. {
  717. $process = $this->getProcessForCode('sleep(36);');
  718. $process->start();
  719. $this->assertGreaterThan(0, $process->getPid());
  720. $process->stop(0);
  721. }
  722. public function testGetPidIsNullBeforeStart()
  723. {
  724. $process = $this->getProcess('foo');
  725. $this->assertNull($process->getPid());
  726. }
  727. public function testGetPidIsNullAfterRun()
  728. {
  729. $process = $this->getProcess('echo foo');
  730. $process->run();
  731. $this->assertNull($process->getPid());
  732. }
  733. /**
  734. * @requires extension pcntl
  735. */
  736. public function testSignal()
  737. {
  738. $process = $this->getProcess(array(self::$phpBin, __DIR__.'/SignalListener.php'));
  739. $process->start();
  740. while (false === strpos($process->getOutput(), 'Caught')) {
  741. usleep(1000);
  742. }
  743. $process->signal(SIGUSR1);
  744. $process->wait();
  745. $this->assertEquals('Caught SIGUSR1', $process->getOutput());
  746. }
  747. /**
  748. * @requires extension pcntl
  749. */
  750. public function testExitCodeIsAvailableAfterSignal()
  751. {
  752. $this->skipIfNotEnhancedSigchild();
  753. $process = $this->getProcess('sleep 4');
  754. $process->start();
  755. $process->signal(SIGKILL);
  756. while ($process->isRunning()) {
  757. usleep(10000);
  758. }
  759. $this->assertFalse($process->isRunning());
  760. $this->assertTrue($process->hasBeenSignaled());
  761. $this->assertFalse($process->isSuccessful());
  762. $this->assertEquals(137, $process->getExitCode());
  763. }
  764. /**
  765. * @expectedException \Symfony\Component\Process\Exception\LogicException
  766. * @expectedExceptionMessage Can not send signal on a non running process.
  767. */
  768. public function testSignalProcessNotRunning()
  769. {
  770. $process = $this->getProcess('foo');
  771. $process->signal(1); // SIGHUP
  772. }
  773. /**
  774. * @dataProvider provideMethodsThatNeedARunningProcess
  775. */
  776. public function testMethodsThatNeedARunningProcess($method)
  777. {
  778. $process = $this->getProcess('foo');
  779. if (method_exists($this, 'expectException')) {
  780. $this->expectException('Symfony\Component\Process\Exception\LogicException');
  781. $this->expectExceptionMessage(sprintf('Process must be started before calling %s.', $method));
  782. } else {
  783. $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
  784. }
  785. $process->{$method}();
  786. }
  787. public function provideMethodsThatNeedARunningProcess()
  788. {
  789. return array(
  790. array('getOutput'),
  791. array('getIncrementalOutput'),
  792. array('getErrorOutput'),
  793. array('getIncrementalErrorOutput'),
  794. array('wait'),
  795. );
  796. }
  797. /**
  798. * @dataProvider provideMethodsThatNeedATerminatedProcess
  799. * @expectedException \Symfony\Component\Process\Exception\LogicException
  800. * @expectedExceptionMessage Process must be terminated before calling
  801. */
  802. public function testMethodsThatNeedATerminatedProcess($method)
  803. {
  804. $process = $this->getProcessForCode('sleep(37);');
  805. $process->start();
  806. try {
  807. $process->{$method}();
  808. $process->stop(0);
  809. $this->fail('A LogicException must have been thrown');
  810. } catch (\Exception $e) {
  811. }
  812. $process->stop(0);
  813. throw $e;
  814. }
  815. public function provideMethodsThatNeedATerminatedProcess()
  816. {
  817. return array(
  818. array('hasBeenSignaled'),
  819. array('getTermSignal'),
  820. array('hasBeenStopped'),
  821. array('getStopSignal'),
  822. );
  823. }
  824. /**
  825. * @dataProvider provideWrongSignal
  826. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  827. */
  828. public function testWrongSignal($signal)
  829. {
  830. if ('\\' === DIRECTORY_SEPARATOR) {
  831. $this->markTestSkipped('POSIX signals do not work on Windows');
  832. }
  833. $process = $this->getProcessForCode('sleep(38);');
  834. $process->start();
  835. try {
  836. $process->signal($signal);
  837. $this->fail('A RuntimeException must have been thrown');
  838. } catch (RuntimeException $e) {
  839. $process->stop(0);
  840. }
  841. throw $e;
  842. }
  843. public function provideWrongSignal()
  844. {
  845. return array(
  846. array(-4),
  847. array('Céphalopodes'),
  848. );
  849. }
  850. public function testDisableOutputDisablesTheOutput()
  851. {
  852. $p = $this->getProcess('foo');
  853. $this->assertFalse($p->isOutputDisabled());
  854. $p->disableOutput();
  855. $this->assertTrue($p->isOutputDisabled());
  856. $p->enableOutput();
  857. $this->assertFalse($p->isOutputDisabled());
  858. }
  859. /**
  860. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  861. * @expectedExceptionMessage Disabling output while the process is running is not possible.
  862. */
  863. public function testDisableOutputWhileRunningThrowsException()
  864. {
  865. $p = $this->getProcessForCode('sleep(39);');
  866. $p->start();
  867. $p->disableOutput();
  868. }
  869. /**
  870. * @expectedException \Symfony\Component\Process\Exception\RuntimeException
  871. * @expectedExceptionMessage Enabling output while the process is running is not possible.
  872. */
  873. public function testEnableOutputWhileRunningThrowsException()
  874. {
  875. $p = $this->getProcessForCode('sleep(40);');
  876. $p->disableOutput();
  877. $p->start();
  878. $p->enableOutput();
  879. }
  880. public function testEnableOrDisableOutputAfterRunDoesNotThrowException()
  881. {
  882. $p = $this->getProcess('echo foo');
  883. $p->disableOutput();
  884. $p->run();
  885. $p->enableOutput();
  886. $p->disableOutput();
  887. $this->assertTrue($p->isOutputDisabled());
  888. }
  889. /**
  890. * @expectedException \Symfony\Component\Process\Exception\LogicException
  891. * @expectedExceptionMessage Output can not be disabled while an idle timeout is set.
  892. */
  893. public function testDisableOutputWhileIdleTimeoutIsSet()
  894. {
  895. $process = $this->getProcess('foo');
  896. $process->setIdleTimeout(1);
  897. $process->disableOutput();
  898. }
  899. /**
  900. * @expectedException \Symfony\Component\Process\Exception\LogicException
  901. * @expectedExceptionMessage timeout can not be set while the output is disabled.
  902. */
  903. public function testSetIdleTimeoutWhileOutputIsDisabled()
  904. {
  905. $process = $this->getProcess('foo');
  906. $process->disableOutput();
  907. $process->setIdleTimeout(1);
  908. }
  909. public function testSetNullIdleTimeoutWhileOutputIsDisabled()
  910. {
  911. $process = $this->getProcess('foo');
  912. $process->disableOutput();
  913. $this->assertSame($process, $process->setIdleTimeout(null));
  914. }
  915. /**
  916. * @dataProvider provideOutputFetchingMethods
  917. * @expectedException \Symfony\Component\Process\Exception\LogicException
  918. * @expectedExceptionMessage Output has been disabled.
  919. */
  920. public function testGetOutputWhileDisabled($fetchMethod)
  921. {
  922. $p = $this->getProcessForCode('sleep(41);');
  923. $p->disableOutput();
  924. $p->start();
  925. $p->{$fetchMethod}();
  926. }
  927. public function provideOutputFetchingMethods()
  928. {
  929. return array(
  930. array('getOutput'),
  931. array('getIncrementalOutput'),
  932. array('getErrorOutput'),
  933. array('getIncrementalErrorOutput'),
  934. );
  935. }
  936. public function testStopTerminatesProcessCleanly()
  937. {
  938. $process = $this->getProcessForCode('echo 123; sleep(42);');
  939. $process->run(function () use ($process) {
  940. $process->stop();
  941. });
  942. $this->assertTrue(true, 'A call to stop() is not expected to cause wait() to throw a RuntimeException');
  943. }
  944. public function testKillSignalTerminatesProcessCleanly()
  945. {
  946. $process = $this->getProcessForCode('echo 123; sleep(43);');
  947. $process->run(function () use ($process) {
  948. $process->signal(9); // SIGKILL
  949. });
  950. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  951. }
  952. public function testTermSignalTerminatesProcessCleanly()
  953. {
  954. $process = $this->getProcessForCode('echo 123; sleep(44);');
  955. $process->run(function () use ($process) {
  956. $process->signal(15); // SIGTERM
  957. });
  958. $this->assertTrue(true, 'A call to signal() is not expected to cause wait() to throw a RuntimeException');
  959. }
  960. public function responsesCodeProvider()
  961. {
  962. return array(
  963. //expected output / getter / code to execute
  964. //array(1,'getExitCode','exit(1);'),
  965. //array(true,'isSuccessful','exit();'),
  966. array('output', 'getOutput', 'echo \'output\';'),
  967. );
  968. }
  969. public function pipesCodeProvider()
  970. {
  971. $variations = array(
  972. 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
  973. 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
  974. );
  975. if ('\\' === DIRECTORY_SEPARATOR) {
  976. // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
  977. $sizes = array(1, 2, 4, 8);
  978. } else {
  979. $sizes = array(1, 16, 64, 1024, 4096);
  980. }
  981. $codes = array();
  982. foreach ($sizes as $size) {
  983. foreach ($variations as $code) {
  984. $codes[] = array($code, $size);
  985. }
  986. }
  987. return $codes;
  988. }
  989. /**
  990. * @dataProvider provideVariousIncrementals
  991. */
  992. public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method)
  993. {
  994. $process = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }', null, null, null, null);
  995. $process->start();
  996. $result = '';
  997. $limit = microtime(true) + 3;
  998. $expected = '012';
  999. while ($result !== $expected && microtime(true) < $limit) {
  1000. $result .= $process->$method();
  1001. }
  1002. $this->assertSame($expected, $result);
  1003. $process->stop();
  1004. }
  1005. public function provideVariousIncrementals()
  1006. {
  1007. return array(
  1008. array('php://stdout', 'getIncrementalOutput'),
  1009. array('php://stderr', 'getIncrementalErrorOutput'),
  1010. );
  1011. }
  1012. public function testIteratorInput()
  1013. {
  1014. $input = function () {
  1015. yield 'ping';
  1016. yield 'pong';
  1017. };
  1018. $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);', null, null, $input());
  1019. $process->run();
  1020. $this->assertSame('pingpong', $process->getOutput());
  1021. }
  1022. public function testSimpleInputStream()
  1023. {
  1024. $input = new InputStream();
  1025. $process = $this->getProcessForCode('echo \'ping\'; echo fread(STDIN, 4); echo fread(STDIN, 4);');
  1026. $process->setInput($input);
  1027. $process->start(function ($type, $data) use ($input) {
  1028. if ('ping' === $data) {
  1029. $input->write('pang');
  1030. } elseif (!$input->isClosed()) {
  1031. $input->write('pong');
  1032. $input->close();
  1033. }
  1034. });
  1035. $process->wait();
  1036. $this->assertSame('pingpangpong', $process->getOutput());
  1037. }
  1038. public function testInputStreamWithCallable()
  1039. {
  1040. $i = 0;
  1041. $stream = fopen('php://memory', 'w+');
  1042. $stream = function () use ($stream, &$i) {
  1043. if ($i < 3) {
  1044. rewind($stream);
  1045. fwrite($stream, ++$i);
  1046. rewind($stream);
  1047. return $stream;
  1048. }
  1049. };
  1050. $input = new InputStream();
  1051. $input->onEmpty($stream);
  1052. $input->write($stream());
  1053. $process = $this->getProcessForCode('echo fread(STDIN, 3);');
  1054. $process->setInput($input);
  1055. $process->start(function ($type, $data) use ($input) {
  1056. $input->close();
  1057. });
  1058. $process->wait();
  1059. $this->assertSame('123', $process->getOutput());
  1060. }
  1061. public function testInputStreamWithGenerator()
  1062. {
  1063. $input = new InputStream();
  1064. $input->onEmpty(function ($input) {
  1065. yield 'pong';
  1066. $input->close();
  1067. });
  1068. $process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
  1069. $process->setInput($input);
  1070. $process->start();
  1071. $input->write('ping');
  1072. $process->wait();
  1073. $this->assertSame('pingpong', $process->getOutput());
  1074. }
  1075. public function testInputStreamOnEmpty()
  1076. {
  1077. $i = 0;
  1078. $input = new InputStream();
  1079. $input->onEmpty(function () use (&$i) { ++$i; });
  1080. $process = $this->getProcessForCode('echo 123; echo fread(STDIN, 1); echo 456;');
  1081. $process->setInput($input);
  1082. $process->start(function ($type, $data) use ($input) {
  1083. if ('123' === $data) {
  1084. $input->close();
  1085. }
  1086. });
  1087. $process->wait();
  1088. $this->assertSame(0, $i, 'InputStream->onEmpty callback should be called only when the input *becomes* empty');
  1089. $this->assertSame('123456', $process->getOutput());
  1090. }
  1091. public function testIteratorOutput()
  1092. {
  1093. $input = new InputStream();
  1094. $process = $this->getProcessForCode('fwrite(STDOUT, 123); fwrite(STDERR, 234); flush(); usleep(10000); fwrite(STDOUT, fread(STDIN, 3)); fwrite(STDERR, 456);');
  1095. $process->setInput($input);
  1096. $process->start();
  1097. $output = array();
  1098. foreach ($process as $type => $data) {
  1099. $output[] = array($type, $data);
  1100. break;
  1101. }
  1102. $expectedOutput = array(
  1103. array($process::OUT, '123'),
  1104. );
  1105. $this->assertSame($expectedOutput, $output);
  1106. $input->write(345);
  1107. foreach ($process as $type => $data) {
  1108. $output[] = array($type, $data);
  1109. }
  1110. $this->assertSame('', $process->getOutput());
  1111. $this->assertFalse($process->isRunning());
  1112. $expectedOutput = array(
  1113. array($process::OUT, '123'),
  1114. array($process::ERR, '234'),
  1115. array($process::OUT, '345'),
  1116. array($process::ERR, '456'),
  1117. );
  1118. $this->assertSame($expectedOutput, $output);
  1119. }
  1120. public function testNonBlockingNorClearingIteratorOutput()
  1121. {
  1122. $input = new InputStream();
  1123. $process = $this->getProcessForCode('fwrite(STDOUT, fread(STDIN, 3));');
  1124. $process->setInput($input);
  1125. $process->start();
  1126. $output = array();
  1127. foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
  1128. $output[] = array($type, $data);
  1129. break;
  1130. }
  1131. $expectedOutput = array(
  1132. array($process::OUT, ''),
  1133. );
  1134. $this->assertSame($expectedOutput, $output);
  1135. $input->write(123);
  1136. foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
  1137. if ('' !== $data) {
  1138. $output[] = array($type, $data);
  1139. }
  1140. }
  1141. $this->assertSame('123', $process->getOutput());
  1142. $this->assertFalse($process->isRunning());
  1143. $expectedOutput = array(
  1144. array($process::OUT, ''),
  1145. array($process::OUT, '123'),
  1146. );
  1147. $this->assertSame($expectedOutput, $output);
  1148. }
  1149. public function testChainedProcesses()
  1150. {
  1151. $p1 = $this->getProcessForCode('fwrite(STDERR, 123); fwrite(STDOUT, 456);');
  1152. $p2 = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
  1153. $p2->setInput($p1);
  1154. $p1->start();
  1155. $p2->run();
  1156. $this->assertSame('123', $p1->getErrorOutput());
  1157. $this->assertSame('', $p1->getOutput());
  1158. $this->assertSame('', $p2->getErrorOutput());
  1159. $this->assertSame('456', $p2->getOutput());
  1160. }
  1161. public function testSetBadEnv()
  1162. {
  1163. $process = $this->getProcess('echo hello');
  1164. $process->setEnv(array('bad%%' => '123'));
  1165. $process->inheritEnvironmentVariables(true);
  1166. $process->run();
  1167. $this->assertSame('hello'.PHP_EOL, $process->getOutput());
  1168. $this->assertSame('', $process->getErrorOutput());
  1169. }
  1170. public function testEnvBackupDoesNotDeleteExistingVars()
  1171. {
  1172. putenv('existing_var=foo');
  1173. $_ENV['existing_var'] = 'foo';
  1174. $process = $this->getProcess('php -r "echo getenv(\'new_test_var\');"');
  1175. $process->setEnv(array('existing_var' => 'bar', 'new_test_var' => 'foo'));
  1176. $process->inheritEnvironmentVariables();
  1177. $process->run();
  1178. $this->assertSame('foo', $process->getOutput());
  1179. $this->assertSame('foo', getenv('existing_var'));
  1180. $this->assertFalse(getenv('new_test_var'));
  1181. putenv('existing_var');
  1182. unset($_ENV['existing_var']);
  1183. }
  1184. public function testEnvIsInherited()
  1185. {
  1186. $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ', 'EMPTY' => ''));
  1187. putenv('FOO=BAR');
  1188. $_ENV['FOO'] = 'BAR';
  1189. $process->run();
  1190. $expected = array('BAR' => 'BAZ', 'EMPTY' => '', 'FOO' => 'BAR');
  1191. $env = array_intersect_key(unserialize($process->getOutput()), $expected);
  1192. $this->assertEquals($expected, $env);
  1193. putenv('FOO');
  1194. unset($_ENV['FOO']);
  1195. }
  1196. /**
  1197. * @group legacy
  1198. */
  1199. public function testInheritEnvDisabled()
  1200. {
  1201. $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ'));
  1202. putenv('FOO=BAR');
  1203. $_ENV['FOO'] = 'BAR';
  1204. $this->assertSame($process, $process->inheritEnvironmentVariables(false));
  1205. $this->assertFalse($process->areEnvironmentVariablesInherited());
  1206. $process->run();
  1207. $expected = array('BAR' => 'BAZ', 'FOO' => 'BAR');
  1208. $env = array_intersect_key(unserialize($process->getOutput()), $expected);
  1209. unset($expected['FOO']);
  1210. $this->assertSame($expected, $env);
  1211. putenv('FOO');
  1212. unset($_ENV['FOO']);
  1213. }
  1214. public function testGetCommandLine()
  1215. {
  1216. $p = new Process(array('/usr/bin/php'));
  1217. $expected = '\\' === DIRECTORY_SEPARATOR ? '"/usr/bin/php"' : "'/usr/bin/php'";
  1218. $this->assertSame($expected, $p->getCommandLine());
  1219. }
  1220. /**
  1221. * @dataProvider provideEscapeArgument
  1222. */
  1223. public function testEscapeArgument($arg)
  1224. {
  1225. $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg));
  1226. $p->run();
  1227. $this->assertSame($arg, $p->getOutput());
  1228. }
  1229. /**
  1230. * @dataProvider provideEscapeArgument
  1231. * @group legacy
  1232. */
  1233. public function testEscapeArgumentWhenInheritEnvDisabled($arg)
  1234. {
  1235. $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg), null, array('BAR' => 'BAZ'));
  1236. $p->inheritEnvironmentVariables(false);
  1237. $p->run();
  1238. $this->assertSame($arg, $p->getOutput());
  1239. }
  1240. public function testRawCommandLine()
  1241. {
  1242. $p = new Process(sprintf('"%s" -r %s "a" "" "b"', self::$phpBin, escapeshellarg('print_r($argv);')));
  1243. $p->run();
  1244. $expected = <<<EOTXT
  1245. Array
  1246. (
  1247. [0] => -
  1248. [1] => a
  1249. [2] =>
  1250. [3] => b
  1251. )
  1252. EOTXT;
  1253. $this->assertSame($expected, str_replace('Standard input code', '-', $p->getOutput()));
  1254. }
  1255. public function provideEscapeArgument()
  1256. {
  1257. yield array('a"b%c%');
  1258. yield array('a"b^c^');
  1259. yield array("a\nb'c");
  1260. yield array('a^b c!');
  1261. yield array("a!b\tc");
  1262. yield array('a\\\\"\\"');
  1263. yield array('éÉèÈàÀöä');
  1264. }
  1265. public function testEnvArgument()
  1266. {
  1267. $env = array('FOO' => 'Foo', 'BAR' => 'Bar');
  1268. $cmd = '\\' === DIRECTORY_SEPARATOR ? 'echo !FOO! !BAR! !BAZ!' : 'echo $FOO $BAR $BAZ';
  1269. $p = new Process($cmd, null, $env);
  1270. $p->run(null, array('BAR' => 'baR', 'BAZ' => 'baZ'));
  1271. $this->assertSame('Foo baR baZ', rtrim($p->getOutput()));
  1272. $this->assertSame($env, $p->getEnv());
  1273. }
  1274. /**
  1275. * @param string $commandline
  1276. * @param null|string $cwd
  1277. * @param null|array $env
  1278. * @param null|string $input
  1279. * @param int $timeout
  1280. * @param array $options
  1281. *
  1282. * @return Process
  1283. */
  1284. private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60)
  1285. {
  1286. $process = new Process($commandline, $cwd, $env, $input, $timeout);
  1287. $process->inheritEnvironmentVariables();
  1288. if (false !== $enhance = getenv('ENHANCE_SIGCHLD')) {
  1289. try {
  1290. $process->setEnhanceSigchildCompatibility(false);
  1291. $process->getExitCode();
  1292. $this->fail('ENHANCE_SIGCHLD must be used together with a sigchild-enabled PHP.');
  1293. } catch (RuntimeException $e) {
  1294. $this->assertSame('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.', $e->getMessage());
  1295. if ($enhance) {
  1296. $process->setEnhanceSigchildCompatibility(true);
  1297. } else {
  1298. self::$notEnhancedSigchild = true;
  1299. }
  1300. }
  1301. }
  1302. if (self::$process) {
  1303. self::$process->stop(0);
  1304. }
  1305. return self::$process = $process;
  1306. }
  1307. /**
  1308. * @return Process
  1309. */
  1310. private function getProcessForCode($code, $cwd = null, array $env = null, $input = null, $timeout = 60)
  1311. {
  1312. return $this->getProcess(array(self::$phpBin, '-r', $code), $cwd, $env, $input, $timeout);
  1313. }
  1314. private function skipIfNotEnhancedSigchild($expectException = true)
  1315. {
  1316. if (self::$sigchild) {
  1317. if (!$expectException) {
  1318. $this->markTestSkipped('PHP is compiled with --enable-sigchild.');
  1319. } elseif (self::$notEnhancedSigchild) {
  1320. if (method_exists($this, 'expectException')) {
  1321. $this->expectException('Symfony\Component\Process\Exception\RuntimeException');
  1322. $this->expectExceptionMessage('This PHP has been compiled with --enable-sigchild.');
  1323. } else {
  1324. $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild.');
  1325. }
  1326. }
  1327. }
  1328. }
  1329. }
  1330. class NonStringifiable
  1331. {
  1332. }