org.junit.jupiter.api.io.TempDir Java Examples

The following examples show how to use org.junit.jupiter.api.io.TempDir. 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: RemoteArtifactTests.java    From embedded-cassandra with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #2
Source File: DepositRegisterCommandTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #3
Source File: FileLockTests.java    From embedded-cassandra with Apache License 2.0 6 votes vote down vote up
@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();
	}
}
 
Example #4
Source File: KeystoresValidatorKeyProviderTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: DefaultArtifactTests.java    From embedded-cassandra with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #6
Source File: ProjectGenerationIntegrationTests.java    From start.spring.io with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: YamlConfigFileDefaultProviderTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #8
Source File: TestEdit.java    From jbang with MIT License 6 votes vote down vote up
@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));
}
 
Example #9
Source File: KeystoresValidatorKeyProviderTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: RegisterParamsTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: FileBasedTomlLoadingAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #12
Source File: FileBasedTomlLoadingAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: GenerateActionTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: ClientSideTlsAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #15
Source File: ServerSideTlsCaClientAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: RemoteArtifactTests.java    From embedded-cassandra with Apache License 2.0 5 votes vote down vote up
@Test
void shouldDownloadArtifactProgress(@TempDir Path temporaryFolder) throws Exception {
	RemoteArtifact artifact = new RemoteArtifact(VERSION);
	artifact.setDestination(temporaryFolder);
	artifact.setUrlFactory(version -> Collections.singletonList(
			new URL(String.format("http:/%s/apache-cassandra-3.11.6-bin.tar.gz", this.httpServer.getAddress()))));
	assertDistribution(artifact.getDistribution());
	assertThat(this.output.toString()).contains("Downloaded");
	this.output.reset();
	assertDistribution(artifact.getDistribution());
	assertThat(this.output.toString()).doesNotContain("Downloaded");
}
 
Example #17
Source File: ValidatorLoaderTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void initializeValidatorsWithBothLocalAndExternalSigners(@TempDir Path tempDir)
    throws IOException {
  final Path validatorKeyFile = tempDir.resolve("validatorKeyFile");
  Files.writeString(validatorKeyFile, VALIDATOR_KEY_FILE);

  final TekuConfiguration tekuConfiguration =
      TekuConfiguration.builder()
          .setValidatorExternalSignerUrl("http://localhost:9000")
          .setValidatorExternalSignerPublicKeys(Collections.singletonList(PUBLIC_KEY2))
          .setValidatorKeyFile(validatorKeyFile.toAbsolutePath().toString())
          .setValidatorKeystoreFiles(emptyList())
          .setValidatorKeystorePasswordFiles(emptyList())
          .build();
  final Map<BLSPublicKey, Validator> validators =
      ValidatorLoader.initializeValidators(tekuConfiguration);

  assertThat(validators).hasSize(2);

  final BLSPublicKey key1 = BLSPublicKey.fromBytes(Bytes.fromHexString(PUBLIC_KEY1));
  final Validator validator1 = validators.get(key1);
  assertThat(validator1).isNotNull();
  assertThat(validator1.getPublicKey()).isEqualTo(key1);
  assertThat(validator1.getSigner().getMessageSignerService())
      .isInstanceOf(LocalMessageSignerService.class);

  final BLSPublicKey key2 = BLSPublicKey.fromBytes(Bytes.fromHexString(PUBLIC_KEY2));
  final Validator validator2 = validators.get(key2);
  assertThat(validator2).isNotNull();
  assertThat(validator2.getPublicKey()).isEqualTo(key2);
  assertThat(validator2.getSigner().getMessageSignerService())
      .isInstanceOf(ExternalMessageSignerService.class);
}
 
Example #18
Source File: Log4j2ConfigurationFactoryTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testLogFileJson(@TempDir Path tempDir) {
    String logFile = tempDir.resolve("agent.json").toString();
    Configuration configuration = getLogConfig(Map.of("log_file", logFile, "log_format_file", "json"));

    assertThat(configuration.getAppenders().values()).hasSize(1);
    Appender appender = configuration.getAppenders().values().iterator().next();

    assertThat(appender).isInstanceOf(RollingFileAppender.class);
    assertThat(((RollingFileAppender) appender).getFileName()).isEqualTo(logFile);
    assertThat(appender.getLayout()).isInstanceOf(EcsLayout.class);
}
 
Example #19
Source File: RunProcessTests.java    From embedded-cassandra with Apache License 2.0 5 votes vote down vote up
@Test
@DisabledOnOs(OS.WINDOWS)
void shouldRunProcessUnix(@TempDir Path temporaryFolder) throws Exception {
	StringBuilder output = new StringBuilder();
	int exit = runProcess(temporaryFolder, "bash", "-c", command("echo", "$RUN_PROCESS_TEST")).run(output::append);
	assertThat(output.toString()).isEqualTo("TEST");
	assertThat(exit).isEqualTo(0);
}
 
Example #20
Source File: DeleteOnCloseFileInputStreamTest.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
void file_should_be_deleted_on_close( @TempDir final Path temp ) throws IOException {
	final Path file = temp.resolve( "foo" );
	Files.createFile( file );
	final InputStream in = new DeleteOnCloseFileInputStream( file.toFile() );

	in.close();

	assertThat( file ).doesNotExist();
}
 
Example #21
Source File: ManagedDependenciesKotlinVersionResolverTests.java    From start.spring.io with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void kotlinVersionCanBeResolved(@TempDir Path temp) {
	MutableProjectDescription description = new MutableProjectDescription();
	description.setPlatformVersion(Version.parse("2.1.6.RELEASE"));
	Function<ProjectDescription, String> fallback = mock(Function.class);
	String version = new ManagedDependenciesKotlinVersionResolver(
			DependencyManagementVersionResolver.withCacheLocation(temp), fallback)
					.resolveKotlinVersion(description);
	assertThat(version).isEqualTo("1.2.71");
	verifyNoInteractions(fallback);
}
 
Example #22
Source File: YamlConfigFileDefaultProviderTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void parsingValidYamlFilePopulatesCommandObject(@TempDir final Path tempDir) throws IOException {
  final Path configFile = writeToYamlConfigFile(defaultOptions(), tempDir);
  final CommandLine commandLine = new CommandLine(TestCommand.class);
  commandLine.setDefaultValueProvider(
      new YamlConfigFileDefaultProvider(commandLine, configFile.toFile()));
  commandLine.parseArgs();
  final TestCommand testCommand = commandLine.getCommand();

  Assertions.assertThat(testCommand.getCount()).isEqualTo(10);
  Assertions.assertThat(testCommand.getNames()).containsExactlyInAnyOrder("a", "b");
  Assertions.assertThat(testCommand.isTestEnabled()).isTrue();
}
 
Example #23
Source File: WriteFxImageTests.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
@Test
public void testWritingImageToFile(@TempDir File tempDir) throws IOException {
    File tmpfile = new File(tempDir.getPath() + "test.png");
    // convert to png
    WriteFxImage.savePng(imageOvals, tmpfile);
    // load from png
    try (InputStream is = new FileInputStream(tmpfile.getPath())) {
        Image recovered = new Image(is);
        // compare against original
        assertImageEqual(imageOvals, recovered);
    }
}
 
Example #24
Source File: KryoPersistenceTest.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
void roundtrip_should_work( @TempDir final Path temp ) throws IOException {
	final Path file = temp.resolve( "test.test" );
	Files.createFile( file );
	final URI identifier = file.toUri();

	final KryoPersistence<de.retest.recheck.test.Test> kryoPersistence = new KryoPersistence<>();
	final de.retest.recheck.test.Test persisted = createDummyTest();
	kryoPersistence.save( identifier, persisted );
	final de.retest.recheck.test.Test loaded = kryoPersistence.load( identifier );

	assertThat( persisted.getRelativeActionSequencePaths() ).isEqualTo( loaded.getRelativeActionSequencePaths() );
}
 
Example #25
Source File: TestInit.java    From jbang with MIT License 5 votes vote down vote up
@Test
void testInitExtensionless(@TempDir Path outputDir) throws IOException {

	Path x = outputDir.resolve("xyzplug");
	String s = x.toString();
	int result = Jbang.getCommandLine().execute("init", s);
	assertThat(new File(s).exists(), is(true));
	assertThat(result, is(0));

	assertThat(Util.readString(x), containsString("class xyzplug"));
}
 
Example #26
Source File: GenerateActionTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void encryptedKeystoresAreCreatedWithPasswordFromFile(@TempDir final Path tempDir)
    throws IOException {
  final Path outputPath = Files.createTempDirectory(tempDir, "keystores");
  final Path passwordFile = Files.writeString(tempDir.resolve("password.txt"), EXPECTED_PASSWORD);

  final ValidatorPasswordOptions validatorPasswordOptions = new ValidatorPasswordOptions();
  validatorPasswordOptions.validatorPasswordFile = passwordFile.toFile();
  final WithdrawalPasswordOptions withdrawalPasswordOptions = new WithdrawalPasswordOptions();
  withdrawalPasswordOptions.withdrawalPasswordFile = passwordFile.toFile();

  assertEncryptedKeystoresAreCreated(
      outputPath, validatorPasswordOptions, withdrawalPasswordOptions);
}
 
Example #27
Source File: ScreenshotFolderPersistenceTest.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
@BeforeEach
void setUp( @TempDir final Path temp ) throws Exception {
	baseFolder = temp.toFile();
	screenshotFolder = new File( baseFolder, "screenshot" );
	screenshotPersistence = new ScreenshotFolderPersistence( baseFolder );

	filledImageBytes = "testcontent1".getBytes();
	filledScreenshot = new Screenshot( "testimage", filledImageBytes, ImageType.PNG );
	filledImageFile = new File( screenshotFolder, "testimage." + ImageType.PNG.getFileExtension() );

	emptyScreenshot = new Screenshot( "emptyimage", new byte[0], ImageType.PNG );
	emptyImageFile = new File( screenshotFolder, "emptyimage." + ImageType.PNG.getFileExtension() );
}
 
Example #28
Source File: TestInit.java    From jbang with MIT License 5 votes vote down vote up
@Test
void testMissingTemplate(@TempDir Path outputDir) throws IOException {

	Path x = outputDir.resolve("edit.java");
	String s = x.toString();
	int result = Jbang.getCommandLine().execute("init", "--template=bogus", s);
	assertThat(new File(s).exists(), is(false));
	assertThat(result, not(0));
}
 
Example #29
Source File: YamlValidatorKeyProviderTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLoadExampleFile(@TempDir Path tempDirectory) throws Exception {
  final Path tempFile =
      writeTestFile(
          tempDirectory,
          "- {privkey: '0x25295f0d1d592a90b333e26e85149708208e9f8e8bc18f6c77bd62f8ad7a6866',\n"
              + "  pubkey: '0xa99a76ed7796f7be22d5b7e85deeb7c5677e88e511e0b337618f8c4eb61349b4bf2d153f649f7b53359fe8b94a38e44c'}\n"
              + "- {privkey: '0x51d0b65185db6989ab0b560d6deed19c7ead0e24b9b6372cbecb1f26bdfad000',\n"
              + "  pubkey: '0xb89bebc699769726a318c8e9971bd3171297c61aea4a6578a7a4f94b547dcba5bac16a89108b6b6a1fe3695d1a874a0b'}\n"
              + "- {privkey: '0x315ed405fafe339603932eebe8dbfd650ce5dafa561f6928664c75db85f97857',\n"
              + "  pubkey: '0xa3a32b0f8b4ddb83f1a0a853d81dd725dfe577d4f4c3db8ece52ce2b026eca84815c1a7e8e92a4de3d755733bf7e4a9b'}");

  final List<String> EXPECTED_PRIVATE_KEYS =
      asList(
          "0x0000000000000000000000000000000025295f0d1d592a90b333e26e85149708208e9f8e8bc18f6c77bd62f8ad7a6866",
          "0x0000000000000000000000000000000051d0b65185db6989ab0b560d6deed19c7ead0e24b9b6372cbecb1f26bdfad000",
          "0x00000000000000000000000000000000315ed405fafe339603932eebe8dbfd650ce5dafa561f6928664c75db85f97857");

  when(config.getValidatorsKeyFile()).thenReturn(tempFile.toAbsolutePath().toString());

  final List<BLSKeyPair> keys = provider.loadValidatorKeys(config);
  final List<String> actualPrivateKeys =
      keys.stream()
          .map(keypair -> keypair.getSecretKey().getSecretKey().toBytes().toHexString())
          .collect(Collectors.toList());

  assertEquals(EXPECTED_PRIVATE_KEYS, actualPrivateKeys);
}
 
Example #30
Source File: GenerateActionTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void emptyInteractivePasswordRaisesError(@TempDir final Path tempDir) throws IOException {
  when(consoleAdapter.readPassword(anyString(), any())).thenReturn(null);
  final Path outputPath = Files.createTempDirectory(tempDir, "keystores");
  assertThatExceptionOfType(CommandLine.ParameterException.class)
      .isThrownBy(() -> assertEncryptedKeystoresAreCreated(outputPath, null, null))
      .withMessage("Error: Password is blank");
}