下面列出了org.junit.jupiter.api.extension.ExtendWith#org.junit.jupiter.api.DynamicTest 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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))));
}
@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());
}));
}
@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))
);
}
@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);
});
}
}));
}
@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);
});
}
}));
}
/** 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);
}
});
}
@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");
}));
}
@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())
)
);
}
@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())
)
);
}
@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())
)
);
}
@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.");
}));
}
@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;
}
@TestFactory
Iterable<DynamicTest> testAllPbeTypes() throws Exception {
List<DynamicTest> tests = new ArrayList<>();
for (PrivateKey privateKey : privateKeys()) {
for (OpenSslPbeType pbeType : OpenSslPbeType.values()) {
tests.add(dynamicTest("test " + pbeType.name() + "/" + privateKey.getClass().getSimpleName(), () -> {
byte[] encKey = OpenSslPvkUtil.getEncrypted(privateKey, pbeType, PASSWORD).getBytes();
assertEquals(privateKey, OpenSslPvkUtil.loadEncrypted(encKey, PASSWORD));
assertEquals(ENC_OPENSSL_PVK, CryptoFileUtil.detectFileType(encKey));
}));
}
}
return tests;
}
@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();
}
@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")))
);
}
@TestFactory
Collection<DynamicTest> validateGetAndSet() {
return getPojoClasses()
.map(
cl ->
DynamicTest.dynamicTest(
"Test set & get " + cl.getSimpleName(),
() -> validateWithTester(cl, new GetterTester(), new SetterTester())))
.collect(Collectors.toList());
}
@TestFactory
@DisplayName("tests for int32 field conversions")
List<DynamicTest> testInt32FieldConverter() {
SinkFieldConverter converter = new Int32FieldConverter();
List<DynamicTest> tests = new ArrayList<>();
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;
}
@TestFactory
Collection<DynamicTest> validateNoStaticExceptFinalFields() {
return getPojoClasses()
.map(
cl ->
DynamicTest.dynamicTest(
"Check static fields for " + cl.getSimpleName(),
() -> validateWithRules(cl, new NoStaticExceptFinalRule())))
.collect(Collectors.toList());
}
@TestFactory
Stream<DynamicTest> testMod2pi() {
return DoubleStream.of(0d, 1.1, 2.3, 3.1).mapToObj(value ->
DoubleStream.of(Math.PI * 2d, Math.PI * 4d).
mapToObj(piVal -> dynamicTest("testMod2pi", () -> assertEquals(value, MathUtils.INST.mod2pi(value + piVal), 0.0001))
)).flatMap(s -> s);
}
@TestFactory
Iterator<DynamicTest> dynamicTestsFromIterator() {
return Arrays.asList(
dynamicTest("5th dynamic test", () -> assertTrue(true)),
dynamicTest("6th dynamic test", () -> assertEquals(4, 2 * 2)))
.iterator();
}
private static <T extends BaseEnum> Stream<DynamicTest> code(final Class<T> clz, final T[] instances,
final Function<String, T> converter) {
var test1 = Stream.of(instances)
.map(value -> dynamicTest("bidirectional " + value.getClass()
.getSimpleName() + '.' + value,
() -> bidirectionality(value, converter)));
var test2 = Stream.of(dynamicTest("wrong " + clz.getSimpleName(), () -> wrong(converter)));
return Stream.concat(test1, test2);
}
@TestFactory
public Stream<DynamicTest> testFlexReconstruction() throws Exception {
return Files.list(Paths.get(getSystemResource("flex/reconstruction/README.md").toURI()).getParent())
.filter(path -> path.getFileName().toString().endsWith(".json"))
.sorted()
.map(this::testResource);
}
@TestFactory
default Collection<DynamicTest> dynamicTestsFromCollection() {
return Arrays.asList(
dynamicTest("1st dynamic test in test interface",
() -> assertTrue(true)),
dynamicTest("2nd dynamic test in test interface",
() -> assertTrue(true)));
}
@TestFactory
@ExtendWith(RandomIntegerResolver.class)
Stream<DynamicTest> dynamic(int randomized) {
return Stream.of(
dynamicTest("#1", () -> System.out.println("Random integer: " + randomized)),
dynamicTest("#2", () -> System.out.println("Random integer: " + randomized))
);
}
@TestFactory
@DisplayName("when valid cdc operation type then correct RDBMS CdcOperation")
Stream<DynamicTest> testValidCdcOpertionTypes() {
return Stream.of(
dynamicTest(
"test operation " + OperationType.CREATE,
() ->
assertTrue(
RDBMS_HANDLER_DEFAULT_MAPPING.getCdcOperation(BsonDocument.parse("{op: 'c'}"))
instanceof RdbmsInsert)),
dynamicTest(
"test operation " + OperationType.READ,
() ->
assertTrue(
RDBMS_HANDLER_DEFAULT_MAPPING.getCdcOperation(BsonDocument.parse("{op: 'r'}"))
instanceof RdbmsInsert)),
dynamicTest(
"test operation " + OperationType.UPDATE,
() ->
assertTrue(
RDBMS_HANDLER_DEFAULT_MAPPING.getCdcOperation(BsonDocument.parse("{op: 'u'}"))
instanceof RdbmsUpdate)),
dynamicTest(
"test operation " + OperationType.DELETE,
() ->
assertTrue(
RDBMS_HANDLER_DEFAULT_MAPPING.getCdcOperation(BsonDocument.parse("{op: 'd'}"))
instanceof RdbmsDelete)));
}
@TestFactory
Stream<DynamicNode> should_DetectCorpusChristiAsHoliday_When_CorpusChristiIsEnabled() {
WorkingDaysToDaysConverter converter = new WorkingDaysToDaysConverter(true, true);
DynamicTest year1980 =
DynamicTest.dynamicTest(
"year 1980",
() -> assertThat(converter.isGermanHoliday(LocalDate.parse("1980-06-05"))).isTrue());
DynamicTest year2020 =
DynamicTest.dynamicTest(
"year 2020",
() -> assertThat(converter.isGermanHoliday(LocalDate.parse("2020-06-11"))).isTrue());
return Stream.of(year1980, year2020);
}
@TestFactory
public final Stream<DynamicTest> sequenceOfNextAndComplete() {
return toDynamicTests(scenarios_operatorSuccess(), scenario -> {
Consumer<StepVerifier.Step<O>> verifier = scenario.verifier();
if (verifier == null) {
verifier = step -> scenario.applySteps(step)
.verifyComplete();
}
int fusion = scenario.fusionMode();
this.inputHiddenOutputBackpressured(scenario)
.consumeSubscriptionWith(s -> s.request(0))
.verifyComplete();
verifier.accept(this.inputHidden(scenario));
verifier.accept(this.inputHiddenOutputConditionalTryNext(scenario));
verifier.accept(this.inputFused(scenario));
verifier.accept(this.inputFusedConditionalTryNext(scenario));
if ((fusion & Fuseable.SYNC) != 0) {
verifier.accept(this.inputFusedSyncOutputFusedSync(scenario));
verifier.accept(this.inputFusedSyncOutputFusedSyncConditional(scenario));
}
if ((fusion & Fuseable.ASYNC) != 0) {
verifier.accept(this.inputFusedAsyncOutputFusedAsync(scenario));
verifier.accept(this.inputFusedAsyncOutputFusedAsyncConditional(scenario));
}
verifier.accept(this.inputConditionalTryNext(scenario));
verifier.accept(this.inputConditionalOutputConditional(scenario));
verifier.accept(this.inputFusedConditionalOutputConditional(scenario));
verifier.accept(this.inputFusedConditionalOutputConditionalTryNext(scenario));
});
}
@TestFactory
@DisplayName("test valid change data capture handler names")
Collection<DynamicTest> testValidChangeDataCaptureHandlerNames() {
List<DynamicTest> tests = new ArrayList<>();
String json = "{'%s': '%s'}";
List<String> cdcHandlers =
asList(
MongoDbHandler.class.getName(),
RdbmsHandler.class.getName(),
MysqlHandler.class.getName(),
PostgresHandler.class.getName());
cdcHandlers.forEach(
s ->
tests.add(
dynamicTest(
"cdc Handler for " + s,
() -> {
MongoSinkConfig cfg =
createSinkConfig(format(json, CHANGE_DATA_CAPTURE_HANDLER_CONFIG, s));
assertEquals(
cfg.getMongoSinkTopicConfig(TEST_TOPIC)
.getCdcHandler()
.get()
.getClass()
.getName(),
s);
})));
return tests;
}
private DynamicTest toDynamicTest(OperatorScenario<I, PI, O, PO> scenario, ThrowingRunnable runnable) {
return DynamicTest.dynamicTest(scenario.description(), () -> {
if (scenario.stack != null) {
System.out.println("\tat " + scenario.stack.getStackTrace()[2]);
}
runnable.run();
});
}
@TestFactory
@DisplayName("when valid cdc operation type then correct RDBMS CdcOperation")
public Stream<DynamicTest> testValidCdcOpertionTypes() {
return Stream.of(
dynamicTest("test operation " + OperationType.CREATE, () ->
assertTrue(RDBMS_HANDLER_DEFAULT_MAPPING.getCdcOperation(
new BsonDocument("op", new BsonString("c")))
instanceof RdbmsInsert)
),
dynamicTest("test operation " + OperationType.READ, () ->
assertTrue(RDBMS_HANDLER_DEFAULT_MAPPING.getCdcOperation(
new BsonDocument("op", new BsonString("r")))
instanceof RdbmsInsert)
),
dynamicTest("test operation " + OperationType.UPDATE, () ->
assertTrue(RDBMS_HANDLER_DEFAULT_MAPPING.getCdcOperation(
new BsonDocument("op", new BsonString("u")))
instanceof RdbmsUpdate)
),
dynamicTest("test operation " + OperationType.DELETE, () ->
assertTrue(RDBMS_HANDLER_DEFAULT_MAPPING.getCdcOperation(
new BsonDocument("op", new BsonString("d")))
instanceof RdbmsDelete)
)
);
}