From d2a9767e22f6b367afd415cf654376511da6a552 Mon Sep 17 00:00:00 2001 From: Bernd Stellwag Date: Mon, 10 Mar 2025 22:18:42 +0100 Subject: [PATCH] Add command requiring user input and test passing inputs works --- src/Command/AskForInputCommand.php | 35 ++++++++++++++++++++++++++++++ tests/Functional/ConsoleCest.php | 32 ++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 src/Command/AskForInputCommand.php diff --git a/src/Command/AskForInputCommand.php b/src/Command/AskForInputCommand.php new file mode 100644 index 0000000..85e5f00 --- /dev/null +++ b/src/Command/AskForInputCommand.php @@ -0,0 +1,35 @@ +getHelper('question'); + + $question = new ConfirmationQuestion('continue?', false); + if (!$helper->ask($input, $output, $question)) { + $output->writeln('bye'); + + return Command::FAILURE; + } + + $question = new Question('input'); + $answer = $helper->ask($input, $output, $question); + + $output->writeln("user input: '$answer'"); + + return Command::SUCCESS; + } +} diff --git a/tests/Functional/ConsoleCest.php b/tests/Functional/ConsoleCest.php index 183586e..9b136a3 100644 --- a/tests/Functional/ConsoleCest.php +++ b/tests/Functional/ConsoleCest.php @@ -4,12 +4,15 @@ namespace App\Tests\Functional; +use App\Command\AskForInputCommand; use App\Command\ExampleCommand; use App\Tests\Support\FunctionalTester; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\MissingInputException; final class ConsoleCest { - public function runSymfonyConsoleCommand(FunctionalTester $I) + public function runSymfonyConsoleCommand(FunctionalTester $I): void { // Call Symfony console without option $output = $I->runSymfonyConsoleCommand(ExampleCommand::getDefaultName()); @@ -29,4 +32,31 @@ public function runSymfonyConsoleCommand(FunctionalTester $I) ); $I->assertStringContainsString('Bye world!', $output); } + + public function runSymfonyConsoleCommandInput(FunctionalTester $I): void + { + // Confirmation question not confirmed + $output = $I->runSymfonyConsoleCommand( + AskForInputCommand::getDefaultName(), + consoleInputs: ['n'], + expectedExitCode: Command::FAILURE, + ); + $I->assertStringContainsString('bye', $output); + + // Exception on missing input + $I->expectThrowable( + MissingInputException::class, + fn () => $I->runSymfonyConsoleCommand( + AskForInputCommand::getDefaultName(), + consoleInputs: ['y'], + ), + ); + + // Multiple inputs + $output = $I->runSymfonyConsoleCommand( + AskForInputCommand::getDefaultName(), + consoleInputs: ['y', 'foobar'], + ); + $I->assertStringContainsString("user input: 'foobar'", $output); + } }