org.junit.rules.TemporaryFolder#create()源码实例Demo

下面列出了org.junit.rules.TemporaryFolder#create() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hadoop-ozone   文件: MiniOzoneClusterImpl.java
protected void configureRecon() throws IOException {
  ConfigurationProvider.resetConfiguration();

  TemporaryFolder tempFolder = new TemporaryFolder();
  tempFolder.create();
  File tempNewFolder = tempFolder.newFolder();
  conf.set(OZONE_RECON_DB_DIR,
      tempNewFolder.getAbsolutePath());
  conf.set(OZONE_RECON_OM_SNAPSHOT_DB_DIR, tempNewFolder
      .getAbsolutePath());
  conf.set(OZONE_RECON_SCM_DB_DIR,
      tempNewFolder.getAbsolutePath());
  conf.set(OZONE_RECON_SQL_DB_JDBC_URL, "jdbc:derby:" +
      tempNewFolder.getAbsolutePath() + "/ozone_recon_derby.db");

  conf.set(OZONE_RECON_HTTP_ADDRESS_KEY, "0.0.0.0:0");
  conf.set(OZONE_RECON_DATANODE_ADDRESS_KEY, "0.0.0.0:0");

  ConfigurationProvider.setConfiguration(conf);
}
 
源代码2 项目: iaf   文件: MessageTest.java
@Test
public void testSerializeWithURL() throws Exception {
	TemporaryFolder folder = new TemporaryFolder();
	folder.create();
	File file = folder.newFile();
	writeContentsToFile(file, testString);
	URL source = file.toURL();

	Message in = new Message(source);
	byte[] wire = serializationTester.serialize(in);
	writeContentsToFile(file, "fakeContentAsReplacementOfThePrevious");
	Message out = serializationTester.deserialize(wire);
	
	assertTrue(out.isBinary());
	assertEquals(testString,out.asString());
}
 
源代码3 项目: cc-dbp   文件: FileUtilTest.java
@Before
 public void setUp() throws Exception {
folder = new TemporaryFolder();
folder.create();
   testDir = folder.newFolder("fileTests");
   childDirA = testDir+File.separator+"childDirA";
   childDirB = testDir+File.separator+"childDirB";
   childDirC = childDirA+File.separator+"childDirC";
   childDirD = childDirC+File.separator+"childDirD/";
   fileName1 = childDirA+File.separator+"testFile1.txt";
   fileName1Zipped = fileName1+".gz";
   fileName2 = childDirD+File.separator+"testFile2.txt";
   fileName3 = childDirB+File.separator+".testFile3.txt";
   objectFileName = childDirA+File.separator+"person1.ser";
   objectFileNameZipped = objectFileName+".gz";
   fileText = "Sample Text";
 }
 
源代码4 项目: batfish   文件: WorkMgrTest.java
@Test
public void testAddToSerializedListNoAddition() 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, ImmutableList.of(), new TypeReference<List<NodeInterfacePair>>() {});

  // Confirm original interface shows up in the merged list, even if there are no additions
  assertThat(
      BatfishObjectMapper.mapper()
          .readValue(
              CommonUtil.readFile(serializedListPath),
              new TypeReference<List<NodeInterfacePair>>() {}),
      containsInAnyOrder(baseInterface));
}
 
源代码5 项目: batfish   文件: WorkMgrTest.java
@Test
public void testRemoveFromSerializedListEmptyBaseList() throws IOException {
  TemporaryFolder tmp = new TemporaryFolder();
  tmp.create();
  File serializedList = tmp.newFile();
  Path serializedListPath = serializedList.toPath();

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

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

  // Confirm no issue if base list didn't exist
  assertThat(
      BatfishObjectMapper.mapper()
          .readValue(
              CommonUtil.readFile(serializedListPath),
              new TypeReference<List<NodeInterfacePair>>() {}),
      iterableWithSize(0));
}
 
@Test
public void testSingleFile() throws IOException {
	TemporaryFolder folder = new TemporaryFolder();
	folder.create();

	SensorContextTester ctxTester = SensorContextTester.create(folder.getRoot());

	ctxTester.settings().setProperty(Constants.PLUGIN_SKIP, false);
	ctxTester.settings().setProperty(Constants.PLUGIN_SKIP_CUSTOM_RULES, false);
	ctxTester.settings().setProperty(Constants.PLUGIN_SKIP_CUSTOM, false);
	ctxTester.settings().setProperty(Constants.PLUGIN_MAX_FILE_SIZE, 100);
	String tempName = "test.sql";

	File f = folder.newFile(tempName);

	FileUtils.write(f, "select * from dbo.test;\r\n--test", Charset.defaultCharset());
	DefaultInputFile file1 = new TestInputFileBuilder(folder.getRoot().getAbsolutePath(), tempName)
			.initMetadata(new String(Files.readAllBytes(f.toPath()))).setLanguage(TSQLLanguage.KEY).build();
	ctxTester.fileSystem().add(file1);

	CustomChecksSensor sensor = new CustomChecksSensor();
	sensor.execute(ctxTester);
	Collection<Issue> issues = ctxTester.allIssues();
	for (Issue i : issues) {
		System.out.println(i.ruleKey() + " " + i.primaryLocation());
	}

	Assert.assertEquals(1, issues.size());
	Assert.assertEquals(2, ctxTester.cpdTokens(file1.key()).size());
	Assert.assertEquals(1, ctxTester.highlightingTypeAt(file1.key(), 2, 1).size());
	Assert.assertEquals(4, ctxTester.measures(file1.key()).size());
}
 
源代码7 项目: james-project   文件: SmtpTestRule.java
@Override
public void beforeTest() throws Exception {
    inMemoryDNSService = new InMemoryDNSService();
    folder = new TemporaryFolder();
    folder.create();
    jamesServer = createJamesServer.build(folder, inMemoryDNSService);
    jamesServer.start();

    createSessionFactory();
}
 
@Test
public void testTSQLGrammarFiles() throws IOException {
	TemporaryFolder folder = new TemporaryFolder();
	folder.create();
	SensorContextTester ctxTester = SensorContextTester.create(folder.getRoot());

	ctxTester.settings().setProperty(Constants.PLUGIN_SKIP, false);
	ctxTester.settings().setProperty(Constants.PLUGIN_SKIP_CUSTOM_RULES, false);
	ctxTester.settings().setProperty(Constants.PLUGIN_SKIP_CUSTOM, false);
	ctxTester.settings().setProperty(Constants.PLUGIN_MAX_FILE_SIZE, 100);
	String dirPath = "..\\grammars\\tsql";
	File dir = new File(dirPath);
	Collection<File> files = FileUtils.listFiles(dir, new String[] { "sql" }, true);
	for (File f : files) {
		String tempName = f.getName() + System.nanoTime();
		File dest = folder.newFile(tempName);
		FileUtils.copyFile(f, dest);

		DefaultInputFile file1 = new TestInputFileBuilder(folder.getRoot().getAbsolutePath(), tempName)
				.initMetadata(new String(Files.readAllBytes(f.toPath()))).setLanguage(TSQLLanguage.KEY).build();
		ctxTester.fileSystem().add(file1);

	}
	CustomChecksSensor sensor = new CustomChecksSensor();
	sensor.execute(ctxTester);
	Collection<Issue> issues = ctxTester.allIssues();
	Assert.assertEquals(183, issues.size());

}
 
源代码9 项目: iaf   文件: AmazonS3FileSystemTestHelper.java
@Override
public OutputStream _createFile(final String foldername, final String filename) throws IOException {
	TemporaryFolder folder = new TemporaryFolder();
	folder.create();

	String fileName = folder.getRoot().getAbsolutePath()+"tempFile";

	final File file = new File(fileName);
	final FileOutputStream fos = new FileOutputStream(file);
	final BufferedOutputStream bos = new BufferedOutputStream(fos);
	
	FilterOutputStream filterOutputStream = new FilterOutputStream(bos) {
		@Override
		public void close() throws IOException {
			super.close();
			bos.close();

			FileInputStream fis = new FileInputStream(file);
			ObjectMetadata metaData = new ObjectMetadata();
			metaData.setContentLength(file.length());
			String filePath = foldername == null ? filename : foldername + "/" + filename;
			s3Client.putObject(bucketName, filePath, fis, metaData);
			
			fis.close();
			file.delete();
		}
	};
	return filterOutputStream;
}
 
源代码10 项目: flink   文件: EventTimeWindowCheckpointingITCase.java
protected Configuration createClusterConfig() throws IOException {
	TemporaryFolder temporaryFolder = new TemporaryFolder();
	temporaryFolder.create();
	final File haDir = temporaryFolder.newFolder();

	Configuration config = new Configuration();
	config.setString(AkkaOptions.FRAMESIZE, String.valueOf(MAX_MEM_STATE_SIZE) + "b");

	if (zkServer != null) {
		config.setString(HighAvailabilityOptions.HA_MODE, "ZOOKEEPER");
		config.setString(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM, zkServer.getConnectString());
		config.setString(HighAvailabilityOptions.HA_STORAGE_PATH, haDir.toURI().toString());
	}
	return config;
}
 
源代码11 项目: vespa   文件: DirConfigSource.java
private static TemporaryFolder createTemporaryFolder() {
    TemporaryFolder folder = new TemporaryFolder();
    try {
        folder.create();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return folder;
}
 
源代码12 项目: buck   文件: RuleKeyLogFileUploaderTest.java
@Before
public void setUp() throws IOException {
  TemporaryFolder tempDirectory = new TemporaryFolder();
  tempDirectory.create();
  filesystem = TestProjectFilesystems.createProjectFilesystem(tempDirectory.getRoot().toPath());
  buildReportConfig = FakeBuckConfig.builder().build().getView(BuildReportConfig.class);
  clock = new DefaultClock();

  ruleKeyLogFile = tempDirectory.newFile(BuckConstant.RULE_KEY_LOGGER_FILE_NAME).toPath();
  String ruleKeyLogContent =
      "target\t//test/com/facebook/buck/testutil/integration:util\tbf90764fa7d161f6ac7988dfaeed4f1b6f7d03d1\n";
  filesystem.writeContentsToPath(ruleKeyLogContent, ruleKeyLogFile);
}
 
源代码13 项目: batfish   文件: WorkMgrTest.java
@Test
public void testDeserializeAndDeleteInterfaceBlacklist_invalidBlacklist() throws IOException {
  // Invalid blacklist: Should return an empty list and delete file
  TemporaryFolder tmp = new TemporaryFolder();
  tmp.create();
  File blacklistFile = tmp.newFile();
  Path blacklistPath = blacklistFile.toPath();
  writeFile(blacklistPath, "invalid json");
  assertThat(deserializeAndDeleteInterfaceBlacklist(blacklistPath), empty());
  assertFalse(blacklistFile.exists());
}
 
源代码14 项目: batfish   文件: WorkMgrTest.java
@Test
public void testAddToSerializedList() throws IOException {
  TemporaryFolder tmp = new TemporaryFolder();
  tmp.create();
  File serializedList = tmp.newFile();
  Path serializedListPath = serializedList.toPath();

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

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

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

  // Confirm the additional and original interfaces show up in the merged list
  assertThat(
      BatfishObjectMapper.mapper()
          .readValue(
              CommonUtil.readFile(serializedListPath),
              new TypeReference<List<NodeInterfacePair>>() {}),
      containsInAnyOrder(baseInterface, additionalInterface));
}
 
源代码15 项目: dremio-oss   文件: TestSchemaConverter.java
@Test
public void mixed() throws Exception {
  BatchSchema schema = BatchSchema.newBuilder()
    .addField(CompleteType.INT.toField("rownum"))
    .addField(CompleteType.VARCHAR.toField("name"))
    .addField(CompleteType.INT.toField("age"))
    .addField(CompleteType.FLOAT.toField("gpa"))
    .addField(CompleteType.BIGINT.toField("studentnum"))
    .addField(CompleteType.TIMESTAMP.toField("create_time"))
    .addField(CompleteType.VARCHAR.asList().toField("interests"))
    .addField(CompleteType.struct(
      CompleteType.VARCHAR.toField("color"),
      CompleteType.VARCHAR.toField("sport"),
      CompleteType.VARCHAR.toField("food")
    ).toField("favorites"))
    .build();

  org.apache.iceberg.Schema expectedSchema = new org.apache.iceberg.Schema(
    NestedField.optional(1, "rownum", Types.IntegerType.get()),
    NestedField.optional(2, "name", Types.StringType.get()),
    NestedField.optional(3, "age", Types.IntegerType.get()),
    NestedField.optional(4, "gpa", Types.FloatType.get()),
    NestedField.optional(5, "studentnum", Types.LongType.get()),
    NestedField.optional(6, "create_time", Types.TimestampType.withZone()),
    NestedField.optional(7, "interests",
      Types.ListType.ofOptional(9, Types.StringType.get())),
    NestedField.optional(8, "favorites",
      Types.StructType.of(
        NestedField.optional(10, "color", Types.StringType.get()),
        NestedField.optional(11, "sport", Types.StringType.get()),
        NestedField.optional(12, "food", Types.StringType.get())
      ))
  );

  org.apache.iceberg.Schema icebergResult = schemaConverter.toIceberg(schema);
  assertEquals(expectedSchema.toString(), icebergResult.toString());

  TemporaryFolder folder = new TemporaryFolder();
  folder.create();

  String rootPath = folder.getRoot().toString();
  Configuration conf = new Configuration();
  IcebergCatalog catalog = new IcebergCatalog(rootPath, conf);
  catalog.beginCreateTable(schema, Collections.emptyList());
  catalog.endCreateTable();

  Table table = new HadoopTables(conf).load(rootPath);
  assertEquals(expectedSchema.toString(), table.schema().toString());
}
 
@BeforeClass
public static void beforeClass() throws IOException {
	temporaryFolder = new TemporaryFolder();
	temporaryFolder.create();
}
 
@Test
public void fetchesFilesThatAreMissingFromUrlStoreCache()
        throws IOException, GitUserException {
    final String testProjectName = "123abc";
    final String testUrl = "http://localhost:"
            + mockServerRule.getPort() + "/123abc";
    final String oldTestPath = "testPath";
    final String newTestPath = "missingPath";

    mockServerClient.when(
        request()
        .withMethod("GET")
        .withPath("/123abc")
    )
    .respond(
        response()
        .withStatusCode(200)
        .withBody("content")
    );

    final Mockery context = new Mockery();
    final DBStore dbStore = context.mock(DBStore.class);
    context.checking(new Expectations() {{
        // It should fetch the file once it finds it is missing.
        oneOf(dbStore).getPathForURLInProject(testProjectName, testUrl);
        will(returnValue(oldTestPath));

        // It should update the URL index store once it has fetched;
        // at present, it does not actually change the stored path.
        oneOf(dbStore).addURLIndexForProject(
                testProjectName, testUrl, oldTestPath);
    }});

    ResourceCache resources = new UrlResourceCache(dbStore);
    TemporaryFolder repositoryFolder = new TemporaryFolder();
    repositoryFolder.create();
    String repoStorePath = repositoryFolder.getRoot().getAbsolutePath();
    RepoStore repoStore
            = new FSGitRepoStore(repoStorePath, Optional.empty());
    ProjectRepo repo = repoStore.initRepo("repo");
    Map<String, RawFile> fileTable = repo.getDirectory().getFileTable();
    Map<String, byte[]> fetchedUrls = new HashMap<>();
    resources.get(
            testProjectName, testUrl, newTestPath,
            fileTable, fetchedUrls, Optional.empty());

    // We don't bother caching in this case, at present.
    assertEquals(0, fetchedUrls.size());
}
 
源代码18 项目: flink   文件: StatefulOperatorChainedTaskTest.java
@Before
public void setup() throws IOException {
	RESTORED_OPERATORS.clear();
	temporaryFolder = new TemporaryFolder();
	temporaryFolder.create();
}
 
源代码19 项目: iaf   文件: DirectoryListenerTest.java
@Override
public void setUp() throws Exception {
	folder = new TemporaryFolder();
	folder.create();
	super.setUp();
}
 
源代码20 项目: gradle-plugins   文件: SystemdApplicationTest.java
@Test
public void check() throws IOException {
    File tempDir = new File("build/tmp");
    tempDir.mkdirs();
    testFolder = new TemporaryFolder(tempDir);

    testFolder.create();
    workingDir = new File(testFolder.getRoot(), "demo");
    workingDir.mkdirs();

    File javaFolder = new File(workingDir, "src/main/java/example");
    javaFolder.mkdirs();
    File rpmFolder = new File(workingDir, "src/main/rpm");
    rpmFolder.mkdirs();

    System.setProperty("org.gradle.daemon", "false");

    File gradleFile = new File(workingDir, "build.gradle");
    File settingsFile = new File(workingDir, "settings.gradle");
    File entityFile = new File(javaFolder, "Main.java");
    File propertiesFile = new File(rpmFolder, "application.properties");

    Assert.assertNotNull(getClass().getClassLoader().getResource("plugin-under-test-metadata.properties"));

    IOUtils.copy(getClass().getClassLoader().getResourceAsStream("helm-app/input.gradle"),
            new FileOutputStream(gradleFile));
    IOUtils.copy(getClass().getClassLoader().getResourceAsStream("helm-app/input_settings.gradle"),
            new FileOutputStream(settingsFile));
    IOUtils.copy(getClass().getClassLoader().getResourceAsStream("helm-app/input_main.java"),
            new FileOutputStream(entityFile));
    IOUtils.copy(getClass().getClassLoader().getResourceAsStream("helm-app/input_application.properties"),
            new FileOutputStream(propertiesFile));

    GradleRunner runner = GradleRunner.create();
    runner = runner.forwardOutput();
    runner = runner.withPluginClasspath();
    runner = runner.withProjectDir(workingDir).withArguments("buildRpm", "--stacktrace").forwardOutput();
    runner.build();

    File rpmFile = new File(workingDir, "build/distributions/demo.rpm");
    Assert.assertTrue(rpmFile.exists());

    File serviceFile = new File(workingDir, "build/systemd/services/demo-app.service");
    Assert.assertTrue(serviceFile.exists());

    String serviceDesc = IOUtils.toString(new FileInputStream(serviceFile));
    Assert.assertTrue(serviceDesc.contains("ExecStart=/var/demo-app/bin/demo run"));
}