Java 类org.junit.Assume 实例源码

项目:firebase-admin-java    文件:FirebaseAuthTest.java   
@Test
public void testCreateCustomToken() throws Exception {
  GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines.getCredentials(firebaseOptions);
  Assume.assumeTrue("Skipping testCredentialCertificateRequired for cert credential",
      credentials instanceof ServiceAccountCredentials);

  FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "testCreateCustomToken");
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync("user1").get();

  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), ServiceAccount.EDITOR.getEmail());
  assertEquals(parsedToken.getPayload().getIssuer(), ServiceAccount.EDITOR.getEmail());
  assertNull(parsedToken.getPayload().getDeveloperClaims());
  assertTrue(ServiceAccount.EDITOR.verifySignature(parsedToken));
}
项目:elastic-db-tools-for-java    文件:ScenarioTests.java   
@Test
@Category(value = ExcludeFromGatedCheckin.class)
public void basicScenarioListShardMapsWithSqlAuthentication() {
    // Try to create a test login
    Assume.assumeTrue("Failed to create sql login, test skipped", createTestLogin());

    SqlConnectionStringBuilder gsmSb = new SqlConnectionStringBuilder(Globals.SHARD_MAP_MANAGER_CONN_STRING);
    gsmSb.setIntegratedSecurity(false);
    gsmSb.setUser(testUser);
    gsmSb.setPassword(testPassword);

    SqlConnectionStringBuilder lsmSb = new SqlConnectionStringBuilder(Globals.SHARD_USER_CONN_STRING);
    lsmSb.setIntegratedSecurity(false);
    lsmSb.setUser(testUser);
    lsmSb.setPassword(testPassword);

    basicScenarioListShardMapsInternal(gsmSb.getConnectionString(), lsmSb.getConnectionString());

    // Drop test login
    dropTestLogin();
}
项目:hadoop    文件:TestLinuxContainerExecutor.java   
@Test
public void testNonSecureRunAsSubmitter() throws Exception {
  Assume.assumeTrue(shouldRun());
  Assume.assumeFalse(UserGroupInformation.isSecurityEnabled());
  String expectedRunAsUser = appSubmitter;
  conf.set(YarnConfiguration.NM_NONSECURE_MODE_LIMIT_USERS, "false");
  exec.setConf(conf);
  File touchFile = new File(workSpace, "touch-file");
  int ret = runAndBlock("touch", touchFile.getAbsolutePath());

  assertEquals(0, ret);
  FileStatus fileStatus =
      FileContext.getLocalFSFileContext().getFileStatus(
        new Path(touchFile.getAbsolutePath()));
  assertEquals(expectedRunAsUser, fileStatus.getOwner());
  cleanupAppFiles(expectedRunAsUser);
  // reset conf
  conf.unset(YarnConfiguration.NM_NONSECURE_MODE_LIMIT_USERS);
  exec.setConf(conf);
}
项目:qpp-conversion-tool    文件:StorageServiceImplIntegration.java   
@Before
public void setup() throws IllegalAccessException, NoSuchFieldException {

    Assume.assumeTrue(System.getProperty("skip.long") == null);
    TestUtils.disableSslCertChecking();

    amazonS3Client = AmazonS3ClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
                    LocalstackTestRunner.getEndpointS3(),
                    LocalstackTestRunner.getDefaultRegion()))
            .withChunkedEncodingDisabled(true)
            .withPathStyleAccessEnabled(true).build();
    amazonS3Client.createBucket(bucketName);

    S3Config config = new S3Config();

    Field field = StorageServiceImpl.class.getDeclaredField("s3TransferManager");
    field.setAccessible(true);
    field.set(underTest, config.s3TransferManager(amazonS3Client));

    field = StorageServiceImpl.class.getDeclaredField("environment");
    field.setAccessible(true);
    field.set(underTest, environment);
}
项目:openjdk-jdk10    文件:CompressedNullCheckTest.java   
@SuppressWarnings("try")
private void testImplicit(Integer i) {
    Assume.assumeTrue(runtime().getVMConfig().useCompressedOops);

    Container c = new Container();
    c.i = i;

    ResolvedJavaMethod method = getResolvedJavaMethod("testSnippet");
    Result expect = executeExpected(method, null, c);

    // make sure we don't get a profile that removes the implicit null check
    method.reprofile();

    OptionValues options = new OptionValues(getInitialOptions(), OptImplicitNullChecks, true);
    Result actual = executeActual(options, method, null, c);
    assertEquals(expect, actual);
}
项目:AppCoins-ethereumj    文件:GitHubJSONTestSuite.java   
public static void runGitHubJsonVMTest(String json) throws ParseException {
    Assume.assumeFalse("Online test is not available", json.equals(""));

    JSONParser parser = new JSONParser();
    JSONObject testSuiteObj = (JSONObject) parser.parse(json);

    TestSuite testSuite = new TestSuite(testSuiteObj);
    Iterator<TestCase> testIterator = testSuite.iterator();

    while (testIterator.hasNext()) {

        TestCase testCase = testIterator.next();

        TestRunner runner = new TestRunner();
        List<String> result = runner.runTestCase(testCase);
        try {
            Assert.assertTrue(result.isEmpty());
        } catch (AssertionError e) {
            System.out.println(String.format("Error on running testcase %s : %s", testCase.getName(), result.get(0)));
            throw e;
        }
    }
}
项目:hadoop-oss    文件:TestStat.java   
@Test(timeout=10000)
public void testStat() throws Exception {
  Assume.assumeTrue(Stat.isAvailable());
  FileSystem fs = FileSystem.getLocal(new Configuration());
  Path testDir = new Path(getTestRootPath(fs), "teststat");
  fs.mkdirs(testDir);
  Path sub1 = new Path(testDir, "sub1");
  Path sub2 = new Path(testDir, "sub2");
  fs.mkdirs(sub1);
  fs.createSymlink(sub1, sub2, false);
  FileStatus stat1 = new Stat(sub1, 4096l, false, fs).getFileStatus();
  FileStatus stat2 = new Stat(sub2, 0, false, fs).getFileStatus();
  assertTrue(stat1.isDirectory());
  assertFalse(stat2.isDirectory());
  fs.delete(testDir, true);
}
项目:hadoop    文件:TestStat.java   
@Test(timeout=10000)
public void testStat() throws Exception {
  Assume.assumeTrue(Stat.isAvailable());
  FileSystem fs = FileSystem.getLocal(new Configuration());
  Path testDir = new Path(getTestRootPath(fs), "teststat");
  fs.mkdirs(testDir);
  Path sub1 = new Path(testDir, "sub1");
  Path sub2 = new Path(testDir, "sub2");
  fs.mkdirs(sub1);
  fs.createSymlink(sub1, sub2, false);
  FileStatus stat1 = new Stat(sub1, 4096l, false, fs).getFileStatus();
  FileStatus stat2 = new Stat(sub2, 0, false, fs).getFileStatus();
  assertTrue(stat1.isDirectory());
  assertFalse(stat2.isDirectory());
  fs.delete(testDir, true);
}
项目:hadoop-oss    文件:TestOpensslCipher.java   
@Test(timeout=120000)
public void testDoFinalArguments() throws Exception {
  Assume.assumeTrue(OpensslCipher.getLoadingFailureReason() == null);
  OpensslCipher cipher = OpensslCipher.getInstance("AES/CTR/NoPadding");
  Assert.assertTrue(cipher != null);

  cipher.init(OpensslCipher.ENCRYPT_MODE, key, iv);

  // Require direct buffer
  ByteBuffer output = ByteBuffer.allocate(1024);

  try {
    cipher.doFinal(output);
    Assert.fail("Output buffer should be direct buffer.");
  } catch (IllegalArgumentException e) {
    GenericTestUtils.assertExceptionContains(
        "Direct buffer is required", e);
  }
}
项目:hadoop    文件:TestCryptoCodec.java   
@Test(timeout=120000)
public void testJceAesCtrCryptoCodec() throws Exception {
  if (!"true".equalsIgnoreCase(System.getProperty("runningWithNative"))) {
    LOG.warn("Skipping since test was not run with -Pnative flag");
    Assume.assumeTrue(false);
  }
  if (!NativeCodeLoader.buildSupportsOpenssl()) {
    LOG.warn("Skipping test since openSSL library not loaded");
    Assume.assumeTrue(false);
  }
  Assert.assertEquals(null, OpensslCipher.getLoadingFailureReason());
  cryptoCodecTest(conf, seed, 0, jceCodecClass, jceCodecClass, iv);
  cryptoCodecTest(conf, seed, count, jceCodecClass, jceCodecClass, iv);
  cryptoCodecTest(conf, seed, count, jceCodecClass, opensslCodecClass, iv);
  // Overflow test, IV: xx xx xx xx xx xx xx xx ff ff ff ff ff ff ff ff 
  for(int i = 0; i < 8; i++) {
    iv[8 + i] = (byte) 0xff;
  }
  cryptoCodecTest(conf, seed, count, jceCodecClass, jceCodecClass, iv);
  cryptoCodecTest(conf, seed, count, jceCodecClass, opensslCodecClass, iv);
}
项目:openjdk-jdk10    文件:DeoptimizeOnExceptionTest.java   
@Test
public void test3() {
    Assume.assumeTrue("Only works on jdk8 right now", Java8OrEarlier);
    ResolvedJavaMethod method = getResolvedJavaMethod("test3Snippet");

    for (int i = 0; i < 2; i++) {
        Result actual;
        boolean expectedCompiledCode = (method.getProfilingInfo().getDeoptimizationCount(DeoptimizationReason.NotCompiledExceptionHandler) != 0);
        InstalledCode code = getCode(method, null, false, true, new OptionValues(getInitialOptions(), HighTier.Options.Inline, false));
        assertTrue(code.isValid());

        try {
            actual = new Result(code.executeVarargs(false), null);
        } catch (Exception e) {
            actual = new Result(null, e);
        }

        assertTrue(i > 0 == expectedCompiledCode, "expect compiled code to stay around after the first iteration");
        assertEquals(new Result(expectedCompiledCode, null), actual);
        assertTrue(expectedCompiledCode == code.isValid());
    }
}
项目:cyberduck    文件:MantaSearchFeatureTest.java   
@Test
public void testSearchSameDirectory() throws Exception {
    Assume.assumeTrue(session.getClient().existsAndIsAccessible(testPathPrefix.getAbsolute()));

    final String newDirectoryName = new AlphanumericRandomStringService().random();
    final Path newDirectory = new Path(testPathPrefix, newDirectoryName, TYPE_DIRECTORY);
    final String newFileName = new AlphanumericRandomStringService().random();
    new MantaDirectoryFeature(session).mkdir(newDirectory, null, null);
    new MantaTouchFeature(session).touch(new Path(newDirectory, newFileName, TYPE_FILE), null);

    final MantaSearchFeature s = new MantaSearchFeature(session);
    final AttributedList<Path> search = s.search(newDirectory, new NullFilter<>(), new DisabledListProgressListener());

    assertEquals(1, search.size());
    assertEquals(newFileName, search.get(0).getName());
}
项目:hadoop    文件:TestDFSClientFailover.java   
/**
 * Spy on the Java DNS infrastructure.
 * This likely only works on Sun-derived JDKs, but uses JUnit's
 * Assume functionality so that any tests using it are skipped on
 * incompatible JDKs.
 */
private NameService spyOnNameService() {
  try {
    Field f = InetAddress.class.getDeclaredField("nameServices");
    f.setAccessible(true);
    Assume.assumeNotNull(f);
    @SuppressWarnings("unchecked")
    List<NameService> nsList = (List<NameService>) f.get(null);

    NameService ns = nsList.get(0);
    Log log = LogFactory.getLog("NameServiceSpy");

    ns = Mockito.mock(NameService.class,
        new GenericTestUtils.DelegateAnswer(log, ns));
    nsList.set(0, ns);
    return ns;
  } catch (Throwable t) {
    LOG.info("Unable to spy on DNS. Skipping test.", t);
    // In case the JDK we're testing on doesn't work like Sun's, just
    // skip the test.
    Assume.assumeNoException(t);
    throw new RuntimeException(t);
  }
}
项目:ModifiableVariable    文件:ModifiableByteArrayTest.java   
/**
 * Test of setDeleteLastBytes method, of class ModifiableByteArray.
 */
@Test
public void testDeleteLastBytes() {
    LOGGER.info("testDeleteLastBytes");
    // Löscht modification lenght viele bytes
    Assume.assumeTrue(modification1.length < originalValue.length);
    int len = originalValue.length - modification1.length;
    byte[] expResult = new byte[len];
    System.arraycopy(originalValue, 0, expResult, 0, len);
    VariableModification<byte[]> modifier = ByteArrayModificationFactory.delete(len, modification1.length);
    start.setModification(modifier);

    LOGGER.debug("Expected: " + ArrayConverter.bytesToHexString(expResult));
    LOGGER.debug("Computed: " + ArrayConverter.bytesToHexString(start.getValue()));
    assertArrayEquals(expResult, start.getValue());

}
项目:hashsdn-controller    文件:DistributedDataStoreRemotingIntegrationTest.java   
@Test
public void testReadWriteMessageSlicing() throws Exception {
    // The slicing is only implemented for tell-based protocol
    Assume.assumeTrue(testParameter.equals(ClientBackedDataStore.class));

    leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
    followerDatastoreContextBuilder.maximumMessageSliceSize(100);
    initDatastoresWithCars("testLargeReadReplySlicing");

    final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();

    final NormalizedNode<?, ?> carsNode = CarsModel.create();
    rwTx.write(CarsModel.BASE_PATH, carsNode);

    verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
}
项目:dremio-oss    文件:TestSupportService.java   
@Test
@Ignore("DX-4093")
public void failSupport() throws Exception {
  Assume.assumeTrue(!BaseTestServer.isMultinode());

  String badFileName = "fake_file_one";
  final Invocation invocation = getBuilder(
      getAPIv2()
          .path("datasets/new_untitled_sql")
          .queryParam("newVersion", newVersion())
  ).buildPost(Entity.entity(new CreateFromSQL("select * from " + badFileName, null), MediaType.APPLICATION_JSON_TYPE));
  expectError(FamilyExpectation.CLIENT_ERROR, invocation, Object.class);

  List<Job> jobs = ImmutableList.copyOf(l(JobsService.class).getAllJobs("*=contains=" + badFileName, null, null, 0, 1, null));
  assertEquals(1, jobs.size());
  Job job = jobs.get(0);
  String url = "/support/" + job.getJobId().getId();
  SupportResponse response = expectSuccess(getBuilder(url).buildPost(null), SupportResponse.class);
  assertTrue(response.getUrl().contains("Unable to upload diagnostics"));
  assertTrue("Failure including logs.", response.isIncludesLogs());
}
项目:hadoop    文件:TestCryptoCodec.java   
@Test(timeout=120000)
public void testOpensslAesCtrCryptoCodec() throws Exception {
  if (!"true".equalsIgnoreCase(System.getProperty("runningWithNative"))) {
    LOG.warn("Skipping since test was not run with -Pnative flag");
    Assume.assumeTrue(false);
  }
  if (!NativeCodeLoader.buildSupportsOpenssl()) {
    LOG.warn("Skipping test since openSSL library not loaded");
    Assume.assumeTrue(false);
  }
  Assert.assertEquals(null, OpensslCipher.getLoadingFailureReason());
  cryptoCodecTest(conf, seed, 0, opensslCodecClass, opensslCodecClass, iv);
  cryptoCodecTest(conf, seed, count, opensslCodecClass, opensslCodecClass, iv);
  cryptoCodecTest(conf, seed, count, opensslCodecClass, jceCodecClass, iv);
  // Overflow test, IV: xx xx xx xx xx xx xx xx ff ff ff ff ff ff ff ff 
  for(int i = 0; i < 8; i++) {
    iv[8 + i] = (byte) 0xff;
  }
  cryptoCodecTest(conf, seed, count, opensslCodecClass, opensslCodecClass, iv);
  cryptoCodecTest(conf, seed, count, opensslCodecClass, jceCodecClass, iv);
}
项目:syndesis    文件:ConnectorsITCase.java   
@Test
@Ignore
public void verifyBadTwitterConnectionSettings() throws IOException {

    // AlwaysOkVerifier never fails.. do don't try this test case, if that's
    // whats being used.
    Assume.assumeFalse(verifier instanceof AlwaysOkVerifier);

    final Properties credentials = new Properties();
    try (InputStream is = getClass().getResourceAsStream("/valid-twitter-keys.properties")) {
        credentials.load(is);
    }
    credentials.put("accessTokenSecret", "badtoken");

    final ResponseEntity<Verifier.Result> response = post("/api/v1/connectors/twitter/verifier/connectivity", credentials,
        Verifier.Result.class);
    assertThat(response.getStatusCode()).as("component list status code").isEqualTo(HttpStatus.OK);
    final Verifier.Result result = response.getBody();
    assertThat(result).isNotNull();
    assertThat(result.getStatus()).isEqualTo(Verifier.Result.Status.ERROR);
    assertThat(result.getErrors()).isNotEmpty();
}
项目:hekate    文件:AwsCloudSeedNodeProviderTest.java   
@BeforeClass
public static void setUpClass() throws RunNodesException {
    Assume.assumeTrue(HekateTestProps.is("AWS_TEST_ENABLED"));

    Properties props = new Properties();

    props.setProperty(LocationConstants.PROPERTY_REGIONS, REGION);

    ContextBuilder builder = newBuilder("aws-ec2").credentials(
        ACCESS_KEY,
        SECRET_KEY
    ).overrides(props);

    ComputeService compute = builder.modules(ImmutableSet.<Module>of(new SLF4JLoggingModule()))
        .buildView(ComputeServiceContext.class)
        .getComputeService();

    for (int i = 0; i < 4; i++) {
        ensureNodeExists(i, compute);
    }
}
项目:hadoop    文件:TestLinuxContainerExecutor.java   
@Test
public void testContainerLaunch() throws Exception {
  Assume.assumeTrue(shouldRun());
  String expectedRunAsUser =
      conf.get(YarnConfiguration.NM_NONSECURE_MODE_LOCAL_USER_KEY,
        YarnConfiguration.DEFAULT_NM_NONSECURE_MODE_LOCAL_USER);

  File touchFile = new File(workSpace, "touch-file");
  int ret = runAndBlock("touch", touchFile.getAbsolutePath());

  assertEquals(0, ret);
  FileStatus fileStatus =
      FileContext.getLocalFSFileContext().getFileStatus(
        new Path(touchFile.getAbsolutePath()));
  assertEquals(expectedRunAsUser, fileStatus.getOwner());
  cleanupAppFiles(expectedRunAsUser);

}
项目:crnk-framework    文件:JsonApiResponseFilterTestBase.java   
@Test
public void testNullResponse() throws Exception {
    // GIVEN
    // mapping of null responses to JSON-API disabled
    Assume.assumeFalse(enableNullResponse);

    // WHEN
    Response response = get("/repositoryActionWithNullResponse", null);

    // THEN
    Assert.assertNotNull(response);
    assertThat(response.getStatus())
            .describedAs("Status code")
            .isEqualTo(Response.Status.NO_CONTENT.getStatusCode());
    MediaType mediaType = response.getMediaType();
    assertThat(mediaType)
            .describedAs("Media-Type")
            .isEqualTo(null);
}
项目:hadoop    文件:TestEnhancedByteBufferAccess.java   
public static HdfsConfiguration initZeroCopyTest() {
  Assume.assumeTrue(NativeIO.isAvailable());
  Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
  HdfsConfiguration conf = new HdfsConfiguration();
  conf.setBoolean(DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY, true);
  conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
  conf.setInt(DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_SIZE, 3);
  conf.setLong(DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_TIMEOUT_MS, 100);
  conf.set(DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY,
      new File(sockDir.getDir(),
        "TestRequestMmapAccess._PORT.sock").getAbsolutePath());
  conf.setBoolean(DFSConfigKeys.
      DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_KEY, true);
  conf.setLong(DFS_HEARTBEAT_INTERVAL_KEY, 1);
  conf.setLong(DFS_CACHEREPORT_INTERVAL_MSEC_KEY, 1000);
  conf.setLong(DFS_NAMENODE_PATH_BASED_CACHE_REFRESH_INTERVAL_MS, 1000);
  return conf;
}
项目:openjdk-jdk10    文件:StaticInterfaceFieldTest.java   
@SuppressWarnings("try")
private void eagerlyParseMethod(Class<C> clazz, String methodName) {
    RuntimeProvider rt = Graal.getRequiredCapability(RuntimeProvider.class);
    Providers providers = rt.getHostBackend().getProviders();
    MetaAccessProvider metaAccess = providers.getMetaAccess();

    PhaseSuite<HighTierContext> graphBuilderSuite = new PhaseSuite<>();
    Plugins plugins = new Plugins(new InvocationPlugins());
    GraphBuilderConfiguration config = GraphBuilderConfiguration.getDefault(plugins).withEagerResolving(true);
    graphBuilderSuite.appendPhase(new GraphBuilderPhase(config));
    HighTierContext context = new HighTierContext(providers, graphBuilderSuite, OptimisticOptimizations.NONE);

    Assume.assumeTrue(VerifyPhase.class.desiredAssertionStatus());

    final Method m = getMethod(clazz, methodName);
    ResolvedJavaMethod method = metaAccess.lookupJavaMethod(m);
    OptionValues options = getInitialOptions();
    DebugContext debug = DebugContext.create(options, DebugHandlersFactory.LOADER);
    StructuredGraph graph = new StructuredGraph.Builder(options, debug).method(method).build();
    try (DebugCloseable s = debug.disableIntercept(); DebugContext.Scope ds = debug.scope("GraphBuilding", graph, method)) {
        graphBuilderSuite.apply(graph, context);
    } catch (Throwable e) {
        throw debug.handle(e);
    }
}
项目:hadoop    文件:TestLinuxContainerExecutor.java   
@Test(timeout = 10000)
public void testPostExecuteAfterReacquisition() throws Exception {
  Assume.assumeTrue(shouldRun());
  // make up some bogus container ID
  ApplicationId appId = ApplicationId.newInstance(12345, 67890);
  ApplicationAttemptId attemptId =
      ApplicationAttemptId.newInstance(appId, 54321);
  ContainerId cid = ContainerId.newContainerId(attemptId, 9876);

  Configuration conf = new YarnConfiguration();
  conf.setClass(YarnConfiguration.NM_LINUX_CONTAINER_RESOURCES_HANDLER,
    TestResourceHandler.class, LCEResourcesHandler.class);
  LinuxContainerExecutor lce = new LinuxContainerExecutor();
  lce.setConf(conf);
  try {
    lce.init();
  } catch (IOException e) {
    // expected if LCE isn't setup right, but not necessary for this test
  }

  Container container = mock(Container.class);
  ContainerLaunchContext context = mock(ContainerLaunchContext.class);
  HashMap<String, String> env = new HashMap<>();

  when(container.getLaunchContext()).thenReturn(context);
  when(context.getEnvironment()).thenReturn(env);

  lce.reacquireContainer(new ContainerReacquisitionContext.Builder()
      .setContainer(container)
      .setUser("foouser")
      .setContainerId(cid)
      .build());
  assertTrue("postExec not called after reacquisition",
      TestResourceHandler.postExecContainers.contains(cid));
}
项目:openjdk-jdk10    文件:HotSpotStampMemoryAccessTest.java   
@Ignore("not all versions are safe yet")
@Test
public void testReadNarrowObject() {
    CompressEncoding oopEncoding = runtime().getVMConfig().getOopEncoding();
    Assume.assumeTrue("Compressed oops must be enabled", runtime().getVMConfig().useCompressedOops);
    MemoryAccessProvider memory = getConstantReflection().getMemoryAccessProvider();
    JavaConstant base = getSnippetReflection().forObject("");
    ObjectStamp stamp = (ObjectStamp) StampFactory.forKind(JavaKind.Object);
    Stamp narrowStamp = HotSpotNarrowOopStamp.compressed(stamp, oopEncoding);
    assertTrue(narrowStamp.readConstant(memory, base, 128) == null);
}
项目:wolfcrypt-jni    文件:HmacTest.java   
@BeforeClass
public static void checkAvailability() {
    try {
        new Hmac();
    } catch (WolfCryptException e) {
        if (e.getError() == WolfCryptError.NOT_COMPILED_IN)
            System.out.println("Hmac test skipped: " + e.getError());
        Assume.assumeNoException(e);
    }
}
项目:springboot-shiro-cas-mybatis    文件:MemCacheTicketRegistryTests.java   
@Before
public void setUp() throws IOException {

    // Abort tests if there is no memcached server available on localhost:11211.
    final boolean environmentOk = isMemcachedListening();
    if (!environmentOk) {
        logger.warn("Aborting test since no memcached server is available on localhost.");
    }
    Assume.assumeTrue(environmentOk);
    final ApplicationContext context = new ClassPathXmlApplicationContext("/ticketRegistry-test.xml");
    registry = context.getBean(registryBean, MemCacheTicketRegistry.class);
}
项目:gplaymusic    文件:PlaylistTest.java   
@Test
public void getSharedPlaylistContent() throws IOException {
  List<Playlist> playlists = getApi().getPlaylistApi().listPlaylists();
  assume(playlists);
  Optional<Playlist> sharedPlaylistOptional =
      playlists.stream().filter(p -> p.getType().equals(Playlist.PlaylistType.SHARED)).findFirst();
  Assume.assumeTrue("Test could not be run. No shared playlist found.",
      sharedPlaylistOptional.isPresent());
  Playlist sharedPlaylist = sharedPlaylistOptional.get();
  List<PlaylistEntry> entries = sharedPlaylist.getContents(100);
  assertNotNull(entries);
  testPlaylistEntries(entries);
  System.out.printf("%d playlist entries found and validated.\n", entries.size());
}
项目:r8    文件:ToolHelper.java   
public static ProcessResult runDX(String[] args) throws IOException {
  Assume.assumeTrue(ToolHelper.artSupported());
  DXCommandBuilder builder = new DXCommandBuilder();
  for (String arg : args) {
    builder.appendProgramArgument(arg);
  }
  return runProcess(builder.asProcessBuilder());
}
项目:r8    文件:ToolHelper.java   
private static ProcessResult runArtProcess(ArtCommandBuilder builder) throws IOException {
  Assume.assumeTrue(ToolHelper.artSupported());
  ProcessResult result = runProcess(builder.asProcessBuilder());
  if (result.exitCode != 0) {
    fail("Unexpected art failure: '" + result.stderr + "'\n" + result.stdout);
  }
  return result;
}
项目:openjdk-jdk10    文件:TimerKeyTest.java   
@Before
public void checkCapabilities() {
    try {
        ThreadMXBean threadMXBean = Management.getThreadMXBean();
        Assume.assumeTrue("skipping management interface test", threadMXBean.isCurrentThreadCpuTimeSupported());
    } catch (LinkageError err) {
        Assume.assumeNoException("Cannot run without java.management JDK9 module", err);
    }
}
项目:openjdk-jdk10    文件:DebugContextTest.java   
/**
 * Tests that using a {@link DebugContext} on a thread other than the one on which it was
 * created causes an assertion failure.
 */
@Test
public void testInvariantChecking() throws InterruptedException {
    Assume.assumeTrue(Assertions.assertionsEnabled());
    EconomicMap<OptionKey<?>, Object> map = EconomicMap.create();
    // Configure with an option that enables counters
    map.put(DebugOptions.Counters, "");
    OptionValues options = new OptionValues(map);
    DebugContext debug = DebugContext.create(options, DebugHandlersFactory.LOADER);
    CounterKey counter = DebugContext.counter("DebugContextTestCounter");
    AssertionError[] result = {null};
    Thread thread = new Thread() {

        @Override
        public void run() {
            try {
                counter.add(debug, 1);
            } catch (AssertionError e) {
                result[0] = e;
            }
        }
    };
    thread.start();
    thread.join();

    Assert.assertNotNull("Expected thread to throw AssertionError", result[0]);
}
项目:hadoop-oss    文件:TestSshFenceByTcpPort.java   
@Test(timeout=20000)
public void testFence() throws BadFencingConfigurationException {
  Assume.assumeTrue(isConfigured());
  Configuration conf = new Configuration();
  conf.set(SshFenceByTcpPort.CONF_IDENTITIES_KEY, TEST_KEYFILE);
  SshFenceByTcpPort fence = new SshFenceByTcpPort();
  fence.setConf(conf);
  assertTrue(fence.tryFence(
      TEST_TARGET,
      null));
}
项目:hadoop-oss    文件:TestStat.java   
@Test(timeout=10000)
public void testStatFileNotFound() throws Exception {
  Assume.assumeTrue(Stat.isAvailable());
  try {
    stat.getFileStatus();
    fail("Expected FileNotFoundException");
  } catch (FileNotFoundException e) {
    // expected
  }
}
项目:wolfcrypt-jni    文件:EccTest.java   
@BeforeClass
public static void checkAvailability() {
    try {
        new Ecc();
    } catch (WolfCryptException e) {
        if (e.getError() == WolfCryptError.NOT_COMPILED_IN)
            System.out.println("Ecc test skipped: " + e.getError());
        Assume.assumeNoException(e);
    }
}
项目:calcite-avatica    文件:InsertTest.java   
@Test public void batchInsert() throws Exception {
  final String tableName = getTableName();
  try (Statement stmt = connection.createStatement()) {
    assertFalse(stmt.execute("DROP TABLE IF EXISTS " + tableName));
    String sql = "CREATE TABLE " + tableName
        + " (pk integer not null primary key, col1 varchar(10))";
    assertFalse(stmt.execute(sql));

    for (int i = 0; i < 10; i++) {
      sql = "INSERT INTO " + tableName + " values (" + i + ", '" + i + "')";
      try {
        stmt.addBatch(sql);
      } catch (SQLFeatureNotSupportedException e) {
        // batch isn't supported in this version, gracefully ignore,
        Assume.assumeTrue("Batch update is not support by the client", false);
      }
    }

    int[] updateCounts = stmt.executeBatch();
    int[] expectedUpdateCounts = new int[10];
    Arrays.fill(expectedUpdateCounts, 1);
    assertArrayEquals(expectedUpdateCounts, updateCounts);

    ResultSet results = stmt.executeQuery("SELECT * FROM " + tableName);
    assertNotNull(results);
    for (int i = 0; i < 10; i++) {
      assertTrue(results.next());
      assertEquals(i, results.getInt(1));
      assertEquals(Integer.toString(i), results.getString(1));
    }
    assertFalse(results.next());
    results.close();
  }
}
项目:hadoop    文件:TestBlockReaderLocalLegacy.java   
@Test
public void testBothOldAndNewShortCircuitConfigured() throws Exception {
  final short REPL_FACTOR = 1;
  final int FILE_LENGTH = 512;
  Assume.assumeTrue(null == DomainSocket.getLoadingFailureReason());
  TemporarySocketDirectory socketDir = new TemporarySocketDirectory();
  HdfsConfiguration conf = getConfiguration(socketDir);
  MiniDFSCluster cluster =
      new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
  cluster.waitActive();
  socketDir.close();
  FileSystem fs = cluster.getFileSystem();

  Path path = new Path("/foo");
  byte orig[] = new byte[FILE_LENGTH];
  for (int i = 0; i < orig.length; i++) {
    orig[i] = (byte)(i%10);
  }
  FSDataOutputStream fos = fs.create(path, (short)1);
  fos.write(orig);
  fos.close();
  DFSTestUtil.waitReplication(fs, path, REPL_FACTOR);
  FSDataInputStream fis = cluster.getFileSystem().open(path);
  byte buf[] = new byte[FILE_LENGTH];
  IOUtils.readFully(fis, buf, 0, FILE_LENGTH);
  fis.close();
  Assert.assertArrayEquals(orig, buf);
  Arrays.equals(orig, buf);
  cluster.shutdown();
}
项目:hadoop    文件:TestStat.java   
@Test(timeout=10000)
public void testStatFileNotFound() throws Exception {
  Assume.assumeTrue(Stat.isAvailable());
  try {
    stat.getFileStatus();
    fail("Expected FileNotFoundException");
  } catch (FileNotFoundException e) {
    // expected
  }
}
项目:openjdk-jdk10    文件:DataPatchTest.java   
@Test
public void testInlineNarrowObject() {
    Assume.assumeTrue(config.useCompressedOops);
    test(asm -> {
        ResolvedJavaType type = metaAccess.lookupJavaType(getConstClass());
        HotSpotConstant c = (HotSpotConstant) constantReflection.asJavaClass(type);
        Register compressed = asm.emitLoadPointer((HotSpotConstant) c.compress());
        Register ret = asm.emitUncompressPointer(compressed, config.narrowOopBase, config.narrowOopShift);
        asm.emitPointerRet(ret);
    });
}
项目:JRediClients    文件:RedissonBatchTest.java   
@Test
public void testSkipResult() {
    Assume.assumeTrue(RedisRunner.getDefaultRedisServerInstance().getRedisVersion().compareTo("3.2.0") > 0);
    RBatch batch = redisson.createBatch();
    batch.getBucket("A1").setAsync("001");
    batch.getBucket("A2").setAsync("001");
    batch.getBucket("A3").setAsync("001");
    batch.getKeys().deleteAsync("A1");
    batch.getKeys().deleteAsync("A2");
    batch.executeSkipResult();

    assertThat(redisson.getBucket("A1").isExists()).isFalse();
    assertThat(redisson.getBucket("A3").isExists()).isTrue();
}