io.vertx.ext.unit.TestContext Java Examples

The following examples show how to use io.vertx.ext.unit.TestContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HQLQueryParameterPositionalLimitTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testFirstResultMaxResultsExtra(TestContext context) {
	test(
			context,
			openSession()
					.thenCompose( s ->
							s.createQuery( "from Flour order by id" )
									.setFirstResult( 1 )
									.setMaxResults( 3 )
									.getResultList()
									.thenAccept( results -> {
										context.assertEquals( 2, results.size() );
										context.assertEquals( rye, results.get( 0 ) );
										context.assertEquals( almond, results.get( 1 ) );
									} )
					)
	);
}
 
Example #2
Source File: RockerTemplateEngineTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateHandler(TestContext should) {
  final Async test = should.async();
  TemplateEngine engine = RockerTemplateEngine.create();

  final JsonObject context = new JsonObject()
    .put("foo", "badger")
    .put("bar", "fox")
    .put("context", new JsonObject().put("path", "/TestRockerTemplate2.rocker.html"));

  engine.render(context, "somedir/TestRockerTemplate2.rocker.html", render -> {
    should.assertTrue(render.succeeded());
    should.assertEquals("Hello badger and fox\nRequest path is /TestRockerTemplate2.rocker.html\n", render.result().toString());
    test.complete();
  });
  test.await();
}
 
Example #3
Source File: JadeTemplateTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateHandlerOnClasspath(TestContext should) {
  final Async test = should.async();
  TemplateEngine engine = JadeTemplateEngine.create(vertx);

  final JsonObject context = new JsonObject()
    .put("foo", "badger")
    .put("bar", "fox");

  context.put("context", new JsonObject().put("path", "/test-jade-template2.jade"));

  engine.render(context, "somedir/test-jade-template2.jade", render -> {
    should.assertTrue(render.succeeded());
    should.assertEquals("<!DOCTYPE html><html><head><title>badger/test-jade-template2.jade</title></head><body></body></html>", render.result().toString());
    test.complete();
  });
  test.await();
}
 
Example #4
Source File: PostgresClientIT.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
@Test
public void streamGetWithLimit(TestContext context) throws IOException, FieldException {
  AtomicInteger objectCount = new AtomicInteger();

  final String tableDefiniton = "id UUID PRIMARY KEY , jsonb JSONB NOT NULL, distinct_test_field TEXT";

  createTableWithPoLines(context, MOCK_POLINES_TABLE, tableDefiniton);

  Async async = context.async();
  CQLWrapper wrapper = new CQLWrapper(new CQL2PgJSON("jsonb"), "edition=First edition")
    .setLimit(new Limit(1));
  postgresClient.streamGet(MOCK_POLINES_TABLE, Object.class, "jsonb", wrapper,
    false, null, context.asyncAssertSuccess(sr -> {
      context.assertEquals(3, sr.resultInto().getTotalRecords());
      sr.handler(streamHandler -> objectCount.incrementAndGet());
      sr.endHandler(x -> {
        context.assertEquals(1, objectCount.get());
        async.complete();
      });
    }));
  async.await(1000);
}
 
Example #5
Source File: OAuth2KeycloakIT.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReloadJWK(TestContext should) {
  final Async test = should.async();

  keycloak.jWKSet(load -> {
    should.assertTrue(load.succeeded());

    keycloak.authenticate(new JsonObject().put("username", "test-user").put("password", "tiger"), authn -> {
      should.assertTrue(authn.succeeded());
      should.assertNotNull(authn.result());

      // generate a access token from the user
      User token = authn.result();

      should.assertNotNull(token.attributes().getJsonObject("accessToken"));
      test.complete();
    });
  });
}
 
Example #6
Source File: SimpleQueryDataTypeCodecTestBase.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
protected <T> void testDecodeGeneric(TestContext ctx,
                                     String data,
                                     String dataType,
                                     String columnName,
                                     ColumnChecker.SerializableBiFunction<Tuple, Integer, T> byIndexGetter,
                                     ColumnChecker.SerializableBiFunction<Row, String, T> byNameGetter,
                                     T expected) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.query("SELECT '" + data + "' :: " + dataType + " \"" + columnName + "\"").execute(ctx.asyncAssertSuccess(result -> {
      ctx.assertEquals(1, result.size());
      Row row = result.iterator().next();
      ColumnChecker.checkColumn(0, columnName)
        .returns(Tuple::getValue, Row::getValue, expected)
        .returns(byIndexGetter, byNameGetter, expected)
        .forRow(row);
      async.complete();
    }));
  }));
}
 
Example #7
Source File: UUIDTypeExtendedCodecTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeUUID(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE \"CharacterDataType\" SET \"uuid\" = $1 WHERE \"id\" = $2 RETURNING \"uuid\"",
      ctx.asyncAssertSuccess(p -> {
        UUID uuid = UUID.fromString("92b53cf1-2ad0-49f9-be9d-ca48966e43ee");
        p.query().execute(Tuple.tuple()
          .addUUID(uuid)
          .addInteger(2), ctx.asyncAssertSuccess(result -> {
          ctx.assertEquals(1, result.size());
          ctx.assertEquals(1, result.rowCount());
          Row row = result.iterator().next();
          ColumnChecker.checkColumn(0, "uuid")
            .returns(Tuple::getValue, Row::getValue, uuid)
            .returns(Tuple::getUUID, Row::getUUID, uuid)
            .forRow(row);
          async.complete();
        }));
      }));
  }));
}
 
Example #8
Source File: RoleBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch1(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", RoleBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertTrue(RoleBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r1", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #9
Source File: TransactionalProducerTest.java    From vertx-kafka-client with Apache License 2.0 6 votes vote down vote up
@Test
public void abortTransactionKeepsTopicEmpty(TestContext ctx) {
  final String topicName = "transactionalProduceAbort";
  final Async done = ctx.async();

  producer.initTransactions(ctx.asyncAssertSuccess());
  producer.beginTransaction(ctx.asyncAssertSuccess());
  final ProducerRecord<String, String> record_0 = createRecord(topicName, 0);
  producer.write(record_0, whenWritten -> {
    producer.abortTransaction(ctx.asyncAssertSuccess());
    final KafkaReadStream<String, String> consumer = consumer(topicName);
    consumer.exceptionHandler(ctx::fail);
    consumer.subscribe(Collections.singleton(topicName));
    consumer.poll(Duration.ofSeconds(5), records -> {
      ctx.assertTrue(records.result().isEmpty());
      done.complete();
    });
  });
}
 
Example #10
Source File: MutinySessionTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void reactiveFindThenWriteLock(TestContext context) {
	final GuineaPig expectedPig = new GuineaPig( 5, "Aloi" );
	test(
			context,
			populateDB()
					.flatMap( v -> openSession() )
					.flatMap( session -> session.find( GuineaPig.class, expectedPig.getId() )
							.flatMap( pig -> session.lock(pig, LockMode.PESSIMISTIC_WRITE).map( v -> pig ) )
							.onItem().invoke( actualPig -> {
								assertThatPigsAreEqual( context, expectedPig, actualPig );
								context.assertEquals( session.getLockMode( actualPig ), LockMode.PESSIMISTIC_WRITE );
							} )
							.on().termination( (v, err, c) -> session.close() )
					)
	);
}
 
Example #11
Source File: PetStoreTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 2000)
public void testGetOrderById(TestContext context) {
    Async async = context.async();
    httpClient.getNow(TEST_PORT, TEST_HOST, "/v2/store/order/1", response -> {
        response.bodyHandler(body -> {
            JsonObject jsonObject = new JsonObject(body.toString());
            try {
                Order resultOrder = Json.mapper.readValue(jsonObject.encode(), Order.class);
                context.assertEquals(orderDog, resultOrder);
            } catch (Exception e) {
                context.fail(e);
            }
            async.complete();
        });
        response.exceptionHandler(err -> {
            context.fail(err);
        });
    });
}
 
Example #12
Source File: TenantLoadingTest.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoOkapiUrlTo(TestContext context) {
  Async async = context.async();
  List<Parameter> parameters = new LinkedList<>();
  parameters.add(new Parameter().withKey("loadRef").withValue("true"));
  TenantAttributes tenantAttributes = new TenantAttributes()
    .withModuleTo("mod-1.0.0")
    .withParameters(parameters);
  Map<String, String> headers = new HashMap<String, String>();

  TenantLoading tl = new TenantLoading();
  tl.addJsonIdContent("loadRef", "tenant-load-ref", "data", "data");
  tl.perform(tenantAttributes, headers, vertx, res -> {
    context.assertTrue(res.failed());
    context.assertEquals("No X-Okapi-Url header", res.cause().getLocalizedMessage());
    async.complete();
  });
}
 
Example #13
Source File: DirectoryConfigStoreTest.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testWith2FileSetsAndNoIntersection(TestContext context) {
  Async async = context.async();
  retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions()
      .addStore(new ConfigStoreOptions()
          .setType("directory")
          .setConfig(new JsonObject().put("path", "src/test/resources")
              .put("filesets", new JsonArray()
                  .add(new JsonObject().put("pattern", "file/reg*.json"))
                  .add(new JsonObject().put("pattern", "dir/a.*son"))
              ))));
  retriever.getConfig(ar -> {
    ConfigChecker.check(ar);
    assertThat(ar.result().getString("a.name")).isEqualTo("A");
    async.complete();
  });
}
 
Example #14
Source File: SimpleQueryDataTypeCodecTestBase.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
protected <T> void testDecodeXXXArray(TestContext ctx,
                                      String columnName,
                                      String tableName,
                                      ColumnChecker.SerializableBiFunction<Tuple, Integer, Object> byIndexGetter,
                                      ColumnChecker.SerializableBiFunction<Row, String, Object> byNameGetter,
                                      Object... expected) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.query("SET TIME ZONE 'UTC'").execute(
      ctx.asyncAssertSuccess(res -> {
        conn.query("SELECT \"" + columnName + "\" FROM \"" + tableName + "\" WHERE \"id\" = 1").execute(
          ctx.asyncAssertSuccess(result -> {
            ColumnChecker.checkColumn(0, columnName)
              .returns(Tuple::getValue, Row::getValue, expected)
              .returns(byIndexGetter, byNameGetter, expected)
              .forRow(result.iterator().next());
            async.complete();
          }));
      }));
  }));
}
 
Example #15
Source File: NumericTypesSimpleCodecTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerial8(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn
      .query("SELECT \"BigSerial\" FROM \"NumericDataType\" WHERE \"id\" = 1").execute(ctx.asyncAssertSuccess(result -> {
        ctx.assertEquals(1, result.size());
        ctx.assertEquals(1, result.rowCount());
        Row row = result.iterator().next();
        ColumnChecker.checkColumn(0, "BigSerial")
          .returns(Tuple::getValue, Row::getValue, 1L)
          .returns(Tuple::getShort, Row::getShort, (short) 1)
          .returns(Tuple::getInteger, Row::getInteger, 1)
          .returns(Tuple::getLong, Row::getLong, 1L)
          .returns(Tuple::getFloat, Row::getFloat, 1f)
          .returns(Tuple::getDouble, Row::getDouble, 1d)
          .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(1))
          .returns(Numeric.class, Numeric.create(1))
          .forRow(row);
        async.complete();
      }));
  }));
}
 
Example #16
Source File: DateTimeTypesExtendedCodecTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeLocalTimeArray(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.prepare("UPDATE \"ArrayDataType\" SET \"LocalTime\" = $1  WHERE \"id\" = $2 RETURNING \"LocalTime\"",
      ctx.asyncAssertSuccess(p -> {
        final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss.SSSSS");
        final LocalTime dt = LocalTime.parse("17:55:04.90512", dtf);
        p.query().execute(Tuple.tuple()
            .addLocalTimeArray(new LocalTime[]{dt})
            .addInteger(2)
          , ctx.asyncAssertSuccess(result -> {
            ColumnChecker.checkColumn(0, "LocalTime")
              .returns(Tuple::getValue, Row::getValue, new LocalTime[]{dt})
              .returns(Tuple::getLocalTimeArray, Row::getLocalTimeArray, new LocalTime[]{dt})
              .forRow(result.iterator().next());
            async.complete();
          }));
      }));
  }));
}
 
Example #17
Source File: PebbleTemplateTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateHandlerChangeExtension(TestContext should) {
  final Async test = should.async();
  TemplateEngine engine = PebbleTemplateEngine.create(vertx, "beb");

  final JsonObject context = new JsonObject()
    .put("foo", "badger")
    .put("bar", "fox")
    .put("context", new JsonObject().put("path", "/test-pebble-template2.peb"));

  engine.render(context, "somedir/test-pebble-template2", render -> {
    should.assertTrue(render.succeeded());
    should.assertEquals("Cheerio badger and foxRequest path is /test-pebble-template2.peb", render.result().toString());
    test.complete();
  });
  test.await();
}
 
Example #18
Source File: ProcessModuleHandleTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@Test
public void test1a(TestContext context) {
  final Async async = context.async();
  LaunchDescriptor desc = new LaunchDescriptor();
  // program starts OK, but do not listen to port..
  desc.setExec("java -version %p");
  ModuleHandle mh = createModuleHandle(desc, 9231);

  mh.start(res -> {
    if (res.succeeded()) { // error did not expect to succeed!
      mh.stop(res2 -> {
        context.assertTrue(res2.succeeded());
        context.assertFalse(res.failed());
        async.complete();
      });
    }
    context.assertFalse(res.succeeded());
    String msg = res.cause().getMessage();
    context.assertTrue(msg.startsWith("Deployment failed. Could not connect to port 9231"));
    async.complete();
  });
}
 
Example #19
Source File: VertxCompletableFutureTest.java    From vertx-completable-future with Apache License 2.0 6 votes vote down vote up
@Test
public void testExceptionally(TestContext tc) {
  Async async1 = tc.async();
  Async async2 = tc.async();

  VertxCompletableFuture<Integer> failure = new VertxCompletableFuture<>(vertx);
  VertxCompletableFuture<Integer> success = new VertxCompletableFuture<>(vertx);

  failure.exceptionally(t -> 43).thenAccept(i -> {
    tc.assertEquals(i, 43);
    async1.complete();
  });

  success.exceptionally(t -> 43).thenAccept(i -> {
    tc.assertEquals(i, 42);
    async2.complete();
  });

  success.complete(42);
  failure.completeExceptionally(new RuntimeException("my bad"));

}
 
Example #20
Source File: ChainAuthTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void singleTestAll(TestContext should) {
  final Async test = should.async();
  ChainAuth auth = ChainAuth.all();

  auth.add((authInfo, res) -> {
    // always OK
    res.handle(Future.succeededFuture(createUser(new JsonObject())));
  });

  auth.authenticate(new JsonObject(), res -> {
    if (res.succeeded()) {
      test.complete();
    } else {
      should.fail();
    }
  });
}
 
Example #21
Source File: JsonDataTypeTest.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeStringNull(TestContext ctx) {
  testDecodeJsonWithCast(ctx, "\'\"null\"\'", "null", row -> {
    ctx.assertEquals("null", row.getString(0));
    ctx.assertEquals("null", row.getString("json"));
  });
}
 
Example #22
Source File: CollectorTestBase.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCollectorFailureInAccumulator(TestContext ctx) {
  RuntimeException cause = new RuntimeException();
  testCollectorFailure(ctx, cause, new CollectorBase() {
    @Override
    public BiConsumer<Object, Row> accumulator() {
      return (o, row) -> {
        throw cause;
      };
    }
  });
}
 
Example #23
Source File: MasterKeysTest.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeyReEncrypt(TestContext context) {
    runOnServerContext(context, () -> {
        MasterKeys masterKeys = vertxContext().verticle().masterKeys();
        AtomicReference<byte[]> notExpectedArray = new AtomicReference<>();
        return just((Void) null)
                .flatMap(aVoid -> masterKeys.getPreferredKey(vertxContext()))
                .map(MasterKey::getKeyId)
                .flatMap(new LoadMasterKey(vertxContext()))
                .map(Optional::get)
                .map(pmk -> {
                    assertEquals(context, masterKeys.firstKey(), pmk.getId());
                    Calendar now = getInstance();
                    long thePast = DAYS.toMillis(365);
                    now.setTimeInMillis(thePast);
                    pmk.setReEncrypteTs(now);
                    notExpectedArray.set(pmk.getEncryptedKey().get());
                    return pmk;
                })
                .flatMap(new UpdateMasterKey(vertxContext()))
                .map(Optional::get)
                .map(new ToVoid<>())
                .flatMap(new RefreshIndex(httpClient(), authAdmin))
                .flatMap(aVoid -> masterKeys.maintain(vertxContext()))
                .flatMap(new RefreshIndex(httpClient(), authAdmin))
                .flatMap(new GetNewestMasterKey(vertxContext(), AlgorithmDef.getPreferred()))
                .map(Optional::get)
                .map(pmk -> {
                    assertEquals(context, masterKeys.firstKey(), pmk.getId());
                    byte[] currentArray = pmk.getEncryptedKey().get();
                    assertFalse(context, Arrays.equals(notExpectedArray.get(), currentArray));
                    return pmk;
                })
                .map(new ToVoid<>());
    });
}
 
Example #24
Source File: PreparedQueryTestBase.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrepareError(TestContext ctx) {
  connect(ctx.asyncAssertSuccess(conn -> {
    conn.prepare("SELECT whatever from DOES_NOT_EXIST", ctx.asyncAssertFailure(error -> {
      if (msgVerifier != null) {
        msgVerifier.accept(error);
      }
    }));
  }));
}
 
Example #25
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test()
public void testKoFormDataSimpleRequiredWithEmptyValue(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 400);
            async.complete();
        });
    });
    // Construct form
    StringBuffer payload = new StringBuffer().append("formDataRequired=");
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example #26
Source File: VertxCompletableFutureTest.java    From vertx-completable-future with Apache License 2.0 5 votes vote down vote up
@Test
public void testApplyFailurePropagation(TestContext tc) {
  Async async0 = tc.async();
  Async async1 = tc.async();
  CompletableFuture<Integer> failure1 = new VertxCompletableFuture<>(vertx);
  CompletableFuture<Integer> failure2 = new VertxCompletableFuture<>(vertx);

  failure1.thenApply(i -> {
    tc.fail("Should not be called");
    return 0;
  }).whenComplete((res, err) -> {
    tc.assertEquals(err.getClass(), CompletionException.class);
    tc.assertTrue(err.getMessage().contains("A"));
    async0.complete();
  });

  failure1.applyToEither(failure2, i -> {
    tc.fail("Should not be called");
    return 0;
  }).whenComplete((res, err) -> {
    tc.assertEquals(err.getClass(), CompletionException.class);
    tc.assertTrue(err.getMessage().contains("B"));
    async1.complete();
  });

  failure2.completeExceptionally(new RuntimeException("B"));
  failure1.completeExceptionally(new RuntimeException("A"));

}
 
Example #27
Source File: CascadeComplicatedToOnesEagerTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testPersist(TestContext context) {
	test(
			context,
			openSession()
					.thenCompose(s -> s.persist(b))
					.thenApply( s -> {
						bId = b.id;
						return s;
					})
					.thenCompose(s -> s.flush())
					.thenCompose(ignore -> check( openSession(), context ))
	);
}
 
Example #28
Source File: IntegrationTestBase.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateRx(TestContext testContext) throws Exception {

    final Async async = testContext.async();
    JsonObject source = new JsonObject()
            .put("user", source_user)
            .put("message", source_message)
            .put("obj", new JsonObject()
                    .put("array", new JsonArray()
                            .add("1")
                            .add("2")));

    final IndexOptions options = new IndexOptions().setId(id);
    rxService.index(index, type, source, options)
            .flatMap(indexResponse -> {
                final UpdateOptions updateOptions = new UpdateOptions().setScript("ctx._source.message = 'updated message'", ScriptType.INLINE);
                return rxService.update(index, type, id, updateOptions);
            })
            .flatMap(updateResponse -> rxService.get(index, type, id))
            .subscribe(
                    getResponse -> {
                        assertUpdate(testContext, getResponse);
                        async.complete();
                    },
                    error -> testContext.fail(error)
            );
}
 
Example #29
Source File: NumericDataTypeTest.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testBinaryDecodeUnsignedSmallInt(TestContext ctx) {
  testBinaryDecodeGenericWithTable(ctx, "test_unsigned_smallint", ((row, columnName) -> {
    ctx.assertTrue(row.getValue(0) instanceof Integer);
    ctx.assertEquals(65535, row.getValue(0));
    ctx.assertEquals(65535, row.getValue(columnName));
    ctx.assertEquals(65535, row.getInteger(0));
    ctx.assertEquals(65535, row.getInteger(columnName));
    ctx.assertEquals(65535L, row.getLong(0));
    ctx.assertEquals(65535L, row.getLong(columnName));
    ctx.assertEquals(new BigDecimal(65535), row.getBigDecimal(0));
    ctx.assertEquals(new BigDecimal(65535), row.getBigDecimal(columnName));
  }));
}
 
Example #30
Source File: IntegrationTestBase.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(TestContext testContext) throws Exception {
    config = readConfig();
    configure(config);

    deployVerticle(testContext, getVerticleName(), new DeploymentOptions().setConfig(config));

    service = ElasticSearchService.createEventBusProxy(vertx, "et.elasticsearch");
    adminService = ElasticSearchAdminService.createEventBusProxy(vertx, "et.elasticsearch.admin");
    rxService = new DefaultRxElasticSearchService(service);
    rxAdminService = new DefaultRxElasticSearchAdminService(adminService);
    rx2Service = new DefaultRx2ElasticSearchService(service);
    rx2AdminService = new DefaultRx2ElasticSearchAdminService(adminService);

    final CountDownLatch latch = new CountDownLatch(1);
    adminService.deleteIndex(index, deleteIndexResult -> {
        adminService.createIndex(index, new JsonObject(), new CreateIndexOptions(), createMappingResult -> {
            adminService.putMapping(index, type, readJson("mapping.json"), putMappingResult -> {
                if (putMappingResult.failed()) {
                    putMappingResult.cause().printStackTrace();
                    testContext.fail();
                }
                latch.countDown();
            });
        });
    });

    latch.await(15, TimeUnit.SECONDS);
}