QuestionHelperTest.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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 testAskWithAutocompleteWithNonSequentialKeys()
  157. {
  158. if (!$this->hasSttyAvailable()) {
  159. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  160. }
  161. // <UP ARROW><UP ARROW><NEWLINE><DOWN ARROW><DOWN ARROW><NEWLINE>
  162. $inputStream = $this->getInputStream("\033[A\033[A\n\033[B\033[B\n");
  163. $dialog = new QuestionHelper();
  164. $dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
  165. $question = new ChoiceQuestion('Please select a bundle', [1 => 'AcmeDemoBundle', 4 => 'AsseticBundle']);
  166. $question->setMaxAttempts(1);
  167. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  168. $this->assertEquals('AsseticBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  169. }
  170. public function testAskWithAutocompleteWithExactMatch()
  171. {
  172. if (!$this->hasSttyAvailable()) {
  173. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  174. }
  175. $inputStream = $this->getInputStream("b\n");
  176. $possibleChoices = [
  177. 'a' => 'berlin',
  178. 'b' => 'copenhagen',
  179. 'c' => 'amsterdam',
  180. ];
  181. $dialog = new QuestionHelper();
  182. $dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
  183. $question = new ChoiceQuestion('Please select a city', $possibleChoices);
  184. $question->setMaxAttempts(1);
  185. $this->assertSame('b', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  186. }
  187. public function getInputs()
  188. {
  189. return [
  190. ['$'], // 1 byte character
  191. ['¢'], // 2 bytes character
  192. ['€'], // 3 bytes character
  193. ['𐍈'], // 4 bytes character
  194. ];
  195. }
  196. /**
  197. * @dataProvider getInputs
  198. */
  199. public function testAskWithAutocompleteWithMultiByteCharacter($character)
  200. {
  201. if (!$this->hasSttyAvailable()) {
  202. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  203. }
  204. $inputStream = $this->getInputStream("$character\n");
  205. $possibleChoices = [
  206. '$' => '1 byte character',
  207. '¢' => '2 bytes character',
  208. '€' => '3 bytes character',
  209. '𐍈' => '4 bytes character',
  210. ];
  211. $dialog = new QuestionHelper();
  212. $dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
  213. $question = new ChoiceQuestion('Please select a character', $possibleChoices);
  214. $question->setMaxAttempts(1);
  215. $this->assertSame($character, $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  216. }
  217. public function testAutocompleteWithTrailingBackslash()
  218. {
  219. if (!$this->hasSttyAvailable()) {
  220. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  221. }
  222. $inputStream = $this->getInputStream('E');
  223. $dialog = new QuestionHelper();
  224. $helperSet = new HelperSet([new FormatterHelper()]);
  225. $dialog->setHelperSet($helperSet);
  226. $question = new Question('');
  227. $expectedCompletion = 'ExampleNamespace\\';
  228. $question->setAutocompleterValues([$expectedCompletion]);
  229. $output = $this->createOutputInterface();
  230. $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $output, $question);
  231. $outputStream = $output->getStream();
  232. rewind($outputStream);
  233. $actualOutput = stream_get_contents($outputStream);
  234. // Shell control (esc) sequences are not so important: we only care that
  235. // <hl> tag is interpreted correctly and replaced
  236. $irrelevantEscSequences = [
  237. "\0337" => '', // Save cursor position
  238. "\0338" => '', // Restore cursor position
  239. "\033[K" => '', // Clear line from cursor till the end
  240. ];
  241. $importantActualOutput = strtr($actualOutput, $irrelevantEscSequences);
  242. // Remove colors (e.g. "\033[30m", "\033[31;41m")
  243. $importantActualOutput = preg_replace('/\033\[\d+(;\d+)?m/', '', $importantActualOutput);
  244. $this->assertEquals($expectedCompletion, $importantActualOutput);
  245. }
  246. public function testAskHiddenResponse()
  247. {
  248. if ('\\' === \DIRECTORY_SEPARATOR) {
  249. $this->markTestSkipped('This test is not supported on Windows');
  250. }
  251. $dialog = new QuestionHelper();
  252. $question = new Question('What time is it?');
  253. $question->setHidden(true);
  254. $this->assertEquals('8AM', $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("8AM\n")), $this->createOutputInterface(), $question));
  255. }
  256. /**
  257. * @dataProvider getAskConfirmationData
  258. */
  259. public function testAskConfirmation($question, $expected, $default = true)
  260. {
  261. $dialog = new QuestionHelper();
  262. $inputStream = $this->getInputStream($question."\n");
  263. $question = new ConfirmationQuestion('Do you like French fries?', $default);
  264. $this->assertEquals($expected, $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question), 'confirmation question should '.($expected ? 'pass' : 'cancel'));
  265. }
  266. public function getAskConfirmationData()
  267. {
  268. return [
  269. ['', true],
  270. ['', false, false],
  271. ['y', true],
  272. ['yes', true],
  273. ['n', false],
  274. ['no', false],
  275. ];
  276. }
  277. public function testAskConfirmationWithCustomTrueAnswer()
  278. {
  279. $dialog = new QuestionHelper();
  280. $inputStream = $this->getInputStream("j\ny\n");
  281. $question = new ConfirmationQuestion('Do you like French fries?', false, '/^(j|y)/i');
  282. $this->assertTrue($dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  283. $question = new ConfirmationQuestion('Do you like French fries?', false, '/^(j|y)/i');
  284. $this->assertTrue($dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  285. }
  286. public function testAskAndValidate()
  287. {
  288. $dialog = new QuestionHelper();
  289. $helperSet = new HelperSet([new FormatterHelper()]);
  290. $dialog->setHelperSet($helperSet);
  291. $error = 'This is not a color!';
  292. $validator = function ($color) use ($error) {
  293. if (!\in_array($color, ['white', 'black'])) {
  294. throw new \InvalidArgumentException($error);
  295. }
  296. return $color;
  297. };
  298. $question = new Question('What color was the white horse of Henry IV?', 'white');
  299. $question->setValidator($validator);
  300. $question->setMaxAttempts(2);
  301. $inputStream = $this->getInputStream("\nblack\n");
  302. $this->assertEquals('white', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  303. $this->assertEquals('black', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  304. try {
  305. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("green\nyellow\norange\n")), $this->createOutputInterface(), $question);
  306. $this->fail();
  307. } catch (\InvalidArgumentException $e) {
  308. $this->assertEquals($error, $e->getMessage());
  309. }
  310. }
  311. /**
  312. * @dataProvider simpleAnswerProvider
  313. */
  314. public function testSelectChoiceFromSimpleChoices($providedAnswer, $expectedValue)
  315. {
  316. $possibleChoices = [
  317. 'My environment 1',
  318. 'My environment 2',
  319. 'My environment 3',
  320. ];
  321. $dialog = new QuestionHelper();
  322. $helperSet = new HelperSet([new FormatterHelper()]);
  323. $dialog->setHelperSet($helperSet);
  324. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  325. $question->setMaxAttempts(1);
  326. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream($providedAnswer."\n")), $this->createOutputInterface(), $question);
  327. $this->assertSame($expectedValue, $answer);
  328. }
  329. public function simpleAnswerProvider()
  330. {
  331. return [
  332. [0, 'My environment 1'],
  333. [1, 'My environment 2'],
  334. [2, 'My environment 3'],
  335. ['My environment 1', 'My environment 1'],
  336. ['My environment 2', 'My environment 2'],
  337. ['My environment 3', 'My environment 3'],
  338. ];
  339. }
  340. /**
  341. * @dataProvider specialCharacterInMultipleChoice
  342. */
  343. public function testSpecialCharacterChoiceFromMultipleChoiceList($providedAnswer, $expectedValue)
  344. {
  345. $possibleChoices = [
  346. '.',
  347. 'src',
  348. ];
  349. $dialog = new QuestionHelper();
  350. $inputStream = $this->getInputStream($providedAnswer."\n");
  351. $helperSet = new HelperSet([new FormatterHelper()]);
  352. $dialog->setHelperSet($helperSet);
  353. $question = new ChoiceQuestion('Please select the directory', $possibleChoices);
  354. $question->setMaxAttempts(1);
  355. $question->setMultiselect(true);
  356. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question);
  357. $this->assertSame($expectedValue, $answer);
  358. }
  359. public function specialCharacterInMultipleChoice()
  360. {
  361. return [
  362. ['.', ['.']],
  363. ['., src', ['.', 'src']],
  364. ];
  365. }
  366. /**
  367. * @dataProvider mixedKeysChoiceListAnswerProvider
  368. */
  369. public function testChoiceFromChoicelistWithMixedKeys($providedAnswer, $expectedValue)
  370. {
  371. $possibleChoices = [
  372. '0' => 'No environment',
  373. '1' => 'My environment 1',
  374. 'env_2' => 'My environment 2',
  375. 3 => 'My environment 3',
  376. ];
  377. $dialog = new QuestionHelper();
  378. $helperSet = new HelperSet([new FormatterHelper()]);
  379. $dialog->setHelperSet($helperSet);
  380. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  381. $question->setMaxAttempts(1);
  382. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream($providedAnswer."\n")), $this->createOutputInterface(), $question);
  383. $this->assertSame($expectedValue, $answer);
  384. }
  385. public function mixedKeysChoiceListAnswerProvider()
  386. {
  387. return [
  388. ['0', '0'],
  389. ['No environment', '0'],
  390. ['1', '1'],
  391. ['env_2', 'env_2'],
  392. [3, '3'],
  393. ['My environment 1', '1'],
  394. ];
  395. }
  396. /**
  397. * @dataProvider answerProvider
  398. */
  399. public function testSelectChoiceFromChoiceList($providedAnswer, $expectedValue)
  400. {
  401. $possibleChoices = [
  402. 'env_1' => 'My environment 1',
  403. 'env_2' => 'My environment',
  404. 'env_3' => 'My environment',
  405. ];
  406. $dialog = new QuestionHelper();
  407. $helperSet = new HelperSet([new FormatterHelper()]);
  408. $dialog->setHelperSet($helperSet);
  409. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  410. $question->setMaxAttempts(1);
  411. $answer = $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream($providedAnswer."\n")), $this->createOutputInterface(), $question);
  412. $this->assertSame($expectedValue, $answer);
  413. }
  414. /**
  415. * @expectedException \InvalidArgumentException
  416. * @expectedExceptionMessage The provided answer is ambiguous. Value should be one of env_2 or env_3.
  417. */
  418. public function testAmbiguousChoiceFromChoicelist()
  419. {
  420. $possibleChoices = [
  421. 'env_1' => 'My first environment',
  422. 'env_2' => 'My environment',
  423. 'env_3' => 'My environment',
  424. ];
  425. $dialog = new QuestionHelper();
  426. $helperSet = new HelperSet([new FormatterHelper()]);
  427. $dialog->setHelperSet($helperSet);
  428. $question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
  429. $question->setMaxAttempts(1);
  430. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("My environment\n")), $this->createOutputInterface(), $question);
  431. }
  432. public function answerProvider()
  433. {
  434. return [
  435. ['env_1', 'env_1'],
  436. ['env_2', 'env_2'],
  437. ['env_3', 'env_3'],
  438. ['My environment 1', 'env_1'],
  439. ];
  440. }
  441. public function testNoInteraction()
  442. {
  443. $dialog = new QuestionHelper();
  444. $question = new Question('Do you have a job?', 'not yet');
  445. $this->assertEquals('not yet', $dialog->ask($this->createStreamableInputInterfaceMock(null, false), $this->createOutputInterface(), $question));
  446. }
  447. /**
  448. * @requires function mb_strwidth
  449. */
  450. public function testChoiceOutputFormattingQuestionForUtf8Keys()
  451. {
  452. $question = 'Lorem ipsum?';
  453. $possibleChoices = [
  454. 'foo' => 'foo',
  455. 'żółw' => 'bar',
  456. 'łabądź' => 'baz',
  457. ];
  458. $outputShown = [
  459. $question,
  460. ' [<info>foo </info>] foo',
  461. ' [<info>żółw </info>] bar',
  462. ' [<info>łabądź</info>] baz',
  463. ];
  464. $output = $this->getMockBuilder('\Symfony\Component\Console\Output\OutputInterface')->getMock();
  465. $output->method('getFormatter')->willReturn(new OutputFormatter());
  466. $dialog = new QuestionHelper();
  467. $helperSet = new HelperSet([new FormatterHelper()]);
  468. $dialog->setHelperSet($helperSet);
  469. $output->expects($this->once())->method('writeln')->with($this->equalTo($outputShown));
  470. $question = new ChoiceQuestion($question, $possibleChoices, 'foo');
  471. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream("\n")), $output, $question);
  472. }
  473. /**
  474. * @expectedException \Symfony\Component\Console\Exception\RuntimeException
  475. * @expectedExceptionMessage Aborted.
  476. */
  477. public function testAskThrowsExceptionOnMissingInput()
  478. {
  479. $dialog = new QuestionHelper();
  480. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?'));
  481. }
  482. /**
  483. * @expectedException \Symfony\Component\Console\Exception\RuntimeException
  484. * @expectedExceptionMessage Aborted.
  485. */
  486. public function testAskThrowsExceptionOnMissingInputForChoiceQuestion()
  487. {
  488. $dialog = new QuestionHelper();
  489. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new ChoiceQuestion('Choice', ['a', 'b']));
  490. }
  491. /**
  492. * @expectedException \Symfony\Component\Console\Exception\RuntimeException
  493. * @expectedExceptionMessage Aborted.
  494. */
  495. public function testAskThrowsExceptionOnMissingInputWithValidator()
  496. {
  497. $dialog = new QuestionHelper();
  498. $question = new Question('What\'s your name?');
  499. $question->setValidator(function () {
  500. if (!$value) {
  501. throw new \Exception('A value is required.');
  502. }
  503. });
  504. $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), $question);
  505. }
  506. /**
  507. * @expectedException \LogicException
  508. * @expectedExceptionMessage Choice question must have at least 1 choice available.
  509. */
  510. public function testEmptyChoices()
  511. {
  512. new ChoiceQuestion('Question', [], 'irrelevant');
  513. }
  514. public function testTraversableAutocomplete()
  515. {
  516. if (!$this->hasSttyAvailable()) {
  517. $this->markTestSkipped('`stty` is required to test autocomplete functionality');
  518. }
  519. // Acm<NEWLINE>
  520. // Ac<BACKSPACE><BACKSPACE>s<TAB>Test<NEWLINE>
  521. // <NEWLINE>
  522. // <UP ARROW><UP ARROW><NEWLINE>
  523. // <UP ARROW><UP ARROW><UP ARROW><UP ARROW><UP ARROW><TAB>Test<NEWLINE>
  524. // <DOWN ARROW><NEWLINE>
  525. // S<BACKSPACE><BACKSPACE><DOWN ARROW><DOWN ARROW><NEWLINE>
  526. // F00<BACKSPACE><BACKSPACE>oo<TAB><NEWLINE>
  527. $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");
  528. $dialog = new QuestionHelper();
  529. $helperSet = new HelperSet([new FormatterHelper()]);
  530. $dialog->setHelperSet($helperSet);
  531. $question = new Question('Please select a bundle', 'FrameworkBundle');
  532. $question->setAutocompleterValues(new AutocompleteValues(['irrelevant' => 'AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle']));
  533. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  534. $this->assertEquals('AsseticBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  535. $this->assertEquals('FrameworkBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  536. $this->assertEquals('SecurityBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  537. $this->assertEquals('FooBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  538. $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  539. $this->assertEquals('AsseticBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  540. $this->assertEquals('FooBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
  541. }
  542. protected function getInputStream($input)
  543. {
  544. $stream = fopen('php://memory', 'r+', false);
  545. fwrite($stream, $input);
  546. rewind($stream);
  547. return $stream;
  548. }
  549. protected function createOutputInterface()
  550. {
  551. return new StreamOutput(fopen('php://memory', 'r+', false));
  552. }
  553. protected function createInputInterfaceMock($interactive = true)
  554. {
  555. $mock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
  556. $mock->expects($this->any())
  557. ->method('isInteractive')
  558. ->will($this->returnValue($interactive));
  559. return $mock;
  560. }
  561. private function hasSttyAvailable()
  562. {
  563. exec('stty 2>&1', $output, $exitcode);
  564. return 0 === $exitcode;
  565. }
  566. }
  567. class AutocompleteValues implements \IteratorAggregate
  568. {
  569. private $values;
  570. public function __construct(array $values)
  571. {
  572. $this->values = $values;
  573. }
  574. public function getIterator()
  575. {
  576. return new \ArrayIterator($this->values);
  577. }
  578. }