ProcessTest.php 46 KB

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