AbstractProcessTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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 Symfony\Component\Process\Process;
  12. use Symfony\Component\Process\Exception\RuntimeException;
  13. /**
  14. * @author Robert Schönthal <seroscho@googlemail.com>
  15. */
  16. abstract class AbstractProcessTest extends \PHPUnit_Framework_TestCase
  17. {
  18. public function testThatProcessDoesNotThrowWarningDuringRun()
  19. {
  20. @trigger_error('Test Error', E_USER_NOTICE);
  21. $process = $this->getProcess("php -r 'sleep(3)'");
  22. $process->run();
  23. $actualError = error_get_last();
  24. $this->assertEquals('Test Error', $actualError['message']);
  25. $this->assertEquals(E_USER_NOTICE, $actualError['type']);
  26. }
  27. /**
  28. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  29. */
  30. public function testNegativeTimeoutFromConstructor()
  31. {
  32. $this->getProcess('', null, null, null, -1);
  33. }
  34. /**
  35. * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
  36. */
  37. public function testNegativeTimeoutFromSetter()
  38. {
  39. $p = $this->getProcess('');
  40. $p->setTimeout(-1);
  41. }
  42. public function testFloatAndNullTimeout()
  43. {
  44. $p = $this->getProcess('');
  45. $p->setTimeout(10);
  46. $this->assertSame(10.0, $p->getTimeout());
  47. $p->setTimeout(null);
  48. $this->assertNull($p->getTimeout());
  49. $p->setTimeout(0.0);
  50. $this->assertNull($p->getTimeout());
  51. }
  52. public function testStopWithTimeoutIsActuallyWorking()
  53. {
  54. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  55. $this->markTestSkipped('Stop with timeout does not work on windows, it requires posix signals');
  56. }
  57. if (!function_exists('pcntl_signal')) {
  58. $this->markTestSkipped('This test require pcntl_signal function');
  59. }
  60. // exec is mandatory here since we send a signal to the process
  61. // see https://github.com/symfony/symfony/issues/5030 about prepending
  62. // command with exec
  63. $p = $this->getProcess('exec php '.__DIR__.'/NonStopableProcess.php 3');
  64. $p->start();
  65. usleep(100000);
  66. $start = microtime(true);
  67. $p->stop(1.1);
  68. while ($p->isRunning()) {
  69. usleep(1000);
  70. }
  71. $duration = microtime(true) - $start;
  72. $this->assertLessThan(1.3, $duration);
  73. }
  74. public function testCallbacksAreExecutedWithStart()
  75. {
  76. $data = '';
  77. $process = $this->getProcess('echo foo && php -r "sleep(1);" && echo foo');
  78. $process->start(function ($type, $buffer) use (&$data) {
  79. $data .= $buffer;
  80. });
  81. while ($process->isRunning()) {
  82. usleep(10000);
  83. }
  84. $this->assertEquals(2, preg_match_all('/foo/', $data, $matches));
  85. }
  86. /**
  87. * tests results from sub processes
  88. *
  89. * @dataProvider responsesCodeProvider
  90. */
  91. public function testProcessResponses($expected, $getter, $code)
  92. {
  93. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code)));
  94. $p->run();
  95. $this->assertSame($expected, $p->$getter());
  96. }
  97. /**
  98. * tests results from sub processes
  99. *
  100. * @dataProvider pipesCodeProvider
  101. */
  102. public function testProcessPipes($code, $size)
  103. {
  104. $expected = str_repeat(str_repeat('*', 1024), $size) . '!';
  105. $expectedLength = (1024 * $size) + 1;
  106. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code)));
  107. $p->setStdin($expected);
  108. $p->run();
  109. $this->assertEquals($expectedLength, strlen($p->getOutput()));
  110. $this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
  111. }
  112. public function chainedCommandsOutputProvider()
  113. {
  114. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  115. return array(
  116. array("2 \r\n2\r\n", '&&', '2')
  117. );
  118. }
  119. return array(
  120. array("1\n1\n", ';', '1'),
  121. array("2\n2\n", '&&', '2'),
  122. );
  123. }
  124. /**
  125. *
  126. * @dataProvider chainedCommandsOutputProvider
  127. */
  128. public function testChainedCommandsOutput($expected, $operator, $input)
  129. {
  130. $process = $this->getProcess(sprintf('echo %s %s echo %s', $input, $operator, $input));
  131. $process->run();
  132. $this->assertEquals($expected, $process->getOutput());
  133. }
  134. public function testCallbackIsExecutedForOutput()
  135. {
  136. $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('echo \'foo\';')));
  137. $called = false;
  138. $p->run(function ($type, $buffer) use (&$called) {
  139. $called = $buffer === 'foo';
  140. });
  141. $this->assertTrue($called, 'The callback should be executed with the output');
  142. }
  143. public function testGetErrorOutput()
  144. {
  145. $p = new Process(sprintf('php -r %s', escapeshellarg('ini_set(\'display_errors\',\'on\'); $n = 0; while ($n < 3) { echo $a; $n++; }')));
  146. $p->run();
  147. $this->assertEquals(3, preg_match_all('/PHP Notice/', $p->getErrorOutput(), $matches));
  148. }
  149. public function testGetIncrementalErrorOutput()
  150. {
  151. $p = new Process(sprintf('php -r %s', escapeshellarg('ini_set(\'display_errors\',\'on\'); usleep(50000); $n = 0; while ($n < 3) { echo $a; $n++; }')));
  152. $p->start();
  153. while ($p->isRunning()) {
  154. $this->assertLessThanOrEqual(1, preg_match_all('/PHP Notice/', $p->getIncrementalOutput(), $matches));
  155. usleep(20000);
  156. }
  157. }
  158. public function testGetOutput()
  159. {
  160. $p = new Process(sprintf('php -r %s', escapeshellarg('$n=0;while ($n<3) {echo \' foo \';$n++; usleep(500); }')));
  161. $p->run();
  162. $this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
  163. }
  164. public function testGetIncrementalOutput()
  165. {
  166. $p = new Process(sprintf('php -r %s', escapeshellarg('$n=0;while ($n<3) { echo \' foo \'; usleep(50000); $n++; }')));
  167. $p->start();
  168. while ($p->isRunning()) {
  169. $this->assertLessThanOrEqual(1, preg_match_all('/foo/', $p->getIncrementalOutput(), $matches));
  170. usleep(20000);
  171. }
  172. }
  173. public function testExitCodeCommandFailed()
  174. {
  175. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  176. $this->markTestSkipped('Windows does not support POSIX exit code');
  177. }
  178. // such command run in bash return an exitcode 127
  179. $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
  180. $process->run();
  181. $this->assertGreaterThan(0, $process->getExitCode());
  182. }
  183. public function testExitCodeText()
  184. {
  185. $process = $this->getProcess('');
  186. $r = new \ReflectionObject($process);
  187. $p = $r->getProperty('exitcode');
  188. $p->setAccessible(true);
  189. $p->setValue($process, 2);
  190. $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
  191. }
  192. public function testStartIsNonBlocking()
  193. {
  194. $process = $this->getProcess('php -r "sleep(4);"');
  195. $start = microtime(true);
  196. $process->start();
  197. $end = microtime(true);
  198. $this->assertLessThan(1 , $end-$start);
  199. }
  200. public function testUpdateStatus()
  201. {
  202. $process = $this->getProcess('php -h');
  203. $process->run();
  204. $this->assertTrue(strlen($process->getOutput()) > 0);
  205. }
  206. public function testGetExitCodeIsNullOnStart()
  207. {
  208. $process = $this->getProcess('php -r "usleep(200000);"');
  209. $this->assertNull($process->getExitCode());
  210. $process->start();
  211. $this->assertNull($process->getExitCode());
  212. $process->wait();
  213. $this->assertEquals(0, $process->getExitCode());
  214. }
  215. public function testGetExitCodeIsNullOnWhenStartingAgain()
  216. {
  217. $process = $this->getProcess('php -r "usleep(200000);"');
  218. $process->run();
  219. $this->assertEquals(0, $process->getExitCode());
  220. $process->start();
  221. $this->assertNull($process->getExitCode());
  222. $process->wait();
  223. $this->assertEquals(0, $process->getExitCode());
  224. }
  225. public function testGetExitCode()
  226. {
  227. $process = $this->getProcess('php -m');
  228. $process->run();
  229. $this->assertEquals(0, $process->getExitCode());
  230. }
  231. public function testStatus()
  232. {
  233. $process = $this->getProcess('php -r "sleep(1);"');
  234. $this->assertFalse($process->isRunning());
  235. $this->assertFalse($process->isStarted());
  236. $this->assertFalse($process->isTerminated());
  237. $this->assertSame(Process::STATUS_READY, $process->getStatus());
  238. $process->start();
  239. $this->assertTrue($process->isRunning());
  240. $this->assertTrue($process->isStarted());
  241. $this->assertFalse($process->isTerminated());
  242. $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
  243. $process->wait();
  244. $this->assertFalse($process->isRunning());
  245. $this->assertTrue($process->isStarted());
  246. $this->assertTrue($process->isTerminated());
  247. $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
  248. }
  249. public function testStop()
  250. {
  251. $process = $this->getProcess('php -r "sleep(4);"');
  252. $process->start();
  253. $this->assertTrue($process->isRunning());
  254. $process->stop();
  255. $this->assertFalse($process->isRunning());
  256. }
  257. public function testIsSuccessful()
  258. {
  259. $process = $this->getProcess('php -m');
  260. $process->run();
  261. $this->assertTrue($process->isSuccessful());
  262. }
  263. public function testIsSuccessfulOnlyAfterTerminated()
  264. {
  265. $process = $this->getProcess('php -r "sleep(1);"');
  266. $process->start();
  267. while ($process->isRunning()) {
  268. $this->assertFalse($process->isSuccessful());
  269. usleep(300000);
  270. }
  271. $this->assertTrue($process->isSuccessful());
  272. }
  273. public function testIsNotSuccessful()
  274. {
  275. $process = $this->getProcess('php -r "sleep(4);"');
  276. $process->start();
  277. $this->assertTrue($process->isRunning());
  278. $process->stop();
  279. $this->assertFalse($process->isSuccessful());
  280. }
  281. public function testProcessIsNotSignaled()
  282. {
  283. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  284. $this->markTestSkipped('Windows does not support POSIX signals');
  285. }
  286. $process = $this->getProcess('php -m');
  287. $process->run();
  288. $this->assertFalse($process->hasBeenSignaled());
  289. }
  290. public function testProcessWithoutTermSignal()
  291. {
  292. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  293. $this->markTestSkipped('Windows does not support POSIX signals');
  294. }
  295. $process = $this->getProcess('php -m');
  296. $process->run();
  297. $this->assertEquals(0, $process->getTermSignal());
  298. }
  299. public function testProcessIsSignaledIfStopped()
  300. {
  301. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  302. $this->markTestSkipped('Windows does not support POSIX signals');
  303. }
  304. $process = $this->getProcess('php -r "sleep(4);"');
  305. $process->start();
  306. $process->stop();
  307. $this->assertTrue($process->hasBeenSignaled());
  308. }
  309. public function testProcessWithTermSignal()
  310. {
  311. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  312. $this->markTestSkipped('Windows does not support POSIX signals');
  313. }
  314. // SIGTERM is only defined if pcntl extension is present
  315. $termSignal = defined('SIGTERM') ? SIGTERM : 15;
  316. $process = $this->getProcess('php -r "sleep(4);"');
  317. $process->start();
  318. $process->stop();
  319. $this->assertEquals($termSignal, $process->getTermSignal());
  320. }
  321. public function testRestart()
  322. {
  323. $process1 = $this->getProcess('php -r "echo getmypid();"');
  324. $process1->run();
  325. $process2 = $process1->restart();
  326. usleep(300000); // wait for output
  327. // Ensure that both processed finished and the output is numeric
  328. $this->assertFalse($process1->isRunning());
  329. $this->assertFalse($process2->isRunning());
  330. $this->assertTrue(is_numeric($process1->getOutput()));
  331. $this->assertTrue(is_numeric($process2->getOutput()));
  332. // Ensure that restart returned a new process by check that the output is different
  333. $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
  334. }
  335. public function testPhpDeadlock()
  336. {
  337. $this->markTestSkipped('Can course php to hang');
  338. // Sleep doesn't work as it will allow the process to handle signals and close
  339. // file handles from the other end.
  340. $process = $this->getProcess('php -r "while (true) {}"');
  341. $process->start();
  342. // PHP will deadlock when it tries to cleanup $process
  343. }
  344. public function testRunProcessWithTimeout()
  345. {
  346. $timeout = 0.5;
  347. $process = $this->getProcess('php -r "sleep(3);"');
  348. $process->setTimeout($timeout);
  349. $start = microtime(true);
  350. try {
  351. $process->run();
  352. $this->fail('A RuntimeException should have been raised');
  353. } catch (RuntimeException $e) {
  354. }
  355. $duration = microtime(true) - $start;
  356. $this->assertLessThan($timeout + Process::TIMEOUT_PRECISION, $duration);
  357. }
  358. public function testCheckTimeoutOnStartedProcess()
  359. {
  360. $timeout = 0.5;
  361. $precision = 100000;
  362. $process = $this->getProcess('php -r "sleep(3);"');
  363. $process->setTimeout($timeout);
  364. $start = microtime(true);
  365. $process->start();
  366. try {
  367. while ($process->isRunning()) {
  368. $process->checkTimeout();
  369. usleep($precision);
  370. }
  371. $this->fail('A RuntimeException should have been raised');
  372. } catch (RuntimeException $e) {
  373. }
  374. $duration = microtime(true) - $start;
  375. $this->assertLessThan($timeout + $precision, $duration);
  376. }
  377. public function responsesCodeProvider()
  378. {
  379. return array(
  380. //expected output / getter / code to execute
  381. //array(1,'getExitCode','exit(1);'),
  382. //array(true,'isSuccessful','exit();'),
  383. array('output', 'getOutput', 'echo \'output\';'),
  384. );
  385. }
  386. public function pipesCodeProvider()
  387. {
  388. $variations = array(
  389. 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
  390. 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
  391. );
  392. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  393. // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
  394. $sizes = array(1, 2, 4, 8);
  395. } else {
  396. $sizes = array(1, 16, 64, 1024, 4096);
  397. }
  398. $codes = array();
  399. foreach ($sizes as $size) {
  400. foreach ($variations as $code) {
  401. $codes[] = array($code, $size);
  402. }
  403. }
  404. return $codes;
  405. }
  406. /**
  407. * provides default method names for simple getter/setter
  408. */
  409. public function methodProvider()
  410. {
  411. $defaults = array(
  412. array('CommandLine'),
  413. array('Timeout'),
  414. array('WorkingDirectory'),
  415. array('Env'),
  416. array('Stdin'),
  417. array('Options')
  418. );
  419. return $defaults;
  420. }
  421. /**
  422. * @param string $commandline
  423. * @param null $cwd
  424. * @param array $env
  425. * @param null $stdin
  426. * @param integer $timeout
  427. * @param array $options
  428. *
  429. * @return Process
  430. */
  431. abstract protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array());
  432. }