QuestionHelperTest.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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. $question = new ChoiceQuestion('Who are your favorite superheros?', ['a' => 'Batman', 'b' => 'Superman'], 'a');
  108. $this->assertSame('a', $questionHelper->ask($this->createStreamableInputInterfaceMock('', false), $this->createOutputInterface(), $question), 'ChoiceQuestion validator returns the key if it\'s a string');
  109. try {
  110. $question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, '');
  111. $question->setMultiselect(true);
  112. $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question);
  113. } catch (\InvalidArgumentException $e) {
  114. $this->assertSame('Value "" is invalid', $e->getMessage());
  115. }
  116. }
  117. public function testAsk()
  118. {
  119. $dialog = new QuestionHelper();
  120. $inputStream = $this->getInputStream("\n8AM\n");
  121. $question = new Question('What time is it?', '2PM');
  122. $this->assertEquals('2PM', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  123. $question = new Question('What time is it?', '2PM');
  124. $this->assertEquals('8AM', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question));
  125. rewind($output->getStream());
  126. $this->assertEquals('What time is it?', stream_get_contents($output->getStream()));
  127. }
  128. public function testAskWithAutocomplete()
  129. {
  130. if (!$this->hasSttyAvailable()) {
  131. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  132. }
  133. // Acm<NEWLINE>
  134. // Ac<BACKSPACE><BACKSPACE>s<TAB>Test<NEWLINE>
  135. // <NEWLINE>
  136. // <UP ARROW><UP ARROW><NEWLINE>
  137. // <UP ARROW><UP ARROW><UP ARROW><UP ARROW><UP ARROW><TAB>Test<NEWLINE>
  138. // <DOWN ARROW><NEWLINE>
  139. // S<BACKSPACE><BACKSPACE><DOWN ARROW><DOWN ARROW><NEWLINE>
  140. // F00<BACKSPACE><BACKSPACE>oo<TAB><NEWLINE>
  141. $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");
  142. $dialog = new QuestionHelper();
  143. $helperSet = new HelperSet([new FormatterHelper()]);
  144. $dialog->setHelperSet($helperSet);
  145. $question = new Question('Please select a bundle', 'FrameworkBundle');
  146. $question->setAutocompleterValues(['AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle']);
  147. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  148. $this->assertEquals('AsseticBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  149. $this->assertEquals('FrameworkBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  150. $this->assertEquals('SecurityBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  151. $this->assertEquals('FooBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  152. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  153. $this->assertEquals('AsseticBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  154. $this->assertEquals('FooBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  155. }
  156. public function testAskWithAutocompleteCallback()
  157. {
  158. if (!$this->hasSttyAvailable()) {
  159. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  160. }
  161. // Po<TAB>Cr<TAB>P<DOWN ARROW><DOWN ARROW><NEWLINE>
  162. $inputStream = $this->getInputStream("Pa\177\177o\tCr\tP\033[A\033[A\n");
  163. $dialog = new QuestionHelper();
  164. $helperSet = new HelperSet([new FormatterHelper()]);
  165. $dialog->setHelperSet($helperSet);
  166. $question = new Question('What\'s for dinner?');
  167. // A simple test callback - return an array containing the words the
  168. // user has already completed, suffixed with all known words.
  169. //
  170. // Eg: If the user inputs "Potato C", the return will be:
  171. //
  172. // ["Potato Carrot ", "Potato Creme ", "Potato Curry ", ...]
  173. //
  174. // No effort is made to avoid irrelevant suggestions, as this is handled
  175. // by the autocomplete function.
  176. $callback = function ($input) {
  177. $knownWords = ['Carrot', 'Creme', 'Curry', 'Parsnip', 'Pie', 'Potato', 'Tart'];
  178. $inputWords = explode(' ', $input);
  179. array_pop($inputWords);
  180. $suggestionBase = $inputWords ? implode(' ', $inputWords).' ' : '';
  181. return array_map(
  182. function ($word) use ($suggestionBase) {
  183. return $suggestionBase.$word.' ';
  184. },
  185. $knownWords
  186. );
  187. };
  188. $question->setAutocompleterCallback($callback);
  189. $this->assertSame('Potato Creme Pie', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  190. }
  191. public function testAskWithAutocompleteWithNonSequentialKeys()
  192. {
  193. if (!$this->hasSttyAvailable()) {
  194. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  195. }
  196. // <UP ARROW><UP ARROW><NEWLINE><DOWN ARROW><DOWN ARROW><NEWLINE>
  197. $inputStream = $this->getInputStream("\033[A\033[A\n\033[B\033[B\n");
  198. $dialog = new QuestionHelper();
  199. $dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
  200. $question = new ChoiceQuestion('Please select a bundle', [1 => 'AcmeDemoBundle', 4 => 'AsseticBundle']);
  201. $question->setMaxAttempts(1);
  202. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  203. $this->assertEquals('AsseticBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  204. }
  205. public function testAskWithAutocompleteWithExactMatch()
  206. {
  207. if (!$this->hasSttyAvailable()) {
  208. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  209. }
  210. $inputStream = $this->getInputStream("b\n");
  211. $possibleChoices = [
  212. 'a' => 'berlin',
  213. 'b' => 'copenhagen',
  214. 'c' => 'amsterdam',
  215. ];
  216. $dialog = new QuestionHelper();
  217. $dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
  218. $question = new ChoiceQuestion('Please select a city', $possibleChoices);
  219. $question->setMaxAttempts(1);
  220. $this->assertSame('b', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  221. }
  222. public function getInputs()
  223. {
  224. return [
  225. ['$'], // 1 byte character
  226. ['¢'], // 2 bytes character
  227. ['€'], // 3 bytes character
  228. ['𐍈'], // 4 bytes character
  229. ];
  230. }
  231. /**
  232. * @dataProvider getInputs
  233. */
  234. public function testAskWithAutocompleteWithMultiByteCharacter($character)
  235. {
  236. if (!$this->hasSttyAvailable()) {
  237. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  238. }
  239. $inputStream = $this->getInputStream("$character\n");
  240. $possibleChoices = [
  241. '$' => '1 byte character',
  242. '¢' => '2 bytes character',
  243. '€' => '3 bytes character',
  244. '𐍈' => '4 bytes character',
  245. ];
  246. $dialog = new QuestionHelper();
  247. $dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
  248. $question = new ChoiceQuestion('Please select a character', $possibleChoices);
  249. $question->setMaxAttempts(1);
  250. $this->assertSame($character, $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  251. }
  252. public function testAutocompleteWithTrailingBackslash()
  253. {
  254. if (!$this->hasSttyAvailable()) {
  255. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  256. }
  257. $inputStream = $this->getInputStream('E');
  258. $dialog = new QuestionHelper();
  259. $helperSet = new HelperSet([new FormatterHelper()]);
  260. $dialog->setHelperSet($helperSet);
  261. $question = new Question('');
  262. $expectedCompletion = 'ExampleNamespace\\';
  263. $question->setAutocompleterValues([$expectedCompletion]);
  264. $output = $this->createOutputInterface();
  265. $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $output, $question);
  266. $outputStream = $output->getStream();
  267. rewind($outputStream);
  268. $actualOutput = stream_get_contents($outputStream);
  269. // Shell control (esc) sequences are not so important: we only care that
  270. // <hl> tag is interpreted correctly and replaced
  271. $irrelevantEscSequences = [
  272. "\0337" => '', // Save cursor position
  273. "\0338" => '', // Restore cursor position
  274. "\033[K" => '', // Clear line from cursor till the end
  275. ];
  276. $importantActualOutput = strtr($actualOutput, $irrelevantEscSequences);
  277. // Remove colors (e.g. "\033[30m", "\033[31;41m")
  278. $importantActualOutput = preg_replace('/\033\[\d+(;\d+)?m/', '', $importantActualOutput);
  279. $this->assertEquals($expectedCompletion, $importantActualOutput);
  280. }
  281. public function testAskHiddenResponse()
  282. {
  283. if ('\\' === \DIRECTORY_SEPARATOR) {
  284. $this->markTestSkipped('This test is not supported on Windows');
  285. }
  286. $dialog = new QuestionHelper();
  287. $question = new Question('What time is it?');
  288. $question->setHidden(true);
  289. $this->assertEquals('8AM', $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("8AM\n")), $this->createOutputInterface(), $question));
  290. }
  291. /**
  292. * @dataProvider getAskConfirmationData
  293. */
  294. public function testAskConfirmation($question, $expected, $default = true)
  295. {
  296. $dialog = new QuestionHelper();
  297. $inputStream = $this->getInputStream($question."\n");
  298. $question = new ConfirmationQuestion('Do you like French fries?', $default);
  299. $this->assertEquals($expected, $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question), 'confirmation question should '.($expected ? 'pass' : 'cancel'));
  300. }
  301. public function getAskConfirmationData()
  302. {
  303. return [
  304. ['', true],
  305. ['', false, false],
  306. ['y', true],
  307. ['yes', true],
  308. ['n', false],
  309. ['no', false],
  310. ];
  311. }
  312. public function testAskConfirmationWithCustomTrueAnswer()
  313. {
  314. $dialog = new QuestionHelper();
  315. $inputStream = $this->getInputStream("j\ny\n");
  316. $question = new ConfirmationQuestion('Do you like French fries?', false, '/^(j|y)/i');
  317. $this->assertTrue($dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  318. $question = new ConfirmationQuestion('Do you like French fries?', false, '/^(j|y)/i');
  319. $this->assertTrue($dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  320. }
  321. public function testAskAndValidate()
  322. {
  323. $dialog = new QuestionHelper();
  324. $helperSet = new HelperSet([new FormatterHelper()]);
  325. $dialog->setHelperSet($helperSet);
  326. $error = 'This is not a color!';
  327. $validator = function ($color) use ($error) {
  328. if (!\in_array($color, ['white', 'black'])) {
  329. throw new \InvalidArgumentException($error);
  330. }
  331. return $color;
  332. };
  333. $question = new Question('What color was the white horse of Henry IV?', 'white');
  334. $question->setValidator($validator);
  335. $question->setMaxAttempts(2);
  336. $inputStream = $this->getInputStream("\nblack\n");
  337. $this->assertEquals('white', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  338. $this->assertEquals('black', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  339. try {
  340. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("green\nyellow\norange\n")), $this->createOutputInterface(), $question);
  341. $this->fail();
  342. } catch (\InvalidArgumentException $e) {
  343. $this->assertEquals($error, $e->getMessage());
  344. }
  345. }
  346. /**
  347. * @dataProvider simpleAnswerProvider
  348. */
  349. public function testSelectChoiceFromSimpleChoices($providedAnswer, $expectedValue)
  350. {
  351. $possibleChoices = [
  352. 'My environment 1',
  353. 'My environment 2',
  354. 'My environment 3',
  355. ];
  356. $dialog = new QuestionHelper();
  357. $helperSet = new HelperSet([new FormatterHelper()]);
  358. $dialog->setHelperSet($helperSet);
  359. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  360. $question->setMaxAttempts(1);
  361. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream($providedAnswer."\n")), $this->createOutputInterface(), $question);
  362. $this->assertSame($expectedValue, $answer);
  363. }
  364. public function simpleAnswerProvider()
  365. {
  366. return [
  367. [0, 'My environment 1'],
  368. [1, 'My environment 2'],
  369. [2, 'My environment 3'],
  370. ['My environment 1', 'My environment 1'],
  371. ['My environment 2', 'My environment 2'],
  372. ['My environment 3', 'My environment 3'],
  373. ];
  374. }
  375. /**
  376. * @dataProvider specialCharacterInMultipleChoice
  377. */
  378. public function testSpecialCharacterChoiceFromMultipleChoiceList($providedAnswer, $expectedValue)
  379. {
  380. $possibleChoices = [
  381. '.',
  382. 'src',
  383. ];
  384. $dialog = new QuestionHelper();
  385. $inputStream = $this->getInputStream($providedAnswer."\n");
  386. $helperSet = new HelperSet([new FormatterHelper()]);
  387. $dialog->setHelperSet($helperSet);
  388. $question = new ChoiceQuestion('Please select the directory', $possibleChoices);
  389. $question->setMaxAttempts(1);
  390. $question->setMultiselect(true);
  391. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question);
  392. $this->assertSame($expectedValue, $answer);
  393. }
  394. public function specialCharacterInMultipleChoice()
  395. {
  396. return [
  397. ['.', ['.']],
  398. ['., src', ['.', 'src']],
  399. ];
  400. }
  401. /**
  402. * @dataProvider mixedKeysChoiceListAnswerProvider
  403. */
  404. public function testChoiceFromChoicelistWithMixedKeys($providedAnswer, $expectedValue)
  405. {
  406. $possibleChoices = [
  407. '0' => 'No environment',
  408. '1' => 'My environment 1',
  409. 'env_2' => 'My environment 2',
  410. 3 => 'My environment 3',
  411. ];
  412. $dialog = new QuestionHelper();
  413. $helperSet = new HelperSet([new FormatterHelper()]);
  414. $dialog->setHelperSet($helperSet);
  415. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  416. $question->setMaxAttempts(1);
  417. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream($providedAnswer."\n")), $this->createOutputInterface(), $question);
  418. $this->assertSame($expectedValue, $answer);
  419. }
  420. public function mixedKeysChoiceListAnswerProvider()
  421. {
  422. return [
  423. ['0', '0'],
  424. ['No environment', '0'],
  425. ['1', '1'],
  426. ['env_2', 'env_2'],
  427. [3, '3'],
  428. ['My environment 1', '1'],
  429. ];
  430. }
  431. /**
  432. * @dataProvider answerProvider
  433. */
  434. public function testSelectChoiceFromChoiceList($providedAnswer, $expectedValue)
  435. {
  436. $possibleChoices = [
  437. 'env_1' => 'My environment 1',
  438. 'env_2' => 'My environment',
  439. 'env_3' => 'My environment',
  440. ];
  441. $dialog = new QuestionHelper();
  442. $helperSet = new HelperSet([new FormatterHelper()]);
  443. $dialog->setHelperSet($helperSet);
  444. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  445. $question->setMaxAttempts(1);
  446. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream($providedAnswer."\n")), $this->createOutputInterface(), $question);
  447. $this->assertSame($expectedValue, $answer);
  448. }
  449. /**
  450. * @expectedException \InvalidArgumentException
  451. * @expectedExceptionMessage The provided answer is ambiguous. Value should be one of env_2 or env_3.
  452. */
  453. public function testAmbiguousChoiceFromChoicelist()
  454. {
  455. $possibleChoices = [
  456. 'env_1' => 'My first environment',
  457. 'env_2' => 'My environment',
  458. 'env_3' => 'My environment',
  459. ];
  460. $dialog = new QuestionHelper();
  461. $helperSet = new HelperSet([new FormatterHelper()]);
  462. $dialog->setHelperSet($helperSet);
  463. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  464. $question->setMaxAttempts(1);
  465. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("My environment\n")), $this->createOutputInterface(), $question);
  466. }
  467. public function answerProvider()
  468. {
  469. return [
  470. ['env_1', 'env_1'],
  471. ['env_2', 'env_2'],
  472. ['env_3', 'env_3'],
  473. ['My environment 1', 'env_1'],
  474. ];
  475. }
  476. public function testNoInteraction()
  477. {
  478. $dialog = new QuestionHelper();
  479. $question = new Question('Do you have a job?', 'not yet');
  480. $this->assertEquals('not yet', $dialog->ask($this->createStreamableInputInterfaceMock(null, false), $this->createOutputInterface(), $question));
  481. }
  482. /**
  483. * @requires function mb_strwidth
  484. */
  485. public function testChoiceOutputFormattingQuestionForUtf8Keys()
  486. {
  487. $question = 'Lorem ipsum?';
  488. $possibleChoices = [
  489. 'foo' => 'foo',
  490. 'żółw' => 'bar',
  491. 'łabądź' => 'baz',
  492. ];
  493. $outputShown = [
  494. $question,
  495. ' [<info>foo </info>] foo',
  496. ' [<info>żółw </info>] bar',
  497. ' [<info>łabądź</info>] baz',
  498. ];
  499. $output = $this->getMockBuilder('\Symfony\Component\Console\Output\OutputInterface')->getMock();
  500. $output->method('getFormatter')->willReturn(new OutputFormatter());
  501. $dialog = new QuestionHelper();
  502. $helperSet = new HelperSet([new FormatterHelper()]);
  503. $dialog->setHelperSet($helperSet);
  504. $output->expects($this->once())->method('writeln')->with($this->equalTo($outputShown));
  505. $question = new ChoiceQuestion($question, $possibleChoices, 'foo');
  506. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("\n")), $output, $question);
  507. }
  508. /**
  509. * @expectedException \Symfony\Component\Console\Exception\RuntimeException
  510. * @expectedExceptionMessage Aborted.
  511. */
  512. public function testAskThrowsExceptionOnMissingInput()
  513. {
  514. $dialog = new QuestionHelper();
  515. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?'));
  516. }
  517. /**
  518. * @expectedException \Symfony\Component\Console\Exception\RuntimeException
  519. * @expectedExceptionMessage Aborted.
  520. */
  521. public function testAskThrowsExceptionOnMissingInputForChoiceQuestion()
  522. {
  523. $dialog = new QuestionHelper();
  524. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new ChoiceQuestion('Choice', ['a', 'b']));
  525. }
  526. /**
  527. * @expectedException \Symfony\Component\Console\Exception\RuntimeException
  528. * @expectedExceptionMessage Aborted.
  529. */
  530. public function testAskThrowsExceptionOnMissingInputWithValidator()
  531. {
  532. $dialog = new QuestionHelper();
  533. $question = new Question('What\'s your name?');
  534. $question->setValidator(function () {
  535. if (!$value) {
  536. throw new \Exception('A value is required.');
  537. }
  538. });
  539. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), $question);
  540. }
  541. /**
  542. * @expectedException \LogicException
  543. * @expectedExceptionMessage Choice question must have at least 1 choice available.
  544. */
  545. public function testEmptyChoices()
  546. {
  547. new ChoiceQuestion('Question', [], 'irrelevant');
  548. }
  549. public function testTraversableAutocomplete()
  550. {
  551. if (!$this->hasSttyAvailable()) {
  552. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  553. }
  554. // Acm<NEWLINE>
  555. // Ac<BACKSPACE><BACKSPACE>s<TAB>Test<NEWLINE>
  556. // <NEWLINE>
  557. // <UP ARROW><UP ARROW><NEWLINE>
  558. // <UP ARROW><UP ARROW><UP ARROW><UP ARROW><UP ARROW><TAB>Test<NEWLINE>
  559. // <DOWN ARROW><NEWLINE>
  560. // S<BACKSPACE><BACKSPACE><DOWN ARROW><DOWN ARROW><NEWLINE>
  561. // F00<BACKSPACE><BACKSPACE>oo<TAB><NEWLINE>
  562. $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");
  563. $dialog = new QuestionHelper();
  564. $helperSet = new HelperSet([new FormatterHelper()]);
  565. $dialog->setHelperSet($helperSet);
  566. $question = new Question('Please select a bundle', 'FrameworkBundle');
  567. $question->setAutocompleterValues(new AutocompleteValues(['irrelevant' => 'AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle']));
  568. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  569. $this->assertEquals('AsseticBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  570. $this->assertEquals('FrameworkBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  571. $this->assertEquals('SecurityBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  572. $this->assertEquals('FooBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  573. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  574. $this->assertEquals('AsseticBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  575. $this->assertEquals('FooBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  576. }
  577. public function testTraversableMultiselectAutocomplete()
  578. {
  579. // <NEWLINE>
  580. // F<TAB><NEWLINE>
  581. // A<3x UP ARROW><TAB>,F<TAB><NEWLINE>
  582. // F00<BACKSPACE><BACKSPACE>o<TAB>,A<DOWN ARROW>,<SPACE>SecurityBundle<NEWLINE>
  583. // Acme<TAB>,<SPACE>As<TAB><29x BACKSPACE>S<TAB><NEWLINE>
  584. // Ac<TAB>,As<TAB><3x BACKSPACE>d<TAB><NEWLINE>
  585. $inputStream = $this->getInputStream("\nF\t\nA\033[A\033[A\033[A\t,F\t\nF00\177\177o\t,A\033[B\t, SecurityBundle\nSecurityBundle\nAcme\t, As\t\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177\177S\t\nAc\t,As\t\177\177\177d\t\n");
  586. $dialog = new QuestionHelper();
  587. $helperSet = new HelperSet([new FormatterHelper()]);
  588. $dialog->setHelperSet($helperSet);
  589. $question = new ChoiceQuestion(
  590. 'Please select a bundle (defaults to AcmeDemoBundle and AsseticBundle)',
  591. ['AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle'],
  592. '0,1'
  593. );
  594. // This tests that autocomplete works for all multiselect choices entered by the user
  595. $question->setMultiselect(true);
  596. $this->assertEquals(['AcmeDemoBundle', 'AsseticBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  597. $this->assertEquals(['FooBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  598. $this->assertEquals(['AsseticBundle', 'FooBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  599. $this->assertEquals(['FooBundle', 'AsseticBundle', 'SecurityBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  600. $this->assertEquals(['SecurityBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  601. $this->assertEquals(['AcmeDemoBundle', 'AsseticBundle'], $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  602. }
  603. protected function getInputStream($input)
  604. {
  605. $stream = fopen('php://memory', 'r+', false);
  606. fwrite($stream, $input);
  607. rewind($stream);
  608. return $stream;
  609. }
  610. protected function createOutputInterface()
  611. {
  612. return new StreamOutput(fopen('php://memory', 'r+', false));
  613. }
  614. protected function createInputInterfaceMock($interactive = true)
  615. {
  616. $mock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
  617. $mock->expects($this->any())
  618. ->method('isInteractive')
  619. ->willReturn($interactive);
  620. return $mock;
  621. }
  622. private function hasSttyAvailable()
  623. {
  624. exec('stty 2>&1', $output, $exitcode);
  625. return 0 === $exitcode;
  626. }
  627. }
  628. class AutocompleteValues implements \IteratorAggregate
  629. {
  630. private $values;
  631. public function __construct(array $values)
  632. {
  633. $this->values = $values;
  634. }
  635. public function getIterator()
  636. {
  637. return new \ArrayIterator($this->values);
  638. }
  639. }