org.junit.jupiter.api.DynamicTest Java Examples

The following examples show how to use org.junit.jupiter.api.DynamicTest. 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: ChangeTopicCaseTest.java    From kafka-connect-transform-common with Apache License 2.0 6 votes vote down vote up
@TestFactory
public Stream<DynamicTest> apply() {
  return Arrays.asList(
      of(CaseFormat.UPPER_UNDERSCORE, "TOPIC_NAME", CaseFormat.LOWER_CAMEL, "topicName"),
      of(CaseFormat.LOWER_CAMEL, "topicName", CaseFormat.UPPER_UNDERSCORE, "TOPIC_NAME"),
      of(CaseFormat.LOWER_HYPHEN, "topic-name", CaseFormat.LOWER_UNDERSCORE, "topic_name")
  ).stream()
      .map(t -> DynamicTest.dynamicTest(t.toString(), () -> {
        final Map<String, String> settings = ImmutableMap.of(
            ChangeTopicCaseConfig.FROM_CONFIG, t.from.toString(),
            ChangeTopicCaseConfig.TO_CONFIG, t.to.toString()
        );
        this.transformation.configure(settings);
        final SinkRecord input = record(t.input);
        final SinkRecord actual = this.transformation.apply(input);
        assertNotNull(actual, "actual should not be null.");
        assertEquals(t.expected, actual.topic(), "topic does not match.");
      }));
}
 
Example #2
Source File: BrowserLogCleanningListenerTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@TestFactory
Stream<DynamicTest> testCleanBeforeNavigate()
{
    WebDriver driver = mock(WebDriver.class, withSettings().extraInterfaces(HasCapabilities.class));
    Consumer<Runnable> test = methodUnderTest ->
    {
        Options options = mock(Options.class);
        when(driver.manage()).thenReturn(options);
        Logs logs = mock(Logs.class);
        when(options.logs()).thenReturn(logs);
        when(logs.get(LogType.BROWSER)).thenReturn(mock(LogEntries.class));
        methodUnderTest.run();
    };
    return Stream.of(
            dynamicTest("beforeNavigateBack", () -> test.accept(() -> listener.beforeNavigateBack(driver))),
            dynamicTest("beforeNavigateForward", () -> test.accept(() -> listener.beforeNavigateForward(driver))),
            dynamicTest("beforeNavigateRefresh", () -> test.accept(() -> listener.beforeNavigateRefresh(driver))),
            dynamicTest("beforeNavigateTo", () -> test.accept(() -> listener.beforeNavigateTo("url", driver))));
}
 
Example #3
Source File: RecordBatchesTest.java    From mongo-kafka with Apache License 2.0 6 votes vote down vote up
@TestFactory
@DisplayName("test batching with different config params for max.batch.size")
Stream<DynamicTest> testBatchingWithDifferentConfigsForBatchSize() {

  return Stream.iterate(0, r -> r + 1)
      .limit(NUM_FAKE_RECORDS + 1)
      .map(
          batchSize ->
              dynamicTest(
                  "test batching for "
                      + NUM_FAKE_RECORDS
                      + " records with batchsize="
                      + batchSize,
                  () -> {
                    RecordBatches batches = new RecordBatches(batchSize, NUM_FAKE_RECORDS);
                    assertEquals(LIST_INITIAL_EMPTY, batches.getBufferedBatches());
                    List<SinkRecord> recordList =
                        createSinkRecordList("foo", 0, 0, NUM_FAKE_RECORDS);
                    recordList.forEach(batches::buffer);
                    List<List<SinkRecord>> batchedList =
                        partition(recordList, batchSize > 0 ? batchSize : recordList.size());
                    assertEquals(batchedList, batches.getBufferedBatches());
                  }));
}
 
Example #4
Source File: MetricsCollectorWrapperTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@TestFactory
List<DynamicTest> noop_implementation_never_throws() {
    MetricsCollectorWrapper metricsCollectorWrapper = new NoopMetricsCollectorWrapper();
    return Arrays.asList(
        dynamicTest("newConnection", () -> metricsCollectorWrapper.newConnection(null)),
        dynamicTest("closeConnection", () -> metricsCollectorWrapper.closeConnection(null)),
        dynamicTest("newChannel", () -> metricsCollectorWrapper.newChannel(null)),
        dynamicTest("closeChannel", () -> metricsCollectorWrapper.closeChannel(null)),
        dynamicTest("basicPublish", () -> metricsCollectorWrapper.basicPublish(null)),
        dynamicTest("consumedMessage", () -> metricsCollectorWrapper.consumedMessage(null, 0L, true)),
        dynamicTest("consumedMessage (consumerTag)", () -> metricsCollectorWrapper.consumedMessage(null, 0L, null)),
        dynamicTest("basicAck", () -> metricsCollectorWrapper.basicAck(null, 0L, true)),
        dynamicTest("basicNack", () -> metricsCollectorWrapper.basicNack(null, 0L)),
        dynamicTest("basicReject", () -> metricsCollectorWrapper.basicReject(null, 0L)),
        dynamicTest("basicConsume", () -> metricsCollectorWrapper.basicConsume(null, null, true)),
        dynamicTest("basicCancel", () -> metricsCollectorWrapper.basicCancel(null, null))
    );
}
 
Example #5
Source File: HttpsAndAuthTest.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
@TestFactory
public Stream<DynamicTest> testHerdHttpIsNotAllowedWhenHttpsEnabled() {
    return getTestCases(HTTP_TESTCASES)
            .stream().map(command -> DynamicTest.dynamicTest(COMPONENT + command.getName(), () -> {
                if (!IS_SSLAUTH_ENABLED) {
                    LogVerification("Verify herd/shepherd call pass with http url when enableSslAuth is false");
                    String result = ShellHelper.executeShellTestCase(command, envVars);
                    assertThat(command.getAssertVal(), notNullValue());
                    assertThat(result, containsString(command.getAssertVal()));
                }
                else {
                    LogVerification("Verify herd/shepherd call failed with http url when enableSslAuth is true");
                    assertThrows(RuntimeException.class, () -> {
                        ShellHelper.executeShellTestCase(command, envVars);
                    });
                }
            }));
}
 
Example #6
Source File: HttpsAndAuthTest.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
@TestFactory
public Stream<DynamicTest> testHerdHttpsIsNotAllowedWhenHttpsIsDisabled() {
    return getTestCases(HTTPS_TESTCASES)
            .stream().map(command -> DynamicTest.dynamicTest(COMPONENT + command.getName(), () -> {
                if (IS_SSLAUTH_ENABLED) {
                    LogVerification("Verify herd call pass with https url when enableSslAuth is true");
                    String result = ShellHelper.executeShellTestCase(command, envVars);
                    assertThat(command.getAssertVal(), notNullValue());
                    assertThat(result, containsString(command.getAssertVal()));
                }
                else {
                    LogVerification("Verify herd call failed with https url when enableSslAuth is false");
                    assertThrows(RuntimeException.class, () -> {
                        ShellHelper.executeShellTestCase(command, envVars);
                    });
                }
            }));
}
 
Example #7
Source File: ExamplesTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the dynamics tests for compiling the examples.
 *
 * @return the dynamic tests.
 * @throws Exception in case of error for recovering the example descriptions.
 */
@TestFactory
@DisplayName("SARL compilation of archives")
public Stream<DynamicTest> compilation() throws Exception {
	return dynamicTests(example -> {
		final File projectRoot = createProject();
		final List<File> installedFiles = installFiles(example, projectRoot, true);
		assertFalse(installedFiles.isEmpty(), () -> "No installed file in " + projectRoot);
		if (isMavenProject(example.sourceFolder)) {
			// Maven compilation
			final String errors = compileMaven(projectRoot);
			assertTrue(Strings.isEmpty(errors), errors);
		} else {
			// Standard SARL compilation
			List<String> issues = compileFiles(projectRoot, installedFiles);
			assertNoIssue(issues);
		}
	});
}
 
Example #8
Source File: ByNameAbstractTaskPartitionerPredicateTest.java    From kafka-connect-spooldir with Apache License 2.0 6 votes vote down vote up
@TestFactory
public Stream<DynamicTest> test() {
  List<File> files = new ArrayList<>(500);
  for (int i = 0; i < 500; i++) {
    files.add(new File(UUID.randomUUID().toString()));
  }
  return IntStream.range(2, 50).boxed().map(count -> dynamicTest(count.toString(), () -> {
    Set<File> queue = new LinkedHashSet<>(files);
    for (int index = 0; index <= count; index++) {
      AbstractTaskPartitionerPredicate.ByName predicate = new AbstractTaskPartitionerPredicate.ByName(index, count);
      files.stream()
          .filter(predicate)
          .forEach(queue::remove);
    }
    assertEquals(0, queue.size(), "Queue should be empty");
  }));
}
 
Example #9
Source File: ExpressionSerializationTestCase.java    From yare with MIT License 6 votes vote down vote up
@TestFactory
Stream<DynamicTest> expressionDeserializationTestFactory() {
    return Stream.of(
            DynamicTest.dynamicTest(
                    "Should deserialize value expression",
                    () -> shouldDeserializeExpression(createValueExpressionModel(), getSerializedValueExpression())
            ),
            DynamicTest.dynamicTest(
                    "Should deserialize values expression",
                    () -> shouldDeserializeExpression(createValuesExpressionModel(), getSerializedValuesExpression())
            ),
            DynamicTest.dynamicTest(
                    "Should deserialize function expression",
                    () -> shouldDeserializeExpression(createFunctionExpressionModel(), getSerializedFunctionExpression())
            )
    );
}
 
Example #10
Source File: ParameterSerializationTestCase.java    From yare with MIT License 6 votes vote down vote up
@TestFactory
Stream<DynamicTest> parameterDeserializeTestFactory() {
    return Stream.of(
            DynamicTest.dynamicTest(
                    "Should deserialize value parameter",
                    () -> shouldDeserializeParameter(createValueParameterModel(), getSerializedValueParameter())
            ),
            DynamicTest.dynamicTest(
                    "Should deserialize values parameter",
                    () -> shouldDeserializeParameter(createValuesParameterModel(), getSerializedValuesParameter())
            ),
            DynamicTest.dynamicTest(
                    "Should deserialize function parameter",
                    () -> shouldDeserializeParameter(createFunctionParameterModel(), getSerializedFunctionParameter())
            )
    );
}
 
Example #11
Source File: ValueSerializationTestCase.java    From yare with MIT License 6 votes vote down vote up
@TestFactory
Stream<DynamicTest> valueSerializationTestFactory() {
    return Stream.of(
            DynamicTest.dynamicTest(
                    "Should serialize build-in type value",
                    () -> shouldSerializeValue(createBuildInTypeValueModel(), getSerializedBuildInTypeValue())
            ),
            DynamicTest.dynamicTest(
                    "Should serialize string type value",
                    () -> shouldSerializeValue(createStringTypeValueModel(), getSerializedStringTypeValue())
            ),
            DynamicTest.dynamicTest(
                    "Should serialize custom type value",
                    () -> shouldSerializeValue(createCustomTypeValueModel(), getSerializedCustomTypeValue())
            )
    );
}
 
Example #12
Source File: SinkFieldConverterTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@TestFactory
@DisplayName("tests for int64 field conversions")
public List<DynamicTest> testInt64FieldConverter() {

    SinkFieldConverter converter = new Int64FieldConverter();

    List<DynamicTest> tests = new ArrayList<>();
    new ArrayList<>(Arrays.asList(Long.MIN_VALUE,0L,Long.MAX_VALUE)).forEach(
            el -> tests.add(dynamicTest("conversion with "
                            + converter.getClass().getSimpleName() + " for "+el,
                    () -> assertEquals((long)el, ((BsonInt64)converter.toBson(el)).getValue())
            ))
    );

    tests.add(dynamicTest("optional type conversions", () -> {
        Schema valueOptionalDefault = SchemaBuilder.int64().optional().defaultValue(0L);
        assertAll("checks",
                () -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.INT64_SCHEMA)),
                () -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_INT64_SCHEMA)),
                () -> assertEquals((long)valueOptionalDefault.defaultValue(),
                        ((BsonInt64)converter.toBson(null, valueOptionalDefault)).getValue())
        );
    }));

    return tests;

}
 
Example #13
Source File: QueryTasksAccTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@WithAccessId(user = "admin")
@TestFactory
Stream<DynamicTest> testQueryForCustomX() {
  List<Triplet<String, String[], Integer>> list =
      Arrays.asList(
          new Triplet<>("1", new String[] {"custom%", "p%", "%xyz%", "efg"}, 3),
          new Triplet<>("2", new String[] {"custom%", "a%"}, 2),
          new Triplet<>("3", new String[] {"ffg"}, 1),
          new Triplet<>("4", new String[] {"%ust%", "%ty"}, 2),
          new Triplet<>("5", new String[] {"ew", "al"}, 6),
          new Triplet<>("6", new String[] {"%custom6%", "%vvg%", "11%"}, 5),
          new Triplet<>("7", new String[] {"%"}, 2),
          new Triplet<>("8", new String[] {"%"}, 2),
          new Triplet<>("9", new String[] {"%"}, 2),
          new Triplet<>("10", new String[] {"%"}, 3),
          new Triplet<>("11", new String[] {"%"}, 3),
          new Triplet<>("12", new String[] {"%"}, 3),
          new Triplet<>("13", new String[] {"%"}, 3),
          new Triplet<>("14", new String[] {"%"}, 84),
          new Triplet<>("15", new String[] {"%"}, 3),
          new Triplet<>("16", new String[] {"%"}, 3));

  return DynamicTest.stream(
      list.iterator(),
      t -> ("custom" + t.getLeft()),
      t -> testQueryForCustomX(t.getLeft(), t.getMiddle(), t.getRight()));
}
 
Example #14
Source File: SinkFieldConverterTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@TestFactory
@DisplayName("tests for logical type timestamp field conversions")
public List<DynamicTest> testTimestampFieldConverter() {

    SinkFieldConverter converter = new TimestampFieldConverter();

    List<DynamicTest> tests = new ArrayList<>();
    new ArrayList<>(Arrays.asList(
            java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()),
            java.util.Date.from(ZonedDateTime.of(LocalDate.of(1983,7,31), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()),
            java.util.Date.from(ZonedDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant())
    )).forEach(
            el -> tests.add(dynamicTest("conversion with "
                            + converter.getClass().getSimpleName() + " for "+el,
                    () -> assertEquals(el.toInstant().getEpochSecond()*1000,
                            ((BsonDateTime)converter.toBson(el)).getValue())
            ))
    );

    tests.add(dynamicTest("optional type conversions", () -> {
        Schema valueOptionalDefault = Timestamp.builder().optional().defaultValue(
                java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant())
        );
        assertAll("checks",
                () -> assertThrows(DataException.class, () -> converter.toBson(null, Timestamp.SCHEMA)),
                () -> assertEquals(new BsonNull(), converter.toBson(null, Timestamp.builder().optional())),
                () -> assertEquals(((java.util.Date)valueOptionalDefault.defaultValue()).toInstant().getEpochSecond()*1000,
                        ((BsonDateTime)converter.toBson(null, valueOptionalDefault)).getValue())
        );
    }));

    return tests;

}
 
Example #15
Source File: StringParserTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@TestFactory
Stream<DynamicTest> parseString() {
  List<TestCase> tests = new ArrayList<>();
  of(tests, Schema.FLOAT64_SCHEMA, new Double(Double.MAX_VALUE).toString(), new Double(Double.MAX_VALUE));
  of(tests, Schema.FLOAT64_SCHEMA, new Double(Double.MIN_VALUE).toString(), new Double(Double.MIN_VALUE));

  of(tests, Schema.INT8_SCHEMA, new Byte(Byte.MAX_VALUE).toString(), new Byte(Byte.MAX_VALUE));
  of(tests, Schema.INT8_SCHEMA, new Byte(Byte.MIN_VALUE).toString(), new Byte(Byte.MIN_VALUE));

  of(tests, Schema.INT16_SCHEMA, new Short(Short.MAX_VALUE).toString(), new Short(Short.MAX_VALUE));
  of(tests, Schema.INT16_SCHEMA, new Short(Short.MIN_VALUE).toString(), new Short(Short.MIN_VALUE));

  of(tests, Schema.INT32_SCHEMA, new Integer(Integer.MAX_VALUE).toString(), new Integer(Integer.MAX_VALUE));
  of(tests, Schema.INT32_SCHEMA, new Integer(Integer.MIN_VALUE).toString(), new Integer(Integer.MIN_VALUE));

  of(tests, Schema.INT64_SCHEMA, new Long(Long.MAX_VALUE).toString(), new Long(Long.MAX_VALUE));
  of(tests, Schema.INT64_SCHEMA, new Long(Long.MIN_VALUE).toString(), new Long(Long.MIN_VALUE));

  of(tests, Schema.STRING_SCHEMA, "", "");
  of(tests, Schema.STRING_SCHEMA, "mirror", "mirror");

  for (int SCALE = 3; SCALE < 30; SCALE++) {
    Schema schema = Decimal.schema(SCALE);
    of(tests, schema, "12345", new BigDecimal("12345").setScale(SCALE));
    of(tests, schema, "0", new BigDecimal("0").setScale(SCALE));
    of(tests, schema, "-12345.001", new BigDecimal("-12345.001").setScale(SCALE));
  }

  return tests.stream().map(testCase -> dynamicTest(testCase.toString(), () -> {
    final Object actual = parser.parseString(testCase.schema, testCase.input);
    assertEquals(testCase.expected, actual);
  }));
}
 
Example #16
Source File: DynamicTests.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@TestFactory
Stream<DynamicTest> generateRandomNumberOfTests() {

    // Generates random positive integers between 0 and 100 until
    // a number evenly divisible by 7 is encountered.
    Iterator<Integer> inputGenerator = new Iterator<Integer>() {

        Random random = new Random();

        int current;

        @Override
        public boolean hasNext() {
            current = random.nextInt(100);
            return current % 7 != 0;
        }

        @Override
        public Integer next() {
            return current;
        }
    };

    // Generates display names like: input:5, input:37, input:85, etc.
    Function<Integer, String> displayNameGenerator = (input) -> "input:" + input;

    // Executes tests based on the current input value.
    ThrowingConsumer<Integer> testExecutor = (input) -> assertTrue(input % 7 != 0);

    // Returns a stream of dynamic tests.
    return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor);
}
 
Example #17
Source File: BaseDocumentationTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@TestFactory
public Stream<DynamicTest> rstSources() {
  final String templateName = "rst/source.rst.ftl";

  return this.plugin.getSourceConnectors()
      .stream()
      .map(sc -> connectorRstTest(
          new File(this.sourcesDirectory, sc.getCls().getSimpleName() + ".rst"),
          sc,
          templateName,
          true
          )
      );
}
 
Example #18
Source File: ClientSpecificationTest.java    From unleash-client-java with Apache License 2.0 5 votes vote down vote up
private List<DynamicTest> createVariantTests(String fileName) throws IOException, URISyntaxException {
    TestDefinition testDefinition = getTestDefinition(fileName);

    Unleash unleash = setupUnleash(testDefinition);

    //Create all test cases in testDefinition.
    return testDefinition.getVariantTests().stream()
            .map(test -> DynamicTest.dynamicTest(fileName + "/" + test.getDescription(), () -> {
                Variant result = unleash.getVariant(test.getToggleName(), buildContext(test.getContext()));
                assertEquals(test.getExpectedResult().getName(), result.getName(), test.getDescription());
                assertEquals(test.getExpectedResult().isEnabled(), result.isEnabled(), test.getDescription());
                assertEquals(test.getExpectedResult().getPayload(), result.getPayload(), test.getDescription());
            }))
            .collect(Collectors.toList());
}
 
Example #19
Source File: RuleSerializationTestCase.java    From yare with MIT License 5 votes vote down vote up
@TestFactory
Stream<DynamicTest> ruleSerializationTestFactory() {
    return Stream.of(
            DynamicTest.dynamicTest(
                    "Should serialize rule",
                    () -> shouldSerializeRule(createRuleModel(), getSerializedRule())
            ),
            DynamicTest.dynamicTest(
                    "Should serialize empty rule",
                    () -> shouldSerializeRule(createEmptyRuleModel(), getSerializedEmptyRule())
            )
    );
}
 
Example #20
Source File: Neo4jConversionsIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@TestFactory
@DisplayName("Custom conversions")
Stream<DynamicTest> customConversions() {
	final DefaultConversionService customConversionService = new DefaultConversionService();

	ConverterBuilder.ConverterAware converterAware = ConverterBuilder
		.reading(Value.class, LocalDate.class, v -> {
			String s = v.asString();
			switch (s) {
				case "gestern":
					return LocalDate.now().minusDays(1);
				case "heute":
					return LocalDate.now();
				case "morgen":
					return LocalDate.now().plusDays(1);
				default:
					throw new IllegalArgumentException();
			}
		}).andWriting(d -> {
			if (d.isBefore(LocalDate.now())) {
				return Values.value("gestern");
			} else if (d.isAfter(LocalDate.now())) {
				return Values.value("morgen");
			} else {
				return Values.value("heute");
			}
		});
	new Neo4jConversions(converterAware.getConverters()).registerConvertersIn(customConversionService);

	return Stream.of(
		dynamicTest("read",
			() -> assertThat(customConversionService.convert(Values.value("gestern"), LocalDate.class))
				.isEqualTo(LocalDate.now().minusDays(1))),
		dynamicTest("write",
			() -> assertThat(customConversionService.convert(LocalDate.now().plusDays(1), TYPE_DESCRIPTOR_OF_VALUE))
				.isEqualTo(Values.value("morgen")))
	);
}
 
Example #21
Source File: BaseDocumentationTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@TestFactory
public Stream<DynamicTest> rstSinks() {
  final String templateName = "rst/sink.rst.ftl";

  return this.plugin.getSinkConnectors()
      .stream()
      .map(sc -> connectorRstTest(
          outputRST(this.sinksDirectory, sc.getCls()),
          sc,
          templateName,
          true
          )
      );
}
 
Example #22
Source File: PojoTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@TestFactory
Collection<DynamicTest> validateGetAndSet() {
  return getPojoClasses()
      .map(
          cl ->
              DynamicTest.dynamicTest(
                  "Test set & get " + cl.getSimpleName(),
                  () -> validateWithTester(cl, new GetterTester(), new SetterTester())))
      .collect(Collectors.toList());
}
 
Example #23
Source File: ValidHostAndPortTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@TestFactory
public Stream<DynamicTest> invalid() {
  return Arrays.asList(
      (Object) Byte.MAX_VALUE,
      (Object) true,
      (Object) Integer.MAX_VALUE,
      (Object) Short.MAX_VALUE
  ).stream().map(input -> dynamicTest(input.getClass().getSimpleName(), () -> {
    assertThrows(ConfigException.class, () -> {
      ValidHostAndPort.of().ensureValid("foo", input);
    });
  }));
}
 
Example #24
Source File: ClientSpecificationTest.java    From unleash-client-java with Apache License 2.0 5 votes vote down vote up
private List<DynamicTest> createTests(String fileName) throws IOException, URISyntaxException {
    TestDefinition testDefinition = getTestDefinition(fileName);

    Unleash unleash = setupUnleash(testDefinition);

    //Create all test cases in testDefinition.
    return testDefinition.getTests().stream()
            .map(test -> DynamicTest.dynamicTest(fileName + "/" + test.getDescription(), () -> {
                boolean result = unleash.isEnabled(test.getToggleName(), buildContext(test.getContext()));
                assertEquals(test.getExpectedResult(), result, test.getDescription());
            }))
            .collect(Collectors.toList());
}
 
Example #25
Source File: AbstractNodeTest.java    From gyro with Apache License 2.0 5 votes vote down vote up
@TestFactory
public List<DynamicTest> constructorNull() {
    List<DynamicTest> tests = new ArrayList<>();

    for (Constructor<?> constructor : nodeClass.getConstructors()) {
        Class<?>[] paramTypes = constructor.getParameterTypes();

        for (int i = 0, length = paramTypes.length; i < length; ++i) {
            StringBuilder name = new StringBuilder("(");
            Object[] params = new Object[length];

            for (int j = 0; j < length; ++j) {
                Class<?> paramType = paramTypes[j];

                name.append(paramType.getName());

                if (i == j) {
                    name.append("=null");

                } else {
                    params[j] = getTestValue(paramType);
                }

                name.append(", ");
            }

            name.setLength(name.length() - 2);
            name.append(")");

            tests.add(DynamicTest.dynamicTest(
                name.toString(),
                () -> assertThatExceptionOfType(InvocationTargetException.class)
                    .isThrownBy(() -> constructor.newInstance(params))
                    .withCauseInstanceOf(NullPointerException.class)
            ));
        }
    }

    return tests;
}
 
Example #26
Source File: SinkFieldConverterTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@TestFactory
@DisplayName("tests for logical type time field conversions")
public List<DynamicTest> testTimeFieldConverter() {

    SinkFieldConverter converter = new TimeFieldConverter();

    List<DynamicTest> tests = new ArrayList<>();
    new ArrayList<>(Arrays.asList(
            java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant()),
            java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.NOON, ZoneOffset.systemDefault()).toInstant())
    )).forEach(
            el -> tests.add(dynamicTest("conversion with "
                            + converter.getClass().getSimpleName() + " for "+el,
                    () -> assertEquals(el.toInstant().getEpochSecond()*1000,
                            ((BsonDateTime)converter.toBson(el)).getValue())
            ))
    );

    tests.add(dynamicTest("optional type conversions", () -> {
        Schema valueOptionalDefault = Time.builder().optional().defaultValue(
                java.util.Date.from(ZonedDateTime.of(LocalDate.of(1970,1,1), LocalTime.MIDNIGHT, ZoneOffset.systemDefault()).toInstant())
        );
        assertAll("checks",
                () -> assertThrows(DataException.class, () -> converter.toBson(null, Time.SCHEMA)),
                () -> assertEquals(new BsonNull(), converter.toBson(null, Time.builder().optional())),
                () -> assertEquals(((java.util.Date)valueOptionalDefault.defaultValue()).toInstant().getEpochSecond()*1000,
                        ((BsonDateTime)converter.toBson(null, valueOptionalDefault)).getValue())
        );
    }));

    return tests;

}
 
Example #27
Source File: WorkingDaysToDaysConverterTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@TestFactory
Stream<DynamicTest> should_NotDetectCorpusChristiAsHoliday_When_CorpusChristiIsDisabled() {
  DynamicTest year1980 =
      DynamicTest.dynamicTest(
          "year 1980",
          () -> assertThat(converter.isGermanHoliday(LocalDate.parse("1980-06-05"))).isFalse());
  DynamicTest year2020 =
      DynamicTest.dynamicTest(
          "year 2020",
          () -> assertThat(converter.isGermanHoliday(LocalDate.parse("2020-06-11"))).isFalse());
  return Stream.of(year1980, year2020);
}
 
Example #28
Source File: BdsqlAuthTest.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
@TestFactory
@Tag("authTest")
public Stream<DynamicTest> testPrestoAuthentication() {
    return getJdbcTestCases(JDBC_AUTH_TESTCASES)
        .stream().map(
            (JDBCTestCase command) -> DynamicTest.dynamicTest(COMPONENT + command.getName(), () -> {
                LogVerification("Verify jdbc query response failure with bad credential/permission when enableAuth is true");
                SQLException authenticationException = assertThrows(SQLException.class, () -> {
                    JDBCHelper.executeJDBCTestCase(command, envVars);
                });
                List<String> expectErrorMsg = Arrays.asList("Authentication failed", "Connection property 'user' value is empty");
                String errorMsg = authenticationException.getMessage();
                assertTrue(errorMsg.contains(expectErrorMsg.get(0)) || errorMsg.contains(expectErrorMsg.get(1)));
            }));
}
 
Example #29
Source File: SinkFieldConverterTest.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
@TestFactory
@DisplayName("tests for int32 field conversions")
public List<DynamicTest> testInt32FieldConverter() {

    SinkFieldConverter converter = new Int32FieldConverter();

    List<DynamicTest> tests = new ArrayList<>();
    new ArrayList<>(Arrays.asList(Integer.MIN_VALUE,0,Integer.MAX_VALUE)).forEach(
            el -> tests.add(dynamicTest("conversion with "
                        + converter.getClass().getSimpleName() + " for "+el,
                () -> assertEquals((int)el, ((BsonInt32)converter.toBson(el)).getValue())
        ))
    );

    tests.add(dynamicTest("optional type conversions", () -> {
        Schema valueOptionalDefault = SchemaBuilder.int32().optional().defaultValue(0);
        assertAll("checks",
                () -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.INT32_SCHEMA)),
                () -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_INT32_SCHEMA)),
                () -> assertEquals(valueOptionalDefault.defaultValue(),
                        ((BsonInt32)converter.toBson(null, valueOptionalDefault)).getValue())
        );
    }));

    return tests;

}
 
Example #30
Source File: ExamplesIntegrationTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@TestFactory
Stream<DynamicTest> SingleClassTest() {
    return ExpectedTestFailures
            .forTests(
                    com.tngtech.archunit.exampletest.SingleClassTest.class,
                    com.tngtech.archunit.exampletest.junit4.SingleClassTest.class,
                    com.tngtech.archunit.exampletest.junit5.SingleClassTest.class)

            .ofRule(String.format("the class %s should only be accessed by classes that implement %s",
                    VeryCentralCore.class.getName(), CoreSatellite.class.getName()))
            .by(callFromMethod(EvilCoreAccessor.class, "iShouldNotAccessCore")
                    .toConstructor(VeryCentralCore.class)
                    .inLine(8))
            .by(callFromMethod(EvilCoreAccessor.class, "iShouldNotAccessCore")
                    .toMethod(VeryCentralCore.class, DO_CORE_STUFF_METHOD_NAME)
                    .inLine(8))

            .ofRule(String.format("no class %s should access classes that reside outside of packages ['..core..', 'java..']",
                    VeryCentralCore.class.getName()))
            .by(callFromMethod(VeryCentralCore.class, "coreDoingIllegalStuff")
                    .toConstructor(AnnotatedController.class)
                    .inLine(15))

            .ofRule(String.format("classes that are annotated with @%s should be %s",
                    HighSecurity.class.getSimpleName(), VeryCentralCore.class.getName()))
            .by(ExpectedClass.javaClass(WronglyAnnotated.class).notBeing(VeryCentralCore.class))

            .ofRule(String.format("classes that implement %s should not be %s",
                    SomeOtherBusinessInterface.class.getName(), VeryCentralCore.class.getName()))
            .by(ExpectedClass.javaClass(VeryCentralCore.class).being(VeryCentralCore.class))

            .toDynamicTests();
}