QuestionHelperTest.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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\Console\Tests\Helper;
  11. use Symfony\Component\Console\Formatter\OutputFormatter;
  12. use Symfony\Component\Console\Helper\FormatterHelper;
  13. use Symfony\Component\Console\Helper\HelperSet;
  14. use Symfony\Component\Console\Helper\QuestionHelper;
  15. use Symfony\Component\Console\Output\StreamOutput;
  16. use Symfony\Component\Console\Question\ChoiceQuestion;
  17. use Symfony\Component\Console\Question\ConfirmationQuestion;
  18. use Symfony\Component\Console\Question\Question;
  19. /**
  20. * @group tty
  21. */
  22. class QuestionHelperTest extends AbstractQuestionHelperTest
  23. {
  24. public function testAskChoice()
  25. {
  26. $questionHelper = new QuestionHelper();
  27. $helperSet = new HelperSet([new FormatterHelper()]);
  28. $questionHelper->setHelperSet($helperSet);
  29. $heroes = ['Superman', 'Batman', 'Spiderman'];
  30. $inputStream = $this->getInputStream("\n1\n 1 \nFabien\n1\nFabien\n1\n0,2\n 0 , 2 \n\n\n");
  31. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '2');
  32. $question->setMaxAttempts(1);
  33. // first answer is an empty answer, we're supposed to receive the default value
  34. $this->assertEquals('Spiderman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  35. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes);
  36. $question->setMaxAttempts(1);
  37. $this->assertEquals('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  38. $this->assertEquals('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  39. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes);
  40. $question->setErrorMessage('Input "%s" is not a superhero!');
  41. $question->setMaxAttempts(2);
  42. $this->assertEquals('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question));
  43. rewind($output->getStream());
  44. $stream = stream_get_contents($output->getStream());
  45. $this->assertContains('Input "Fabien" is not a superhero!', $stream);
  46. try {
  47. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '1');
  48. $question->setMaxAttempts(1);
  49. $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question);
  50. $this->fail();
  51. } catch (\InvalidArgumentException $e) {
  52. $this->assertEquals('Value "Fabien" is invalid', $e->getMessage());
  53. }
  54. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, null);
  55. $question->setMaxAttempts(1);
  56. $question->setMultiselect(true);
  57. $this->assertEquals(['Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  58. $this->assertEquals(['Superman', 'Spiderman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  59. $this->assertEquals(['Superman', 'Spiderman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  60. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '0,1');
  61. $question->setMaxAttempts(1);
  62. $question->setMultiselect(true);
  63. $this->assertEquals(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  64. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, ' 0 , 1 ');
  65. $question->setMaxAttempts(1);
  66. $question->setMultiselect(true);
  67. $this->assertEquals(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  68. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, 0);
  69. // We are supposed to get the default value since we are not in interactive mode
  70. $this->assertEquals('Superman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, true), $this->createOutputInterface(), $question));
  71. }
  72. public function testAskChoiceNonInteractive()
  73. {
  74. $questionHelper = new QuestionHelper();
  75. $helperSet = new HelperSet([new FormatterHelper()]);
  76. $questionHelper->setHelperSet($helperSet);
  77. $inputStream = $this->getInputStream("\n1\n 1 \nFabien\n1\nFabien\n1\n0,2\n 0 , 2 \n\n\n");
  78. $heroes = ['Superman', 'Batman', 'Spiderman'];
  79. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '0');
  80. $this->assertSame('Superman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
  81. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, 'Batman');
  82. $this->assertSame('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
  83. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, null);
  84. $this->assertNull($questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
  85. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '0');
  86. $question->setValidator(null);
  87. $this->assertSame('Superman', $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
  88. try {
  89. $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, null);
  90. $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question);
  91. } catch (\InvalidArgumentException $e) {
  92. $this->assertSame('Value "" is invalid', $e->getMessage());
  93. }
  94. $question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, '0, 1');
  95. $question->setMultiselect(true);
  96. $this->assertSame(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
  97. $question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, '0, 1');
  98. $question->setMultiselect(true);
  99. $question->setValidator(null);
  100. $this->assertSame(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
  101. $question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, '0, Batman');
  102. $question->setMultiselect(true);
  103. $this->assertSame(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
  104. $question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, null);
  105. $question->setMultiselect(true);
  106. $this->assertNull($questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
  107. try {
  108. $question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, '');
  109. $question->setMultiselect(true);
  110. $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question);
  111. } catch (\InvalidArgumentException $e) {
  112. $this->assertSame('Value "" is invalid', $e->getMessage());
  113. }
  114. }
  115. public function testAsk()
  116. {
  117. $dialog = new QuestionHelper();
  118. $inputStream = $this->getInputStream("\n8AM\n");
  119. $question = new Question('What time is it?', '2PM');
  120. $this->assertEquals('2PM', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  121. $question = new Question('What time is it?', '2PM');
  122. $this->assertEquals('8AM', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question));
  123. rewind($output->getStream());
  124. $this->assertEquals('What time is it?', stream_get_contents($output->getStream()));
  125. }
  126. public function testAskWithAutocomplete()
  127. {
  128. if (!$this->hasSttyAvailable()) {
  129. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  130. }
  131. // Acm<NEWLINE>
  132. // Ac<BACKSPACE><BACKSPACE>s<TAB>Test<NEWLINE>
  133. // <NEWLINE>
  134. // <UP ARROW><UP ARROW><NEWLINE>
  135. // <UP ARROW><UP ARROW><UP ARROW><UP ARROW><UP ARROW><TAB>Test<NEWLINE>
  136. // <DOWN ARROW><NEWLINE>
  137. // S<BACKSPACE><BACKSPACE><DOWN ARROW><DOWN ARROW><NEWLINE>
  138. // F00<BACKSPACE><BACKSPACE>oo<TAB><NEWLINE>
  139. $inputStream = $this->getInputStream("Acm\nAc\177\177s\tTest\n\n\033[A\033[A\n\033[A\033[A\033[A\033[A\033[A\tTest\n\033[B\nS\177\177\033[B\033[B\nF00\177\177oo\t\n");
  140. $dialog = new QuestionHelper();
  141. $helperSet = new HelperSet([new FormatterHelper()]);
  142. $dialog->setHelperSet($helperSet);
  143. $question = new Question('Please select a bundle', 'FrameworkBundle');
  144. $question->setAutocompleterValues(['AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle']);
  145. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  146. $this->assertEquals('AsseticBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  147. $this->assertEquals('FrameworkBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  148. $this->assertEquals('SecurityBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  149. $this->assertEquals('FooBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  150. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  151. $this->assertEquals('AsseticBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  152. $this->assertEquals('FooBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  153. }
  154. public function testAskWithAutocompleteWithNonSequentialKeys()
  155. {
  156. if (!$this->hasSttyAvailable()) {
  157. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  158. }
  159. // <UP ARROW><UP ARROW><NEWLINE><DOWN ARROW><DOWN ARROW><NEWLINE>
  160. $inputStream = $this->getInputStream("\033[A\033[A\n\033[B\033[B\n");
  161. $dialog = new QuestionHelper();
  162. $dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
  163. $question = new ChoiceQuestion('Please select a bundle', [1 => 'AcmeDemoBundle', 4 => 'AsseticBundle']);
  164. $question->setMaxAttempts(1);
  165. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  166. $this->assertEquals('AsseticBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  167. }
  168. public function testAskWithAutocompleteWithExactMatch()
  169. {
  170. if (!$this->hasSttyAvailable()) {
  171. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  172. }
  173. $inputStream = $this->getInputStream("b\n");
  174. $possibleChoices = [
  175. 'a' => 'berlin',
  176. 'b' => 'copenhagen',
  177. 'c' => 'amsterdam',
  178. ];
  179. $dialog = new QuestionHelper();
  180. $dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
  181. $question = new ChoiceQuestion('Please select a city', $possibleChoices);
  182. $question->setMaxAttempts(1);
  183. $this->assertSame('b', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  184. }
  185. public function testAutocompleteWithTrailingBackslash()
  186. {
  187. if (!$this->hasSttyAvailable()) {
  188. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  189. }
  190. $inputStream = $this->getInputStream('E');
  191. $dialog = new QuestionHelper();
  192. $helperSet = new HelperSet([new FormatterHelper()]);
  193. $dialog->setHelperSet($helperSet);
  194. $question = new Question('');
  195. $expectedCompletion = 'ExampleNamespace\\';
  196. $question->setAutocompleterValues([$expectedCompletion]);
  197. $output = $this->createOutputInterface();
  198. $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $output, $question);
  199. $outputStream = $output->getStream();
  200. rewind($outputStream);
  201. $actualOutput = stream_get_contents($outputStream);
  202. // Shell control (esc) sequences are not so important: we only care that
  203. // <hl> tag is interpreted correctly and replaced
  204. $irrelevantEscSequences = [
  205. "\0337" => '', // Save cursor position
  206. "\0338" => '', // Restore cursor position
  207. "\033[K" => '', // Clear line from cursor till the end
  208. ];
  209. $importantActualOutput = strtr($actualOutput, $irrelevantEscSequences);
  210. // Remove colors (e.g. "\033[30m", "\033[31;41m")
  211. $importantActualOutput = preg_replace('/\033\[\d+(;\d+)?m/', '', $importantActualOutput);
  212. $this->assertEquals($expectedCompletion, $importantActualOutput);
  213. }
  214. public function testAskHiddenResponse()
  215. {
  216. if ('\\' === \DIRECTORY_SEPARATOR) {
  217. $this->markTestSkipped('This test is not supported on Windows');
  218. }
  219. $dialog = new QuestionHelper();
  220. $question = new Question('What time is it?');
  221. $question->setHidden(true);
  222. $this->assertEquals('8AM', $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("8AM\n")), $this->createOutputInterface(), $question));
  223. }
  224. /**
  225. * @dataProvider getAskConfirmationData
  226. */
  227. public function testAskConfirmation($question, $expected, $default = true)
  228. {
  229. $dialog = new QuestionHelper();
  230. $inputStream = $this->getInputStream($question."\n");
  231. $question = new ConfirmationQuestion('Do you like French fries?', $default);
  232. $this->assertEquals($expected, $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question), 'confirmation question should '.($expected ? 'pass' : 'cancel'));
  233. }
  234. public function getAskConfirmationData()
  235. {
  236. return [
  237. ['', true],
  238. ['', false, false],
  239. ['y', true],
  240. ['yes', true],
  241. ['n', false],
  242. ['no', false],
  243. ];
  244. }
  245. public function testAskConfirmationWithCustomTrueAnswer()
  246. {
  247. $dialog = new QuestionHelper();
  248. $inputStream = $this->getInputStream("j\ny\n");
  249. $question = new ConfirmationQuestion('Do you like French fries?', false, '/^(j|y)/i');
  250. $this->assertTrue($dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  251. $question = new ConfirmationQuestion('Do you like French fries?', false, '/^(j|y)/i');
  252. $this->assertTrue($dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  253. }
  254. public function testAskAndValidate()
  255. {
  256. $dialog = new QuestionHelper();
  257. $helperSet = new HelperSet([new FormatterHelper()]);
  258. $dialog->setHelperSet($helperSet);
  259. $error = 'This is not a color!';
  260. $validator = function ($color) use ($error) {
  261. if (!\in_array($color, ['white', 'black'])) {
  262. throw new \InvalidArgumentException($error);
  263. }
  264. return $color;
  265. };
  266. $question = new Question('What color was the white horse of Henry IV?', 'white');
  267. $question->setValidator($validator);
  268. $question->setMaxAttempts(2);
  269. $inputStream = $this->getInputStream("\nblack\n");
  270. $this->assertEquals('white', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  271. $this->assertEquals('black', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  272. try {
  273. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("green\nyellow\norange\n")), $this->createOutputInterface(), $question);
  274. $this->fail();
  275. } catch (\InvalidArgumentException $e) {
  276. $this->assertEquals($error, $e->getMessage());
  277. }
  278. }
  279. /**
  280. * @dataProvider simpleAnswerProvider
  281. */
  282. public function testSelectChoiceFromSimpleChoices($providedAnswer, $expectedValue)
  283. {
  284. $possibleChoices = [
  285. 'My environment 1',
  286. 'My environment 2',
  287. 'My environment 3',
  288. ];
  289. $dialog = new QuestionHelper();
  290. $helperSet = new HelperSet([new FormatterHelper()]);
  291. $dialog->setHelperSet($helperSet);
  292. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  293. $question->setMaxAttempts(1);
  294. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream($providedAnswer."\n")), $this->createOutputInterface(), $question);
  295. $this->assertSame($expectedValue, $answer);
  296. }
  297. public function simpleAnswerProvider()
  298. {
  299. return [
  300. [0, 'My environment 1'],
  301. [1, 'My environment 2'],
  302. [2, 'My environment 3'],
  303. ['My environment 1', 'My environment 1'],
  304. ['My environment 2', 'My environment 2'],
  305. ['My environment 3', 'My environment 3'],
  306. ];
  307. }
  308. /**
  309. * @dataProvider specialCharacterInMultipleChoice
  310. */
  311. public function testSpecialCharacterChoiceFromMultipleChoiceList($providedAnswer, $expectedValue)
  312. {
  313. $possibleChoices = [
  314. '.',
  315. 'src',
  316. ];
  317. $dialog = new QuestionHelper();
  318. $inputStream = $this->getInputStream($providedAnswer."\n");
  319. $helperSet = new HelperSet([new FormatterHelper()]);
  320. $dialog->setHelperSet($helperSet);
  321. $question = new ChoiceQuestion('Please select the directory', $possibleChoices);
  322. $question->setMaxAttempts(1);
  323. $question->setMultiselect(true);
  324. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question);
  325. $this->assertSame($expectedValue, $answer);
  326. }
  327. public function specialCharacterInMultipleChoice()
  328. {
  329. return [
  330. ['.', ['.']],
  331. ['., src', ['.', 'src']],
  332. ];
  333. }
  334. /**
  335. * @dataProvider mixedKeysChoiceListAnswerProvider
  336. */
  337. public function testChoiceFromChoicelistWithMixedKeys($providedAnswer, $expectedValue)
  338. {
  339. $possibleChoices = [
  340. '0' => 'No environment',
  341. '1' => 'My environment 1',
  342. 'env_2' => 'My environment 2',
  343. 3 => 'My environment 3',
  344. ];
  345. $dialog = new QuestionHelper();
  346. $helperSet = new HelperSet([new FormatterHelper()]);
  347. $dialog->setHelperSet($helperSet);
  348. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  349. $question->setMaxAttempts(1);
  350. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream($providedAnswer."\n")), $this->createOutputInterface(), $question);
  351. $this->assertSame($expectedValue, $answer);
  352. }
  353. public function mixedKeysChoiceListAnswerProvider()
  354. {
  355. return [
  356. ['0', '0'],
  357. ['No environment', '0'],
  358. ['1', '1'],
  359. ['env_2', 'env_2'],
  360. [3, '3'],
  361. ['My environment 1', '1'],
  362. ];
  363. }
  364. /**
  365. * @dataProvider answerProvider
  366. */
  367. public function testSelectChoiceFromChoiceList($providedAnswer, $expectedValue)
  368. {
  369. $possibleChoices = [
  370. 'env_1' => 'My environment 1',
  371. 'env_2' => 'My environment',
  372. 'env_3' => 'My environment',
  373. ];
  374. $dialog = new QuestionHelper();
  375. $helperSet = new HelperSet([new FormatterHelper()]);
  376. $dialog->setHelperSet($helperSet);
  377. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  378. $question->setMaxAttempts(1);
  379. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream($providedAnswer."\n")), $this->createOutputInterface(), $question);
  380. $this->assertSame($expectedValue, $answer);
  381. }
  382. /**
  383. * @expectedException \InvalidArgumentException
  384. * @expectedExceptionMessage The provided answer is ambiguous. Value should be one of env_2 or env_3.
  385. */
  386. public function testAmbiguousChoiceFromChoicelist()
  387. {
  388. $possibleChoices = [
  389. 'env_1' => 'My first environment',
  390. 'env_2' => 'My environment',
  391. 'env_3' => 'My environment',
  392. ];
  393. $dialog = new QuestionHelper();
  394. $helperSet = new HelperSet([new FormatterHelper()]);
  395. $dialog->setHelperSet($helperSet);
  396. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  397. $question->setMaxAttempts(1);
  398. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("My environment\n")), $this->createOutputInterface(), $question);
  399. }
  400. public function answerProvider()
  401. {
  402. return [
  403. ['env_1', 'env_1'],
  404. ['env_2', 'env_2'],
  405. ['env_3', 'env_3'],
  406. ['My environment 1', 'env_1'],
  407. ];
  408. }
  409. public function testNoInteraction()
  410. {
  411. $dialog = new QuestionHelper();
  412. $question = new Question('Do you have a job?', 'not yet');
  413. $this->assertEquals('not yet', $dialog->ask($this->createStreamableInputInterfaceMock(null, false), $this->createOutputInterface(), $question));
  414. }
  415. /**
  416. * @requires function mb_strwidth
  417. */
  418. public function testChoiceOutputFormattingQuestionForUtf8Keys()
  419. {
  420. $question = 'Lorem ipsum?';
  421. $possibleChoices = [
  422. 'foo' => 'foo',
  423. 'żółw' => 'bar',
  424. 'łabądź' => 'baz',
  425. ];
  426. $outputShown = [
  427. $question,
  428. ' [<info>foo </info>] foo',
  429. ' [<info>żółw </info>] bar',
  430. ' [<info>łabądź</info>] baz',
  431. ];
  432. $output = $this->getMockBuilder('\Symfony\Component\Console\Output\OutputInterface')->getMock();
  433. $output->method('getFormatter')->willReturn(new OutputFormatter());
  434. $dialog = new QuestionHelper();
  435. $helperSet = new HelperSet([new FormatterHelper()]);
  436. $dialog->setHelperSet($helperSet);
  437. $output->expects($this->once())->method('writeln')->with($this->equalTo($outputShown));
  438. $question = new ChoiceQuestion($question, $possibleChoices, 'foo');
  439. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("\n")), $output, $question);
  440. }
  441. /**
  442. * @expectedException \Symfony\Component\Console\Exception\RuntimeException
  443. * @expectedExceptionMessage Aborted
  444. */
  445. public function testAskThrowsExceptionOnMissingInput()
  446. {
  447. $dialog = new QuestionHelper();
  448. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?'));
  449. }
  450. /**
  451. * @expectedException \Symfony\Component\Console\Exception\RuntimeException
  452. * @expectedExceptionMessage Aborted
  453. */
  454. public function testAskThrowsExceptionOnMissingInputWithValidator()
  455. {
  456. $dialog = new QuestionHelper();
  457. $question = new Question('What\'s your name?');
  458. $question->setValidator(function () {
  459. if (!$value) {
  460. throw new \Exception('A value is required.');
  461. }
  462. });
  463. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), $question);
  464. }
  465. /**
  466. * @expectedException \LogicException
  467. * @expectedExceptionMessage Choice question must have at least 1 choice available.
  468. */
  469. public function testEmptyChoices()
  470. {
  471. new ChoiceQuestion('Question', [], 'irrelevant');
  472. }
  473. public function testTraversableAutocomplete()
  474. {
  475. if (!$this->hasSttyAvailable()) {
  476. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  477. }
  478. // Acm<NEWLINE>
  479. // Ac<BACKSPACE><BACKSPACE>s<TAB>Test<NEWLINE>
  480. // <NEWLINE>
  481. // <UP ARROW><UP ARROW><NEWLINE>
  482. // <UP ARROW><UP ARROW><UP ARROW><UP ARROW><UP ARROW><TAB>Test<NEWLINE>
  483. // <DOWN ARROW><NEWLINE>
  484. // S<BACKSPACE><BACKSPACE><DOWN ARROW><DOWN ARROW><NEWLINE>
  485. // F00<BACKSPACE><BACKSPACE>oo<TAB><NEWLINE>
  486. $inputStream = $this->getInputStream("Acm\nAc\177\177s\tTest\n\n\033[A\033[A\n\033[A\033[A\033[A\033[A\033[A\tTest\n\033[B\nS\177\177\033[B\033[B\nF00\177\177oo\t\n");
  487. $dialog = new QuestionHelper();
  488. $helperSet = new HelperSet([new FormatterHelper()]);
  489. $dialog->setHelperSet($helperSet);
  490. $question = new Question('Please select a bundle', 'FrameworkBundle');
  491. $question->setAutocompleterValues(new AutocompleteValues(['irrelevant' => 'AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle']));
  492. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  493. $this->assertEquals('AsseticBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  494. $this->assertEquals('FrameworkBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  495. $this->assertEquals('SecurityBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  496. $this->assertEquals('FooBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  497. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  498. $this->assertEquals('AsseticBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  499. $this->assertEquals('FooBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  500. }
  501. protected function getInputStream($input)
  502. {
  503. $stream = fopen('php://memory', 'r+', false);
  504. fwrite($stream, $input);
  505. rewind($stream);
  506. return $stream;
  507. }
  508. protected function createOutputInterface()
  509. {
  510. return new StreamOutput(fopen('php://memory', 'r+', false));
  511. }
  512. protected function createInputInterfaceMock($interactive = true)
  513. {
  514. $mock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
  515. $mock->expects($this->any())
  516. ->method('isInteractive')
  517. ->will($this->returnValue($interactive));
  518. return $mock;
  519. }
  520. private function hasSttyAvailable()
  521. {
  522. exec('stty 2>&1', $output, $exitcode);
  523. return 0 === $exitcode;
  524. }
  525. }
  526. class AutocompleteValues implements \IteratorAggregate
  527. {
  528. private $values;
  529. public function __construct(array $values)
  530. {
  531. $this->values = $values;
  532. }
  533. public function getIterator()
  534. {
  535. return new \ArrayIterator($this->values);
  536. }
  537. }