org.junit.jupiter.api.DisplayName Java Examples

The following examples show how to use org.junit.jupiter.api.DisplayName. 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: TestSolution2OptionalConditionalFetching.java    From java-katas with MIT License 6 votes vote down vote up
@Test
@DisplayName("return a value either from non-empty Optional or from a Supplier")
@Tag("PASSING")
@Order(3)
public void orElseGetSupplierValue() {

    String defaultOptional = "supplied";
    Optional<String> anOptional = Optional.empty();

    /*
     * DONE:
     *  Replace the below to use an orElseGet(?) - instead of - the or(?)
     *  and the need to use get()
     *  Check API: java.util.Optional.ofNullable(?)
     */
    String nonNullString = anOptional.orElseGet(() -> defaultOptional);

    assertTrue(nonNullString instanceof String,
            "The nonNullString should be an instance of String");

    assertEquals(nonNullString,
            "supplied",
            "The nonNullString should have a value of \"supplied\"");
}
 
Example #2
Source File: IdStrategyTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("test PartialKeyStrategy with Allow List")
void testPartialKeyStrategyAllowList() {
  BsonDocument keyDoc = BsonDocument.parse("{keyPart1: 123, keyPart2: 'ABC', keyPart3: true}");
  BsonDocument expected = BsonDocument.parse("{keyPart1: 123}");

  MongoSinkTopicConfig cfg =
      createTopicConfig(
          format(
              "{'%s': '%s', '%s': 'keyPart1'}",
              DOCUMENT_ID_STRATEGY_PARTIAL_KEY_PROJECTION_TYPE_CONFIG,
              ALLOWLIST,
              DOCUMENT_ID_STRATEGY_PARTIAL_KEY_PROJECTION_LIST_CONFIG));

  IdStrategy ids = new PartialKeyStrategy();
  ids.configure(cfg);
  SinkDocument sd = new SinkDocument(keyDoc, null);
  BsonValue id = ids.generateId(sd, null);

  assertAll(
      "id checks",
      () -> assertTrue(id instanceof BsonDocument),
      () -> assertEquals(expected, id.asDocument()));
  assertEquals(new BsonDocument(), ids.generateId(new SinkDocument(null, null), null));
}
 
Example #3
Source File: BinarySerialiserTests.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
@DisplayName("test getGenericArrayAsBoxedPrimitive(...) helper method")
@ParameterizedTest(name = "IoBuffer class - {0}")
@ValueSource(classes = { FastByteBuffer.class, ByteBuffer.class })
public void testgetGenericArrayAsBoxedPrimitiveHelper(final Class<? extends IoBuffer> bufferClass) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
    assertNotNull(bufferClass, "bufferClass being not null");
    assertNotNull(bufferClass.getConstructor(int.class), "Constructor(Integer) present");
    final IoBuffer buffer = bufferClass.getConstructor(int.class).newInstance(2 * BUFFER_SIZE); // a bit larger buffer since we test more cases at once

    putGenericTestArrays(buffer);

    buffer.reset();

    // test conversion to double array
    assertThrows(IllegalArgumentException.class, () -> BinarySerialiser.getGenericArrayAsBoxedPrimitive(buffer, DataType.OTHER));

    assertArrayEquals(new Boolean[] { true, false, true }, BinarySerialiser.getGenericArrayAsBoxedPrimitive(buffer, DataType.BOOL));
    assertArrayEquals(new Byte[] { (byte) 1.0, (byte) 0.0, (byte) 2.0 }, BinarySerialiser.getGenericArrayAsBoxedPrimitive(buffer, DataType.BYTE));
    assertArrayEquals(new Character[] { (char) 1.0, (char) 0.0, (char) 2.0 }, BinarySerialiser.getGenericArrayAsBoxedPrimitive(buffer, DataType.CHAR));
    assertArrayEquals(new Short[] { (short) 1.0, (short) 0.0, (short) 2.0 }, BinarySerialiser.getGenericArrayAsBoxedPrimitive(buffer, DataType.SHORT));
    assertArrayEquals(new Integer[] { (int) 1.0, (int) 0.0, (int) 2.0 }, BinarySerialiser.getGenericArrayAsBoxedPrimitive(buffer, DataType.INT));
    assertArrayEquals(new Long[] { (long) 1.0, (long) 0.0, (long) 2.0 }, BinarySerialiser.getGenericArrayAsBoxedPrimitive(buffer, DataType.LONG));
    assertArrayEquals(new Float[] { 1.0f, 0.0f, 2.0f }, BinarySerialiser.getGenericArrayAsBoxedPrimitive(buffer, DataType.FLOAT));
    assertArrayEquals(new Double[] { 1.0, 0.0, 2.0 }, BinarySerialiser.getGenericArrayAsBoxedPrimitive(buffer, DataType.DOUBLE));
    assertArrayEquals(new String[] { "1.0", "0.0", "2.0" }, BinarySerialiser.getGenericArrayAsBoxedPrimitive(buffer, DataType.STRING));
}
 
Example #4
Source File: TestKata1OptionalCreationAndFetchingValues.java    From java-katas with MIT License 6 votes vote down vote up
@Test
@DisplayName("create an Optional from a variable")
@Tag("TODO")
@Order(2)
public void createOptionalFromValue() {

    Integer anInteger = 10;

    /*
     * TODO:
     *  Replace the "null" to create an Optional for anInteger.
     *  Check API: java.util.Optional.of(?)
     */
    Optional<Integer> optionalForInteger = null;

    assertTrue(optionalForInteger instanceof Optional,
            "The optionalEmptyString should be an instance of Optional");

    assertFalse(optionalForInteger.isEmpty(),
            "The optionalForInteger should not be empty");
}
 
Example #5
Source File: BinarySerialiserTests.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
@DisplayName("test getDoubleArray([boolean[], byte[], ..., String[]) helper method")
@ParameterizedTest(name = "IoBuffer class - {0}")
@ValueSource(classes = { FastByteBuffer.class, ByteBuffer.class })
public void testGetDoubleArrayHelper(final Class<? extends IoBuffer> bufferClass) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
    assertNotNull(bufferClass, "bufferClass being not null");
    assertNotNull(bufferClass.getConstructor(int.class), "Constructor(Integer) present");
    final IoBuffer buffer = bufferClass.getConstructor(int.class).newInstance(2 * BUFFER_SIZE); // a bit larger buffer since we test more cases at once

    putGenericTestArrays(buffer);

    buffer.reset();

    // test conversion to double array
    assertThrows(IllegalArgumentException.class, () -> BinarySerialiser.getDoubleArray(buffer, DataType.OTHER));
    assertArrayEquals(new double[] { 1.0, 0.0, 1.0 }, BinarySerialiser.getDoubleArray(buffer, DataType.BOOL_ARRAY));
    assertArrayEquals(new double[] { 1.0, 0.0, 2.0 }, BinarySerialiser.getDoubleArray(buffer, DataType.BYTE_ARRAY));
    assertArrayEquals(new double[] { 1.0, 0.0, 2.0 }, BinarySerialiser.getDoubleArray(buffer, DataType.CHAR_ARRAY));
    assertArrayEquals(new double[] { 1.0, 0.0, 2.0 }, BinarySerialiser.getDoubleArray(buffer, DataType.SHORT_ARRAY));
    assertArrayEquals(new double[] { 1.0, 0.0, 2.0 }, BinarySerialiser.getDoubleArray(buffer, DataType.INT_ARRAY));
    assertArrayEquals(new double[] { 1.0, 0.0, 2.0 }, BinarySerialiser.getDoubleArray(buffer, DataType.LONG_ARRAY));
    assertArrayEquals(new double[] { 1.0, 0.0, 2.0 }, BinarySerialiser.getDoubleArray(buffer, DataType.FLOAT_ARRAY));
    assertArrayEquals(new double[] { 1.0, 0.0, 2.0 }, BinarySerialiser.getDoubleArray(buffer, DataType.DOUBLE_ARRAY));
    assertArrayEquals(new double[] { 1.0, 0.0, 2.0 }, BinarySerialiser.getDoubleArray(buffer, DataType.STRING_ARRAY));
}
 
Example #6
Source File: MongoDbUpdateTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName(
    "when valid doc change cdc event containing internal oplog fields then correct UpdateOneModel")
public void testValidSinkDocumentWithInternalOploagFieldForUpdate() {
  BsonDocument keyDoc = BsonDocument.parse("{id: '1234'}");
  BsonDocument valueDoc =
      new BsonDocument("op", new BsonString("u"))
          .append("patch", new BsonString(UPDATE_DOC_WITH_OPLOG_INTERNALS.toJson()));

  WriteModel<BsonDocument> result = UPDATE.perform(new SinkDocument(keyDoc, valueDoc));
  assertTrue(
      result instanceof UpdateOneModel, () -> "result expected to be of type UpdateOneModel");

  UpdateOneModel<BsonDocument> writeModel = (UpdateOneModel<BsonDocument>) result;
  assertEquals(
      UPDATE_DOC, writeModel.getUpdate(), () -> "update doc not matching what is expected");
  assertTrue(
      writeModel.getFilter() instanceof BsonDocument,
      () -> "filter expected to be of type BsonDocument");
  assertEquals(FILTER_DOC, writeModel.getFilter());
}
 
Example #7
Source File: IirFilterTests.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
@DisplayName("Butterworth - High-Pass")
@ParameterizedTest(name = "{displayName}: filter-order: {0}, algorithm: {1}")
@CsvSource({ "2, 0", "3, 0", "4, 0", "2, 1", "3, 1", "4, 1", "2, 2", "3, 2", "4, 2" })
public void testButterworthHighPass(final int filterOrder, final int algorithmVariant) {
    final Butterworth iirHighPass = new Butterworth();
    switch (algorithmVariant) {
    case 1:
        iirHighPass.highPass(filterOrder, 1.0, F_CUT_HIGH, DirectFormAbstract.DIRECT_FORM_I);
        break;
    case 2:
        iirHighPass.highPass(filterOrder, 1.0, F_CUT_HIGH, DirectFormAbstract.DIRECT_FORM_II);
        break;
    case 0:
    default:
        iirHighPass.highPass(filterOrder, 1.0, F_CUT_HIGH);
        break;
    }

    final DataSet magHighPass = filterAndGetMagnitudeSpectrum(iirHighPass, demoDataSet);
    assertThat("high-pass cut-off", magHighPass.getValue(DIM_X, F_CUT_HIGH), lessThan(-3.0 + EPSILON_DB));
    assertThat("high-pass rejection", magHighPass.getValue(DIM_X, 0.1 * F_CUT_HIGH), lessThan(-3.0 + EPSILON_DB - 20 * filterOrder));
    assertThat("high-pass pass-band ripple", getRange(magHighPass, (int) (N_SAMPLES_FFT * 0.95), N_SAMPLES_FFT), lessThan(EPSILON_DB));
}
 
Example #8
Source File: SinkDocumentTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("test SinkDocument clone with missing key / value")
void testCloneNoKeyValue() {

  SinkDocument orig = new SinkDocument(null, null);

  assertAll(
      "orig key/value docs NOT present",
      () -> assertFalse(orig.getKeyDoc().isPresent()),
      () -> assertFalse(orig.getValueDoc().isPresent()));

  SinkDocument clone = orig.clone();

  assertAll(
      "clone key/value docs NOT present",
      () -> assertFalse(clone.getKeyDoc().isPresent()),
      () -> assertFalse(clone.getValueDoc().isPresent()));
}
 
Example #9
Source File: RdbmsDeleteTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("when valid cdc event with single field PK then correct DeleteOneModel")
void testValidSinkDocumentSingleFieldPK() {
  BsonDocument filterDoc = BsonDocument.parse("{_id: {id: 1004}}");
  BsonDocument keyDoc = BsonDocument.parse("{id: 1004}");
  BsonDocument valueDoc = BsonDocument.parse("{op: 'd'}");

  WriteModel<BsonDocument> result = RDBMS_DELETE.perform(new SinkDocument(keyDoc, valueDoc));
  assertTrue(result instanceof DeleteOneModel, "result expected to be of type DeleteOneModel");

  DeleteOneModel<BsonDocument> writeModel = (DeleteOneModel<BsonDocument>) result;
  assertTrue(
      writeModel.getFilter() instanceof BsonDocument,
      "filter expected to be of type BsonDocument");
  assertEquals(filterDoc, writeModel.getFilter());
}
 
Example #10
Source File: WriteModelStrategyTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName(
    "when sink document is valid for DeleteOneDefaultStrategy then correct DeleteOneModel")
void testDeleteOneDefaultStrategyWitValidSinkDocument() {

  BsonDocument keyDoc = BsonDocument.parse("{id: 1234}");

  WriteModel<BsonDocument> result =
      DELETE_ONE_DEFAULT_STRATEGY.createWriteModel(new SinkDocument(keyDoc, null));

  assertTrue(result instanceof DeleteOneModel, "result expected to be of type DeleteOneModel");

  DeleteOneModel<BsonDocument> writeModel = (DeleteOneModel<BsonDocument>) result;

  assertTrue(
      writeModel.getFilter() instanceof BsonDocument,
      "filter expected to be of type BsonDocument");

  assertEquals(FILTER_DOC_DELETE_DEFAULT, writeModel.getFilter());
}
 
Example #11
Source File: RenamerTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("simple field renamer test with custom field name mappings")
void testRenamerUsingFieldnameMapping() {
  BsonDocument expectedKeyDoc =
      BsonDocument.parse(
          "{'f1': 'my field value', "
              + "'fieldB': true, 'subDoc': {'name_x': 42}, 'my_field1': {'my_field2': 'testing rocks!'}}");
  BsonDocument expectedValueDoc =
      BsonDocument.parse(
          "{'xyz': 'my field value', 'f_two': false, "
              + "'subDoc': {'789': 0.0}, 'foo.foo.foo': {'.blah..blah.': 23}}");
  MongoSinkTopicConfig cfg =
      createTopicConfig(
          FIELD_RENAMER_MAPPING_CONFIG,
          "[{'oldName':'key.fieldA','newName':'f1'}, {'oldName':'key.f2','newName':'fieldB'}, "
              + "{'oldName':'key.subDoc.fieldX','newName':'name_x'}, {'oldName':'key.fieldA','newName':'f1'}, "
              + "{'oldName':'value.abc','newName':'xyz'}, {'oldName':'value.f2','newName':'f_two'}, "
              + "{'oldName':'value.subDoc.123','newName':'789'}]");

  SinkDocument sd = new SinkDocument(keyDoc, valueDoc);
  Renamer renamer = new RenameByMapping(cfg);
  renamer.process(sd, null);

  assertAll(
      "key and value doc checks",
      () -> assertEquals(expectedKeyDoc, sd.getKeyDoc().orElse(new BsonDocument())),
      () -> assertEquals(expectedValueDoc, sd.getValueDoc().orElse(new BsonDocument())));
}
 
Example #12
Source File: KafkaMetaAdderTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("test KafkaMetaAdder null values")
void testKafkaMetaAdderNullValues() {
  SinkDocument sinkDocWithoutValueDoc = new SinkDocument(null, null);
  new KafkaMetaAdder(createTopicConfig()).process(sinkDocWithoutValueDoc, null);
  assertFalse(
      sinkDocWithoutValueDoc.getValueDoc().isPresent(), "no _id added since valueDoc was not");
}
 
Example #13
Source File: CarrinhoTest.java    From acelera-dev-brasil-2019-01 with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Nao deve esvaziar o estoque quando tiver erro no pagamento")
public void naoDeveTerPorqueNaoPagou() {
    Produto produto = new Produto("Banana");
    Mockito.when(estoque.temProdutos(produto)).thenReturn(true);
    Mockito.when(pagamento.pagar(produto))
            .thenThrow(new PagamentoException("houve um error no pagamento"));
    carrinho.adicionar(produto);

    PagamentoException pagamentoException = assertThrows(PagamentoException.class, carrinho::comprar);
    Mockito.verify(estoque, Mockito.never()).reduzirProdutos(produto);

}
 
Example #14
Source File: MongoSinkConfigTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("test topics")
void testTopics() {
  assertAll(
      "topics",
      () ->
          assertEquals(
              singletonList("a"),
              createSinkConfig(TOPICS_CONFIG, "a").getTopics().orElse(emptyList())),
      () ->
          assertEquals(
              asList("a", "b", "c"),
              createSinkConfig(TOPICS_CONFIG, "a,b,c").getTopics().orElse(emptyList())),
      () -> assertInvalid(TOPICS_CONFIG, ""));
}
 
Example #15
Source File: GITMergeUnitTest.java    From MergeProcessor with Apache License 2.0 5 votes vote down vote up
@DisplayName("Tests compareTo() using null as parameter")
@Test
public void testCompareToWithNull() {
	final GITMergeUnit unit = new GITMergeUnit(DEFAULT_TEST_HOST, DEFAULT_REPOSITORY, LocalDateTime.now(),
			DEFAULT_COMMIT_ID, DEFAULT_BRANCH_SOURCE, DEFAULT_BRANCH_TARGET, DEFAULT_FILE_NAME, new ArrayList<>(0),
			new JUnitConfiguration());
	assertNotEquals(0, unit.compareTo(null));
}
 
Example #16
Source File: MongoSinkConnnectorTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("test task configs")
void testConfig() {
  MongoSinkConnector sinkConnector = new MongoSinkConnector();

  assertEquals(MongoSinkConfig.CONFIG, sinkConnector.config());
}
 
Example #17
Source File: MongoSinkConfigTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("test invalid change data capture handler names")
void testInvalidChangeDataCaptureHandlerNames() {
  assertAll(
      "with invalid projection type",
      () -> assertInvalid(CHANGE_DATA_CAPTURE_HANDLER_CONFIG, "not a class format"),
      () ->
          assertInvalid(CHANGE_DATA_CAPTURE_HANDLER_CONFIG, "com.example.kafka.test.CDCHandler"));
}
 
Example #18
Source File: AbstractDownloaderTest.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Keep signature files")
void keepSignatureFiles() throws Exception {
    downloaderProperties.setKeepSignatures(true);
    fileCopier.copy();
    downloader.download();
    assertThat(Files.walk(downloaderProperties.getSignaturesPath()))
            .filteredOn(p -> !p.toFile().isDirectory())
            .hasSizeGreaterThan(0)
            .allMatch(p -> isSigFile(p));
}
 
Example #19
Source File: StringValueProducerTest.java    From JsonTemplate with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("select a string from a list of enumerated string values")
void testProduceWithListParam() {
    List<String> strings = Arrays.asList("A", "B", "C");
    String producedValue = producer.produce(strings).compactString();
    assertThat(producedValue, isIn(Arrays.asList("\"A\"", "\"B\"", "\"C\"")));
}
 
Example #20
Source File: IirFilterTests.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
@DisplayName("ChebyshevI - Band-Stop")
@ParameterizedTest(name = "{displayName}: filter-order: {0}, algorithm: {1}")
@CsvSource({ "2, 0", "3, 0", "4, 0", "2, 1", "3, 1", "4, 1", "2, 2", "3, 2", "4, 2" })
public void testChebyshevIBandStop(final int filterOrder, final int algorithmVariant) {
    final ChebyshevI iirBandStop = new ChebyshevI();
    switch (algorithmVariant) {
    case 1:
        iirBandStop.bandStop(filterOrder, 1.0, F_BAND_CENTRE, F_BAND_WIDTH, ALLOWED_IN_BAND_RIPPLE_DB, DirectFormAbstract.DIRECT_FORM_I);
        break;
    case 2:
        iirBandStop.bandStop(filterOrder, 1.0, F_BAND_CENTRE, F_BAND_WIDTH, ALLOWED_IN_BAND_RIPPLE_DB, DirectFormAbstract.DIRECT_FORM_II);
        break;
    case 0:
    default:
        iirBandStop.bandStop(filterOrder, 1.0, F_BAND_CENTRE, F_BAND_WIDTH, ALLOWED_IN_BAND_RIPPLE_DB);
        break;
    }

    final DataSet magBandStop = filterAndGetMagnitudeSpectrum(iirBandStop, demoDataSet);
    assertThat("band-stop cut-off (low)", magBandStop.getValue(DIM_X, F_BAND_START), lessThan(-3.0 + EPSILON_DB));
    assertThat("band-stop cut-off (high)", magBandStop.getValue(DIM_X, F_BAND_STOP), lessThan(-3.0 + EPSILON_DB));
    assertThat("band-pass pass-band (low)", getRange(magBandStop, 0, magBandStop.getIndex(DIM_X, F_BAND_START * 0.1)), lessThan(ALLOWED_IN_BAND_RIPPLE_DB + EPSILON_DB));
    assertThat("band-pass pass-band (high)", getRange(magBandStop, (int) (N_SAMPLES_FFT * 0.95), N_SAMPLES_FFT), lessThan(ALLOWED_IN_BAND_RIPPLE_DB + EPSILON_DB));
    final double rangeStopBand = getMaximum(magBandStop,
            magBandStop.getIndex(DIM_X, (F_BAND_CENTRE - 0.03 * F_BAND_WIDTH)),
            magBandStop.getIndex(DIM_X, (F_BAND_CENTRE + 0.03 * F_BAND_WIDTH)));
    assertThat("band-pass stop-band ripple", rangeStopBand, lessThan(-3.0 + EPSILON_DB - 20 * filterOrder));
}
 
Example #21
Source File: Neo4jDataAutoConfigurationTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("…should not replace existing Neo4j Operations")
void shouldNotReplaceExisting() {
	contextRunner
		.withUserConfiguration(ConfigurationWithExistingTemplate.class)
		.run(ctx -> assertThat(ctx)
			.hasSingleBean(Neo4jOperations.class)
			.hasBean("myCustomOperations")
		);
}
 
Example #22
Source File: MongoCopyDataManagerTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("test returns the expected collection results")
void testReturnsTheExpectedCollectionResults() {
  BsonDocument result =
      BsonDocument.parse(
          "{'_id': {'_id': 1, 'copy': true}, "
              + "'operationType': 'insert', 'ns': {'db': 'myDB', 'coll': 'myColl'}, "
              + "'documentKey': {'_id': 1}, "
              + "'fullDocument': {'_id': 1, 'a': 'a', 'b': 121}}");

  when(mongoClient.getDatabase(TEST_DATABASE)).thenReturn(mongoDatabase);
  when(mongoDatabase.getCollection(TEST_COLLECTION, BsonDocument.class))
      .thenReturn(mongoCollection);
  when(mongoCollection.aggregate(anyList())).thenReturn(aggregateIterable);
  doCallRealMethod().when(aggregateIterable).forEach(any(Consumer.class));
  when(aggregateIterable.iterator()).thenReturn(cursor);
  when(cursor.hasNext()).thenReturn(true, false);
  when(cursor.next()).thenReturn(result);

  List<Optional<BsonDocument>> results;
  try (MongoCopyDataManager copyExistingDataManager =
      new MongoCopyDataManager(createSourceConfig(), mongoClient)) {
    sleep();
    results = asList(copyExistingDataManager.poll(), copyExistingDataManager.poll());
  }

  List<Optional<BsonDocument>> expected = asList(Optional.of(result), Optional.empty());
  assertEquals(expected, results);
}
 
Example #23
Source File: Neo4jDataAutoConfigurationTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("…should not replace existing Neo4j Client")
void shouldNotReplaceExisting() {
	contextRunner
		.withUserConfiguration(ConfigurationWithExistingClient.class)
		.run(ctx -> assertThat(ctx)
			.hasSingleBean(Neo4jClient.class)
			.hasBean("myCustomClient")
		);
}
 
Example #24
Source File: Base64ValueProducerTest.java    From JsonTemplate with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("generate a base64 string with the expected length which can be mod by 4")
void produceWithParamLengthModBy4() {
    Map<String, String> mapParam = new HashMap<>();
    mapParam.put("length", "40");
    String base64String = producer.produce(mapParam).compactString();
    int expectedLength = 40 + 2; // 2 for quotes
    assertThat(base64String.length(), is(expectedLength));
}
 
Example #25
Source File: AWSXRayTracerTests.java    From java-xray-tracer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("store a reference to the current span")
void storeReference() {
    final Scope scope = tracer
        .buildSpan("simple-span")
        .startActive(true);

    assertNotNull(tracer.activeSpan());
    assertNotNull(tracer.scopeManager().active().span());

    assertEquals(tracer.activeSpan(), scope.span());
    assertEquals(tracer.scopeManager().active().span(), scope.span());

    scope.close();
}
 
Example #26
Source File: RecordFileDownloaderTest.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Non-unanimous consensus reached")
void partialConsensus() throws Exception {
    fileCopier.filterDirectories("*0.0.3").filterDirectories("*0.0.4").filterDirectories("*0.0.5").copy();
    downloader.download();
    verify(applicationStatusRepository).updateStatusValue(
            ApplicationStatusCode.LAST_VALID_DOWNLOADED_RECORD_FILE, "2019-08-30T18_10_00.419072Z.rcd");
    verify(applicationStatusRepository).updateStatusValue(
            ApplicationStatusCode.LAST_VALID_DOWNLOADED_RECORD_FILE, "2019-08-30T18_10_05.249678Z.rcd");
    verify(applicationStatusRepository, times(2)).updateStatusValue(
            eq(ApplicationStatusCode.LAST_VALID_DOWNLOADED_RECORD_FILE_HASH), any());
    assertValidFiles(List.of("2019-08-30T18_10_05.249678Z.rcd", "2019-08-30T18_10_00.419072Z.rcd"));
}
 
Example #27
Source File: MongoSinkConfigTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("test topics and topic regex")
void testTopicsAndTopicRegex() {
  Map<String, String> configMap = createConfigMap();
  configMap.put(TOPICS_REGEX_CONFIG, ".*");
  assertInvalid(TOPICS_CONFIG, configMap);
}
 
Example #28
Source File: RdbmsInsertTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("when valid cdc event without PK then correct ReplaceOneModel")
void testValidSinkDocumentNoPK() {
  BsonDocument valueDocCreate =
      BsonDocument.parse("{op: 'c', after: {text: 'misc', active: false}}");
  verifyResultsNoPK(valueDocCreate);

  BsonDocument valueDocRead =
      BsonDocument.parse("{op: 'r', after: {text: 'misc', active: false}}");
  verifyResultsNoPK(valueDocRead);
}
 
Example #29
Source File: ConnectorValidationTest.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Ensure source configuration validation handles invalid user")
void testSourceConfigValidationInvalidUser() {
  assertInvalidSource(
      createSourceProperties(
          format(
              "mongodb://fakeUser:fakePass@%s/",
              String.join(",", getConnectionString().getHosts()))));
}
 
Example #30
Source File: TestKata2OptionalConditionalFetching.java    From java-katas with MIT License 5 votes vote down vote up
@Test
@DisplayName("return a value either from non-empty Optional or throw Custom Exception")
@Tag("TODO")
@Order(5)
public void orElseThrowCustomException() {

    Optional<String> anOptional = Optional.empty();

    String exceptionMessage = "Empty value";

    Supplier<RuntimeException> exceptionSupplier = () -> new RuntimeException(exceptionMessage);

    /*
     * TODO:
     *  Replace the below to use an orElseThrow() - instead of - the get()
     *  Check API: java.util.Optional.orElseThrow(?)
     */
    Exception caughtException = assertThrows(
            RuntimeException.class,
            () -> {
                String nonNullString = null;

            });

    assertEquals("Empty value",
            caughtException.getMessage(),
            "The custom exception should have benn thrown");

}