package backend.academy.service; import backend.academy.model.Complexity; import…
- User
package backend.academy.service;
import backend.academy.model.Complexity; import backend.academy.model.GameStatus; import backend.academy.model.Word; import backend.academy.repository.WordRepository; import backend.academy.repository.WordsWordRepositoryImpl; import backend.academy.service.cliParams.GuessParams; import backend.academy.service.cliParams.HelpParams; import backend.academy.service.cliParams.HintParam; import backend.academy.service.cliParams.StartParams; import backend.academy.util.GetRandomEnum; import backend.academy.util.Properties; import backend.academy.util.impl.CsvWordsReader; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import lombok.extern.slf4j.Slf4j;
@Slf4j public class GameSession { private final HangmanInterface hangmanInterface; private final WordRepository wordRepository;
private Game game; private boolean gameSessionIsActive = true; public GameSession() { String path = Properties.getResourcesFilePath() + Properties.getWordsFileName(); wordRepository = new WordsWordRepositoryImpl(new CsvWordsReader(), path); hangmanInterface = new HangmanInterface(); } private void startGame(Complexity complexity) { Word word = wordRepository.getRandomWordByComplexity(complexity); game = new Game(word, complexity.attemptsCount()); } public void startGameSession() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); log.info("Starting game session. \nWelcome to HangMan Game! Please review the commands \"help\""); while (gameSessionIsActive) { if (!reader.ready()) { continue; } StartParams startParams = new StartParams(); HintParam hintParam = new HintParam(); GuessParams guessParams = new GuessParams(); HelpParams helpParams = new HelpParams(); JCommander jCommander = JCommander.newBuilder() .addCommand(startParams.command(), startParams) .addCommand(hintParam.command(), hintParam) .addCommand(helpParams.command(), helpParams) .addCommand(guessParams.command(), guessParams) .build(); String line = reader.readLine(); if (line == null) { continue; } String[] cmds = line.split(" "); try { jCommander.parse(cmds); } catch (ParameterException e) { log.error("Something went wrong, try again or type \"help\""); continue; } if (jCommander.getParsedCommand().equals(startParams.command())) { Complexity complexity; if (startParams.complexity() == null) { complexity = GetRandomEnum.random(Complexity.class); } else { complexity = startParams.complexity(); } startGame(complexity); printGameInterface(); } else { if (game == null) { log.error("Cannot call command while game is not running"); continue; } if (jCommander.getParsedCommand().equals(hintParam.command())) { if (game.getGameStatus() == GameStatus.GOING) { log.info("Hint: {}", game.getHint()); } else { log.error("First you need to start the game"); } } else if (jCommander.getParsedCommand().equals(guessParams.command())) { handleGuessLetterCommand(guessParams); } else if (jCommander.getParsedCommand().equals(helpParams.command())) { jCommander.usage(); } else { log.error("Unknown command"); } } } } private void handleGuessLetterCommand(GuessParams guessParams) { if (game.getGameStatus() == GameStatus.NOT_STARTED) { log.error("First you need to start the game. Type \"help\" to get more details"); } else if (game.getGameStatus() == GameStatus.WON || game.getGameStatus() == GameStatus.LOST) { log.error("Game over. To start the game type" + " \"start (complexity)\". \"help\" to get more details"); } else { game.guessLetter(guessParams.letter()); printGameInterface(); if (game.getGameStatus() == GameStatus.WON) { log.warn("Congratulations! You have won the game!"); } else if (game.getGameStatus() == GameStatus.LOST) { log.warn("Game over. You have lost"); log.warn("Hidden word: {}", game.getWord()); } } } private void printGameInterface() { int imageIndex = (int) ( (((float) game.getCurrentAttempt()) / game.getMaxAttempts()) * (hangmanInterface.imagesCount() - 1) ); log.info("\nImage\n{}", hangmanInterface.getCurrentImage(imageIndex)); log.info("Word: {}", game.getCurrentWord()); log.info("Attempts left: {}", game.getAttemptsLeft()); log.info("Used letters: {}", game.usedCharacters()); }}
сделай mock system.in
- Assistant
Mocking
System.incan be useful in testing environments where you want to simulate user input for yourGameSessionclass. Using libraries like JUnit for testing and libraries like Mockito for mocking is common in Java development. Here's an example of how you might set up a test that mocksSystem.in:import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.InputStream; import static org.mockito.Mockito.*; // Assuming the GameSession class and command line interfaces are imported public class GameSessionTest { private final InputStream originalIn = System.in; @Before public void setUp() { // Setup can initialize any required objects or configurations } @After public void tearDown() { // Restore original System.in after the test System.setIn(originalIn); } @Test public void testStartCommand() throws Exception { String simulatedUserInput = "start EASY\n"; System.setIn(new ByteArrayInputStream(simulatedUserInput.getBytes())); // Create a game session instance GameSession gameSession = new GameSession(); // Run the method you want to test gameSession.startGameSession(); // Add your assertions here // For example, verify that certain methods were called on mock objects, // or check the output if you’ve redirected System.out in a similar way. // For now, this test will only check that no exceptions are thrown. } // Add more test methods for different scenarios and commands }Explanation:
-
Setup and Teardown:
@Beforeand@Afterannotations allow you to set up the testing environment before each test and clean up afterward.- The
tearDownmethod restores the originalSystem.inafter each test, ensuring no side effects between tests.
-
Mocking
System.in:System.setIn(new ByteArrayInputStream(simulatedUserInput.getBytes()))allows us to simulate user input.- In this example, the user inputs "start EASY" which triggers the start of a game with the EASY complexity level.
-
Testing the Game Session:
- You create an instance of your
GameSessionclass and call thestartGameSession()method, which should read from the mockedSystem.in. - Assertions are not shown here but can be added to verify correct behavior, such as checking if the right state transitions occur within the game.
- You create an instance of your
This approach is suitable for unit tests where commands are predefined. However, full interaction tests might require more complex setups or integration tests.
-
- User
как теперь считать из консоли данные
- Assistant
To read data from the console in a Java application, you typically use an instance of
BufferedReaderorScannerto read input fromSystem.in. In the providedGameSessionclass, it usesBufferedReaderto achieve this. If you're looking to implement or understand how to read from the console, here's a simple example usingBufferedReader:Using
BufferedReaderimport java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; public class ConsoleReaderExample { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) { System.out.println("Enter something: "); String userInput = reader.readLine(); // This waits for user input System.out.println("You entered: " + userInput); } catch (IOException e) { e.printStackTrace(); } } }Using
ScannerAlternatively, you can use
Scanner, which is often considered easier to use for simple input operations.import java.util.Scanner; public class ConsoleReaderWithScanner { public static void main(String[] args) { Scanner scanner = new Scanner(System.in, "UTF-8"); System.out.println("Enter something: "); String userInput = scanner.nextLine(); // This waits for user input System.out.println("You entered: " + userInput); scanner.close(); } }Explanation
-
Using
BufferedReader:- We wrap
System.inwithInputStreamReaderand then withBufferedReader. This combination allows us to read text input efficiently, line by line. reader.readLine()reads a line of text from the console.
- We wrap
-
Using
Scanner:Scanneris a utility class that can parse primitive types and strings using regular expressions. It's often simpler to use for basic input.scanner.nextLine()reads a line of input from the console.
Note
In the context of your
GameSessionclass:- The loop checks if
reader.ready()to see if there's input available, which is a non-blocking way to check for input. reader.readLine()waits for the user to enter a line of input and then processes it.
Both of these methods (
BufferedReaderandScanner) are suitable for reading console input, and the choice between them often comes down to preference and the complexity of the input parsing required for your application. -
- User
@Test void wrongCmdBeforeGame() throws IOException { GameSession gameSession = new GameSession(wordsPath); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
String simulatedUserInput = "hint\n"; System.setIn(new ByteArrayInputStream(simulatedUserInput.getBytes())); gameSession.startGameSession(); String response = reader.readLine(); assertEquals(response, "Cannot call command while game is not running"); }почему reader не считывает с консоли
- Assistant
The issue you're experiencing arises from a misunderstanding about how input streams work and how they are being utilized in your test. When you set
System.into aByteArrayInputStream, you simulate the user input for theGameSession. However, you're trying to read fromSystem.intwice, which is leading to confusion.Here's a breakdown of what's happening and the correct approach:
-
System.in Redirection: You are redirecting
System.into read from aByteArrayInputStream. This is appropriate for simulating input for methods that internally read fromSystem.in. -
Reading Twice: The code with
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, ...))is attempting to read fromSystem.inagain. However,System.inis already being processed within yourGameSession.startGameSession()method. Once consumed, it cannot be read again in this way, sinceInputStreamdoesn't support rewinding (unlike files or other storage mediums). -
Expected Response: If you want to capture console output rather than input, you'll need to redirect
System.outinstead of trying to read fromSystem.in.
Revising the Test to Capture Output
To verify the log output or printed messages, you can redirect
System.outto aByteArrayOutputStreamwithin your test:import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import static org.junit.jupiter.api.Assertions.assertTrue; class GameSessionTest { private final InputStream originalIn = System.in; private final PrintStream originalOut = System.out; private ByteArrayOutputStream outContent; @BeforeEach void setUp() { outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); } @AfterEach void tearDown() { System.setIn(originalIn); System.setOut(originalOut); } @Test void wrongCmdBeforeGame() throws IOException { // Prepare simulated user input String simulatedUserInput = "hint\n"; System.setIn(new ByteArrayInputStream(simulatedUserInput.getBytes())); // Run the game session GameSession gameSession = new GameSession(); gameSession.startGameSession(); // Capture console output String consoleOutput = outContent.toString(); // Assert the expected output is present within the logs or console output assertTrue(consoleOutput.contains("Cannot call command while game is not running")); } }Explanation
- System Output Redirection: Redirect
System.outto capture printed messages by using aByteArrayOutputStream. - Input Simulation: Continue simulating user input with
System.setIn(). - Assertions: Adjust your assertions to work with captured output rather than trying to reread from
System.in, which doesn't work as described.
This technique will allow you to verify whether certain messages are being printed to the console, aiding in validation of outputs produced by commands during the game session.
-
- User
outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent));
идет бесконечное ожидание чего-то
- Assistant
If you find that your test is hanging indefinitely, it's likely due to a logic issue within the
GameSession.startGameSession()method loop. Such an issue often occurs when the loop doesn't terminate, particularly if it depends on conditions that aren't met because of the simulated input or an oversight in how data is redirected and read. Here's how you can address and troubleshoot the problem:Troubleshooting Infinite Waiting
-
Check the Loop Condition: Ensure the loop within
startGameSession()has a condition that allows it to exit. If you have a loop likewhile (gameSessionIsActive), ensure there's a mechanism in place to setgameSessionIsActivetofalsebased on specific input or state changes. -
Simulate Input Correctly: Make sure you're simulating all necessary input so the application logic can proceed. For example, if the application expects some ending command or input to change the state of
gameSessionIsActive, ensure your test provides it. -
Add a Termination Command: If your test hangs due to expecting more input, you may need to simulate an additional command that gracefully ends the session, such as an
exitcommand:
String simulatedUserInput = "hint\nexit\n"; System.setIn(new ByteArrayInputStream(simulatedUserInput.getBytes()));- Debug Logging: Consider adding debug logs or temporarily printing debug information to verify where the code gets stuck.
Modifying the Game Session for Testing
If your
GameSessionclass does not have an explicit way to exit from the loop in a test scenario, you might consider providing a mechanism, such as responding to a special command or interpreting a certain state to terminate the loop.Example for Breaking the Loop
Ensure your
GameSessionhandles a command like"exit":public void startGameSession() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); log.info("Starting game session. \nWelcome to HangMan Game! Please review the commands \"help\""); while (gameSessionIsActive) { if (!reader.ready()) { continue; } String line = reader.readLine(); if ("exit".equals(line)) { gameSessionIsActive = false; continue; } // Existing command handling code... } }Update Your Test
Compose the simulated input to include a termination command:
@Test void wrongCmdBeforeGame() throws IOException { // Simulate user input with a termination command String simulatedUserInput = "hint\nexit\n"; System.setIn(new ByteArrayInputStream(simulatedUserInput.getBytes())); // Redirect System.out to capture console output outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); // Run the game session GameSession gameSession = new GameSession(); gameSession.startGameSession(); // Capture and assert the console output String consoleOutput = outContent.toString(); assertTrue(consoleOutput.contains("Cannot call command while game is not running")); }Summary
By ensuring your loop can exit based on simulated test input, and also by capturing output correctly using redirection, you can prevent the test from hanging and verify expected behaviors. Adjustments to the
GameSessionlogic should allow you to handle proper command termination in a controlled way suitable for both production and test environments. -