Java Code Examples for org.junit.jupiter.api.Assumptions

The following examples show how to use org.junit.jupiter.api.Assumptions. These examples are extracted from open source projects. 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
@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 2
@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 3
Source Project: PolyGlot   Source File: PGrammarPaneTest.java    License: 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 4
Source Project: synopsys-detect   Source File: PipelinesTest.java    License: 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 5
@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 6
Source Project: PolyGlot   Source File: OpenScreensTest.java    License: 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 7
Source Project: synopsys-detect   Source File: PipelinesTest.java    License: 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 8
Source Project: synopsys-detect   Source File: BlackDuckIntegrationTest.java    License: 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 9
@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 10
Source Project: apm-agent-java   Source File: MdcActivationListenerIT.java    License: 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 11
Source Project: quarkus   Source File: Http2TestCase.java    License: 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 12
Source Project: genie   Source File: JobMonitorTest.java    License: 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 13
Source Project: genie   Source File: DiskCleanupTaskTest.java    License: 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 Project: genie   Source File: JobMonitorTest.java    License: 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 15
Source Project: genie   Source File: DiskCleanupTaskTest.java    License: 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 16
/**
 * 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 17
Source Project: cloudbreak   Source File: ExternalDatabaseServiceTest.java    License: 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 18
Source Project: genie   Source File: JobMonitorTest.java    License: 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 19
Source Project: synopsys-detect   Source File: DetectorFinderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@DisabledOnOs(WINDOWS) //TODO: See if we can fix on windows.
public void testSimple() throws DetectorFinderDirectoryListException {
    Assumptions.assumeFalse(SystemUtils.IS_OS_WINDOWS);

    final File initialDirectory = initialDirectoryPath.toFile();
    final File subDir = new File(initialDirectory, "testSimple");
    subDir.mkdirs();

    final File subSubDir1 = new File(subDir, "subSubDir1");
    subSubDir1.mkdir();

    final File subSubDir2 = new File(subDir, "subSubDir2");
    subSubDir2.mkdir();

    final DetectorRuleSet detectorRuleSet = new DetectorRuleSet(new ArrayList<>(0), new HashMap<>(0), new HashMap<>());
    final Predicate<File> fileFilter = f -> true;
    final int maximumDepth = 10;
    final DetectorFinderOptions options = new DetectorFinderOptions(fileFilter, maximumDepth);

    final DetectorFinder finder = new DetectorFinder();
    final Optional<DetectorEvaluationTree> tree = finder.findDetectors(initialDirectory, detectorRuleSet, options);

    // make sure both dirs were found
    final Set<DetectorEvaluationTree> testDirs = tree.get().getChildren();
    DetectorEvaluationTree simpleTestDir = null;
    for (final DetectorEvaluationTree testDir : testDirs) {
        if (testDir.getDirectory().getName().equals("testSimple")) {
            simpleTestDir = testDir;
            break;
        }
    }
    final Set<DetectorEvaluationTree> subDirResults = simpleTestDir.getChildren();
    assertEquals(2, subDirResults.size());
    final String subDirContentsName = subDirResults.iterator().next().getDirectory().getName();
    assertTrue(subDirContentsName.startsWith("subSubDir"));
}
 
Example 20
Source Project: PolyGlot   Source File: FormattedTextHelperTest.java    License: MIT License 5 votes vote down vote up
public FormattedTextHelperTest() {
    Assumptions.assumeFalse(GraphicsEnvironment.isHeadless());
    
    System.out.println("FormattedTextHelperTest.FormattedTextHelperTest");
    core = DummyCore.newCore();
    try {
        core.readFile(PGTUtil.TESTRESOURCES + "Lodenkur_TEST.pgd");
    } catch (IOException | IllegalStateException e) {
        IOHandler.writeErrorLog(e, "FORMATTEDTEXTHELPERTEST");
    }
}
 
Example 21
Source Project: PolyGlot   Source File: IPAHandlerTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testPlayProcUcla() {
    Assumptions.assumeFalse(GraphicsEnvironment.isHeadless());
    
    System.out.println("IPAHandlerTest.testPlayProcUcla");
    
    IPAHandler handler = new IPAHandler(null);
    
    try {
        handler.playChar("a", IPAHandler.IPALibrary.UCLA_IPA);
    } catch (Exception e) {
        fail(e);
    }
}
 
Example 22
Source Project: synopsys-detect   Source File: BatteryTest.java    License: Apache License 2.0 5 votes vote down vote up
private void checkEnvironment() {
    Assumptions.assumeTrue(StringUtils.isNotBlank(System.getenv().get("BATTERY_TESTS_PATH")), "The environment variable BATTERY_TESTS_PATH must be set.");

    batteryDirectory = new File(System.getenv("BATTERY_TESTS_PATH"));
    if (!batteryDirectory.exists()) {
        Assertions.assertTrue(batteryDirectory.mkdirs(), String.format("Failed to create battery directory at: %s", batteryDirectory.getAbsolutePath()));
    }
    Assertions.assertTrue(batteryDirectory.exists(), "The detect battery path must exist.");
}
 
Example 23
Source Project: kogito-runtimes   Source File: SwitchOverStringTest.java    License: Apache License 2.0 5 votes vote down vote up
@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!");
}
 
Example 24
Source Project: helidon-build-tools   Source File: MetadataTestServer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param port The port to listen on.
 * @param latest The version to return for the "/latest" request.
 * @param verbose Whether or not to do verbose logging.
 */
@SuppressWarnings("ConstantConditions")
public MetadataTestServer(int port, TestVersion latest, boolean verbose) {
    if (MockServer.class.getClassLoader() != ClassLoader.getSystemClassLoader()) {
        final String reason = "MockServer must be in system class loader";
        Log.info("$(italic,yellow Skipping: %s)", reason);
        Assumptions.assumeTrue(false, reason);
    }
    ConfigurationProperties.logLevel(verbose ? VERBOSE_LEVEL : NORMAL_LEVEL);
    this.port = port;
    this.url = URL_PREFIX + port;
    this.latest = latest;
}
 
Example 25
Source Project: fdb-record-layer   Source File: RecordTypeKeyTest.java    License: Apache License 2.0 5 votes vote down vote up
@ParameterizedTest(name = "testDoublyBoundedScanWithSort [sortExpr = {0}, reverse = {1}]")
@MethodSource("sortArgs")
public void testDoublyBoundedScanWithSort(@Nonnull KeyExpression sortExpr, boolean reverse) throws Exception {
    List<FDBStoredRecord<Message>> recs = saveSomeRecords(BASIC_HOOK);

    try (FDBRecordContext context = openContext()) {
        openSimpleRecordStore(context, BASIC_HOOK);

        RecordQuery query = RecordQuery.newBuilder()
                .setRecordType("MySimpleRecord")
                .setFilter(Query.and(
                        Query.field("rec_no").greaterThan(200L),
                        Query.field("rec_no").lessThan(500L)))
                .setSort(sortExpr, reverse)
                .build();
        final RecordQueryPlan plan = planner.plan(query);

        List<FDBStoredRecord<Message>> expectedResults = recs.subList(1, 2);
        if (reverse) {
            expectedResults = Lists.reverse(expectedResults);
        }
        assertEquals(expectedResults, recordStore.executeQuery(query)
                .map(FDBQueriedRecord::getStoredRecord).asList().join());
        // This is currently broken on concat(recordType(), field("rec_no")).
        // See: https://github.com/FoundationDB/fdb-record-layer/issues/744
        Assumptions.assumeTrue(sortExpr.getColumnSize() == 1,
                "sort not correctly planned yet if record type is in sort expression");
        assertThat(plan, scan(bounds(anyOf(
                hasTupleString("[IS MySimpleRecord, [GREATER_THAN 200 && LESS_THAN 500]]"),
                hasTupleString("[IS MySimpleRecord, [LESS_THAN 500 && GREATER_THAN 200]]")))));
    }
}
 
Example 26
Source Project: fdb-record-layer   Source File: VersionIndexTest.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private static FDBRecordVersion getSmallerVersion(@Nonnull FDBRecordVersion olderVersion) {
    byte[] versionBytes = olderVersion.toBytes();
    int i = 0;
    while (i < versionBytes.length) {
        if (versionBytes[i] != 0L) {
            versionBytes[i]--;
            break;
        }
        i++;
    }
    Assumptions.assumeTrue(i != versionBytes.length, "could not decrease version as all bytes were 0");
    return FDBRecordVersion.fromBytes(versionBytes);
}
 
Example 27
Source Project: fdb-record-layer   Source File: VersionIndexTest.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private static FDBRecordVersion getBiggerVersion(@Nonnull FDBRecordVersion olderVersion) {
    byte[] versionBytes = olderVersion.toBytes();
    int i = 0;
    while (i < versionBytes.length) {
        if (versionBytes[i] != (byte)-1) {
            versionBytes[i]++;
            break;
        }
        i++;
    }
    Assumptions.assumeTrue(i != versionBytes.length, "could not increase version as all bytes were 0xff");
    return FDBRecordVersion.fromBytes(versionBytes);
}
 
Example 28
Source Project: quarkus   Source File: NativeImageIT.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests that the {@code java.library.path} can be overridden/configurable by passing the system property
 * when launching the generated application's native image.
 *
 * @throws Exception
 */
@Test
public void testJavaLibraryPathAtRuntime() throws Exception {
    final File testDir = initProject("projects/native-image-app", "projects/native-image-app-output");
    final RunningInvoker running = new RunningInvoker(testDir, false);

    // trigger mvn package -Pnative -Dquarkus.ssl.native=true
    final String[] mvnArgs = new String[] { "package", "-DskipTests", "-Pnative", "-Dquarkus.ssl.native=true" };
    final MavenProcessInvocationResult result = running.execute(Arrays.asList(mvnArgs), Collections.emptyMap());
    await().atMost(5, TimeUnit.MINUTES).until(() -> result.getProcess() != null && !result.getProcess().isAlive());
    final String processLog = running.log();
    try {
        assertThat(processLog).containsIgnoringCase("BUILD SUCCESS");
    } catch (AssertionError ae) {
        // skip this test (instead of failing), if the native-image command wasn't available.
        // Bit brittle to rely on the log message, but it's OK in the context of this test
        Assumptions.assumeFalse(processLog.contains("Cannot find the `native-image"),
                "Skipping test since native-image tool isn't available");
        // native-image command was available but the build failed for some reason, throw the original error
        throw ae;
    } finally {
        running.stop();
    }

    // now that the native image is built, run it
    final Path nativeImageRunner = testDir.toPath().toAbsolutePath().resolve(Paths.get("target/acme-1.0-SNAPSHOT-runner"));
    final Path tmpDir = Files.createTempDirectory("native-image-test");
    tmpDir.toFile().deleteOnExit();
    final Process nativeImageRunWithAdditionalLibPath = runNativeImage(nativeImageRunner,
            new String[] { "-Djava.library.path=" + tmpDir.toString() });
    try {
        final String response = DevModeTestUtils.getHttpResponse("/hello/javaLibraryPath");
        Assertions.assertTrue(response.contains(tmpDir.toString()),
                "Response " + response + " for java.library.path was expected to contain the " + tmpDir + ", but didn't");
    } finally {
        nativeImageRunWithAdditionalLibPath.destroy();
    }

}
 
Example 29
Source Project: quarkus   Source File: Http2Test.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 30
Source Project: genie   Source File: UnixProcessCheckerTest.java    License: 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
}