@Test
  public void shouldReturnEmptySetWhenPlayerIsPlayingAtOnlyTableAndTableIsExcluded()
      throws Exception {
    RandomTableGenerator generator = new RandomTableGenerator();
    generator.setGameTypes(gameType);
    generator.setTemplateNames(toMap(gameType, variation));
    generator.setClients(toMap(gameType, clientId));

    generator.setFulls(false);
    generator.setShowInLobbys(true);
    generator.setAvailableForJoinings(true);
    generator.setStatii(TableStatus.open);
    Set<Table> generated = generator.generateTables(1);
    Table tableWithPlayer = generated.iterator().next();
    tableWithPlayer.addPlayerToTable(new PlayerInformation(BigDecimal.TEN));

    generated = generator.generateTables(1);
    Table excludedTable = generated.iterator().next();
    excludedTable.setTableId(BigDecimal.valueOf(45));

    gigaSpace.writeMultiple(new Table[] {tableWithPlayer, excludedTable});

    Collection<TableSearchResult> found =
        tableSearchService.findTables(
            BigDecimal.TEN,
            new TableSearchCriteria(
                gameType,
                variation,
                clientId,
                Collections.<String>emptySet(),
                BigDecimal.valueOf(45)));

    assertEquals(0, found.size());
  }
  @Test
  public void testPlayersGetNewStatus() throws com.yazino.game.api.GameException {
    whenGameStart();
    command = commandFrom(PLAYER1_ID);
    com.yazino.game.api.GamePlayer p1 =
        new com.yazino.game.api.GamePlayer(PLAYER1_ID, SESSION_ID, "");
    com.yazino.game.api.GamePlayer p2 =
        new com.yazino.game.api.GamePlayer(PLAYER2_ID, SESSION_ID, "");
    table.setCurrentGame(gameStatus1);
    whenPlayers(p1, p2);
    when(gameRules.getObservableStatus(gameStatus1, getContextFor(p1, false, table.getIncrement())))
        .thenReturn(new PrintlnStatus());
    when(gameRules.getObservableStatus(gameStatus1, getContextFor(p2, true, table.getIncrement())))
        .thenReturn(new PrintlnStatus());
    final com.yazino.game.api.ExecutionResult result =
        new com.yazino.game.api.ExecutionResult.Builder(gameRules, gameStatus1)
            .scheduledEvents(emptyEvents)
            .build();
    when(gameRules.execute(
            isA(com.yazino.game.api.ExecutionContext.class), eq(command.toCommand(PLAYER_NAME))))
        .thenReturn(result);
    final List<HostDocument> hostDocuments = executeCommand();

    // table.lastGameChanges?
    assertThat(hostDocuments.size(), is(equalTo(2)));
    assertThat(
        (GameStatusHostDocument) hostDocuments.get(0), Matchers.isA(GameStatusHostDocument.class));
    assertThat(
        (GameStatusHostDocument) hostDocuments.get(1), Matchers.isA(GameStatusHostDocument.class));
  }
  @Test
  public void shouldReturnMatchingTablesWhenTagsAreSpecified() throws Exception {
    RandomTableGenerator generator = new RandomTableGenerator();
    generator.setGameTypes("BLACKJACK", "HISSTERIA", "ROULETTE");
    generator.setGameTypes(gameType);
    generator.setTemplateNames(toMap(gameType, variation));
    generator.setClients(toMap(gameType, clientId));

    generator.setFulls(false);
    generator.setShowInLobbys(true);
    generator.setAvailableForJoinings(true);
    generator.setStatii(TableStatus.open);
    generator.setTags("tag1", "tag2", "tag3");

    Set<Table> generated = generator.generateTables(12);
    Table firstTable = generated.iterator().next();
    firstTable.setTags(newHashSet("tag4"));
    gigaSpace.writeMultiple(generated.toArray(new Table[generated.size()]));

    Collection<TableSearchResult> found =
        tableSearchService.findTables(
            BigDecimal.TEN,
            new TableSearchCriteria(gameType, variation, clientId, newHashSet("tag4")));
    assertThat(found.size(), is(equalTo(1)));
    assertThat(found.iterator().next().getTableId(), is(equalTo(firstTable.getTableId())));
  }
 @Test
 public void testProcessTransactionResultCorrectlyCallsAuditOnSuccessWithNonNullExecutionResult()
     throws com.yazino.game.api.GameException {
   final String auditLabel = "test424243542354";
   gameStatus = mock(com.yazino.game.api.GameStatus.class);
   when(gameRules.canBeClosed(gameStatus)).thenReturn(false);
   when(gameRules.isComplete(gameStatus)).thenReturn(false);
   whenPlayers();
   when(gameRules.getPlayerInformation(gameStatus))
       .thenReturn(Collections.<com.yazino.game.api.PlayerAtTableInformation>emptyList());
   when(gameRules.getNumberOfSeatsTaken(gameStatus)).thenReturn(0);
   table.setCurrentGame(gameStatus);
   table.setGameId(GAME_ID);
   final com.yazino.game.api.TransactionResult txResult =
       new com.yazino.game.api.TransactionResult("foo", true, null, null, null, null);
   final com.yazino.game.api.ExecutionResult executionResult =
       new com.yazino.game.api.ExecutionResult.Builder(gameRules, gameStatus).build();
   when(gameRules.processTransactionResult(
           isA(com.yazino.game.api.ExecutionContext.class), eq(txResult)))
       .thenReturn(executionResult);
   auditor = mock(Auditor.class);
   when(auditor.newLabel()).thenReturn(auditLabel);
   host = gameHost(new InMemoryGameRepository(gameRules));
   host.processTransactionResult(table, GAME_ID, txResult);
 }
  @Test
  public void shouldReturnEmptyWhenOnlyTableIsExcluded() throws Exception {
    TableSearchCriteria searchCriteria =
        new TableSearchCriteria(
            gameType, variation, clientId, Collections.<String>emptySet(), BigDecimal.valueOf(80));

    RandomTableGenerator generator = new RandomTableGenerator();
    generator.setGameTypes(gameType);
    generator.setTemplateNames(toMap(gameType, variation));
    generator.setClients(toMap(gameType, clientId));

    generator.setFulls(false);
    generator.setShowInLobbys(true);
    generator.setAvailableForJoinings(true);
    generator.setStatii(TableStatus.open);

    Set<Table> generated = generator.generateTables(1);

    Table first = generated.iterator().next();
    first.setTableId(BigDecimal.valueOf(80));

    Collection<TableSearchResult> found =
        tableSearchService.findTables(BigDecimal.TEN, searchCriteria);
    assertEquals(0, found.size());
  }
  private void addPlayersToGame(
      com.yazino.game.api.GameStatus gameStatus, com.yazino.game.api.GamePlayer... players) {
    Collection<com.yazino.game.api.PlayerAtTableInformation> playerAtTableInformationCollection =
        new ArrayList<>();
    for (com.yazino.game.api.GamePlayer player : players) {
      playerAtTableInformationCollection.add(
          new com.yazino.game.api.PlayerAtTableInformation(
              player, Collections.<String, String>emptyMap()));
      if (table.playerAtTable(player.getId()) == null) {
        if (player.getId().equals(PLAYER_ID)) {
          table.addPlayerToTable(
              new PlayerInformation(
                  PLAYER_ID, PLAYER_NAME, PLAYER_ACCOUNT_ID, BigDecimal.TEN, BigDecimal.ZERO));
        } else if (player.getId().equals(PLAYER1_ID)) {
          table.addPlayerToTable(
              new PlayerInformation(
                  PLAYER1_ID, "player1", PLAYER1_ACCOUNT_ID, BigDecimal.TEN, BigDecimal.ZERO));
        } else if (player.getId().equals(PLAYER2_ID)) {
          table.addPlayerToTable(
              new PlayerInformation(
                  PLAYER2_ID, "player2", PLAYER2_ACCOUNT_ID, BigDecimal.TEN, BigDecimal.ZERO));
        } else {
          table.addPlayerToTable(
              new PlayerInformation(
                  player.getId(),
                  player.getName(),
                  player.getId(),
                  BigDecimal.TEN,
                  BigDecimal.ZERO));
        }
      }
    }

    when(gameRules.getPlayerInformation(gameStatus)).thenReturn(playerAtTableInformationCollection);
  }
 @Test
 public void forceNewGameWillRestartTableAndStartNewGame() {
   Map<BigDecimal, BigDecimal> playerIdToAccountIdOverrides = new HashMap<>();
   playerIdToAccountIdOverrides.put(PLAYER_ID, BigDecimal.valueOf(202020));
   com.yazino.game.api.GameStatus status = new GameStatus(new PrintlnStatus());
   com.yazino.game.api.ExecutionResult result =
       new com.yazino.game.api.ExecutionResult.Builder(gameRules, status).build();
   when(gameRules.startNewGame(isA(com.yazino.game.api.GameCreationContext.class)))
       .thenReturn(result);
   when(auditor.newLabel()).thenReturn("X");
   host = gameHost(new InMemoryGameRepository(gameRules));
   table.setTableStatus(TableStatus.closed);
   table.setCurrentGame(null);
   Collection<com.yazino.game.api.PlayerAtTableInformation> playersAtTable =
       Arrays.asList(
           new com.yazino.game.api.PlayerAtTableInformation(
               new com.yazino.game.api.GamePlayer(PLAYER1_ID, null, "One"),
               Collections.<String, String>emptyMap()),
           new com.yazino.game.api.PlayerAtTableInformation(
               new com.yazino.game.api.GamePlayer(PLAYER2_ID, null, "Two"),
               Collections.<String, String>emptyMap()));
   host.forceNewGame(table, playersAtTable, playerIdToAccountIdOverrides);
   ArgumentCaptor<com.yazino.game.api.GameCreationContext> contextCaptor =
       ArgumentCaptor.forClass(com.yazino.game.api.GameCreationContext.class);
   verify(gameRules).startNewGame(contextCaptor.capture());
   assertEquals(TableStatus.open, table.getTableStatus());
   assertEquals(status, table.getCurrentGame());
   assertEquals(playersAtTable, contextCaptor.getValue().getPlayersAtTableInformation());
 }
  @Test
  public void shouldReturnTransformedTableOnExecute() throws Exception {
    Table expected = createTable();
    when(tableGigaSpace.read(new Table())).thenReturn(expected);

    TableSummary tableSummary = underTest.execute();

    assertEquals(expected.summarise(gameRules), tableSummary);
  }
 @Test
 public void shouldCreateNewGameWhenNotAllowed() {
   Table table = tableWithPhase(GameFinished, 6L);
   when(wallet.getTable()).thenReturn(table);
   GameInitialiser.GameInitialisationContext context = defaultEventContext();
   context.setAllowedToMoveToNextGame(false);
   underTest.initialiseGame(context);
   assertEquals(Long.valueOf(6), table.getGameId());
 }
 @Test
 public void shouldntRunPostProcessorsWhenDisabledAndNewGameCreated() {
   Table table = tableWithPhase(null, 100L);
   when(wallet.getTable()).thenReturn(table);
   GameInitialiser.GameInitialisationContext context = defaultEventContext();
   context.setRunPostProcessors(false);
   Postprocessor processor = mockPostProcessor();
   underTest.setPostInitialisationProcessors(toList(processor));
   underTest.initialiseGame(context);
   assertEquals(Long.valueOf(1), table.getGameId());
   verifyZeroInteractions(processor);
 }
  @Test
  public void shouldReturnFalseIfAPreProcessorFails() {
    Table table = tableWithPhase(Playing, 100L);
    when(wallet.getTable()).thenReturn(table);

    EventPreprocessor processor3 = mockEventPreprocessor(true);
    underTest.setEventPreInitialisationProcessors(
        Arrays.asList(mockEventPreprocessor(true), mockEventPreprocessor(false), processor3));
    boolean successful = underTest.runPreProcessors(gameRules, defaultEventContext());
    assertFalse(successful);
    assertEquals(Long.valueOf(100), table.getGameId());
    verifyZeroInteractions(processor3);
  }
 @Test
 public void testProcessTransactionResultIsNotProcessedForCompleteGame() {
   final GameRepository mockGameRepository = mock(GameRepository.class);
   when(mockGameRepository.getGameRules(GAME_TYPE)).thenReturn(gameRules);
   gameStatus = mock(com.yazino.game.api.GameStatus.class);
   when(gameRules.isComplete(gameStatus)).thenReturn(true);
   table.setCurrentGame(gameStatus);
   table.setGameId(GAME_ID);
   final com.yazino.game.api.TransactionResult txResult =
       new com.yazino.game.api.TransactionResult("foo", true, null, null, null, null);
   host = gameHost(mockGameRepository);
   host.processTransactionResult(table, GAME_ID, txResult);
   verifyNoMoreInteractions(documentDispatcher);
 }
 @Test
 public void testProcessTransactionResultCorrectlyCallsAuditOnSuccessWithNullExecutionResult() {
   final String auditLabel = "test424542542354";
   gameStatus = mock(com.yazino.game.api.GameStatus.class);
   when(gameRules.isComplete(gameStatus)).thenReturn(false);
   table.setCurrentGame(gameStatus);
   table.setGameId(GAME_ID);
   final com.yazino.game.api.TransactionResult txResult =
       new com.yazino.game.api.TransactionResult("foo", true, null, null, null, null);
   auditor = mock(Auditor.class);
   when(auditor.newLabel()).thenReturn(auditLabel);
   host = gameHost(new InMemoryGameRepository(gameRules));
   host.processTransactionResult(table, GAME_ID, txResult);
 }
 @Test
 public void testProcessTransactionResultIsOnlyExecutedForTheCurrentGame() {
   final GameRepository mockGameRepository = mock(GameRepository.class);
   when(mockGameRepository.getGameRules(GAME_TYPE)).thenReturn(gameRules);
   final long differentGameId = GAME_ID + 6;
   gameStatus = mock(com.yazino.game.api.GameStatus.class);
   when(gameRules.isComplete(gameStatus)).thenReturn(false);
   table.setCurrentGame(gameStatus);
   table.setGameId(GAME_ID);
   final com.yazino.game.api.TransactionResult txResult =
       new com.yazino.game.api.TransactionResult("foo", true, null, null, null, null);
   host = gameHost(mockGameRepository);
   host.processTransactionResult(table, differentGameId, txResult);
   verifyNoMoreInteractions(locationService);
 }
  @Test
  public void shouldntRunPostProcessorsWhenDisabledAndNextGameCreated() {
    Table table = tableWithPhase(GameFinished, 6L);
    when(wallet.getTable()).thenReturn(table);
    GameInitialiser.GameInitialisationContext context = defaultEventContext();
    context.setAllowedToMoveToNextGame(true);
    context.setRunPostProcessors(false);
    when(gameRules.isComplete(table.getCurrentGame())).thenReturn(true);
    underTest.setPostInitialisationProcessors(toList(postprocessor));

    underTest.initialiseGame(context);

    assertEquals(Long.valueOf(7), table.getGameId());
    verifyZeroInteractions(postprocessor);
  }
  @Test(expected = IllegalStateException.class)
  public void anIllegalStateExceptionShouldBeThrownWhenThePlayerIsNotAtTheTable()
      throws GameException {
    table.removeAllPlayers();

    underTest.forPlayer(GAME_PLAYER).increaseBalanceBy(AMOUNT, REFERENCE, null);
  }
 private static Table tableWithPhase(MockGameStatus.MockGamePhase phase, long gameId) {
   Table table =
       new Table(
           new com.yazino.game.api.GameType("SLOTS", "Slots", Collections.<String>emptySet()),
           BigDecimal.ONE,
           "DefaultSlots",
           true);
   table.setTableId(BigDecimal.ONE);
   if (phase != null) {
     table.setCurrentGame(
         new GameStatus(
             MockGameStatus.emptyStatus(new HashMap<String, String>()).withPhase(phase)));
   }
   table.setGameId(gameId);
   return table;
 }
  @Test
  public void shutdownIgnoresTablesWithNullGames() {
    table.setCurrentGame(null);

    List<HostDocument> result = gameHost(gameRules).shutdown(table);
    assertEquals(0, result.size());
  }
 @Test
 public void tournamentTableShouldNotRetrievePlayersMainAccount() {
   table.setShowInLobby(false);
   table.setGameId(1l);
   host = gameHost(new InMemoryGameRepository(gameRules));
   BigDecimal playerId = BigDecimal.valueOf(54321);
   CommandWrapper aCommand =
       new CommandWrapper(table.getTableId(), 1l, playerId, SESSION_ID, "aCommand");
   aCommand.setRequestId(UUID);
   when(playerRepository.findSummaryByPlayerAndSession(playerId, SESSION_ID))
       .thenReturn(
           aPlayerSessionSummary(playerId, "", BigDecimal.valueOf(10), BigDecimal.valueOf(100)));
   List<HostDocument> documents = host.execute(table, aCommand);
   assertEquals(1, documents.size());
   assertThat((ErrorHostDocument) documents.get(0), Matchers.isA(ErrorHostDocument.class));
 }
  @Before
  public void setUp() throws WalletServiceException {
    MockitoAnnotations.initMocks(this);

    playerInfo =
        new PlayerInformation(
            PLAYER_ID, PLAYER_NAME, PLAYER_ACCOUNT_ID, BigDecimal.TEN, PLAYER_BALANCE);

    table = new Table();
    table.setTableId(TABLE_ID);
    table.setGameId(GAME_ID);
    table.addPlayerToTable(playerInfo);

    when(uuidSource.getNewUUID()).thenReturn(NEW_UUID).thenReturn("anotherUuid");

    underTest =
        new TableBoundGamePlayerWalletFactory(table, gameHostWallet, AUDIT_LABEL, uuidSource);
  }
  private com.yazino.game.api.ObservableContext getContextFor(
      final com.yazino.game.api.GamePlayer player, boolean skipIfPossible, long startIncrement) {
    if (player == null) {
      return new com.yazino.game.api.ObservableContext(null, null);
    }

    final PlayerInformation playerInfo = table.playerAtTable(player.getId());
    return playerInfo.toObservableContext(skipIfPossible, startIncrement);
  }
 @Test
 public void shutdownReturnsInvestedAmountsOnlyOnceForPlayer() throws WalletServiceException {
   com.yazino.game.api.GamePlayer player1 =
       new com.yazino.game.api.GamePlayer(BigDecimal.valueOf(1), null, "p1");
   com.yazino.game.api.PlayerAtTableInformation p1 =
       new com.yazino.game.api.PlayerAtTableInformation(
           player1, BigDecimal.valueOf(10), Collections.<String, String>emptyMap());
   PlayerInformation pi1 =
       new PlayerInformation(
           player1.getId(),
           player1.getName(),
           BigDecimal.valueOf(501),
           BigDecimal.TEN,
           BigDecimal.valueOf(0));
   com.yazino.game.api.PlayerAtTableInformation p2 =
       new com.yazino.game.api.PlayerAtTableInformation(
           player1, BigDecimal.valueOf(15), Collections.<String, String>emptyMap());
   PlayerInformation pi2 =
       new PlayerInformation(
           player1.getId(),
           player1.getName(),
           BigDecimal.valueOf(501),
           BigDecimal.TEN,
           BigDecimal.valueOf(0));
   table.addPlayerToTable(pi1);
   table.addPlayerToTable(pi2);
   Collection<com.yazino.game.api.PlayerAtTableInformation> players = Arrays.asList(p1, p2);
   when(gameRules.getPlayerInformation(gameStatus)).thenReturn(players);
   table.setCurrentGame(gameStatus);
   List<HostDocument> documents = gameHost(gameRules).shutdown(table);
   assertEquals(1, documents.size());
   verify(bufferedGameHostWallet)
       .post(
           table.getTableId(),
           table.getGameId(),
           pi1,
           BigDecimal.valueOf(25),
           com.yazino.game.api.TransactionType.Return,
           AUDIT_LABEL,
           "Shutdown refund",
           NEW_UUID);
   verify(bufferedGameHostWallet).flush();
   verifyNoMoreInteractions(bufferedGameHostWallet);
 }
  @Test
  public void removeAllPlayersShouldSendLocationNotifications() throws WalletServiceException {
    com.yazino.game.api.GamePlayer p1 =
        new com.yazino.game.api.GamePlayer(PLAYER1_ID, SESSION_ID, "");
    com.yazino.game.api.GamePlayer p2 =
        new com.yazino.game.api.GamePlayer(PLAYER2_ID, SESSION_ID, "");
    table.setCurrentGame(gameStatus);
    table.setTableName(TABLE_NAME);
    addPlayersToGame(gameStatus, p1, p2);

    gameHost(gameRules).removeAllPlayers(table);

    final Location tableLocation =
        new Location(TABLE_ID.toString(), TABLE_NAME, table.getGameTypeId(), null, PUBLIC);
    verify(locationService)
        .notify(PLAYER1_ID, SESSION_ID, LocationChangeType.REMOVE, tableLocation);
    verify(locationService)
        .notify(PLAYER2_ID, SESSION_ID, LocationChangeType.REMOVE, tableLocation);
  }
 @SuppressWarnings({"unchecked"})
 @Test
 public void shouldUpdateGameIdWhenNewGameCreatedAndNotifyPostProcessors() {
   Table table = tableWithPhase(null, 100L);
   when(wallet.getTable()).thenReturn(table);
   GameInitialiser.GameInitialisationContext context = defaultEventContext();
   Postprocessor processor = mockPostProcessor();
   underTest.setPostInitialisationProcessors(toList(processor));
   underTest.initialiseGame(context);
   assertEquals(Long.valueOf(1), table.getGameId());
   verify(processor)
       .postProcess(
           any(com.yazino.game.api.ExecutionResult.class),
           any(com.yazino.game.api.Command.class),
           eq(table),
           anyString(),
           anyList(),
           eq(context.getPlayerId()));
 }
  @Test
  public void shouldReturnOneTableWhenOnlyOneMatchesAndClientAndTemplateAreSpecified()
      throws Exception {
    RandomTableGenerator generator = new RandomTableGenerator();
    generator.setGameTypes("BLACKJACK", "HISSTERIA", "ROULETTE");
    Set<Table> nonMatching = generator.generateTables(100);

    generator.setGameTypes(gameType);
    generator.setTemplateNames(toMap(gameType, variation));
    generator.setClients(toMap(gameType, clientId));
    generator.setFulls(false);
    generator.setShowInLobbys(true);
    generator.setAvailableForJoinings(true);
    generator.setStatii(TableStatus.open);

    GameStatus gameStatus = mock(GameStatus.class);
    when(gameRepository.getGameRules(anyString())).thenReturn(gameRules);
    when(gameRules.getJoiningDesirability(gameStatus)).thenReturn(45);

    Set<Table> matching = generator.generateTables(1);
    Table generatedTable = matching.iterator().next();
    generatedTable.setTableId(BigDecimal.valueOf(67));
    generatedTable.setCurrentGame(gameStatus);

    Set<Table> all = new HashSet<Table>(nonMatching);
    all.addAll(matching);
    gigaSpace.writeMultiple(all.toArray(new Table[all.size()]));

    assertEquals(101, gigaSpace.count(new Table()));

    Collection<TableSearchResult> found =
        tableSearchService.findTables(
            BigDecimal.TEN,
            new TableSearchCriteria(gameType, variation, clientId, Collections.<String>emptySet()));

    assertEquals(1, found.size());
    TableSearchResult table = found.iterator().next();
    assertEquals(BigDecimal.valueOf(67), table.getTableId());
    assertEquals(10, table.getSpareSeats());
    assertEquals(45, table.getJoiningDesirability());
  }
  @Test
  public void testProcessTransactionResultUpdatesCachedBalance() {
    BigDecimal ORIGINAL_BALANCE = BigDecimal.ONE;
    BigDecimal NEW_BALANCE = BigDecimal.TEN;
    table.setCurrentGame(gameStatus);
    table.setGameId(GAME_ID);
    com.yazino.game.api.GamePlayer player =
        new com.yazino.game.api.GamePlayer(PLAYER1_ID, SESSION_ID, "");
    addPlayersToGame(gameStatus, player);
    table.playerWithAccountId(PLAYER1_ACCOUNT_ID).setCachedBalance(ORIGINAL_BALANCE);
    final com.yazino.game.api.TransactionResult txResult =
        new com.yazino.game.api.TransactionResult(
            "foo", true, null, PLAYER1_ACCOUNT_ID, NEW_BALANCE, null);
    host = gameHost(new InMemoryGameRepository(gameRules));

    // exercise SUT
    host.processTransactionResult(table, GAME_ID, txResult);

    // verify
    assertEquals(NEW_BALANCE, table.playerWithAccountId(PLAYER1_ACCOUNT_ID).getCachedBalance());
  }
  @Test
  public void shouldReturnMergedResults() throws Exception {
    final Table aTable = createTable();
    List<AsyncResult<TableSummary>> taskResults = new ArrayList<AsyncResult<TableSummary>>();
    final TableSummary expected = aTable.summarise(gameRules);
    taskResults.add(
        new AsyncResult<TableSummary>() {
          @Override
          public TableSummary getResult() {
            return expected;
          }

          @Override
          public Exception getException() {
            return null;
          }
        });
    TableSummary result = underTest.reduce(taskResults);

    assertEquals(expected, result);
  }
  @Test
  public void shouldIncrementGameIdWhenCreatedNextGameAndNotifyPostProcessors() {
    Table table = tableWithPhase(GameFinished, 6L);
    when(wallet.getTable()).thenReturn(table);
    GameInitialiser.GameInitialisationContext context = defaultEventContext();
    context.setAllowedToMoveToNextGame(true);
    when(gameRules.isComplete(table.getCurrentGame())).thenReturn(true);
    underTest.setPostInitialisationProcessors(toList(postprocessor));

    underTest.initialiseGame(context);

    assertEquals(Long.valueOf(7), table.getGameId());
    verify(postprocessor)
        .postProcess(
            any(com.yazino.game.api.ExecutionResult.class),
            any(com.yazino.game.api.Command.class),
            eq(table),
            anyString(),
            anyList(),
            eq(context.getPlayerId()));
  }
 @Test
 public void shutdownIgnoresNullInvestedAmounts() {
   com.yazino.game.api.PlayerAtTableInformation p1 =
       new com.yazino.game.api.PlayerAtTableInformation(
           new com.yazino.game.api.GamePlayer(BigDecimal.valueOf(1), SESSION_ID, "p1"),
           null,
           Collections.<String, String>emptyMap());
   PlayerInformation pi1 =
       new PlayerInformation(
           BigDecimal.valueOf(1),
           "p1",
           BigDecimal.valueOf(501),
           BigDecimal.TEN,
           BigDecimal.valueOf(0));
   table.addPlayerToTable(pi1);
   Collection<com.yazino.game.api.PlayerAtTableInformation> players = Arrays.asList(p1);
   when(gameRules.getPlayerInformation(gameStatus)).thenReturn(players);
   table.setCurrentGame(gameStatus);
   List<HostDocument> documents = gameHost(gameRules).shutdown(table);
   assertEquals(1, documents.size());
   verify(bufferedGameHostWallet).flush();
   verifyNoMoreInteractions(bufferedGameHostWallet);
 }
  @Before
  public void setUp() throws com.yazino.game.api.GameException, WalletServiceException {
    MockitoAnnotations.initMocks(this);

    timeSource = new SettableTimeSource(System.currentTimeMillis());

    command = new CommandWrapper(TABLE_ID, GAME_ID, A_PLAYER.getId(), SESSION_ID, "T");
    command.setRequestId(UUID);
    playerStatisticEventsPublisher = new InMemoryPlayerStatisticEventsPublisher();

    table =
        new Table(
            new com.yazino.game.api.GameType(GAME_TYPE, "Test", Collections.<String>emptySet()),
            BigDecimal.ONE,
            "test",
            true);
    table.setTableId(TABLE_ID);
    table.setTableStatus(TableStatus.open);
    table.setVariationProperties(new HashMap<String, String>());

    when(bufferedGameHostWalletFactory.create(table.getTableId(), command.getRequestId()))
        .thenReturn(bufferedGameHostWallet);
    when(bufferedGameHostWalletFactory.create(table.getTableId()))
        .thenReturn(bufferedGameHostWallet);

    when(auditor.newLabel()).thenReturn(AUDIT_LABEL);
    when(bufferedGameHostWallet.getBalance(Mockito.isA(BigDecimal.class)))
        .thenReturn(BigDecimal.ZERO);

    when(uuidSource.getNewUUID()).thenReturn(NEW_UUID);
    when(auditor.newLabel()).thenReturn(AUDIT_LABEL);
    when(bufferedGameHostWallet.getBalance(Mockito.isA(BigDecimal.class)))
        .thenReturn(ACCOUNT_BALANCE);

    when(gameRules.getGameType()).thenReturn("TEST");

    when(playerRepository.findSummaryByPlayerAndSession(PLAYER_ID, SESSION_ID))
        .thenReturn(
            aPlayerSessionSummary(PLAYER_ID, "Player", PLAYER_ACCOUNT_ID, BigDecimal.valueOf(100)));
    when(playerRepository.findSummaryByPlayerAndSession(PLAYER_ID, null))
        .thenReturn(
            aPlayerSessionSummary(PLAYER_ID, "Player", PLAYER_ACCOUNT_ID, BigDecimal.valueOf(100)));
    when(playerRepository.findSummaryByPlayerAndSession(PLAYER1_ID, null))
        .thenReturn(
            aPlayerSessionSummary(
                PLAYER1_ID, "Player1", PLAYER1_ACCOUNT_ID, BigDecimal.valueOf(200)));
    when(playerRepository.findSummaryByPlayerAndSession(PLAYER2_ID, null))
        .thenReturn(
            aPlayerSessionSummary(
                PLAYER2_ID, "Player2", PLAYER2_ACCOUNT_ID, BigDecimal.valueOf(300)));

    when(chatRepository.getOrCreateForLocation(TABLE_ID.toPlainString()))
        .thenReturn(new ChatChannel(TABLE_ID.toPlainString()));
  }