org.junit.jupiter.api.Assumptions Java Examples

The following examples show how to use org.junit.jupiter.api.Assumptions. 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: DiskCleanupTaskTest.java    From genie with Apache License 2.0 6 votes vote down vote up
@Test
void wontScheduleOnNonUnixWithSudo() throws IOException {
    Assumptions.assumeTrue(!SystemUtils.IS_OS_UNIX);
    final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class);
    final Resource jobsDir = Mockito.mock(Resource.class);
    Mockito.when(jobsDir.exists()).thenReturn(true);
    final DataServices dataServices = Mockito.mock(DataServices.class);
    Mockito.when(dataServices.getPersistenceService()).thenReturn(Mockito.mock(PersistenceService.class));
    Assertions.assertThat(
        new DiskCleanupTask(
            new DiskCleanupProperties(),
            scheduler,
            jobsDir,
            dataServices,
            JobsProperties.getJobsPropertiesDefaults(),
            Mockito.mock(Executor.class),
            new SimpleMeterRegistry()
        )
    ).isNotNull();
    Mockito.verify(scheduler, Mockito.never()).schedule(Mockito.any(Runnable.class), Mockito.any(Trigger.class));
}
 
Example #2
Source File: ValueTransferWithAzureAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@BeforeAll
public static void setUpBase() {
  Runtime.getRuntime()
      .addShutdownHook(new Thread(ValueTransferWithAzureAcceptanceTest::tearDownBase));

  Assumptions.assumeTrue(
      System.getenv("ETHSIGNER_AZURE_CLIENT_ID") != null
          && System.getenv("ETHSIGNER_AZURE_CLIENT_SECRET") != null,
      "Ensure Azure client id and client secret env variables are set");

  final DockerClient docker = new DockerClientFactory().create();
  final NodeConfiguration nodeConfig = new NodeConfigurationBuilder().build();

  ethNode = new BesuNode(docker, nodeConfig);
  ethNode.start();
  ethNode.awaitStartupCompletion();

  final SignerConfiguration signerConfig =
      new SignerConfigurationBuilder().withAzureKeyVault("ethsignertestkey").build();

  ethSigner = new Signer(signerConfig, nodeConfig, ethNode.ports());
  ethSigner.start();
  ethSigner.awaitStartupCompletion();
}
 
Example #3
Source File: GenerateJWTTest.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 6 votes vote down vote up
@Test
public void generateJWT(TestReporter reporter) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    Assumptions.assumeTrue(kpg.getAlgorithm().equals("RSA"));
    kpg.initialize(2048);
    reporter.publishEntry("Created RSA key pair generator of size 2048");
    KeyPair keyPair = kpg.generateKeyPair();
    reporter.publishEntry("Created RSA key pair");
    Assumptions.assumeTrue(keyPair != null, "KeyPair is not null");
    PublicKey publicKey = keyPair.getPublic();
    reporter.publishEntry("RSA.publicKey", publicKey.toString());
    PrivateKey privateKey = keyPair.getPrivate();
    reporter.publishEntry("RSA.privateKey", privateKey.toString());

    assertAll("GenerateJWTTest",
        () -> assertEquals("X.509", publicKey.getFormat()),
        () -> assertEquals("PKCS#8", privateKey.getFormat()),
        () -> assertEquals("RSA", publicKey.getAlgorithm()),
        () -> assertEquals("RSA", privateKey.getAlgorithm())
    );
}
 
Example #4
Source File: PGrammarPaneTest.java    From PolyGlot with MIT License 6 votes vote down vote up
@Test
public void testPasteRegular() {
    // do not run test in headless mode (paste explodes without UI)
    if (headless) {
        return;
    }
    
    // TODO: figure out why windows tests are flakey (ancient machine running Windows virtual?)
    Assumptions.assumeTrue(!PGTUtil.IS_WINDOWS);
    
    System.out.println("PGrammarPaneTest.testPasteRegular");
    
    String sourceText = "This is a test! Yeehaw!";
    String expectedResult = sourceText;
    PGrammarPane pane = new PGrammarPane(core);
    ClipboardHandler board = new ClipboardHandler();
    
    board.setClipboardContents(sourceText);
    pane.paste();
    String resut = pane.getText();
    
    assertEquals(expectedResult, resut);
}
 
Example #5
Source File: JobMonitorTest.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that a finished process sends event.
 *
 * @throws Exception on error
 */
@Test
void canCheckFinishedProcessOnUnixLikeSystem() throws Exception {
    Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
    Mockito.doThrow(new ExecuteException("done", 1)).when(processChecker).checkProcess();

    this.monitor.run();

    final ArgumentCaptor<JobFinishedEvent> captor = ArgumentCaptor.forClass(JobFinishedEvent.class);
    Mockito
        .verify(this.genieEventBus, Mockito.times(1))
        .publishAsynchronousEvent(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().getSource()).isEqualTo(this.monitor);
    Mockito.verify(this.finishedRate, Mockito.times(1)).increment();
}
 
Example #6
Source File: AbstractHazelcastIndexedSessionRepositoryITests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void createSessionWithSecurityContextAndFindByPrincipal() {
	Assumptions.assumeTrue(this.hazelcastInstance instanceof HazelcastInstanceProxy,
			"Hazelcast runs in embedded server topology");

	HazelcastSession session = this.repository.createSession();

	String username = "saves-" + System.currentTimeMillis();
	Authentication authentication = new UsernamePasswordAuthenticationToken(username, "password",
			AuthorityUtils.createAuthorityList("ROLE_USER"));
	SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
	securityContext.setAuthentication(authentication);
	session.setAttribute(SPRING_SECURITY_CONTEXT, securityContext);

	this.repository.save(session);

	assertThat(this.repository
			.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username))
					.hasSize(1);
}
 
Example #7
Source File: PipelinesTest.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
@Test
public void testMavenInstallMixedTags() throws IntegrationException {
    Assumptions.assumeFalse(SystemUtils.IS_OS_WINDOWS);

    final List<String> userProvidedCqueryAdditionalOptions = null;

    final MutableDependencyGraph dependencyGraph = doTest(WorkspaceRule.MAVEN_INSTALL, MAVEN_INSTALL_STANDARD_BAZEL_COMMAND_ARGS, userProvidedCqueryAdditionalOptions, MAVEN_INSTALL_OUTPUT_MIXED_TAGS);
    assertEquals(2, dependencyGraph.getRootDependencies().size());
    int foundCount = 0;
    for (final Dependency dependency : dependencyGraph.getRootDependencies()) {
        if ("com.company.thing".equals(dependency.getExternalId().getGroup()) &&
                "thing-common-client".equals(dependency.getExternalId().getName()) &&
                "2.100.0".equals(dependency.getExternalId().getVersion())) {
            foundCount++;
        }
        if ("javax.servlet".equals(dependency.getExternalId().getGroup()) &&
                "javax.servlet-api".equals(dependency.getExternalId().getName()) &&
                "3.0.1".equals(dependency.getExternalId().getVersion())) {
            foundCount++;
        }
    }
    assertEquals(2, foundCount);
}
 
Example #8
Source File: OpenScreensTest.java    From PolyGlot with MIT License 6 votes vote down vote up
public OpenScreensTest() {
    // TODO: figure out why windows tests are flakey (ancient machine running Windows virtual?)
    Assumptions.assumeTrue(!PGTUtil.IS_WINDOWS);
    
    core = DummyCore.newCore();
    errors = IOHandler.getErrorLogFile();
    
    try {
        core.readFile(PGTUtil.TESTRESOURCES + "basic_lang.pgd");

        if (errors.exists()) {
            errors.delete();
        }
    } catch (IOException | IllegalStateException e) {
        IOHandler.writeErrorLog(e, e.getLocalizedMessage());
        fail(e);
    }
}
 
Example #9
Source File: PipelinesTest.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
@Test
public void haskellCabalLibraryTest() throws IntegrationException {
    Assumptions.assumeFalse(SystemUtils.IS_OS_WINDOWS);

    final List<String> userProvidedCqueryAdditionalOptions = null;

    final MutableDependencyGraph dependencyGraph = doTest(WorkspaceRule.HASKELL_CABAL_LIBRARY,
        HASKELL_CABAL_LIBRARY_STANDARD_BAZEL_COMMAND_ARGS, userProvidedCqueryAdditionalOptions, HASKELL_CABAL_LIBRARY_JSONPROTO);
    assertEquals(1, dependencyGraph.getRootDependencies().size());
    int foundCount = 0;
    for (final Dependency dependency : dependencyGraph.getRootDependencies()) {
        if ("optparse-applicative".equals(dependency.getExternalId().getName()) &&
                "0.14.3.0".equals(dependency.getExternalId().getVersion())) {
            foundCount++;
        }
    }
    assertEquals(1, foundCount);
}
 
Example #10
Source File: KnowledgeBaseConfigurationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@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 ) );
}
 
Example #11
Source File: TestThatGeneratesTheFinalReleaseTrainDocumentationTests.java    From spring-cloud-release with Apache License 2.0 6 votes vote down vote up
/**
 * FOR SOME REASON I CAN'T RUN MAIN CLASS FROM MAVEN AS A WORKAOUND WE WILL RUN THIS
 * TEST TO GENERATE THE DOCS
 */
@Test
@Disabled
void should_generate_adocs_with_values_from_system_property() {
	// System property needs to be passed
	Assumptions.assumeTrue(StringUtils.hasText(System.getProperty("bomPath")));

	String bomPath = System.getProperty("bomPath");
	String starterParentPath = System.getProperty("starterParentPath");
	String repoUrl = System.getProperty("repoUrl");
	String unzippedDocs = System.getProperty("unzippedDocs");
	String generatedTrainDocs = System.getProperty("generatedTrainDocs");

	GenerateReleaseTrainDocs.main(bomPath, starterParentPath, repoUrl, unzippedDocs,
			generatedTrainDocs);

	BDDAssertions.then(new File(generatedTrainDocs)).isNotEmptyDirectory();
}
 
Example #12
Source File: JobMonitorTest.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #13
Source File: DiskCleanupTaskTest.java    From genie with Apache License 2.0 6 votes vote down vote up
@Test
void willScheduleOnUnixWithSudo() throws IOException {
    Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
    final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class);
    final Resource jobsDir = Mockito.mock(Resource.class);
    Mockito.when(jobsDir.exists()).thenReturn(true);
    final DataServices dataServices = Mockito.mock(DataServices.class);
    Mockito.when(dataServices.getPersistenceService()).thenReturn(Mockito.mock(PersistenceService.class));
    Assertions.assertThat(
        new DiskCleanupTask(
            new DiskCleanupProperties(),
            scheduler,
            jobsDir,
            dataServices,
            JobsProperties.getJobsPropertiesDefaults(),
            Mockito.mock(Executor.class),
            new SimpleMeterRegistry()
        )
    ).isNotNull();
    Mockito.verify(scheduler, Mockito.times(1)).schedule(Mockito.any(Runnable.class), Mockito.any(Trigger.class));
}
 
Example #14
Source File: JobMonitorTest.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that a process whose std err file has grown too large will attempt to be killed.
 *
 * @throws IOException on error
 */
@Test
void canKillProcessOnTooLargeStdErr() 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(false);
    Mockito.when(this.stdErr.exists()).thenReturn(true);
    Mockito.when(this.stdErr.length())
        .thenReturn(MAX_STD_ERR_LENGTH - 1)
        .thenReturn(MAX_STD_ERR_LENGTH)
        .thenReturn(MAX_STD_ERR_LENGTH + 1);

    for (int i = 0; i < 3; i++) {
        this.monitor.run();
    }

    Mockito.verify(this.successfulCheckRate, Mockito.times(2)).increment();
    Mockito.verify(this.stdErrTooLarge, Mockito.times(1)).increment();
    Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(Mockito.any(KillJobEvent.class));
}
 
Example #15
Source File: Http2TestCase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #16
Source File: ExternalDatabaseServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #17
Source File: MdcActivationListenerIT.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testVerifyThatWithEnabledCorrelationAndLoggedErrorMdcErrorIdIsNotBlankWithLog4j() {
    Assumptions.assumeTrue(() -> {
        org.apache.log4j.MDC.put("test", true);
        return org.apache.log4j.MDC.get("test") == Boolean.TRUE;
    }, "Log4j MDC is not working, this happens with some versions of Java 10 where log4j thinks it's Java 1");
    when(loggingConfiguration.isLogCorrelationEnabled()).thenReturn(true);
    org.apache.logging.log4j.Logger logger = mock(org.apache.logging.log4j.Logger.class);
    doAnswer(invocation -> assertMdcErrorIdIsNotEmpty()).when(logger).error(anyString(), any(Exception.class));

    assertMdcErrorIdIsEmpty();

    Transaction transaction = tracer.startRootTransaction(getClass().getClassLoader()).withType("request").withName("test");
    transaction.activate();
    logger.error("Some apache logger exception", new RuntimeException("Hello exception"));
    assertMdcErrorIdIsEmpty();
    transaction.deactivate().end();

    assertMdcErrorIdIsEmpty();
}
 
Example #18
Source File: BlackDuckIntegrationTest.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
@BeforeAll
public static void setup() {
    logger = new BufferedIntLogger();

    Assumptions.assumeTrue(StringUtils.isNotBlank(System.getenv().get(TEST_BLACKDUCK_URL_KEY)));
    Assumptions.assumeTrue(StringUtils.isNotBlank(System.getenv().get(TEST_BLACKDUCK_USERNAME_KEY)));
    Assumptions.assumeTrue(StringUtils.isNotBlank(System.getenv().get(TEST_BLACKDUCK_PASSWORD_KEY)));

    final BlackDuckServerConfigBuilder blackDuckServerConfigBuilder = BlackDuckServerConfig.newBuilder();
    blackDuckServerConfigBuilder.setProperties(System.getenv().entrySet());
    blackDuckServerConfigBuilder.setUrl(System.getenv().get(TEST_BLACKDUCK_URL_KEY));
    blackDuckServerConfigBuilder.setUsername(System.getenv().get(TEST_BLACKDUCK_USERNAME_KEY));
    blackDuckServerConfigBuilder.setPassword(System.getenv().get(TEST_BLACKDUCK_PASSWORD_KEY));
    blackDuckServerConfigBuilder.setTrustCert(true);
    blackDuckServerConfigBuilder.setTimeoutInSeconds(5 * 60);

    blackDuckServicesFactory = blackDuckServerConfigBuilder.build().createBlackDuckServicesFactory(logger);
    blackDuckService = blackDuckServicesFactory.createBlackDuckService();
    projectService = blackDuckServicesFactory.createProjectService();
    projectBomService = blackDuckServicesFactory.createProjectBomService();
    codeLocationService = blackDuckServicesFactory.createCodeLocationService();
    reportService = blackDuckServicesFactory.createReportService(120 * 1000);

    previousShouldExit = Application.shouldExit();
    Application.setShouldExit(false);
}
 
Example #19
Source File: DatabaseConnectionUtilTest.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetPasswordMySQL_5_1() throws Exception {
    // with MySQL Connector 5.1.38, we use JDBC4Connection and its superclass ConnectionImpl
    // to get hold of the password.
    Class<?> connectionImpl = loadClass("com.mysql.jdbc.ConnectionImpl");
    Assumptions.assumeFalse(connectionImpl == null);
    Field propsField = connectionImpl.getDeclaredField("props");
    Assertions.assertNotNull(propsField, "The field props is not existing");
}
 
Example #20
Source File: DatabaseConnectionUtilTest.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
private static void assumeJava8() {
    String javaVersion = System.getProperty("java.version");
    String[] versionComponents = javaVersion.split("\\.");
    int majorJava = 0;
    if ("1".equals(versionComponents[0])) {
        majorJava = Integer.parseInt(versionComponents[1]);
    } else {
        majorJava = Integer.parseInt(versionComponents[0]);
    }
    Assumptions.assumeTrue(majorJava >= 8, "Java Runtime too old - for this test at least java8 is required");
}
 
Example #21
Source File: UnixProcessCheckerTest.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Setup for the tests.
 */
@BeforeEach
void setup() {
    Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
    this.executor = Mockito.mock(Executor.class);
    this.tomorrow = Instant.now().plus(1, ChronoUnit.DAYS);
    // For standard tests this will keep it from dying
}
 
Example #22
Source File: PostgresqlSendReceiveTest.java    From orion with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp(@TempDirectory final Path tempDir) throws Exception {
  Assumptions.assumeTrue(
      databaseUser != null && databasePassword != null && databaseName != null,
      "PostgreSQL not configured");

  final String jdbcUrl = String.format(JDBC_URL, databaseName, databaseUser, databasePassword);

  try (final Connection conn = DriverManager.getConnection(jdbcUrl)) {
    final Statement st = conn.createStatement();
    st.executeUpdate("create table if not exists store(key char(60), value bytea, primary key(key))");
  }

  final Path key1pub = copyResource("key1.pub", tempDir.resolve("key1.pub"));
  final Path key1key = copyResource("key1.key", tempDir.resolve("key1.key"));
  final Path key2pub = copyResource("key2.pub", tempDir.resolve("key2.pub"));
  final Path key2key = copyResource("key2.key", tempDir.resolve("key2.key"));

  final Config config = NodeUtils.nodeConfig(
      tempDir,
      0,
      HOST_NAME,
      0,
      HOST_NAME,
      "node1",
      joinPathsAsTomlListEntry(key1pub, key2pub),
      joinPathsAsTomlListEntry(key1key, key2key),
      "off",
      "tofu",
      "tofu",
      "sql:" + jdbcUrl,
      "memory");

  vertx = vertx();
  orionLauncher = NodeUtils.startOrion(config);
  httpClient = vertx.createHttpClient();
}
 
Example #23
Source File: IPAHandlerTest.java    From PolyGlot with MIT License 5 votes vote down vote up
@Test
public void testPlaySounds() {
    Assumptions.assumeFalse(GraphicsEnvironment.isHeadless());

    System.out.println("IPAHandlerTest.testPlaySounds");
    IPAHandler handler = new IPAHandler(null);

    try {
        Class<?> myClass = handler.getClass();
        Field field = myClass.getDeclaredField("charMap");
        field.setAccessible(true);
        Map<String, String> charMap = (Map<String, String>)field.get(handler);

        field = myClass.getDeclaredField("soundRecorder");
        field.setAccessible(true);
        SoundRecorder soundRecorder = (SoundRecorder)field.get(handler);

        // only test playing the first sounds of each library (just test the rest exist)
        String firstSound = (String)charMap.values().toArray()[0];

        soundRecorder.playAudioFile(PGTUtil.IPA_SOUNDS_LOCATION + PGTUtil.UCLA_WAV_LOCATION + firstSound + PGTUtil.WAV_SUFFIX);
        soundRecorder.playAudioFile(PGTUtil.IPA_SOUNDS_LOCATION + PGTUtil.WIKI_WAV_LOCATION + firstSound + PGTUtil.WAV_SUFFIX);
    } catch (Exception e) {
        IOHandler.writeErrorLog(e, e.getLocalizedMessage());
        fail(e);
    }
}
 
Example #24
Source File: JobRestControllerIntegrationTest.java    From genie with Apache License 2.0 5 votes vote down vote up
@Test
void testSubmitJobMethodInvalidCommandCriteria() throws Exception {
    Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);

    final List<ClusterCriteria> clusterCriteriaList
        = Lists.newArrayList(new ClusterCriteria(Sets.newHashSet("ok")));

    final String jobId = UUID.randomUUID().toString();

    final Set<String> commandCriteria = Sets.newHashSet(" ", "", null);
    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()));

    RestAssured
        .given(this.getRequestSpecification())
        .when()
        .port(this.port)
        .get(JOBS_API + "/{id}/status", jobId)
        .then()
        .statusCode(Matchers.is(HttpStatus.NOT_FOUND.value()));
}
 
Example #25
Source File: JobMonitorTest.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #26
Source File: WebHookTokenTests.java    From roboslack with Apache License 2.0 5 votes vote down vote up
@Test
void testFromEnvironment() {
    List<String> keysMissingFromEnvironment = WebHookToken.Env.missingTokenKeys();
    Assumptions.assumeTrue(keysMissingFromEnvironment.isEmpty(),
            () -> String.format("Skipping test, environment keys not found: [%s]",
                    Joiner.on(", ").join(keysMissingFromEnvironment)));
    WebHookToken token = WebHookToken.fromEnvironment();
    Assertions.assertFalse(Strings.isNullOrEmpty(token.partB()));
    Assertions.assertFalse(Strings.isNullOrEmpty(token.partT()));
    Assertions.assertFalse(Strings.isNullOrEmpty(token.partX()));
    Assertions.assertFalse(Strings.isNullOrEmpty(token.toString()));
}
 
Example #27
Source File: ReportsTest.java    From jpeek with MIT License 5 votes vote down vote up
@BeforeEach
public void weAreOnline() {
    try {
        new TextOf(new URL("http://www.jpeek.org/")).asString();
    } catch (final IOException ex) {
        Logger.debug(this, "We are not online: %s", ex.getMessage());
        Assumptions.assumeTrue(false);
    }
}
 
Example #28
Source File: KubeClusterResource.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static synchronized KubeClusterResource getInstance() {
    if (cluster == null) {
        try {
            cluster = new KubeClusterResource();
            initNamespaces();
            LOGGER.info("Cluster default namespace is {}", cluster.getNamespace());
            LOGGER.info("Cluster command line client default namespace is {}", cluster.getTestNamespace());
        } catch (RuntimeException e) {
            Assumptions.assumeTrue(false, e.getMessage());
        }
    }
    return cluster;
}
 
Example #29
Source File: MetadataImportBasedOnSchemasTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ParameterizedTest
@MethodSource( "getSchemaEndpoints" )
public void postBasedOnSchema( String endpoint, String schema )
{
    RestApiActions apiActions = new RestApiActions( endpoint );

    List blacklistedEndpoints = Arrays.asList( "jobConfigurations",
        "relationshipTypes",
        "messageConversations",
        "users" ); //blacklisted because contains conditionally required properties, which are not marked as required

    List<SchemaProperty> schemaProperties = schemasActions.getRequiredProperties( schema );

    Assumptions.assumeFalse( blacklistedEndpoints.contains( endpoint ), "N/A test case - blacklisted endpoint." );
    Assumptions.assumeFalse(
        schemaProperties.stream().anyMatch( schemaProperty -> schemaProperty.getPropertyType() == PropertyType.COMPLEX ),
        "N/A test case - body would require COMPLEX objects." );

    // post
    JsonObject object = DataGenerator.generateObjectMatchingSchema( schemaProperties );
    ApiResponse response = apiActions.post( object );

    // validate response;
    ResponseValidationHelper.validateObjectCreation( response );

    // validate removal;
    response = apiActions.delete( response.extractUid() );

    ResponseValidationHelper.validateObjectRemoval( response, endpoint + " was not deleted" );
}
 
Example #30
Source File: SynthesisCommandsTests.java    From workcraft with MIT License 5 votes vote down vote up
@Test
public void duplicatorCscHierStandardCelementSynthesis() {
    // FIXME: Skip this test on Windows as petrify.exe produces significantly different circuit
    Assumptions.assumeFalse(DesktopApi.getOs().isWindows());
    String workName = PackageUtils.getPackagePath(getClass(), "duplicator-hier-csc.stg.work");
    testStandardCelementSynthesisCommand(workName, 8, 9);
}