下面列出了org.junit.jupiter.api.condition.EnabledOnOs#org.junit.jupiter.api.io.TempDir 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
void clientNotInCaFailedToConnectToEthSigner(@TempDir final Path tempDir) throws Exception {
ethSigner = createEthSigner(clientCert, tempDir);
ethSigner.start();
ethSigner.awaitStartupCompletion();
// Create a client which presents the server cert (not in CA) - it should fail to connect.
final ClientTlsConfig clientTlsConfig = new ClientTlsConfig(serverCert, serverCert);
final HttpRequest rawRequests =
new HttpRequest(
ethSigner.getUrl(),
OkHttpClientHelpers.createOkHttpClient(Optional.of(clientTlsConfig)));
final Throwable thrown = catchThrowable(() -> rawRequests.get("/upcheck"));
assertThat(thrown.getCause()).isInstanceOf(SSLException.class);
}
@Test
void ethSignerProvidesSpecifiedClientCertificateToDownStreamServer(@TempDir Path workDir)
throws Exception {
final TlsCertificateDefinition serverCert =
TlsCertificateDefinition.loadFromResource("tls/cert1.pfx", "password");
final TlsCertificateDefinition ethSignerCert =
TlsCertificateDefinition.loadFromResource("tls/cert2.pfx", "password2");
// Note: the HttpServer always responds with a JsonRpcSuccess, result=300.
final HttpServer web3ProviderHttpServer =
serverFactory.create(serverCert, ethSignerCert, workDir);
signer =
createAndStartSigner(
ethSignerCert, serverCert, web3ProviderHttpServer.actualPort(), 0, workDir);
assertThat(signer.accounts().balance("0x123456"))
.isEqualTo(BigInteger.valueOf(MockBalanceReporter.REPORTED_BALANCE));
}
@Test
void emptyPasswordFileRaisesException(@TempDir final Path tempDir) throws IOException {
final Path outputPath = Files.createTempDirectory(tempDir, "keystores");
final ValidatorPasswordOptions validatorPasswordOptions = new ValidatorPasswordOptions();
final File passwordFile = Files.writeString(outputPath.resolve("password.txt"), "").toFile();
validatorPasswordOptions.validatorPasswordFile = passwordFile;
final WithdrawalPasswordOptions withdrawalPasswordOptions = new WithdrawalPasswordOptions();
withdrawalPasswordOptions.withdrawalPasswordFile = passwordFile;
assertThatExceptionOfType(CommandLine.ParameterException.class)
.isThrownBy(
() ->
assertEncryptedKeystoresAreCreated(
outputPath, validatorPasswordOptions, withdrawalPasswordOptions))
.withMessage("Error: Empty password from file: " + passwordFile);
}
@Test
void validFileBasedTomlFileWithMultineLinePasswordFileProducesSignerWhichReportsMatchingAddress(
@TempDir Path tomlDirectory) throws URISyntaxException, IOException {
final Path passwordFile =
Files.writeString(
tomlDirectory.resolve("password.txt"), String.format("password%nsecond line%n"));
createFileBasedTomlFileAt(
tomlDirectory.resolve("arbitrary_prefix" + FILENAME + ".toml").toAbsolutePath(),
new File(
Resources.getResource(
"UTC--2019-12-05T05-17-11.151993000Z--a01f618424b0113a9cebdc6cb66ca5b48e9120c5.key")
.toURI())
.getAbsolutePath(),
passwordFile.toString());
setup(tomlDirectory);
assertThat(ethSigner.accounts().list()).containsOnly(FILE_ETHEREUM_ADDRESS);
}
@Test
void incorrectlyNamedFileBasedSignerIsNotLoaded(@TempDir Path tomlDirectory)
throws URISyntaxException {
createFileBasedTomlFileAt(
tomlDirectory.resolve("ffffffffffffffffffffffffffffffffffffffff.toml").toAbsolutePath(),
new File(
Resources.getResource(
"UTC--2019-12-05T05-17-11.151993000Z--a01f618424b0113a9cebdc6cb66ca5b48e9120c5.key")
.toURI())
.getAbsolutePath(),
new File(
Resources.getResource(
"UTC--2019-12-05T05-17-11.151993000Z--a01f618424b0113a9cebdc6cb66ca5b48e9120c5.password")
.toURI())
.getAbsolutePath());
setup(tomlDirectory);
assertThat(ethSigner.accounts().list()).isEmpty();
}
@Test
void registerWithEncryptedValidatorKeystoreWithEnv(@TempDir final Path tempDir)
throws IOException {
final Path keyStoreFile = tempDir.resolve("keystore.json");
KeyStoreLoader.saveToFile(keyStoreFile, VALIDATOR_KEYSTORE);
ValidatorKeyOptions validatorKeyOptions = buildValidatorKeyOptionsWithEnv(keyStoreFile);
final DepositRegisterCommand depositRegisterCommand =
new DepositRegisterCommand(
shutdownFunction, envSupplier, commandSpec, registerParams, validatorKeyOptions, "");
assertThatCode(depositRegisterCommand::run).doesNotThrowAnyException();
verify(registerAction).sendDeposit(any(), any());
}
@Test
void nonExistentKeystoreFileThrowsError(@TempDir final Path tempDir) throws IOException {
// load keystores from resources
final Path scryptKeystore = tempDir.resolve("scryptTestVector.json");
final Path pbkdf2Keystore = tempDir.resolve("pbkdf2TestVector.json");
// create password file
final Path tempPasswordFile = createTempFile(tempDir, "pass", ".txt");
writeString(tempPasswordFile, EXPECTED_PASSWORD);
final List<Pair<Path, Path>> keystorePasswordFilePairs =
List.of(
Pair.of(scryptKeystore, tempPasswordFile), Pair.of(pbkdf2Keystore, tempPasswordFile));
when(config.getValidatorKeystorePasswordFilePairs()).thenReturn(keystorePasswordFilePairs);
Assertions.assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> keystoresValidatorKeyProvider.loadValidatorKeys(config))
.withMessage("KeyStore file not found: " + scryptKeystore);
}
@Test
void validJsonNotComplaintWithKeystoreFormatThrowsError(@TempDir final Path tempDir)
throws IOException {
final Eth1PrivateKeyOptions.Eth1EncryptedKeystoreOptions keystoreOptions =
new Eth1PrivateKeyOptions.Eth1EncryptedKeystoreOptions();
keystoreOptions.eth1KeystoreFile =
Files.writeString(tempDir.resolve("v3.json"), "{test:123}").toFile();
keystoreOptions.eth1KeystorePasswordFile =
Files.writeString(tempDir.resolve("password.txt"), "test123").toFile();
final Eth1PrivateKeyOptions eth1PrivateKeyOptions = new Eth1PrivateKeyOptions();
eth1PrivateKeyOptions.keystoreOptions = keystoreOptions;
final RegisterParams registerParams =
new RegisterParams(commandSpec, eth1PrivateKeyOptions, SHUTDOWN_FUNCTION, consoleAdapter);
when(commandSpec.commandLine()).thenReturn(mock(CommandLine.class));
assertThatExceptionOfType(CommandLine.ParameterException.class)
.isThrownBy(registerParams::getEth1Credentials)
.withMessage(
"Error: Unable to decrypt Eth1 keystore [%s] : Wallet version is not supported",
keystoreOptions.eth1KeystoreFile);
}
@Test
void testArtifact(@TempDir Path temporaryFolder) throws Exception {
Path home = temporaryFolder.resolve("apache-cassandra-3.11.6");
Files.createDirectories(home);
Files.createDirectories(home.resolve("bin"));
Files.createDirectories(home.resolve("lib"));
Files.createDirectories(home.resolve("conf"));
Files.createFile(home.resolve("conf/cassandra.yaml"));
Version version = Version.of("3.11.6");
Artifact artifact = new DefaultArtifact(version, temporaryFolder);
Artifact.Distribution distribution = artifact.getDistribution();
assertThat(distribution.getVersion()).isEqualTo(version);
Path directory = distribution.getDirectory();
assertThat(directory.resolve("bin")).exists();
assertThat(directory.resolve("conf")).exists();
assertThat(directory.resolve("lib")).exists();
assertThat(directory.resolve("conf/cassandra.yaml")).exists();
}
@Test
void testEditDeps(@TempDir Path outputDir) throws IOException {
Path p = outputDir.resolve("edit.java");
String s = p.toString();
Jbang.getCommandLine().execute("init", s);
assertThat(new File(s).exists(), is(true));
Util.writeString(p, "//DEPS org.openjfx:javafx-graphics:11.0.2${bougus:}\n" + Util.readString(p));
Script script = BaseScriptCommand.prepareScript(s, null, null);
File project = new Edit().createProjectForEdit(script, false);
File gradle = new File(project, "build.gradle");
assert (gradle.exists());
assertThat(Util.readString(gradle.toPath()), not(containsString("bogus")));
File java = new File(project, "src/edit.java");
// first check for symlink. in some cases on windows (non admin privileg)
// symlink cannot be created, as fallback a hardlink will be created.
assert (Files.isSymbolicLink(java.toPath()) || java.exists());
assertThat(Files.isSameFile(java.toPath(), p), equalTo(true));
}
@ParameterizedTest(name = "{0} - {1} - {2} - {3}")
@MethodSource("parameters")
void projectBuilds(Version bootVersion, Packaging packaging, Language language, BuildSystem buildSystem,
@TempDir Path directory) throws IOException, InterruptedException {
WebProjectRequest request = new WebProjectRequest();
request.setBootVersion(bootVersion.toString());
request.setLanguage(language.id());
request.setPackaging(packaging.id());
request.setType(buildSystem.id() + "-project");
request.setGroupId("com.example");
request.setArtifactId("demo");
request.setApplicationName("DemoApplication");
request.setDependencies(Arrays.asList("devtools", "configuration-processor"));
Path project = this.invoker.invokeProjectStructureGeneration(request).getRootDirectory();
ProcessBuilder processBuilder = createProcessBuilder(buildSystem);
processBuilder.directory(project.toFile());
Path output = Files.createTempFile(directory, "output-", ".log");
processBuilder.redirectError(output.toFile());
processBuilder.redirectOutput(output.toFile());
assertThat(processBuilder.start().waitFor()).describedAs(String.join("\n", Files.readAllLines(output)))
.isEqualTo(0);
}
@Test
void shouldNotDownloadArtifactReadTimeout(@TempDir Path temporaryFolder) throws Exception {
this.httpServer.createContext("/dist/apache-cassandra-3.11.6.zip", exchange -> {
try {
Thread.sleep(600);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
exchange.close();
});
RemoteArtifact artifact = new RemoteArtifact(VERSION);
artifact.setDestination(temporaryFolder);
artifact.setReadTimeout(Duration.ofMillis(200));
artifact.setUrlFactory(version -> Collections.singletonList(
new URL(String.format("http:/%s/dist/apache-cassandra-3.11.6.zip", this.httpServer.getAddress()))));
assertThatThrownBy(artifact::getDistribution).hasStackTraceContaining("Read timed out");
}
@Test
void failTryLockThreads(@TempDir Path folder) throws IOException, InterruptedException {
try (FileLock fileLock = FileLock.of(folder.resolve(LOCK_FILE))) {
if (!fileLock.tryLock(50, TimeUnit.MICROSECONDS)) {
throw new IllegalStateException();
}
AtomicBoolean fail = new AtomicBoolean(false);
Thread thread = new Thread(() -> {
try {
fail.set(!fileLock.tryLock(100, TimeUnit.MILLISECONDS));
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
});
thread.start();
thread.join(1000);
assertThat(fail).isTrue();
}
}
@Test
void shouldLoadKeysFromKeyStores(@TempDir final Path tempDir) throws Exception {
// load keystores from resources
final Path scryptKeystore = Path.of(Resources.getResource("scryptTestVector.json").toURI());
final Path pbkdf2Keystore = Path.of(Resources.getResource("pbkdf2TestVector.json").toURI());
// create password file
final Path tempPasswordFile = createTempFile(tempDir, "pass", ".txt");
writeString(tempPasswordFile, EXPECTED_PASSWORD);
final List<Pair<Path, Path>> keystorePasswordFilePairs =
List.of(
Pair.of(scryptKeystore, tempPasswordFile), Pair.of(pbkdf2Keystore, tempPasswordFile));
when(config.getValidatorKeystorePasswordFilePairs()).thenReturn(keystorePasswordFilePairs);
final List<BLSKeyPair> blsKeyPairs = keystoresValidatorKeyProvider.loadValidatorKeys(config);
// since both test vectors encrypted same private key, we should get 1 element
Assertions.assertThat(blsKeyPairs).containsExactly(EXPECTED_BLS_KEY_PAIR);
}
@Test
void parsingUnknownOptionsInYamlConfigFileThrowsException(@TempDir final Path tempDir)
throws IOException {
final Map<String, Object> options = defaultOptions();
options.put("additional-option-3", "x");
options.put("additional-option-1", "x");
options.put("additional-option-2", "y");
final Path configFile = writeToYamlConfigFile(options, tempDir);
final CommandLine commandLine = new CommandLine(TestCommand.class);
commandLine.setDefaultValueProvider(
new YamlConfigFileDefaultProvider(commandLine, configFile.toFile()));
Assertions.assertThatExceptionOfType(CommandLine.ParameterException.class)
.isThrownBy(commandLine::parseArgs)
.withMessage(
"Unknown options in yaml configuration file: additional-option-1, additional-option-2, additional-option-3");
}
@Test
void clientWithCertificateNotInCertificateAuthorityCanConnectAndQueryAccounts(
@TempDir final Path tempDir) throws Exception {
ethSigner = createEthSigner(clientCert, tempDir);
ethSigner.start();
ethSigner.awaitStartupCompletion();
assertThat(ethSigner.accounts().list()).isNotEmpty();
}
@Test
@SuppressWarnings("unchecked")
void shouldNotStoreValuesThatAreSafeToChange(@TempDir final File tempDir) throws Exception {
final File metadataFile = new File(tempDir, "metadata.yml");
final DatabaseMetadata expectedMetadata = DatabaseMetadata.v5Defaults();
DatabaseMetadata.init(metadataFile, expectedMetadata);
final Map<String, Object> metadata = loadMetaData(metadataFile);
final Map<String, Object> hotConfig =
(Map<String, Object>) metadata.get(HOT_DB_CONFIGURATION_KEY);
assertThat(hotConfig).doesNotContainKeys("maxOpenFiles", "databaseDir");
}
@Test
void missingKeyStoreForEthSignerResultsInEthSignerTerminating(@TempDir Path workDir)
throws Exception {
final TlsCertificateDefinition serverPresentedCert =
TlsCertificateDefinition.loadFromResource("tls/cert1.pfx", "password");
final TlsCertificateDefinition ethSignerCert =
new TlsCertificateDefinition(
workDir.resolve("Missing_keyStore").toFile(), "arbitraryPassword");
// Ports are arbitrary as EthSigner should exit
signer = createSigner(ethSignerCert, serverPresentedCert, 9000, 9001, workDir);
signer.start();
waitFor(() -> assertThat(signer.isRunning()).isFalse());
}
@Test
void testJavaHome(@TempDir Path temporaryFolder) {
this.cassandraFactory.setJavaHome(temporaryFolder);
assertThat(this.cassandraFactory.getJavaHome()).isEqualTo(temporaryFolder);
Cassandra cassandra = this.cassandraFactory.create();
Object node = ReflectionTestUtils.getField(ReflectionTestUtils.getField(cassandra, "database"), "node");
assertThat(node).hasFieldOrPropertyWithValue("environmentVariables",
Collections.singletonMap("JAVA_HOME", temporaryFolder));
}
@Test
void encryptedKeystoresAreCreatedWithPasswordFromEnvironmentVariable(@TempDir final Path tempDir)
throws IOException {
final Path outputPath = Files.createTempDirectory(tempDir, "keystores");
final ValidatorPasswordOptions validatorPasswordOptions = new ValidatorPasswordOptions();
validatorPasswordOptions.validatorPasswordEnv = EXPECTED_ENV_VARIABLE;
final WithdrawalPasswordOptions withdrawalPasswordOptions = new WithdrawalPasswordOptions();
withdrawalPasswordOptions.withdrawalPasswordEnv = EXPECTED_ENV_VARIABLE;
assertEncryptedKeystoresAreCreated(
outputPath, validatorPasswordOptions, withdrawalPasswordOptions);
}
@Test
void incorrectlyNamedHashicorpConfigFileIsNotLoaded(@TempDir final Path tempDir) {
createHashicorpTomlFileAt(
tempDir.resolve("ffffffffffffffffffffffffffffffffffffffff.toml"), hashicorpNode);
setup(tempDir);
assertThat(ethSigner.accounts().list()).isEmpty();
}
@Test
void hashicorpLoadedFromMultiKeyCanSignValueTransferTransaction(@TempDir Path tomlDirectory) {
createHashicorpTomlFileAt(tomlDirectory.resolve(FILENAME + ".toml"), hashicorpNode);
setup(tomlDirectory);
performTransaction();
}
@Test
void testArtifactFailNoCassandraHome(@TempDir Path temporaryFolder) {
assertThatIllegalStateException().isThrownBy(() -> {
Version version = Version.of("3.11.6");
Artifact artifact = new DefaultArtifact(version, temporaryFolder);
artifact.getDistribution();
});
}
@BeforeEach
void setUp( @TempDir final Path temp ) throws Exception {
configFolder = temp.resolve( RETEST_FOLDER_NAME );
Files.createDirectory( configFolder );
final Path jsIgnoreFile = configFolder.resolve( RECHECK_IGNORE_JSRULES );
Files.createFile( jsIgnoreFile );
final Path origIgnoreFile =
Paths.get( "src/test/resources/de/retest/recheck/review/workers/legacy-recheck.ignore" );
migratedIgnoreFile = Paths.get( "src/test/resources/de/retest/recheck/review/workers/" + RECHECK_IGNORE );
tempIgnoreFile = configFolder.resolve( RECHECK_IGNORE );
Files.copy( origIgnoreFile, tempIgnoreFile );
}
@Test
void emptyPasswordFileThrowsException(@TempDir final Path tempDir) throws IOException {
final Path passwordFile = tempDir.resolve("password.txt");
final String expectedPassword = "";
Files.writeString(passwordFile, expectedPassword + lineSeparator());
Assertions.assertThatExceptionOfType(CommandLine.ParameterException.class)
.isThrownBy(() -> KeystorePasswordOptions.readFromFile(commandLine, passwordFile.toFile()))
.withMessage(EXPECTED_EMPTY_PASSWORD_FILE_ERROR, passwordFile.toFile());
}
@Test
void testTopologyConfig(@TempDir Path temporaryFolder) throws IOException {
Path file = Files.createTempFile(temporaryFolder, "", "");
FileSystemResource config = new FileSystemResource(file);
this.cassandraFactory.setTopologyConfig(config);
assertThat(this.cassandraFactory.getTopologyConfig()).isEqualTo(config);
Cassandra cassandra = this.cassandraFactory.create();
Object database = ReflectionTestUtils.getField(cassandra, "database");
assertThat(database).hasFieldOrPropertyWithValue("topologyConfig", config);
}
@ParameterizedTest
@ValueSource(strings = { SUB_DIRECTORY, NO_SUB_DIRECTORY })
void shouldCreateCsvFilesInAnyDirectory(String subDirectory, @TempDir Path outputDirectory) throws IOException
{
new CsvFileCreator(outputDirectory.toFile()).createCsvFiles(subDirectory, createCsvFileData(DATA));
verifyCsvFile(outputDirectory, subDirectory, List.of(dataToCsvLine(HEADER), dataToCsvLine(DATA)));
}
@Test
void shouldDeleteCleanableDirectories(@TempDir Path tempDir) throws IOException
{
Path dir = tempDir.resolve("to-be-cleaned-up");
Files.createDirectories(dir);
StartContextListener startContextListener = new StartContextListener();
startContextListener.setCleanableDirectories(Optional.of(List.of(dir.toFile())));
startContextListener.onApplicationEvent(mock(ContextStartedEvent.class));
assertTrue(Files.exists(tempDir));
assertFalse(Files.exists(dir));
}
@Test
void shouldIgnoreNonExistentCleanableDirectories(@TempDir Path tempDir)
{
StartContextListener startContextListener = new StartContextListener();
startContextListener.setCleanableDirectories(Optional.of(List.of(tempDir.resolve("non-existent").toFile())));
startContextListener.onApplicationEvent(mock(ContextStartedEvent.class));
assertTrue(Files.exists(tempDir));
}
@Test
void mismatchedValidatorInteractivePasswordRaisesError(@TempDir final Path tempDir)
throws IOException {
when(consoleAdapter.readPassword(anyString(), any()))
.thenReturn(EXPECTED_PASSWORD.toCharArray())
.thenReturn("mismatched".toCharArray());
final Path outputPath = Files.createTempDirectory(tempDir, "keystores");
assertThatExceptionOfType(CommandLine.ParameterException.class)
.isThrownBy(() -> assertEncryptedKeystoresAreCreated(outputPath, null, null))
.withMessage("Error: Password mismatched");
}