下面列出了org.junit.jupiter.api.Assumptions#assumeTrue() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testHttp2EnabledSsl() throws ExecutionException, InterruptedException {
Assumptions.assumeTrue(JdkSSLEngineOptions.isAlpnAvailable()); //don't run on JDK8
Vertx vertx = Vertx.vertx();
try {
WebClientOptions options = new WebClientOptions()
.setUseAlpn(true)
.setProtocolVersion(HttpVersion.HTTP_2)
.setSsl(true)
.setKeyStoreOptions(
new JksOptions().setPath("src/test/resources/client-keystore.jks").setPassword("password"))
.setTrustStoreOptions(
new JksOptions().setPath("src/test/resources/client-truststore.jks").setPassword("password"));
WebClient client = WebClient.create(vertx, options);
int port = sslUrl.getPort();
runTest(client, port);
} finally {
vertx.close();
}
}
/**
* Make sure that a process whose std out file has grown too large will attempt to be killed.
*
* @throws IOException on error
*/
@Test
void canKillProcessOnTooLargeStdOut() throws IOException {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
Mockito
.when(this.executor.execute(Mockito.any(CommandLine.class)))
.thenReturn(0)
.thenReturn(0)
.thenReturn(0);
Mockito.when(this.stdOut.exists()).thenReturn(true);
Mockito.when(this.stdOut.length())
.thenReturn(MAX_STD_OUT_LENGTH - 1)
.thenReturn(MAX_STD_OUT_LENGTH)
.thenReturn(MAX_STD_OUT_LENGTH + 1);
Mockito.when(this.stdErr.exists()).thenReturn(false);
for (int i = 0; i < 3; i++) {
this.monitor.run();
}
Mockito.verify(this.successfulCheckRate, Mockito.times(2)).increment();
Mockito.verify(this.stdOutTooLarge, Mockito.times(1)).increment();
Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(Mockito.any(KillJobEvent.class));
}
@Test
public void testPermGenThresholdConfiguration() {
Assumptions.assumeTrue(MemoryUtil.hasPermGen());
// setting the option using the type safe method
config.setOption( PermGenThresholdOption.get(85) );
// checking the type safe getOption() method
assertEquals( PermGenThresholdOption.get(85),
config.getOption( PermGenThresholdOption.class ) );
// checking the string based getProperty() method
assertEquals( "85",
config.getProperty( PermGenThresholdOption.PROPERTY_NAME ) );
// setting the options using the string based setProperty() method
config.setProperty( PermGenThresholdOption.PROPERTY_NAME,
"87" );
// checking the type safe getOption() method
assertEquals( PermGenThresholdOption.get(87),
config.getOption( PermGenThresholdOption.class ) );
// checking the string based getProperty() method
assertEquals( "87",
config.getProperty( PermGenThresholdOption.PROPERTY_NAME ) );
}
/**
* Make sure that a running process doesn't publish anything.
*
* @throws Exception on error
*/
@Test
void canCheckRunningProcessOnUnixLikeSystem() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
Mockito.when(this.stdOut.exists()).thenReturn(false);
Mockito.when(this.stdErr.exists()).thenReturn(false);
for (int i = 0; i < 3; i++) {
this.monitor.run();
}
Mockito.verify(this.processChecker, Mockito.times(3)).checkProcess();
Mockito.verify(this.successfulCheckRate, Mockito.times(3)).increment();
Mockito
.verify(this.genieEventBus, Mockito.never())
.publishSynchronousEvent(Mockito.any(ApplicationEvent.class));
Mockito
.verify(this.genieEventBus, Mockito.never())
.publishAsynchronousEvent(Mockito.any(ApplicationEvent.class));
}
@ParameterizedTest
@EnumSource(DatabaseAvailabilityType.class)
void provisionDatabase(DatabaseAvailabilityType availabilty) throws JsonProcessingException {
Assumptions.assumeTrue(availabilty != DatabaseAvailabilityType.NONE);
DatabaseServerStatusV4Response createResponse = new DatabaseServerStatusV4Response();
createResponse.setResourceCrn(RDBMS_CRN);
Cluster cluster = spy(new Cluster());
when(redbeamsClient.create(any())).thenReturn(createResponse);
when(databaseObtainerService.obtainAttemptResult(eq(cluster), eq(DatabaseOperation.CREATION), eq(RDBMS_CRN), eq(true)))
.thenReturn(AttemptResults.finishWith(new DatabaseServerV4Response()));
underTest.provisionDatabase(cluster, availabilty, environmentResponse);
ArgumentCaptor<DatabaseServerParameter> serverParameterCaptor = ArgumentCaptor.forClass(DatabaseServerParameter.class);
verify(redbeamsClient).create(any(AllocateDatabaseServerV4Request.class));
verify(cluster).setDatabaseServerCrn(RDBMS_CRN);
verify(dbServerParameterDecorator).setParameters(any(), serverParameterCaptor.capture());
verify(clusterRepository).save(cluster);
DatabaseServerParameter paramValue = serverParameterCaptor.getValue();
assertThat(paramValue.isHighlyAvailable()).isEqualTo(availabilty == DatabaseAvailabilityType.HA);
}
@Test
public void testHttp2EnabledSsl() throws ExecutionException, InterruptedException {
Assumptions.assumeTrue(JdkSSLEngineOptions.isAlpnAvailable()); //don't run on JDK8
WebClientOptions options = new WebClientOptions()
.setUseAlpn(true)
.setProtocolVersion(HttpVersion.HTTP_2)
.setSsl(true)
.setTrustAll(true);
WebClient client = WebClient.create(VertxCoreRecorder.getVertx().get(), options);
int port = sslUrl.getPort();
runTest(client, port);
}
@Test
public void testCompileSwitchOverStringWithLngLevel17() {
double javaVersion = Double.valueOf(System.getProperty("java.specification.version"));
Assumptions.assumeTrue(javaVersion >= 1.7);
System.setProperty("drools.dialect.java.compiler.lnglevel", "1.7");
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newByteArrayResource(FUNCTION_WITH_SWITCH_OVER_STRING.getBytes()), ResourceType.DRL);
assertFalse(kbuilder.hasErrors(), "Compilation error(s) occurred!");
}
@Test
public void filterByTaskTest() {
Assumptions.assumeTrue(enabledScheduler);
logger.info("schedule-find-by-task-test");
try (Task task1 = tasks.builder().name(randomName("task1")).definition("timestamp").create();
Task task2 = tasks.builder().name(randomName("task2")).definition("timestamp").create();
TaskSchedule taskSchedule1 = schedules.builder().prefix(randomName("schedule1")).task(task1).create();
TaskSchedule taskSchedule2 = schedules.builder().prefix(randomName("schedule2")).task(task2).create()) {
assertThat(schedules.list().size()).isEqualTo(0);
assertThat(schedules.list(task1).size()).isEqualTo(0);
assertThat(schedules.list(task2).size()).isEqualTo(0);
taskSchedule1.schedule(Collections.singletonMap(DEFAULT_SCDF_EXPRESSION_KEY, DEFAULT_CRON_EXPRESSION));
taskSchedule2.schedule(Collections.singletonMap(DEFAULT_SCDF_EXPRESSION_KEY, DEFAULT_CRON_EXPRESSION));
assertThat(schedules.list().size()).isEqualTo(2);
assertThat(schedules.list(task1).size()).isEqualTo(1);
assertThat(schedules.list(task2).size()).isEqualTo(1);
assertThat(schedules.list(task1).get(0).getScheduleName()).isEqualTo(taskSchedule1.getScheduleName());
assertThat(schedules.list(task1).get(0).getScheduleProperties().containsKey(SchedulerPropertyKeys.CRON_EXPRESSION)).isTrue();
assertThat(schedules.list(task1).get(0).getScheduleProperties().get(SchedulerPropertyKeys.CRON_EXPRESSION)).isEqualTo(DEFAULT_CRON_EXPRESSION);
assertThat(schedules.list(task2).get(0).getScheduleName()).isEqualTo(taskSchedule2.getScheduleName());
assertThat(schedules.list(task2).get(0).getScheduleProperties().containsKey(SchedulerPropertyKeys.CRON_EXPRESSION)).isTrue();
assertThat(schedules.list(task2).get(0).getScheduleProperties().get(SchedulerPropertyKeys.CRON_EXPRESSION)).isEqualTo(DEFAULT_CRON_EXPRESSION);
}
}
@Test
void testSubmitJobMethodMissingCommand() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<ClusterCriteria> clusterCriteriaList = new ArrayList<>();
final Set<String> clusterTags = Sets.newHashSet(LOCALHOST_CLUSTER_TAG);
final ClusterCriteria clusterCriteria = new ClusterCriteria(clusterTags);
clusterCriteriaList.add(clusterCriteria);
final String jobId = UUID.randomUUID().toString();
final Set<String> commandCriteria = Sets.newHashSet("undefined");
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withId(jobId)
.withCommandArgs(SLEEP_AND_ECHO_COMMAND_ARGS)
.withDisableLogArchival(true)
.build();
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.PRECONDITION_FAILED.value()));
Assertions.assertThat(this.getStatus(jobId)).isEqualByComparingTo(JobStatus.FAILED);
}
@Test
void messagesRetrievedUsingFetchTypeMetadataShouldHaveAttachmentsEmptyWhenOneAttachment() throws MailboxException {
Assumptions.assumeTrue(mapperProvider.supportPartialAttachmentFetch());
saveMessages();
MessageMapper.FetchType fetchType = MessageMapper.FetchType.Metadata;
Iterator<MailboxMessage> retrievedMessageIterator = messageMapper.findInMailbox(attachmentsMailbox, MessageRange.one(messageWith1Attachment.getUid()), fetchType, LIMIT);
assertThat(retrievedMessageIterator.next().getAttachments()).isEmpty();
}
@BeforeAll
static void setupDatabase(@TempDir Path temp) throws Exception {
system = new PluginMockComponent(temp).getPlanSystem();
Optional<Database> mysql = new DBPreparer(system, TEST_PORT_NUMBER).prepareMySQL();
Assumptions.assumeTrue(mysql.isPresent());
database = mysql.get();
}
/**
* Make sure that a timed out process sends event.
*
* @throws Exception in case of error
*/
@Test
void canTryToKillTimedOutProcess() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
// Set timeout to yesterday to force timeout when check happens
final Instant yesterday = Instant.now().minus(1, ChronoUnit.DAYS);
this.jobExecution = new JobExecution.Builder(UUID.randomUUID().toString())
.withProcessId(3808)
.withCheckDelay(DELAY)
.withTimeout(yesterday)
.withId(UUID.randomUUID().toString())
.build();
this.monitor = new JobMonitor(
this.jobExecution,
this.stdOut,
this.stdErr,
this.genieEventBus,
this.registry,
JobsProperties.getJobsPropertiesDefaults(),
processChecker
);
Mockito.doThrow(new GenieTimeoutException("...")).when(processChecker).checkProcess();
this.monitor.run();
final ArgumentCaptor<KillJobEvent> captor = ArgumentCaptor.forClass(KillJobEvent.class);
Mockito
.verify(this.genieEventBus, Mockito.times(1))
.publishSynchronousEvent(captor.capture());
Assertions.assertThat(captor.getValue()).isNotNull();
final String jobId = this.jobExecution.getId().orElseThrow(IllegalArgumentException::new);
Assertions.assertThat(captor.getValue().getId()).isEqualTo(jobId);
Assertions.assertThat(captor.getValue().getReason()).isEqualTo(JobStatusMessages.JOB_EXCEEDED_TIMEOUT);
Assertions.assertThat(captor.getValue().getSource()).isEqualTo(this.monitor);
Mockito.verify(this.timeoutRate, Mockito.times(1)).increment();
}
protected void ignoreForNativeStore() {
// ignore these tests for native store
Assumptions.assumeTrue(isSPARQLServer(), "Test is ignored for native store federation");
}
@Test
@DisplayName("Properly generates ... for multiple fields")
void testHappyPathMultipleFields() throws IOException {
// GIVEN
final var sut = Record.builder().build();
final var source = Source.mock(sut).lines("package javax0.geci.record;\n" +
"\n" +
"public class ToRecordMultipleFields {\n" +
"\n" +
" private String z;\n" +
" private String k;\n" +
"\n" +
" private void ToRecordMultipleFields(){}\n" +
"\n" +
" //<editor-fold id=\"record\">\n" +
" //</editor-fold>\n" +
"\n" +
"}\n")
.getSource();
final var fields = ToRecordMultipleFields.class.getDeclaredFields();
final var segment = source.open("record");
Assumptions.assumeTrue(segment != null);
// WHEN
sut.process(source, ToRecordMultipleFields.class, null, fields, segment);
// THEN
source.consolidate();
Assertions.assertEquals("package javax0.geci.record;\n" +
"\n" +
"public final class ToRecordMultipleFields {\n" +
"\n" +
" final private String z;\n" +
" final private String k;\n" +
"\n" +
" private void ToRecordMultipleFields(final String z, final String k){}\n" +
"\n" +
" //<editor-fold id=\"record\">\n" +
" public ToRecordMultipleFields(final String z, final String k) {\n" +
" ToRecordMultipleFields(z, k);\n" +
" this.z = z;\n" +
" this.k = k;\n" +
" }\n" +
"\n" +
" public String getZ() {\n" +
" return z;\n" +
" }\n" +
"\n" +
" public String getK() {\n" +
" return k;\n" +
" }\n" +
"\n" +
" @Override\n" +
" public int hashCode() {\n" +
" return java.util.Objects.hash(z, k);\n" +
" }\n" +
"\n" +
" @Override\n" +
" public boolean equals(Object o) {\n" +
" if (this == o) return true;\n" +
" if (o == null || getClass() != o.getClass()) return false;\n" +
" ToRecordMultipleFields that = (ToRecordMultipleFields) o;\n" +
" return java.util.Objects.equals(that.z, z) && java.util.Objects.equals(that.k, k);\n" +
" }\n" +
" //</editor-fold>\n" +
"\n" +
"}",
String.join("\n", source.getLines()));
}
@Test
@DisplayName("Properly generates the getters, constructor, hashCode and equals and fixes field and class")
void testHappyPath() throws IOException {
// GIVEN
final var sut = Record.builder().build();
final var source = Source.mock(sut).lines("package javax0.geci.record;\n" +
"\n" +
"public class ToRecord {\n" +
"\n" +
" private String z;\n" +
"\n" +
" private void ToRecord(){}\n" +
"\n" +
" //<editor-fold id=\"record\">\n" +
" //</editor-fold>\n" +
"\n" +
"}\n")
.getSource();
final var fields = ToRecord.class.getDeclaredFields();
final var segment = source.open("record");
Assumptions.assumeTrue(segment != null);
// WHEN
sut.process(source, ToRecord.class, null, fields, segment);
// THEN
source.consolidate();
Assertions.assertEquals("package javax0.geci.record;\n" +
"\n" +
"public final class ToRecord {\n" +
"\n" +
" final private String z;\n" +
"\n" +
" private void ToRecord(final String z){}\n" +
"\n" +
" //<editor-fold id=\"record\">\n" +
" public ToRecord(final String z) {\n" +
" ToRecord(z);\n" +
" this.z = z;\n" +
" }\n" +
"\n" +
" public String getZ() {\n" +
" return z;\n" +
" }\n" +
"\n" +
" @Override\n" +
" public int hashCode() {\n" +
" return java.util.Objects.hash(z);\n" +
" }\n" +
"\n" +
" @Override\n" +
" public boolean equals(Object o) {\n" +
" if (this == o) return true;\n" +
" if (o == null || getClass() != o.getClass()) return false;\n" +
" ToRecord that = (ToRecord) o;\n" +
" return java.util.Objects.equals(that.z, z);\n" +
" }\n" +
" //</editor-fold>\n" +
"\n" +
"}",
String.join("\n", source.getLines()));
}
@Test
public void testAssumptionsWork() {
//these were broken at one point
Assumptions.assumeTrue(false);
}
@Test
void givenFalseIsTrue_whenTestAbortedThenCaptureResult() {
Assumptions.assumeTrue(false);
}
@Test
void givenTrueIsTrue_whenTestAbortedThenCaptureResult() {
Assumptions.assumeTrue(true);
}
@Test
void testSubmitJobMethodFailure() throws Exception {
Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
final List<String> commandArgs;
commandArgs = Lists.newArrayList("-c", "'exit 1'");
final List<ClusterCriteria> clusterCriteriaList = new ArrayList<>();
final Set<String> clusterTags = Sets.newHashSet(LOCALHOST_CLUSTER_TAG);
final ClusterCriteria clusterCriteria = new ClusterCriteria(clusterTags);
clusterCriteriaList.add(clusterCriteria);
final Set<String> commandCriteria = Sets.newHashSet(BASH_COMMAND_TAG);
final JobRequest jobRequest = new JobRequest.Builder(
JOB_NAME,
JOB_USER,
JOB_VERSION,
clusterCriteriaList,
commandCriteria
)
.withCommandArgs(commandArgs)
.withDisableLogArchival(true)
.build();
final String id = this.getIdFromLocation(
RestAssured
.given(this.getRequestSpecification())
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest))
.when()
.port(this.port)
.post(JOBS_API)
.then()
.statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
.header(HttpHeaders.LOCATION, Matchers.notNullValue())
.extract()
.header(HttpHeaders.LOCATION)
);
this.waitForDone(id);
Assertions.assertThat(this.getStatus(id)).isEqualByComparingTo(JobStatus.FAILED);
RestAssured
.given(this.getRequestSpecification())
.when()
.port(this.port)
.get(JOBS_API + "/{id}", id)
.then()
.statusCode(Matchers.is(HttpStatus.OK.value()))
.contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
.body(ID_PATH, Matchers.is(id))
.body(STATUS_PATH, Matchers.is(JobStatus.FAILED.toString()))
.body(STATUS_MESSAGE_PATH, Matchers.is(JobStatusMessages.JOB_FAILED));
}
@Test
public void scheduleLifeCycle() {
Assumptions.assumeTrue(enabledScheduler);
logger.info("schedule-lifecycle-test");
try (Task task = tasks.builder().name(randomName("task")).definition("timestamp").create();
TaskSchedule taskSchedule = schedules.builder().prefix(randomName("schedule")).task(task).create()) {
assertThat(taskSchedule.isScheduled()).isFalse();
logger.info("schedule-lifecycle-test: SCHEDULE");
taskSchedule.schedule(Collections.singletonMap(DEFAULT_SCDF_EXPRESSION_KEY, DEFAULT_CRON_EXPRESSION));
assertThat(taskSchedule.isScheduled()).isTrue();
TaskSchedule retrievedSchedule = schedules.findByScheduleName(taskSchedule.getScheduleName());
assertThat(retrievedSchedule.getScheduleName()).isEqualTo(taskSchedule.getScheduleName());
assertThat(retrievedSchedule.getScheduleProperties().containsKey(SchedulerPropertyKeys.CRON_EXPRESSION)).isTrue();
assertThat(retrievedSchedule.getScheduleProperties().get(SchedulerPropertyKeys.CRON_EXPRESSION)).isEqualTo(DEFAULT_CRON_EXPRESSION);
logger.info("schedule-lifecycle-test: UNSCHEDULE");
taskSchedule.unschedule();
assertThat(taskSchedule.isScheduled()).isFalse();
}
}