org.junit.rules.TemporaryFolder Java Examples

The following examples show how to use org.junit.rules.TemporaryFolder. 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: RocksDBResource.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected void before() throws Throwable {
	this.temporaryFolder = new TemporaryFolder();
	this.temporaryFolder.create();
	final File rocksFolder = temporaryFolder.newFolder();
	this.dbOptions = optionsFactory.createDBOptions(PredefinedOptions.DEFAULT.createDBOptions()).
		setCreateIfMissing(true);
	this.columnFamilyOptions = optionsFactory.createColumnOptions(PredefinedOptions.DEFAULT.createColumnOptions());
	this.writeOptions = new WriteOptions();
	this.writeOptions.disableWAL();
	this.readOptions = new ReadOptions();
	this.columnFamilyHandles = new ArrayList<>(1);
	this.rocksDB = RocksDB.open(
		dbOptions,
		rocksFolder.getAbsolutePath(),
		Collections.singletonList(new ColumnFamilyDescriptor("default".getBytes(), columnFamilyOptions)),
		columnFamilyHandles);
	this.batchWrapper = new RocksDBWriteBatchWrapper(rocksDB, writeOptions);
}
 
Example #2
Source File: AvroTestUtil.java    From parquet-mr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <D> File write(TemporaryFolder temp, Configuration conf, GenericData model, Schema schema, D... data)
    throws IOException {
  File file = temp.newFile();
  Assert.assertTrue(file.delete());

  try (ParquetWriter<D> writer = AvroParquetWriter
    .<D>builder(new Path(file.toString()))
    .withDataModel(model)
    .withSchema(schema)
    .build()) {
    for (D datum : data) {
      writer.write(datum);
    }
  }

  return file;
}
 
Example #3
Source File: JerseySpecifics.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public TestRule createTestRule() {
  final TemporaryFolder tempFolder = new TemporaryFolder();

  return RuleChain
    .outerRule(tempFolder)
    .around(new ExternalResource() {

      TomcatServerBootstrap bootstrap = new JerseyTomcatServerBootstrap(webXmlResource);

      protected void before() throws Throwable {
        bootstrap.setWorkingDir(tempFolder.getRoot().getAbsolutePath());
        bootstrap.start();
      }

      protected void after() {
        bootstrap.stop();
      }
    });
}
 
Example #4
Source File: KafkaEmbedded.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and starts an embedded Kafka broker.
 *
 * @param config Broker configuration settings.  Used to modify, for example, the listeners
 *               the broker should use.  Note that you cannot change some settings such as
 *               `log.dirs`.
 */
public KafkaEmbedded(final Properties config) throws IOException {
  this.tmpFolder = new TemporaryFolder();
  this.tmpFolder.create();
  this.logDir = tmpFolder.newFolder();
  this.effectiveConfig = effectiveConfigFrom(config, logDir);

  final KafkaConfig kafkaConfig = new KafkaConfig(effectiveConfig, true);
  log.debug("Starting embedded Kafka broker (with log.dirs={} and ZK ensemble at {}) ...",
      logDir, zookeeperConnect());

  kafka = TestUtils.createServer(kafkaConfig, new SystemTime());
  log.debug("Startup of embedded Kafka broker at {} completed (with ZK ensemble at {}) ...",
      brokerList(), zookeeperConnect());
}
 
Example #5
Source File: RuleKeyLoggerListenerTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  TemporaryFolder tempDirectory = new TemporaryFolder();
  tempDirectory.create();
  projectFilesystem =
      TestProjectFilesystems.createProjectFilesystem(tempDirectory.getRoot().toPath());
  outputExecutor =
      MostExecutors.newSingleThreadExecutor(
          new CommandThreadFactory(
              getClass().getName(), GlobalStateManager.singleton().getThreadToCommandRegister()));
  info =
      InvocationInfo.of(
          new BuildId(),
          false,
          false,
          "topspin",
          ImmutableList.of(),
          ImmutableList.of(),
          tempDirectory.getRoot().toPath(),
          false,
          "repository",
          "");
  durationTracker = new BuildRuleDurationTracker();
  managerScope = TestBackgroundTaskManager.of().getNewScope(info.getBuildId());
}
 
Example #6
Source File: ModuleInitTaskTest.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
TestDir(TemporaryFolder testDir) throws IOException {
  String sourcePath = "ml-modules/root/dbfunctiondef/positive/sessions/";
  String apiFilename = baseName + ".api";

  buildFile = testDir.newFile("build.gradle");
  propsFile = testDir.newFile("gradle.properties");
  srcDir = testDir.newFolder("src");

  sjsOutDir = new File(srcDir, "sjs");
  xqyOutDir = new File(srcDir, "xqy");

  sjsOutDir.mkdirs();
  xqyOutDir.mkdirs();

  sjsAPIFile = new File(sjsOutDir, apiFilename);
  xqyAPIFile = new File(xqyOutDir, apiFilename);

  File srcAPIFile = new File("src/test/" + sourcePath + apiFilename);
  GradleTestUtil.copyTextFile(srcAPIFile, sjsAPIFile);
  GradleTestUtil.copyTextFile(srcAPIFile, xqyAPIFile);
}
 
Example #7
Source File: WorkMgrTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddToSerializedListNoList() throws IOException {
  TemporaryFolder tmp = new TemporaryFolder();
  tmp.create();
  File serializedList = tmp.newFile();
  Path serializedListPath = serializedList.toPath();
  serializedList.delete();

  NodeInterfacePair additionalInterface = NodeInterfacePair.of("n2", "iface2");

  addToSerializedList(
      serializedListPath,
      ImmutableList.of(additionalInterface),
      new TypeReference<List<NodeInterfacePair>>() {});

  // Confirm the additional interface shows up in the serialized list, even if the serialized list
  // didn't exist in the first place
  assertThat(
      BatfishObjectMapper.mapper()
          .readValue(
              CommonUtil.readFile(serializedListPath),
              new TypeReference<List<NodeInterfacePair>>() {}),
      containsInAnyOrder(additionalInterface));
}
 
Example #8
Source File: PreferencesCreator.java    From binaryprefs with Apache License 2.0 6 votes vote down vote up
public Preferences create(String name, TemporaryFolder folder) {
    try {
        final File srcDir = folder.newFolder();
        final File backupDir = folder.newFolder();
        final File lockDir = folder.newFolder();
        DirectoryProvider directoryProvider = new DirectoryProvider() {
            @Override
            public File getStoreDirectory() {
                return srcDir;
            }

            @Override
            public File getBackupDirectory() {
                return backupDir;
            }

            @Override
            public File getLockDirectory() {
                return lockDir;
            }
        };
        return create(name, directoryProvider);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: HgTestRepo.java    From gocd with Apache License 2.0 6 votes vote down vote up
public HgTestRepo(String workingCopyName, TemporaryFolder temporaryFolder) throws IOException {
    super(temporaryFolder);
    File tempFolder = temporaryFolder.newFolder();

    remoteRepo = new File(tempFolder, "remote-repo");
    remoteRepo.mkdirs();
    //Copy file to work around bug in hg
    File bundleToExtract = new File(tempFolder, "repo.bundle");
    FileUtils.copyFile(new File(HG_BUNDLE_FILE), bundleToExtract);
    setUpServerRepoFromHgBundle(remoteRepo, bundleToExtract);

    File workingCopy = new File(tempFolder, workingCopyName);
    hgCommand = new HgCommand(null, workingCopy, "default", remoteRepo.getAbsolutePath(), null);
    InMemoryStreamConsumer output = inMemoryConsumer();
    if (hgCommand.clone(output, new UrlArgument(remoteRepo.getAbsolutePath())) != 0) {
        fail("Error creating repository\n" + output.getAllOutput());
    }
}
 
Example #10
Source File: GivenSomeState.java    From audit4j-demo with Apache License 2.0 6 votes vote down vote up
private Configuration getConfigurationForFileHandler(TemporaryFolder folder) {
	Configuration conf = new Configuration();
	List<Handler> handlers = new ArrayList<Handler>();

	FileAuditHandler fileAuditHandler = new FileAuditHandler();
	handlers.add(fileAuditHandler);
	conf.setHandlers(handlers);
	conf.setLayout(new SimpleLayout());
	conf.setMetaData(new DummyMetaData());

	Map<String, String> properties = new HashMap<String, String>();
	properties.put("log.file.location", folder.getRoot().getAbsolutePath());
	conf.setProperties(properties);

	return conf;
       
}
 
Example #11
Source File: BlockSyncTestUtils.java    From besu with Apache License 2.0 6 votes vote down vote up
public static List<Block> firstBlocks(final int count) {
  final List<Block> result = new ArrayList<>(count);
  final TemporaryFolder temp = new TemporaryFolder();
  try {
    temp.create();
    final Path blocks = temp.newFile().toPath();
    BlockTestUtil.write1000Blocks(blocks);
    try (final RawBlockIterator iterator =
        new RawBlockIterator(
            blocks, rlp -> BlockHeader.readFrom(rlp, new MainnetBlockHeaderFunctions()))) {
      for (int i = 0; i < count; ++i) {
        result.add(iterator.next());
      }
    }
  } catch (final IOException ex) {
    throw new IllegalStateException(ex);
  } finally {
    temp.delete();
  }
  return result;
}
 
Example #12
Source File: CoverageSensorTest.java    From sonar-tsql-plugin with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void test() throws Throwable {
	TemporaryFolder folder = new TemporaryFolder();
	folder.create();

	SensorContextTester ctxTester = SensorContextTester.create(folder.getRoot());
	String tempName = "GetStatusMessage.sql";
	String covReport = "test.xml";
	File f = folder.newFile(tempName);
	File coverage = folder.newFile(covReport);

	FileUtils.copyInputStreamToFile(this.getClass().getResourceAsStream("/coverage/Coverage.opencoverxml"),
			coverage);

	FileUtils.copyInputStreamToFile(this.getClass().getResourceAsStream("/coverage/TestCode.sql"), f);
	DefaultInputFile file1 = new TestInputFileBuilder(folder.getRoot().getAbsolutePath(), tempName)
			.initMetadata(new String(Files.readAllBytes(f.toPath()))).setLanguage(TSQLLanguage.KEY).build();
	ctxTester.fileSystem().add(file1);
	ctxTester.settings().setProperty(Constants.COVERAGE_FILE, coverage.getAbsolutePath());
	ctxTester.settings().setProperty(Constants.PLUGIN_SKIP_COVERAGE, false);
	CoverageSensor sut = new CoverageSensor(new SqlCoverCoverageProvider(ctxTester.settings(), ctxTester.fileSystem()));
	sut.execute(ctxTester);
	Assert.assertEquals((int) 2, (int) ctxTester.lineHits(file1.key(), 7));

}
 
Example #13
Source File: WorkMgrTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddToSerializedListNullAddition() throws IOException {
  TemporaryFolder tmp = new TemporaryFolder();
  tmp.create();
  File serializedList = tmp.newFile();
  Path serializedListPath = serializedList.toPath();

  NodeInterfacePair baseInterface = NodeInterfacePair.of("n1", "iface1");

  // Write base serialized list
  List<NodeInterfacePair> interfaces = new ArrayList<>();
  interfaces.add(baseInterface);
  writeFile(serializedListPath, BatfishObjectMapper.writePrettyString(interfaces));

  addToSerializedList(serializedListPath, null, new TypeReference<List<NodeInterfacePair>>() {});

  // Confirm original interface shows up in the merged list, even if addition is null
  assertThat(
      BatfishObjectMapper.mapper()
          .readValue(
              CommonUtil.readFile(serializedListPath),
              new TypeReference<List<NodeInterfacePair>>() {}),
      containsInAnyOrder(baseInterface));
}
 
Example #14
Source File: SmtpTestRule.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeTest() throws Exception {
    inMemoryDNSService = new InMemoryDNSService();
    folder = new TemporaryFolder();
    folder.create();
    jamesServer = createJamesServer.build(folder, inMemoryDNSService);
    jamesServer.start();

    createSessionFactory();
}
 
Example #15
Source File: IsolatedPluginClassLoaderUtil.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
public static @NotNull IsolatedPluginClassloader buildClassLoader(
        final @NotNull TemporaryFolder temporaryFolder, final @NotNull Class[] classes) throws Exception {

    final JavaArchive javaArchive = ShrinkWrap.create(JavaArchive.class).addClasses(classes);

    final File jarFile = temporaryFolder.newFile();
    javaArchive.as(ZipExporter.class).exportTo(jarFile, true);

    return new IsolatedPluginClassloader(new URL[]{jarFile.toURI().toURL()},
            IsolatedPluginClassLoaderUtil.class.getClassLoader());
}
 
Example #16
Source File: Util.java    From graphicsfuzz with Apache License 2.0 5 votes vote down vote up
static File validateAndGetImage(
    ShaderJob shaderJob,
    String shaderJobFilename,
    TemporaryFolder temporaryFolder,
    ShaderJobFileOperations fileOps)
    throws IOException, InterruptedException {
  final File shaderJobFile = new File(
      temporaryFolder.getRoot(),
      shaderJobFilename);
  fileOps.writeShaderJobFile(shaderJob, shaderJobFile);
  return validateAndGetImage(shaderJobFile, temporaryFolder, fileOps);
}
 
Example #17
Source File: Util.java    From graphicsfuzz with Apache License 2.0 5 votes vote down vote up
static File validateAndGetImage(
    File shaderJobFile,
    TemporaryFolder temporaryFolder,
    ShaderJobFileOperations fileOps)
    throws IOException, InterruptedException {
  assertTrue(fileOps.areShadersValid(shaderJobFile, false));
  assertTrue(fileOps.areShadersValidShaderTranslator(shaderJobFile, false));
  return getImage(shaderJobFile, temporaryFolder, fileOps);
}
 
Example #18
Source File: JMH_MVStoreTokyoCabinetBenchmarkBase.java    From xodus with Apache License 2.0 5 votes vote down vote up
private void createEnvironment() throws IOException {
    closeStore();
    temporaryFolder = new TemporaryFolder();
    temporaryFolder.create();
    store = new MVStore.Builder()
        .fileName(temporaryFolder.newFile("data").getAbsolutePath())
        .autoCommitDisabled()
        .open();
}
 
Example #19
Source File: VerificationHost_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public void tearDown() {
    stop();
    TemporaryFolder tempFolder = this.getTemporaryFolder();
    if (tempFolder != null) {
        tempFolder.delete();
    }
}
 
Example #20
Source File: BatfishTestUtils.java    From batfish with Apache License 2.0 5 votes vote down vote up
public static Batfish getBatfishForTextConfigs(
    TemporaryFolder folder, String... configurationNames) throws IOException {
  SortedMap<String, byte[]> configurationBytesMap = new TreeMap<>();
  for (String configName : configurationNames) {
    byte[] configurationBytes = readResourceBytes(configName);
    configurationBytesMap.put(new File(configName).getName(), configurationBytes);
  }
  return BatfishTestUtils.getBatfishFromTestrigText(
      TestrigText.builder().setConfigurationBytes(configurationBytesMap).build(), folder);
}
 
Example #21
Source File: GradleCommandLineTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void testJVMArgs1() throws IOException {
    TemporaryFolder root = new TemporaryFolder();
    root.create();
    File props = root.newFile("gradle.properties");
    Files.write(props.toPath(), Arrays.asList("org.gradle.jvmargs=\"-Dfile.encoding=UTF-8\" -Xmx2g"));
    List<String> jvmargs = new ArrayList<>();
    GradleCommandLine.addGradleSettingJvmargs(root.getRoot(), jvmargs);
    assertEquals(Arrays.asList("-Dfile.encoding=UTF-8", "-Xmx2g"), jvmargs);
}
 
Example #22
Source File: P4TestRepo.java    From gocd with Apache License 2.0 5 votes vote down vote up
public static P4TestRepo createP4TestRepo(TemporaryFolder temporaryFolder, File clientFolder) throws IOException {
    String repo = "../common/src/test/resources/data/p4repo";
    if (SystemUtils.IS_OS_WINDOWS) {
        repo = "../common/src/test/resources/data/p4repoWindows";
    }
    return new P4TestRepo(RandomPort.find("P4TestRepo"), repo, "cceuser", null, PerforceFixture.DEFAULT_CLIENT_NAME, false, temporaryFolder, clientFolder);
}
 
Example #23
Source File: TestUtil.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
public static File setupClasspathResource(TemporaryFolder tempFolder, String name) throws IOException {
	URL resource = TestUtil.class.getClassLoader().getResource(name);
	if (resource == null) {
		throw new IllegalArgumentException("unable to find: " + name + " in classpath");
	}
	if (resource.getProtocol().equals("file")) {
		return new File(resource.getFile());
	}
	// copy only if resource is in jar
	File result = new File(tempFolder.getRoot(), UUID.randomUUID().toString());
	try (FileOutputStream fos = new FileOutputStream(result); InputStream is = resource.openStream()) {
		Util.copy(is, fos);
	}
	return result;
}
 
Example #24
Source File: BatfishTestUtils.java    From batfish with Apache License 2.0 5 votes vote down vote up
private static Batfish initBatfish(
    @Nonnull SortedMap<String, Configuration> baseConfigs,
    @Nonnull SortedMap<String, Configuration> deltaConfigs,
    @Nonnull TemporaryFolder tempFolder)
    throws IOException {
  Settings settings = new Settings(new String[] {});
  settings.setLogger(new BatfishLogger("debug", false));
  final Cache<NetworkSnapshot, SortedMap<String, Configuration>> testrigs = makeTestrigCache();

  settings.setStorageBase(tempFolder.newFolder().toPath());
  settings.setContainer(TEST_SNAPSHOT.getNetwork().getId());
  if (!baseConfigs.isEmpty()) {
    settings.setTestrig(TEST_SNAPSHOT.getSnapshot().getId());
    settings.setSnapshotName(TEST_SNAPSHOT_NAME);
    settings.setDeltaTestrig(TEST_REFERENCE_SNAPSHOT.getSnapshot());
    testrigs.put(TEST_SNAPSHOT, baseConfigs);
    testrigs.put(TEST_REFERENCE_SNAPSHOT, deltaConfigs);
  }
  Batfish batfish =
      new Batfish(
          settings,
          testrigs,
          makeDataPlaneCache(),
          makeEnvBgpCache(),
          makeVendorConfigurationCache(),
          null,
          new TestStorageBasedIdResolver(settings.getStorageBase()));
  batfish.getSettings().setDiffQuestion(true);
  if (!baseConfigs.isEmpty()) {
    batfish.initializeTopology(TEST_SNAPSHOT);
  }
  if (!deltaConfigs.isEmpty()) {
    batfish.initializeTopology(TEST_REFERENCE_SNAPSHOT);
  }
  registerDataPlanePlugins(batfish);
  return batfish;
}
 
Example #25
Source File: AwsConfigurationTestUtils.java    From batfish with Apache License 2.0 5 votes vote down vote up
static IBatfish testSetup(String testconfigsDir, List<String> fileNames, TemporaryFolder folder)
    throws IOException {
  IBatfish batfish =
      BatfishTestUtils.getBatfishFromTestrigText(
          TestrigText.builder().setAwsFiles(testconfigsDir, fileNames).build(), folder);
  batfish.computeDataPlane(batfish.getSnapshot());
  return batfish;
}
 
Example #26
Source File: TestInterceptorUtil.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
public static @NotNull List<Interceptor> getIsolatedInterceptors(
        final @NotNull TemporaryFolder temporaryFolder,
        final @NotNull ClassLoader classLoader) throws Exception {

    return getIsolatedInterceptors(
            List.of(TestPublishInboundInterceptor.class, TestSubscriberInboundInterceptor.class), temporaryFolder);
}
 
Example #27
Source File: TestReconWithDifferentSqlDBs.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> parameters() throws IOException {
  TemporaryFolder temporaryFolder = new TemporaryFolder();
  temporaryFolder.create();
  return Stream.of(
      new DerbyDataSourceConfigurationProvider(temporaryFolder.newFolder()),
      new SqliteDataSourceConfigurationProvider(temporaryFolder.newFolder()))
      .map(each -> new Object[] {each})
      .collect(toList());
}
 
Example #28
Source File: IsolatedPluginClassLoaderUtil.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
public static <T> @NotNull T loadIsolated(
        final @NotNull TemporaryFolder temporaryFolder, final @NotNull Class<T> clazz) throws Exception {

    final IsolatedPluginClassloader isolatedPluginClassloader =
            buildClassLoader(temporaryFolder, new Class[]{clazz});

    return instanceFromClassloader(isolatedPluginClassloader, clazz);
}
 
Example #29
Source File: WorkMgrTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializeAndDeleteInterfaceBlacklist_emptyBlacklist() throws IOException {
  // Empty blacklist: Should return an empty list and delete file
  TemporaryFolder tmp = new TemporaryFolder();
  tmp.create();
  File blacklistFile = tmp.newFile();
  assertTrue(blacklistFile.exists());
  assertThat(deserializeAndDeleteInterfaceBlacklist(blacklistFile.toPath()), empty());
  assertFalse(blacklistFile.exists());
}
 
Example #30
Source File: TaskLocalStateStoreImplTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
	JobID jobID = new JobID();
	AllocationID allocationID = new AllocationID();
	JobVertexID jobVertexID = new JobVertexID();
	int subtaskIdx = 0;
	this.temporaryFolder = new TemporaryFolder();
	this.temporaryFolder.create();
	this.allocationBaseDirs = new File[]{temporaryFolder.newFolder(), temporaryFolder.newFolder()};
	this.internalSnapshotMap = new TreeMap<>();
	this.internalLock = new Object();

	LocalRecoveryDirectoryProviderImpl directoryProvider =
		new LocalRecoveryDirectoryProviderImpl(allocationBaseDirs, jobID, jobVertexID, subtaskIdx);

	LocalRecoveryConfig localRecoveryConfig = new LocalRecoveryConfig(false, directoryProvider);

	this.taskLocalStateStore = new TaskLocalStateStoreImpl(
		jobID,
		allocationID,
		jobVertexID,
		subtaskIdx,
		localRecoveryConfig,
		Executors.directExecutor(),
		internalSnapshotMap,
		internalLock);
}