下面列出了怎么用org.junit.rules.TemporaryFolder的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
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();
}
});
}
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;
}
@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));
}
@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);
}
@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));
}
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);
}
}
@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;
}
@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());
}
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);
}
@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));
}
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());
}
}
@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());
}
private SortedMap<String, Configuration> compressNetwork(
Map<String, Configuration> configs, HeaderSpace headerSpace) throws IOException {
TemporaryFolder tmp = new TemporaryFolder();
tmp.create();
IBatfish batfish = BatfishTestUtils.getBatfish(new TreeMap<>(configs), tmp);
return new TreeMap<>(
new BatfishCompressor(batfish.getSnapshot(), new BDDPacket(), batfish, configs)
.compress(headerSpace));
}
private Path createAndWrite(
final TemporaryFolder temporaryFolder,
final String dir,
final String file,
final String content)
throws IOException {
final Path tmpDir = temporaryFolder.newFolder().toPath().resolve(dir);
Files.createDirectories(tmpDir);
createAndWrite(tmpDir.resolve(file), content);
return tmpDir;
}
public TestCompiler(JavaCompiler compiler, TemporaryFolder temporaryFolder) throws IOException {
this.compiler = compiler;
this.fileManager = compiler.getStandardFileManager(null, null, null);
this.outputLocation = temporaryFolder.newFolder();
Iterable<? extends File> temp = Collections.singletonList(this.outputLocation);
this.fileManager.setLocation(StandardLocation.CLASS_OUTPUT, temp);
this.fileManager.setLocation(StandardLocation.SOURCE_OUTPUT, temp);
}
@Test
public void testAddToSerializedListNoListNoAddition() throws IOException {
TemporaryFolder tmp = new TemporaryFolder();
tmp.create();
File serializedList = tmp.newFile();
Path serializedListPath = serializedList.toPath();
serializedList.delete();
addToSerializedList(
serializedListPath, ImmutableList.of(), new TypeReference<List<NodeInterfacePair>>() {});
// Confirm no file was created (since there was no list to begin with and nothing was added)
assertThat(serializedList, not(FileMatchers.anExistingFile()));
}
@Test
public void sanitizeSymlinkedWorkingDirectory() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
// Setup up a symlink to our working directory.
Path symlinkedRoot = folder.getRoot().toPath().resolve("symlinked-root");
CreateSymlinksForTests.createSymLink(symlinkedRoot, tmp.getRoot());
// Run the build, setting PWD to the above symlink. Typically, this causes compilers to use
// the symlinked directory, even though it's not the right project root.
BuildTarget target = BuildTargetFactory.newInstance("//:simple#default,static");
workspace
.runBuckCommandWithEnvironmentOverridesAndContext(
tmp.getRoot(),
Optional.empty(),
ImmutableMap.of("PWD", symlinkedRoot.toString()),
"build",
target.getFullyQualifiedName())
.assertSuccess();
// Verify that we still sanitized this path correctly.
Path lib =
workspace.getPath(
BuildTargetPaths.getGenPath(
workspace.getProjectFileSystem(), target, "%s/libsimple.a"));
String contents = Files.asByteSource(lib.toFile()).asCharSource(Charsets.ISO_8859_1).read();
assertFalse(lib.toString(), contents.contains(tmp.getRoot().toString()));
assertFalse(lib.toString(), contents.contains(symlinkedRoot.toString()));
folder.delete();
}
public static void initWorkManager(TemporaryFolder folder) {
BatfishLogger logger = new BatfishLogger("debug", false);
Main.mainInit(new String[] {"-containerslocation", folder.getRoot().toString()});
Main.setLogger(logger);
Main.initAuthorizer();
FileBasedStorage fbs = new FileBasedStorage(Main.getSettings().getContainersLocation(), logger);
WorkMgr workMgr = new WorkMgr(Main.getSettings(), logger, new StorageBasedIdManager(fbs), fbs);
// Setup some test version data
Main.setWorkMgr(workMgr);
}
public static TemporaryFolder getTemporaryFolder()
{
return new TemporaryFolder()
{
@Override
public void after()
{
// don't cleanup if using cache tmpdir
if (TMP == null)
{
super.after();
}
}
};
}
@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);
}
private Env<T> env(final TemporaryFolder tmp) {
try {
final File path = tmp.newFile();
return create(proxy)
.setMapSize(KIBIBYTES.toBytes(1_024))
.setMaxReaders(1)
.setMaxDbs(1)
.open(path, POSIX_MODE, MDB_NOSUBDIR);
} catch (final IOException e) {
throw new LmdbException("IO failure", e);
}
}
public static P4TestRepo createP4TestRepoWithTickets(TemporaryFolder temporaryFolder, File clientFolder) throws IOException {
String repo = "../common/src/test/resources/data/p4TicketedRepo";
if (SystemUtils.IS_OS_WINDOWS) {
repo = "../common/src/test/resources/data/p4TicketedRepoWindows";
}
return new P4TestRepo(RandomPort.find("P4TestRepoWithTickets"), repo, "cceuser", "1234abcd", PerforceFixture.DEFAULT_CLIENT_NAME, true, temporaryFolder, clientFolder);
}
private void createEnvironment() throws IOException {
closeTxMaker();
temporaryFolder = new TemporaryFolder();
temporaryFolder.create();
map = ChronicleMap.of(String.class, String.class)
.averageKeySize(8).averageValueSize(8)
.entries(randomKeys.length)
.createPersistedTo(temporaryFolder.newFile("data"));
}
private static GuiceJamesServer createJamesServer(Host cassandraHost, DockerAwsS3TestRule awsS3TestRule, TemporaryFolder folder, DNSService dnsService) throws Exception {
Configuration configuration = Configuration.builder()
.workingDirectory(folder.newFolder())
.configurationFromClasspath()
.build();
return GuiceJamesServer.forConfiguration(configuration)
.combineWith(CassandraJamesServerMain.CASSANDRA_SERVER_CORE_MODULE,
SmtpTestRule.SMTP_PROTOCOL_MODULE,
binder -> binder.bind(MailQueueItemDecoratorFactory.class).to(RawMailQueueItemDecoratorFactory.class),
binder -> binder.bind(CamelMailetContainerModule.DefaultProcessorsConfigurationSupplier.class)
.toInstance(BaseHierarchicalConfiguration::new))
.overrideWith(new RabbitMQModule(), BLOB_STORE_MODULE)
.overrideWith(
new TestRabbitMQModule(DockerRabbitMQSingleton.SINGLETON),
awsS3TestRule.getModule(),
binder -> binder.bind(KeyspacesConfiguration.class)
.toInstance(KeyspacesConfiguration.builder()
.keyspace(DockerCassandra.KEYSPACE)
.cacheKeyspace(DockerCassandra.CACHE_KEYSPACE)
.replicationFactor(1)
.disableDurableWrites()
.build()),
binder -> binder.bind(ClusterConfiguration.class).toInstance(
DockerCassandra.configurationBuilder(cassandraHost)
.build()),
binder -> binder.bind(DNSService.class).toInstance(dnsService),
binder -> binder.bind(CleanupTasksPerformer.class).asEagerSingleton());
}
@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);
}
@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());
}
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);
}
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());
}
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);
}