Ejemplo n.º 1
0
  @Test
  public void testNormal() {
    @SuppressWarnings("unchecked")
    Observer<Object> o = mock(Observer.class);

    final List<Integer> list = Arrays.asList(1, 2, 3);

    Func1<Integer, List<Integer>> func =
        new Func1<Integer, List<Integer>>() {
          @Override
          public List<Integer> call(Integer t1) {
            return list;
          }
        };
    Func2<Integer, Integer, Integer> resFunc =
        new Func2<Integer, Integer, Integer>() {

          @Override
          public Integer call(Integer t1, Integer t2) {
            return t1 | t2;
          }
        };

    List<Integer> source = Arrays.asList(16, 32, 64);

    Observable.from(source).flatMapIterable(func, resFunc).subscribe(o);

    for (Integer s : source) {
      for (Integer v : list) {
        verify(o).onNext(s | v);
      }
    }
    verify(o).onCompleted();
    verify(o, never()).onError(any(Throwable.class));
  }
Ejemplo n.º 2
0
  @Test
  public void testFlatMapTransformsException() {
    Observable<Integer> onNext = Observable.from(Arrays.asList(1, 2, 3));
    Observable<Integer> onCompleted = Observable.from(Arrays.asList(4));
    Observable<Integer> onError = Observable.from(Arrays.asList(5));

    Observable<Integer> source =
        Observable.concat(
            Observable.from(Arrays.asList(10, 20, 30)),
            Observable.<Integer>error(new RuntimeException("Forced failure!")));

    @SuppressWarnings("unchecked")
    Observer<Object> o = mock(Observer.class);

    source.flatMap(just(onNext), just(onError), just0(onCompleted)).subscribe(o);

    verify(o, times(3)).onNext(1);
    verify(o, times(3)).onNext(2);
    verify(o, times(3)).onNext(3);
    verify(o).onNext(5);
    verify(o).onCompleted();
    verify(o, never()).onNext(4);

    verify(o, never()).onError(any(Throwable.class));
  }
Ejemplo n.º 3
0
  @Test
  public void post() throws Exception {
    given(connection.getURL()).willReturn(new URL(URL));
    given(connection.getResponseCode()).willReturn(200);
    given(connection.getResponseMessage()).willReturn("OK");
    Map<String, List<String>> responseHeaderFields = new LinkedHashMap<String, List<String>>();
    responseHeaderFields.put("Set-Cookie", Arrays.asList("aaa"));
    given(connection.getHeaderFields()).willReturn(responseHeaderFields);

    Request request =
        new Request(
            "POST",
            URL,
            Arrays.asList(new Header("Hoge", "Piyo")),
            new FormUrlEncodedTypedOutput().addField("foo", "bar"));

    Response response = underTest.execute(request);

    verify(connection).setRequestMethod("POST");
    verify(connection).addRequestProperty("Hoge", "Piyo");
    verify(connection).getOutputStream();

    assertThat(response.getUrl()).isEqualTo(URL);
    assertThat(response.getStatus()).isEqualTo(200);
    assertThat(response.getReason()).isEqualTo("OK");
    assertThat(response.getHeaders()).isEqualTo(Arrays.asList(new Header("Set-Cookie", "aaa")));
    assertThat(output.toString("UTF-8")).isEqualTo("foo=bar");
  }
Ejemplo n.º 4
0
  @Test
  public void testResultFunctionThrows() {
    @SuppressWarnings("unchecked")
    Observer<Object> o = mock(Observer.class);

    final List<Integer> list = Arrays.asList(1, 2, 3);

    Func1<Integer, List<Integer>> func =
        new Func1<Integer, List<Integer>>() {
          @Override
          public List<Integer> call(Integer t1) {
            return list;
          }
        };
    Func2<Integer, Integer, Integer> resFunc =
        new Func2<Integer, Integer, Integer>() {

          @Override
          public Integer call(Integer t1, Integer t2) {
            throw new TestException();
          }
        };

    List<Integer> source = Arrays.asList(16, 32, 64);

    Observable.from(source).flatMapIterable(func, resFunc).subscribe(o);

    verify(o, never()).onCompleted();
    verify(o, never()).onNext(any());
    verify(o).onError(any(TestException.class));
  }
Ejemplo n.º 5
0
  @Test
  public void testInit_NonEmptyCollection() throws Exception {

    // Mock
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Connection connection1 = mock(Connection.class);
    Statement statement = mock(Statement.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);

    when(connection1.prepareStatement("INSERT OR IGNORE INTO " + TABLE_NAME + " values(?, ?);"))
        .thenReturn(preparedStatement);
    when(connectionManager.getConnection(any(SQLiteIndex.class)))
        .thenReturn(connection)
        .thenReturn(connection1);
    when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
    when(connection.createStatement()).thenReturn(statement);
    when(preparedStatement.executeBatch()).thenReturn(new int[] {2});

    // The objects to add
    Set<Car> initWithObjects = new HashSet<Car>(2);
    initWithObjects.add(
        new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps")));
    initWithObjects.add(
        new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags")));

    SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex =
        new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager);

    carFeaturesOffHeapIndex.init(initWithObjects, new QueryOptions());

    // Verify
    verify(statement, times(1))
        .executeUpdate(
            "CREATE TABLE IF NOT EXISTS "
                + TABLE_NAME
                + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
    verify(statement, times(1))
        .executeUpdate(
            "CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
    verify(statement, times(2)).close();
    verify(connection, times(1)).close();

    verify(preparedStatement, times(2)).setObject(1, 1);
    verify(preparedStatement, times(1)).setObject(1, 2);
    verify(preparedStatement, times(1)).setObject(2, "abs");
    verify(preparedStatement, times(1)).setObject(2, "gps");
    verify(preparedStatement, times(1)).setObject(2, "airbags");
    verify(preparedStatement, times(3)).addBatch();
    verify(preparedStatement, times(1)).executeBatch();
    verify(preparedStatement, times(1)).close();
    verify(connection1, times(1)).close();
  }
Ejemplo n.º 6
0
  @Test
  public void testNotifyObjectsRemoved() throws Exception {

    // Mock
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Connection connection1 = mock(Connection.class);
    Statement statement = mock(Statement.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class)))
        .thenReturn(connection)
        .thenReturn(connection1);
    when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
    when(connection.createStatement()).thenReturn(statement);
    when(connection1.prepareStatement("DELETE FROM " + TABLE_NAME + " WHERE objectKey = ?;"))
        .thenReturn(preparedStatement);
    when(preparedStatement.executeBatch()).thenReturn(new int[] {1});

    // The objects to add
    Set<Car> removedObjects = new HashSet<Car>(2);
    removedObjects.add(
        new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps")));
    removedObjects.add(
        new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags")));

    @SuppressWarnings({"unchecked", "unused"})
    SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex =
        new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager);

    carFeaturesOffHeapIndex.removeAll(removedObjects, new QueryOptions());

    // Verify
    verify(statement, times(1))
        .executeUpdate(
            "CREATE TABLE IF NOT EXISTS "
                + TABLE_NAME
                + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
    verify(statement, times(1))
        .executeUpdate(
            "CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
    verify(connection, times(1)).close();

    verify(preparedStatement, times(1)).setObject(1, 1);
    verify(preparedStatement, times(1)).setObject(1, 2);
    verify(preparedStatement, times(2)).addBatch();
    verify(preparedStatement, times(1)).executeBatch();
    verify(connection1, times(1)).close();
  }
  @Test
  public void testDelayErrorMaxConcurrent() {
    final List<Long> requests = new ArrayList<>();
    Observable<Integer> source =
        Observable.mergeDelayError(
            Observable.just(
                    Observable.just(1).asObservable(),
                    Observable.<Integer>error(new TestException()))
                .doOnRequest(
                    new LongConsumer() {
                      @Override
                      public void accept(long t1) {
                        requests.add(t1);
                      }
                    }),
            1);

    TestSubscriber<Integer> ts = new TestSubscriber<>();

    source.subscribe(ts);

    ts.assertValue(1);
    ts.assertTerminated();
    ts.assertError(TestException.class);
    assertEquals(Arrays.asList(1L, 1L, 1L), requests);
  }
Ejemplo n.º 8
0
 @Test
 public void shouldHonorDiskStorageRootOverride() throws IOException, ClassNotFoundException {
   File tmpDir = TestUtil.createTmpDir();
   try {
     String tmpDirPath = tmpDir.getAbsolutePath();
     systemEnv.put(TlbConstants.Server.TLB_DATA_DIR.key, tmpDirPath);
     initializer = new TlbServerInitializer(new SystemEnvironment(systemEnv));
     EntryRepoFactory factory = initializer.repoFactory();
     File file =
         new File(
             tmpDirPath,
             new EntryRepoFactory.VersionedNamespace(LATEST_VERSION, SUBSET_SIZE)
                 .getIdUnder("quux"));
     file.deleteOnExit();
     writeEntriedTo(file);
     SubsetSizeRepo repo = factory.createSubsetRepo("quux", LATEST_VERSION);
     assertThat(
         (List<SubsetSizeEntry>) repo.list(),
         is(
             Arrays.asList(
                 new SubsetSizeEntry(1), new SubsetSizeEntry(2), new SubsetSizeEntry(3))));
   } finally {
     FileUtils.deleteQuietly(tmpDir);
   }
 }
Ejemplo n.º 9
0
  @Test
  public void testMergeError() {
    @SuppressWarnings("unchecked")
    Observer<Object> o = mock(Observer.class);

    Func1<Integer, Observable<Integer>> func =
        new Func1<Integer, Observable<Integer>>() {
          @Override
          public Observable<Integer> call(Integer t1) {
            return Observable.error(new TestException());
          }
        };
    Func2<Integer, Integer, Integer> resFunc =
        new Func2<Integer, Integer, Integer>() {

          @Override
          public Integer call(Integer t1, Integer t2) {
            return t1 | t2;
          }
        };

    List<Integer> source = Arrays.asList(16, 32, 64);

    Observable.from(source).flatMap(func, resFunc).subscribe(o);

    verify(o, never()).onCompleted();
    verify(o, never()).onNext(any());
    verify(o).onError(any(TestException.class));
  }
 protected VistaUserDetails createUser(
     String vistaId,
     String division,
     String duz,
     String password,
     boolean nonExpired,
     boolean nonLocked,
     boolean credentialsNonExpired,
     boolean enabled,
     GrantedAuthority... authorities) {
   VistaUserDetails user = mock(VistaUserDetails.class);
   when(user.getVistaId()).thenReturn(vistaId);
   when(user.getDivision()).thenReturn(division);
   when(user.getDUZ()).thenReturn(duz);
   when(user.isAccountNonExpired()).thenReturn(nonExpired);
   when(user.isAccountNonLocked()).thenReturn(nonLocked);
   when(user.isCredentialsNonExpired()).thenReturn(credentialsNonExpired);
   when(user.isEnabled()).thenReturn(enabled);
   when(user.getUsername()).thenReturn(duz + "@" + vistaId + ";" + division);
   when(user.getPassword()).thenReturn(password);
   if (password != null) {
     String[] pieces = password.split("\\)");
     String[] credentialsPieces = pieces[1].split(";");
     if (credentialsPieces.length == 2) {
       String accessCode = credentialsPieces[0];
       String verifyCode = credentialsPieces[1];
       when(user.getCredentials()).thenReturn(division + ":" + accessCode + ";" + verifyCode);
     } else if (credentialsPieces.length == 1) {
       String appHandle = credentialsPieces[0];
       when(user.getCredentials()).thenReturn(division + ":" + appHandle);
     }
   }
   when(user.getAuthorities()).thenReturn((Collection) Arrays.asList(authorities));
   return user;
 }
Ejemplo n.º 11
0
  @Test
  public void testFlatMapTransformsOnNextFuncThrows() {
    Observable<Integer> onCompleted = Observable.from(Arrays.asList(4));
    Observable<Integer> onError = Observable.from(Arrays.asList(5));

    Observable<Integer> source = Observable.from(Arrays.asList(10, 20, 30));

    @SuppressWarnings("unchecked")
    Observer<Object> o = mock(Observer.class);

    source.flatMap(funcThrow(1, onError), just(onError), just0(onCompleted)).subscribe(o);

    verify(o).onError(any(TestException.class));
    verify(o, never()).onNext(any());
    verify(o, never()).onCompleted();
  }
 @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());
 }
Ejemplo n.º 13
0
  @Test
  public void testFlatMapMaxConcurrent() {
    final int m = 4;
    final AtomicInteger subscriptionCount = new AtomicInteger();
    Observable<Integer> source =
        Observable.range(1, 10)
            .flatMap(
                new Func1<Integer, Observable<Integer>>() {
                  @Override
                  public Observable<Integer> call(Integer t1) {
                    return compose(Observable.range(t1 * 10, 2), subscriptionCount, m)
                        .subscribeOn(Schedulers.computation());
                  }
                },
                m);

    TestSubscriber<Integer> ts = new TestSubscriber<Integer>();

    source.subscribe(ts);

    ts.awaitTerminalEvent();
    ts.assertNoErrors();
    Set<Integer> expected =
        new HashSet<Integer>(
            Arrays.asList(
                10, 11, 20, 21, 30, 31, 40, 41, 50, 51, 60, 61, 70, 71, 80, 81, 90, 91, 100, 101));
    Assert.assertEquals(expected.size(), ts.getOnNextEvents().size());
    Assert.assertTrue(expected.containsAll(ts.getOnNextEvents()));
  }
Ejemplo n.º 14
0
  @Test
  public void testGetDistinctKeys_LessThanInclusiveAscending() {
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex =
        SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
              @Override
              public Car getValue(Integer carId, QueryOptions queryOptions) {
                return CarFactory.createCar(carId);
              }
            },
            connectionManager);
    offHeapIndex.addAll(CarFactory.createCollectionOfCars(10), QueryFactory.noQueryOptions());
    List<String> expected, actual;

    expected =
        Arrays.asList(
            "Accord", "Avensis", "Civic", "Focus", "Fusion", "Hilux", "Insight", "M6", "Prius");
    actual =
        Lists.newArrayList(
            offHeapIndex.getDistinctKeys(null, true, "Prius", true, noQueryOptions()));
    assertEquals(expected, actual);
  }
Ejemplo n.º 15
0
 private List<SubsetSizeEntry> writeEntriedTo(File file) throws IOException {
   BufferedWriter writer = new BufferedWriter(new FileWriter(file));
   List<SubsetSizeEntry> entries =
       Arrays.asList(new SubsetSizeEntry(1), new SubsetSizeEntry(2), new SubsetSizeEntry(3));
   for (SubsetSizeEntry entry : entries) {
     writer.append(entry.dump());
   }
   writer.close();
   return entries;
 }
Ejemplo n.º 16
0
 @Test
 public void shouldLoadDiskDumpFromStorageRoot() throws IOException, ClassNotFoundException {
   baseDir.mkdirs();
   File file = new File(baseDir, EntryRepoFactory.name("foo", LATEST_VERSION, SUBSET_SIZE));
   FileUtils.writeStringToFile(file, "1\n2\n3\n");
   SubsetSizeRepo repo = factory.createSubsetRepo("foo", LATEST_VERSION);
   assertThat(
       repo.list(),
       is(
           (Collection<SubsetSizeEntry>)
               Arrays.asList(
                   new SubsetSizeEntry(1), new SubsetSizeEntry(2), new SubsetSizeEntry(3))));
 }
Ejemplo n.º 17
0
 @Test
 public void shouldNotLoadDiskDumpWhenUsingARepoThatIsAlreadyCreated()
     throws ClassNotFoundException, IOException {
   SubsetSizeRepo fooRepo = factory.createSubsetRepo("foo", LATEST_VERSION);
   File file = new File(baseDir, EntryRepoFactory.name("foo", LATEST_VERSION, SUBSET_SIZE));
   ObjectOutputStream outStream = new ObjectOutputStream(new FileOutputStream(file));
   outStream.writeObject(
       new ArrayList<SubsetSizeEntry>(
           Arrays.asList(new SubsetSizeEntry(1), new SubsetSizeEntry(2), new SubsetSizeEntry(3))));
   outStream.close();
   assertThat(fooRepo.list().size(), is(0));
   assertThat(factory.createSubsetRepo("foo", LATEST_VERSION).list().size(), is(0));
 }
Ejemplo n.º 18
0
  @Test
  public void testFlatMapTransformsMaxConcurrentNormal() {
    final int m = 2;
    final AtomicInteger subscriptionCount = new AtomicInteger();
    Observable<Integer> onNext =
        compose(
                Observable.from(Arrays.asList(1, 2, 3)).observeOn(Schedulers.computation()),
                subscriptionCount,
                m)
            .subscribeOn(Schedulers.computation());
    Observable<Integer> onCompleted =
        compose(Observable.from(Arrays.asList(4)), subscriptionCount, m)
            .subscribeOn(Schedulers.computation());
    Observable<Integer> onError = Observable.from(Arrays.asList(5));

    Observable<Integer> source = Observable.from(Arrays.asList(10, 20, 30));

    @SuppressWarnings("unchecked")
    Observer<Object> o = mock(Observer.class);
    TestSubscriber<Object> ts = new TestSubscriber<Object>(o);

    source.flatMap(just(onNext), just(onError), just0(onCompleted), m).subscribe(ts);

    ts.awaitTerminalEvent(1, TimeUnit.SECONDS);
    ts.assertNoErrors();
    ts.assertTerminalEvent();

    verify(o, times(3)).onNext(1);
    verify(o, times(3)).onNext(2);
    verify(o, times(3)).onNext(3);
    verify(o).onNext(4);
    verify(o).onCompleted();

    verify(o, never()).onNext(5);
    verify(o, never()).onError(any(Throwable.class));
  }
Ejemplo n.º 19
0
  @Test
  public void testRequestGroupsInfo() throws Exception {
    List<Long> groupIds = Arrays.asList(1L, 2L, 3L);
    String requestGroupsLink = "requestGroupsLink";
    when(linkBuilder.getRequestGroupsLink(groupIds)).thenReturn(requestGroupsLink);
    String answer = "answer";
    when(request.get(requestGroupsLink, 200)).thenReturn(answer);
    when(jsonService.getGroups(answer)).thenReturn(new ArrayList<>());

    apiService.requestGroups(groupIds);

    verify(linkBuilder, times(1)).getRequestGroupsLink(groupIds);
    verify(request, times(1)).get(requestGroupsLink, 200);
    verify(jsonService, times(1)).getGroups(answer);
  }
  /** This uses the public API collect which uses scan under the covers. */
  @Test
  public void testSeedFactory() {
    Observable<List<Integer>> o =
        Observable.range(1, 10)
            .collect(
                new Supplier<List<Integer>>() {

                  @Override
                  public List<Integer> get() {
                    return new ArrayList<>();
                  }
                },
                new BiConsumer<List<Integer>, Integer>() {

                  @Override
                  public void accept(List<Integer> list, Integer t2) {
                    list.add(t2);
                  }
                })
            .takeLast(1);

    assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), o.toBlocking().single());
    assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), o.toBlocking().single());
  }
Ejemplo n.º 21
0
    @Override
    public Integer call(JobContext jc) throws Exception {
      JavaRDD<Integer> rdd = jc.sc().parallelize(Arrays.asList(1, 2, 3, 4, 5));
      JavaFutureAction<?> future =
          jc.monitor(
              rdd.foreachAsync(
                  new VoidFunction<Integer>() {
                    @Override
                    public void call(Integer l) throws Exception {}
                  }));

      future.get(TIMEOUT, TimeUnit.SECONDS);

      return 1;
    }
Ejemplo n.º 22
0
  @Test
  public void postAndGet() throws Exception {
    given(connection.getURL()).willReturn(new URL(URL), new URL(URL + "/secret"));
    given(connection.getResponseCode()).willReturn(302, 200);
    Map<String, List<String>> responseHeaderFields = new LinkedHashMap<String, List<String>>();
    responseHeaderFields.put("Location", Arrays.asList("http://example.com/secret"));
    given(connection.getHeaderFields())
        .willReturn(responseHeaderFields, Collections.<String, List<String>>emptyMap());

    Request request = new Request("POST", URL, Collections.<Header>emptyList(), null);

    Response response = underTest.execute(request);

    assertThat(response.getStatus()).isEqualTo(200);
    assertThat(response.getUrl()).isEqualTo(URL + "/secret");
  }
Ejemplo n.º 23
0
  @Test
  public void testSearch_Has() throws SQLException {
    Connection connection = null;
    ResultSet resultSet = null;
    try {
      ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
      initWithTestData(connectionManager);

      connection = connectionManager.getConnection(null);
      resultSet = DBQueries.search(has(self(Car.class)), NAME, connection);
      assertResultSetObjectKeysOrderAgnostic(resultSet, Arrays.asList(1, 2, 3));

    } finally {
      DBUtils.closeQuietly(connection);
      DBUtils.closeQuietly(resultSet);
    }
  }
Ejemplo n.º 24
0
 @Test
 public void shouldUseWorkingDirAsDiskStorageRootWhenNotGiven()
     throws IOException, ClassNotFoundException {
   final File workingDirStorage = new File(TlbConstants.Server.DEFAULT_TLB_DATA_DIR);
   workingDirStorage.mkdirs();
   File file =
       new File(workingDirStorage, EntryRepoFactory.name("foo", LATEST_VERSION, SUBSET_SIZE));
   FileUtils.writeStringToFile(file, "1\n2\n3\n");
   EntryRepoFactory factory =
       new EntryRepoFactory(new SystemEnvironment(new HashMap<String, String>()));
   SubsetSizeRepo repo = factory.createSubsetRepo("foo", LATEST_VERSION);
   assertThat(
       repo.list(),
       is(
           (Collection<SubsetSizeEntry>)
               Arrays.asList(
                   new SubsetSizeEntry(1), new SubsetSizeEntry(2), new SubsetSizeEntry(3))));
 }
 @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);
 }
Ejemplo n.º 26
0
  @Test
  public void testSearch_StringStartsWith() throws SQLException {
    Connection connection = null;
    ResultSet resultSet = null;
    try {
      ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
      initWithTestData(connectionManager);

      StringStartsWith<Car, String> startsWith = startsWith(Car.FEATURES, "ab");

      connection = connectionManager.getConnection(null);
      resultSet = DBQueries.search(startsWith, NAME, connection);
      assertResultSetObjectKeysOrderAgnostic(resultSet, Arrays.asList(1, 3));

    } finally {
      DBUtils.closeQuietly(connection);
      DBUtils.closeQuietly(resultSet);
    }
  }
  @Test
  public void shouldSetHeaderOnlyListPropertyAnnotation() throws Exception {
    String xml =
        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<testMethodHeaderOnly>\n" //
            + "    <arg0>foo</arg0>\n" //
            + "</testMethodHeaderOnly>\n";
    when(message.getText()).thenReturn(xml);
    when(message.getPropertyNames()).thenReturn(new StringTokenizer("arg1[0] arg1[1] arg1[2]"));
    when(message.getStringProperty("arg1[0]")).thenReturn("one");
    when(message.getStringProperty("arg1[1]")).thenReturn("two");
    when(message.getStringProperty("arg1[2]")).thenReturn("three");

    XmlMessageDecoder<TestInterfaceHeaderOnlyList> decoder =
        XmlMessageDecoder.of(TestInterfaceHeaderOnlyList.class, implList);

    decoder.onMessage(message);

    verify(implList).testMethodHeaderOnly("foo", Arrays.asList("one", "two", "three"));
  }
Ejemplo n.º 28
0
  @Test
  public void testStartWithWithScheduler() {
    TestScheduler scheduler = new TestScheduler();
    Observable<Integer> observable =
        Observable.just(3, 4).startWith(Arrays.asList(1, 2)).subscribeOn(scheduler);

    Subscriber<Integer> observer = TestHelper.mockSubscriber();

    observable.subscribe(observer);

    scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS);

    InOrder inOrder = inOrder(observer);
    inOrder.verify(observer, times(1)).onNext(1);
    inOrder.verify(observer, times(1)).onNext(2);
    inOrder.verify(observer, times(1)).onNext(3);
    inOrder.verify(observer, times(1)).onNext(4);
    inOrder.verify(observer, times(1)).onComplete();
    inOrder.verifyNoMoreInteractions();
  }
Ejemplo n.º 29
0
  @Test
  public void shouldBeAbleToLoadFromDumpedFile()
      throws ClassNotFoundException, IOException, InterruptedException {
    SubsetSizeRepo subsetSizeRepo = factory.createSubsetRepo("foo", LATEST_VERSION);
    subsetSizeRepo.add(new SubsetSizeEntry(50));
    subsetSizeRepo.add(new SubsetSizeEntry(100));
    subsetSizeRepo.add(new SubsetSizeEntry(200));

    SuiteTimeRepo subsetTimeRepo = factory.createSuiteTimeRepo("bar", LATEST_VERSION);
    subsetTimeRepo.update(new SuiteTimeEntry("foo.bar.Baz", 10));
    subsetTimeRepo.update(new SuiteTimeEntry("bar.baz.Quux", 20));

    SuiteResultRepo subsetResultRepo = factory.createSuiteResultRepo("baz", LATEST_VERSION);
    subsetResultRepo.update(new SuiteResultEntry("foo.bar.Baz", true));
    subsetResultRepo.update(new SuiteResultEntry("bar.baz.Quux", false));

    Thread exitHook = factory.exitHook();
    exitHook.start();
    exitHook.join();
    EntryRepoFactory otherFactoryInstance = new EntryRepoFactory(env());
    assertThat(
        otherFactoryInstance.createSubsetRepo("foo", LATEST_VERSION).list(),
        is(
            (Collection<SubsetSizeEntry>)
                Arrays.asList(
                    new SubsetSizeEntry(50), new SubsetSizeEntry(100), new SubsetSizeEntry(200))));
    assertThat(
        otherFactoryInstance.createSuiteTimeRepo("bar", LATEST_VERSION).list().size(), is(2));
    assertThat(
        otherFactoryInstance.createSuiteTimeRepo("bar", LATEST_VERSION).list(),
        hasItems(new SuiteTimeEntry("foo.bar.Baz", 10), new SuiteTimeEntry("bar.baz.Quux", 20)));
    assertThat(
        otherFactoryInstance.createSuiteResultRepo("baz", LATEST_VERSION).list().size(), is(2));
    assertThat(
        otherFactoryInstance.createSuiteResultRepo("baz", LATEST_VERSION).list(),
        hasItems(
            new SuiteResultEntry("foo.bar.Baz", true),
            new SuiteResultEntry("bar.baz.Quux", false)));
  }
 @Test
 public void testTableGetsNewEvents() throws com.yazino.game.api.GameException {
   whenGameStart();
   whenPlayers();
   List<com.yazino.game.api.ScheduledEvent> events =
       Arrays.asList(
           new com.yazino.game.api.ScheduledEvent(
               100l, 100l, "X", "Y", new HashMap<String, String>(), false),
           new com.yazino.game.api.ScheduledEvent(
               300l, 100l, "Z", "Y", new HashMap<String, String>(), false),
           new com.yazino.game.api.ScheduledEvent(
               200l, 100l, "X", "Z", new HashMap<String, String>(), false));
   final com.yazino.game.api.ExecutionResult result =
       new com.yazino.game.api.ExecutionResult.Builder(gameRules, gameStatus1)
           .scheduledEvents(events)
           .build();
   when(gameRules.execute(
           (com.yazino.game.api.ExecutionContext) anyObject(), eq(command.toCommand(PLAYER_NAME))))
       .thenReturn(result);
   executeCommand();
   assertEquals(3, table.scheduledEventCount());
 }