ProcessTest.php 45KB

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