test: use assertThrows instead of try-catch blocks
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Stefan Kalscheuer 2021-02-28 12:59:06 +01:00
parent 2b0f458da3
commit 76a5ea4fe9
15 changed files with 945 additions and 1354 deletions

View File

@ -30,6 +30,7 @@ import org.apache.http.message.BasicStatusLine;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.mockito.MockedStatic; import org.mockito.MockedStatic;
import java.io.IOException; import java.io.IOException;
@ -44,7 +45,8 @@ import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is; import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -85,35 +87,32 @@ class HTTPVaultConnectorOfflineTest {
// Test invalid response code. // Test invalid response code.
final int responseCode = 400; final int responseCode = 400;
mockResponse(responseCode, "", ContentType.APPLICATION_JSON); mockResponse(responseCode, "", ContentType.APPLICATION_JSON);
try { InvalidResponseException e = assertThrows(
connector.getHealth(); InvalidResponseException.class,
fail("Querying health status succeeded on invalid instance"); connector::getHealth,
} catch (Exception e) { "Querying health status succeeded on invalid instance"
assertThat("Unexpected type of exception", e, instanceOf(InvalidResponseException.class)); );
assertThat("Unexpected exception message", e.getMessage(), is("Invalid response code")); assertThat("Unexpected exception message", e.getMessage(), is("Invalid response code"));
assertThat("Unexpected status code in exception", ((InvalidResponseException) e).getStatusCode(), is(responseCode)); assertThat("Unexpected status code in exception", ((InvalidResponseException) e).getStatusCode(), is(responseCode));
assertThat("Response message where none was expected", ((InvalidResponseException) e).getResponse(), is(nullValue())); assertThat("Response message where none was expected", ((InvalidResponseException) e).getResponse(), is(nullValue()));
}
// Simulate permission denied response. // Simulate permission denied response.
mockResponse(responseCode, "{\"errors\":[\"permission denied\"]}", ContentType.APPLICATION_JSON); mockResponse(responseCode, "{\"errors\":[\"permission denied\"]}", ContentType.APPLICATION_JSON);
try { assertThrows(
connector.getHealth(); PermissionDeniedException.class,
fail("Querying health status succeeded on invalid instance"); connector::getHealth,
} catch (Exception e) { "Querying health status succeeded on invalid instance"
assertThat("Unexpected type of exception", e, instanceOf(PermissionDeniedException.class)); );
}
// Test exception thrown during request. // Test exception thrown during request.
when(httpMock.execute(any())).thenThrow(new IOException("Test Exception")); when(httpMock.execute(any())).thenThrow(new IOException("Test Exception"));
try { e = assertThrows(
connector.getHealth(); InvalidResponseException.class,
fail("Querying health status succeeded on invalid instance"); connector::getHealth,
} catch (Exception e) { "Querying health status succeeded on invalid instance"
assertThat("Unexpected type of exception", e, instanceOf(InvalidResponseException.class)); );
assertThat("Unexpected exception message", e.getMessage(), is("Unable to read response")); assertThat("Unexpected exception message", e.getMessage(), is("Unable to read response"));
assertThat("Unexpected cause", e.getCause(), instanceOf(IOException.class)); assertThat("Unexpected cause", e.getCause(), instanceOf(IOException.class));
}
// Now simulate a failing request that succeeds on second try. // Now simulate a failing request that succeeds on second try.
connector = new HTTPVaultConnector("https://127.0.0.1", null, 1, 250); connector = new HTTPVaultConnector("https://127.0.0.1", null, 1, 250);
@ -125,11 +124,7 @@ class HTTPVaultConnectorOfflineTest {
.when(responseMock).getStatusLine(); .when(responseMock).getStatusLine();
when(responseMock.getEntity()).thenReturn(new StringEntity("{}", ContentType.APPLICATION_JSON)); when(responseMock.getEntity()).thenReturn(new StringEntity("{}", ContentType.APPLICATION_JSON));
try { assertDoesNotThrow(connector::getHealth, "Request failed unexpectedly");
connector.getHealth();
} catch (Exception e) {
fail("Request failed unexpectedly: " + e.getMessage());
}
} }
/** /**
@ -188,54 +183,47 @@ class HTTPVaultConnectorOfflineTest {
* This test is designed to test exceptions caught and thrown by seal-methods if Vault is not reachable. * This test is designed to test exceptions caught and thrown by seal-methods if Vault is not reachable.
*/ */
@Test @Test
void sealExceptionTest() throws IOException { void sealExceptionTest() {
HTTPVaultConnector connector = new HTTPVaultConnector(INVALID_URL); HTTPVaultConnector connector = new HTTPVaultConnector(INVALID_URL);
try { VaultConnectorException e = assertThrows(
connector.sealStatus(); InvalidRequestException.class,
fail("Querying seal status succeeded on invalid URL"); connector::sealStatus,
} catch (Exception e) { "Querying seal status succeeded on invalid URL"
assertThat("Unexpected type of exception", e, instanceOf(InvalidRequestException.class)); );
assertThat("Unexpected exception message", e.getMessage(), is("Invalid URI format")); assertThat("Unexpected exception message", e.getMessage(), is("Invalid URI format"));
}
connector = new HTTPVaultConnector("https://127.0.0.1", null, 0, 250);
// Simulate NULL response (mock not supplied with data). // Simulate NULL response (mock not supplied with data).
connector = new HTTPVaultConnector("https://127.0.0.1", null, 0, 250);
try { e = assertThrows(
connector.sealStatus(); InvalidResponseException.class,
fail("Querying seal status succeeded on invalid instance"); connector::sealStatus,
} catch (Exception e) { "Querying seal status succeeded on invalid instance"
assertThat("Unexpected type of exception", e, instanceOf(InvalidResponseException.class)); );
assertThat("Unexpected exception message", e.getMessage(), is("Response unavailable")); assertThat("Unexpected exception message", e.getMessage(), is("Response unavailable"));
} }
}
/** /**
* This test is designed to test exceptions caught and thrown by seal-methods if Vault is not reachable. * This test is designed to test exceptions caught and thrown by seal-methods if Vault is not reachable.
*/ */
@Test @Test
void healthExceptionTest() throws IOException { void healthExceptionTest() {
HTTPVaultConnector connector = new HTTPVaultConnector(INVALID_URL); HTTPVaultConnector connector = new HTTPVaultConnector(INVALID_URL);
try { VaultConnectorException e = assertThrows(
connector.getHealth(); InvalidRequestException.class,
fail("Querying health status succeeded on invalid URL"); connector::getHealth,
} catch (Exception e) { "Querying health status succeeded on invalid URL"
assertThat("Unexpected type of exception", e, instanceOf(InvalidRequestException.class)); );
assertThat("Unexpected exception message", e.getMessage(), is("Invalid URI format")); assertThat("Unexpected exception message", e.getMessage(), is("Invalid URI format"));
}
connector = new HTTPVaultConnector("https://127.0.0.1", null, 0, 250);
// Simulate NULL response (mock not supplied with data). // Simulate NULL response (mock not supplied with data).
try { connector = new HTTPVaultConnector("https://127.0.0.1", null, 0, 250);
connector.getHealth(); e = assertThrows(
fail("Querying health status succeeded on invalid instance"); InvalidResponseException.class,
} catch (Exception e) { connector::getHealth,
assertThat("Unexpected type of exception", e, instanceOf(InvalidResponseException.class)); "Querying health status succeeded on invalid instance"
);
assertThat("Unexpected exception message", e.getMessage(), is("Response unavailable")); assertThat("Unexpected exception message", e.getMessage(), is("Response unavailable"));
} }
}
/** /**
* Test behavior on unparsable responses. * Test behavior on unparsable responses.
@ -249,114 +237,25 @@ class HTTPVaultConnectorOfflineTest {
mockResponse(200, "invalid", ContentType.APPLICATION_JSON); mockResponse(200, "invalid", ContentType.APPLICATION_JSON);
// Now test the methods. // Now test the methods.
try { assertParseError(connector::sealStatus, "sealStatus() succeeded on invalid instance");
connector.sealStatus(); assertParseError(() -> connector.unseal("key"), "unseal() succeeded on invalid instance");
fail("sealStatus() succeeded on invalid instance"); assertParseError(connector::getHealth, "getHealth() succeeded on invalid instance");
} catch (Exception e) { assertParseError(connector::getAuthBackends, "getAuthBackends() succeeded on invalid instance");
assertParseError(e); assertParseError(() -> connector.authToken("token"), "authToken() succeeded on invalid instance");
assertParseError(() -> connector.lookupAppRole("roleName"), "lookupAppRole() succeeded on invalid instance");
assertParseError(() -> connector.getAppRoleID("roleName"), "getAppRoleID() succeeded on invalid instance");
assertParseError(() -> connector.createAppRoleSecret("roleName"), "createAppRoleSecret() succeeded on invalid instance");
assertParseError(() -> connector.lookupAppRoleSecret("roleName", "secretID"), "lookupAppRoleSecret() succeeded on invalid instance");
assertParseError(connector::listAppRoles, "listAppRoles() succeeded on invalid instance");
assertParseError(() -> connector.listAppRoleSecrets("roleName"), "listAppRoleSecrets() succeeded on invalid instance");
assertParseError(() -> connector.read("key"), "read() succeeded on invalid instance");
assertParseError(() -> connector.list("path"), "list() succeeded on invalid instance");
assertParseError(() -> connector.renew("leaseID"), "renew() succeeded on invalid instance");
assertParseError(() -> connector.lookupToken("token"), "lookupToken() succeeded on invalid instance");
} }
try { private void assertParseError(Executable executable, String message) {
connector.unseal("key"); InvalidResponseException e = assertThrows(InvalidResponseException.class, executable, message);
fail("unseal() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.getHealth();
fail("getHealth() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.getAuthBackends();
fail("getAuthBackends() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.authToken("token");
fail("authToken() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.lookupAppRole("roleName");
fail("lookupAppRole() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.getAppRoleID("roleName");
fail("getAppRoleID() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.createAppRoleSecret("roleName");
fail("createAppRoleSecret() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.lookupAppRoleSecret("roleName", "secretID");
fail("lookupAppRoleSecret() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.listAppRoles();
fail("listAppRoles() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.listAppRoleSecrets("roleName");
fail("listAppRoleSecrets() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.read("key");
fail("read() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.list("path");
fail("list() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.renew("leaseID");
fail("renew() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
try {
connector.lookupToken("token");
fail("lookupToken() succeeded on invalid instance");
} catch (Exception e) {
assertParseError(e);
}
}
private void assertParseError(Exception e) {
assertThat("Unexpected type of exception", e, instanceOf(InvalidResponseException.class));
assertThat("Unexpected exception message", e.getMessage(), is("Unable to parse response")); assertThat("Unexpected exception message", e.getMessage(), is("Unable to parse response"));
} }
@ -372,68 +271,59 @@ class HTTPVaultConnectorOfflineTest {
mockResponse(200, "{}", ContentType.APPLICATION_JSON); mockResponse(200, "{}", ContentType.APPLICATION_JSON);
// Now test the methods expecting a 204. // Now test the methods expecting a 204.
try { assertThrows(
connector.registerAppId("appID", "policy", "displayName"); InvalidResponseException.class,
fail("registerAppId() with 200 response succeeded"); () -> connector.registerAppId("appID", "policy", "displayName"),
} catch (VaultConnectorException e) { "registerAppId() with 200 response succeeded"
assertThat("Unexpected exception type", e, instanceOf(InvalidResponseException.class)); );
}
try { assertThrows(
connector.registerUserId("appID", "userID"); InvalidResponseException.class,
fail("registerUserId() with 200 response succeeded"); () -> connector.registerUserId("appID", "userID"),
} catch (VaultConnectorException e) { "registerUserId() with 200 response succeeded"
assertThat("Unexpected exception type", e, instanceOf(InvalidResponseException.class)); );
}
try { assertThrows(
connector.createAppRole("appID", Collections.singletonList("policy")); InvalidResponseException.class,
fail("createAppRole() with 200 response succeeded"); () -> connector.createAppRole("appID", Collections.singletonList("policy")),
} catch (VaultConnectorException e) { "createAppRole() with 200 response succeeded"
assertThat("Unexpected exception type", e, instanceOf(InvalidResponseException.class)); );
}
try { assertThrows(
connector.deleteAppRole("roleName"); InvalidResponseException.class,
fail("deleteAppRole() with 200 response succeeded"); () -> connector.deleteAppRole("roleName"),
} catch (VaultConnectorException e) { "deleteAppRole() with 200 response succeeded"
assertThat("Unexpected exception type", e, instanceOf(InvalidResponseException.class)); );
}
try { assertThrows(
connector.setAppRoleID("roleName", "roleID"); InvalidResponseException.class,
fail("setAppRoleID() with 200 response succeeded"); () -> connector.setAppRoleID("roleName", "roleID"),
} catch (VaultConnectorException e) { "setAppRoleID() with 200 response succeeded"
assertThat("Unexpected exception type", e, instanceOf(InvalidResponseException.class)); );
}
try { assertThrows(
connector.destroyAppRoleSecret("roleName", "secretID"); InvalidResponseException.class,
fail("destroyAppRoleSecret() with 200 response succeeded"); () -> connector.destroyAppRoleSecret("roleName", "secretID"),
} catch (VaultConnectorException e) { "destroyAppRoleSecret() with 200 response succeeded"
assertThat("Unexpected exception type", e, instanceOf(InvalidResponseException.class)); );
}
try { assertThrows(
connector.destroyAppRoleSecret("roleName", "secretUD"); InvalidResponseException.class,
fail("destroyAppRoleSecret() with 200 response succeeded"); () -> connector.destroyAppRoleSecret("roleName", "secretUD"),
} catch (VaultConnectorException e) { "destroyAppRoleSecret() with 200 response succeeded"
assertThat("Unexpected exception type", e, instanceOf(InvalidResponseException.class)); );
}
try { assertThrows(
connector.delete("key"); InvalidResponseException.class,
fail("delete() with 200 response succeeded"); () -> connector.delete("key"),
} catch (VaultConnectorException e) { "delete() with 200 response succeeded"
assertThat("Unexpected exception type", e, instanceOf(InvalidResponseException.class)); );
}
try { assertThrows(
connector.revoke("leaseID"); InvalidResponseException.class,
fail("destroyAppRoleSecret() with 200 response succeeded"); () -> connector.revoke("leaseID"),
} catch (VaultConnectorException e) { "destroyAppRoleSecret() with 200 response succeeded"
assertThat("Unexpected exception type", e, instanceOf(InvalidResponseException.class)); );
}
} }
private Object getRequestHelperPrivate(HTTPVaultConnector connector, String fieldName) { private Object getRequestHelperPrivate(HTTPVaultConnector connector, String fieldName) {

View File

@ -18,7 +18,6 @@ package de.stklcode.jvault.connector.builder;
import de.stklcode.jvault.connector.HTTPVaultConnector; import de.stklcode.jvault.connector.HTTPVaultConnector;
import de.stklcode.jvault.connector.exception.TlsException; import de.stklcode.jvault.connector.exception.TlsException;
import de.stklcode.jvault.connector.exception.VaultConnectorException;
import de.stklcode.jvault.connector.test.EnvironmentMock; import de.stklcode.jvault.connector.test.EnvironmentMock;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
@ -30,7 +29,8 @@ import java.nio.file.NoSuchFileException;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* JUnit test for HTTP Vault connector factory * JUnit test for HTTP Vault connector factory
@ -53,15 +53,11 @@ class HTTPVaultConnectorBuilderTest {
void testFromEnv() throws NoSuchFieldException, IllegalAccessException, IOException { void testFromEnv() throws NoSuchFieldException, IllegalAccessException, IOException {
/* Provide address only should be enough */ /* Provide address only should be enough */
setenv(VAULT_ADDR, null, null, null); setenv(VAULT_ADDR, null, null, null);
HTTPVaultConnectorBuilder factory = assertDoesNotThrow(
HTTPVaultConnectorBuilder factory = null; () -> VaultConnectorBuilder.http().fromEnv(),
HTTPVaultConnector connector; "Factory creation from minimal environment failed"
try { );
factory = VaultConnectorBuilder.http().fromEnv(); HTTPVaultConnector connector = factory.build();
} catch (VaultConnectorException e) {
fail("Factory creation from minimal environment failed");
}
connector = factory.build();
assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/"))); assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/")));
assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue())); assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue()));
@ -70,11 +66,10 @@ class HTTPVaultConnectorBuilderTest {
/* Provide address and number of retries */ /* Provide address and number of retries */
setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null); setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null);
try { factory = assertDoesNotThrow(
factory = VaultConnectorBuilder.http().fromEnv(); () -> VaultConnectorBuilder.http().fromEnv(),
} catch (VaultConnectorException e) { "Factory creation from environment failed"
fail("Factory creation from environment failed"); );
}
connector = factory.build(); connector = factory.build();
assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/"))); assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/")));
@ -85,23 +80,21 @@ class HTTPVaultConnectorBuilderTest {
String VAULT_CACERT = tempDir.toString() + "/doesnotexist"; String VAULT_CACERT = tempDir.toString() + "/doesnotexist";
setenv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null); setenv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null);
try { TlsException e = assertThrows(
VaultConnectorBuilder.http().fromEnv(); TlsException.class,
fail("Creation with unknown cert path failed."); () -> VaultConnectorBuilder.http().fromEnv(),
} catch (VaultConnectorException e) { "Creation with unknown cert path failed."
assertThat(e, is(instanceOf(TlsException.class))); );
assertThat(e.getCause(), is(instanceOf(NoSuchFileException.class))); assertThat(e.getCause(), is(instanceOf(NoSuchFileException.class)));
assertThat(((NoSuchFileException) e.getCause()).getFile(), is(VAULT_CACERT)); assertThat(((NoSuchFileException) e.getCause()).getFile(), is(VAULT_CACERT));
}
/* Automatic authentication */ /* Automatic authentication */
setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN); setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN);
try { factory = assertDoesNotThrow(
factory = VaultConnectorBuilder.http().fromEnv(); () -> VaultConnectorBuilder.http().fromEnv(),
} catch (VaultConnectorException e) { "Factory creation from minimal environment failed"
fail("Factory creation from minimal environment failed"); );
}
assertThat("Token nor set correctly", getPrivate(factory, "token"), is(equalTo(VAULT_TOKEN))); assertThat("Token nor set correctly", getPrivate(factory, "token"), is(equalTo(VAULT_TOKEN)));
} }

View File

@ -18,7 +18,6 @@ package de.stklcode.jvault.connector.factory;
import de.stklcode.jvault.connector.HTTPVaultConnector; import de.stklcode.jvault.connector.HTTPVaultConnector;
import de.stklcode.jvault.connector.exception.TlsException; import de.stklcode.jvault.connector.exception.TlsException;
import de.stklcode.jvault.connector.exception.VaultConnectorException;
import de.stklcode.jvault.connector.test.EnvironmentMock; import de.stklcode.jvault.connector.test.EnvironmentMock;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
@ -30,7 +29,8 @@ import java.nio.file.NoSuchFileException;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* JUnit test for HTTP Vault connector factory * JUnit test for HTTP Vault connector factory
@ -54,14 +54,11 @@ class HTTPVaultConnectorFactoryTest {
/* Provide address only should be enough */ /* Provide address only should be enough */
setenv(VAULT_ADDR, null, null, null); setenv(VAULT_ADDR, null, null, null);
HTTPVaultConnectorFactory factory = null; HTTPVaultConnectorFactory factory = assertDoesNotThrow(
HTTPVaultConnector connector; () -> VaultConnectorFactory.httpFactory().fromEnv(),
try { "Factory creation from minimal environment failed"
factory = VaultConnectorFactory.httpFactory().fromEnv(); );
} catch (VaultConnectorException e) { HTTPVaultConnector connector = factory.build();
fail("Factory creation from minimal environment failed");
}
connector = factory.build();
assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/"))); assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/")));
assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue())); assertThat("Trusted CA cert set when no cert provided", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue()));
@ -70,11 +67,10 @@ class HTTPVaultConnectorFactoryTest {
/* Provide address and number of retries */ /* Provide address and number of retries */
setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null); setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null);
try { factory = assertDoesNotThrow(
factory = VaultConnectorFactory.httpFactory().fromEnv(); () -> VaultConnectorFactory.httpFactory().fromEnv(),
} catch (VaultConnectorException e) { "Factory creation from environment failed"
fail("Factory creation from environment failed"); );
}
connector = factory.build(); connector = factory.build();
assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/"))); assertThat("URL nor set correctly", getRequestHelperPrivate(connector, "baseURL"), is(equalTo(VAULT_ADDR + "/v1/")));
@ -85,23 +81,21 @@ class HTTPVaultConnectorFactoryTest {
String VAULT_CACERT = tempDir.toString() + "/doesnotexist"; String VAULT_CACERT = tempDir.toString() + "/doesnotexist";
setenv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null); setenv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null);
try { TlsException e = assertThrows(
VaultConnectorFactory.httpFactory().fromEnv(); TlsException.class,
fail("Creation with unknown cert path failed."); () -> VaultConnectorFactory.httpFactory().fromEnv(),
} catch (VaultConnectorException e) { "Creation with unknown cert path failed."
assertThat(e, is(instanceOf(TlsException.class))); );
assertThat(e.getCause(), is(instanceOf(NoSuchFileException.class))); assertThat(e.getCause(), is(instanceOf(NoSuchFileException.class)));
assertThat(((NoSuchFileException) e.getCause()).getFile(), is(VAULT_CACERT)); assertThat(((NoSuchFileException) e.getCause()).getFile(), is(VAULT_CACERT));
}
/* Automatic authentication */ /* Automatic authentication */
setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN); setenv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN);
try { factory = assertDoesNotThrow(
factory = VaultConnectorFactory.httpFactory().fromEnv(); () -> VaultConnectorFactory.httpFactory().fromEnv(),
} catch (VaultConnectorException e) { "Factory creation from minimal environment failed"
fail("Factory creation from minimal environment failed"); );
}
assertThat("Token nor set correctly", getPrivate(getPrivate(factory, "delegate"), "token"), is(equalTo(VAULT_TOKEN))); assertThat("Token nor set correctly", getPrivate(getPrivate(factory, "delegate"), "token"), is(equalTo(VAULT_TOKEN)));
} }

View File

@ -16,11 +16,9 @@
package de.stklcode.jvault.connector.model; package de.stklcode.jvault.connector.model;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -29,7 +27,7 @@ import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue;
@ -120,26 +118,17 @@ class AppRoleSecretTest {
/* A simple roundtrip first. All set fields should be present afterwards. */ /* A simple roundtrip first. All set fields should be present afterwards. */
AppRoleSecret secret = new AppRoleSecret(TEST_ID, TEST_META, TEST_CIDR); AppRoleSecret secret = new AppRoleSecret(TEST_ID, TEST_META, TEST_CIDR);
String secretJson = ""; String secretJson = assertDoesNotThrow(() -> mapper.writeValueAsString(secret), "Serialization failed");
try {
secretJson = mapper.writeValueAsString(secret);
} catch (JsonProcessingException e) {
e.printStackTrace();
fail("Serialization failed");
}
/* CIDR list is comma-separated when used as input, but List otherwise, hence convert string to list */ /* CIDR list is comma-separated when used as input, but List otherwise, hence convert string to list */
secretJson = commaSeparatedToList(secretJson); String secretJson2 = commaSeparatedToList(secretJson);
AppRoleSecret secret2; AppRoleSecret secret2 = assertDoesNotThrow(
try { () -> mapper.readValue(secretJson2, AppRoleSecret.class),
secret2 = mapper.readValue(secretJson, AppRoleSecret.class); "Deserialization failed"
);
assertThat(secret.getId(), is(secret2.getId())); assertThat(secret.getId(), is(secret2.getId()));
assertThat(secret.getMetadata(), is(secret2.getMetadata())); assertThat(secret.getMetadata(), is(secret2.getMetadata()));
assertThat(secret.getCidrList(), is(secret2.getCidrList())); assertThat(secret.getCidrList(), is(secret2.getCidrList()));
} catch (IOException e) {
e.printStackTrace();
fail("Deserialization failed");
}
/* Test fields, that should not be written to JSON */ /* Test fields, that should not be written to JSON */
setPrivateField(secret, "accessor", "TEST_ACCESSOR"); setPrivateField(secret, "accessor", "TEST_ACCESSOR");
@ -154,14 +143,11 @@ class AppRoleSecretTest {
assumeTrue(secret.getNumUses() == 678); assumeTrue(secret.getNumUses() == 678);
setPrivateField(secret, "ttl", 12345); setPrivateField(secret, "ttl", 12345);
assumeTrue(secret.getTtl() == 12345); assumeTrue(secret.getTtl() == 12345);
try { String secretJson3 = assertDoesNotThrow(() -> mapper.writeValueAsString(secret), "Serialization failed");
secretJson = mapper.writeValueAsString(secret); secret2 = assertDoesNotThrow(
} catch (JsonProcessingException e) { () -> mapper.readValue(commaSeparatedToList(secretJson3), AppRoleSecret.class),
e.printStackTrace(); "Deserialization failed"
fail("Serialization failed"); );
}
try {
secret2 = mapper.readValue(commaSeparatedToList(secretJson), AppRoleSecret.class);
assertThat(secret.getId(), is(secret2.getId())); assertThat(secret.getId(), is(secret2.getId()));
assertThat(secret.getMetadata(), is(secret2.getMetadata())); assertThat(secret.getMetadata(), is(secret2.getMetadata()));
assertThat(secret.getCidrList(), is(secret2.getCidrList())); assertThat(secret.getCidrList(), is(secret2.getCidrList()));
@ -171,28 +157,19 @@ class AppRoleSecretTest {
assertThat(secret2.getLastUpdatedTime(), is(nullValue())); assertThat(secret2.getLastUpdatedTime(), is(nullValue()));
assertThat(secret2.getNumUses(), is(nullValue())); assertThat(secret2.getNumUses(), is(nullValue()));
assertThat(secret2.getTtl(), is(nullValue())); assertThat(secret2.getTtl(), is(nullValue()));
} catch (IOException e) {
e.printStackTrace();
fail("Deserialization failed");
}
/* Those fields should be deserialized from JSON though */ /* Those fields should be deserialized from JSON though */
secretJson = "{\"secret_id\":\"abc123\",\"metadata\":{\"number\":1337,\"foo\":\"bar\"}," + String secretJson4 = "{\"secret_id\":\"abc123\",\"metadata\":{\"number\":1337,\"foo\":\"bar\"}," +
"\"cidr_list\":[\"203.0.113.0/24\",\"198.51.100.0/24\"],\"secret_id_accessor\":\"TEST_ACCESSOR\"," + "\"cidr_list\":[\"203.0.113.0/24\",\"198.51.100.0/24\"],\"secret_id_accessor\":\"TEST_ACCESSOR\"," +
"\"creation_time\":\"TEST_CREATION\",\"expiration_time\":\"TEST_EXPIRATION\"," + "\"creation_time\":\"TEST_CREATION\",\"expiration_time\":\"TEST_EXPIRATION\"," +
"\"last_updated_time\":\"TEST_LASTUPDATE\",\"secret_id_num_uses\":678,\"secret_id_ttl\":12345}"; "\"last_updated_time\":\"TEST_LASTUPDATE\",\"secret_id_num_uses\":678,\"secret_id_ttl\":12345}";
try { secret2 = assertDoesNotThrow(() -> mapper.readValue(secretJson4, AppRoleSecret.class), "Deserialization failed");
secret2 = mapper.readValue(secretJson, AppRoleSecret.class);
assertThat(secret2.getAccessor(), is("TEST_ACCESSOR")); assertThat(secret2.getAccessor(), is("TEST_ACCESSOR"));
assertThat(secret2.getCreationTime(), is("TEST_CREATION")); assertThat(secret2.getCreationTime(), is("TEST_CREATION"));
assertThat(secret2.getExpirationTime(), is("TEST_EXPIRATION")); assertThat(secret2.getExpirationTime(), is("TEST_EXPIRATION"));
assertThat(secret2.getLastUpdatedTime(), is("TEST_LASTUPDATE")); assertThat(secret2.getLastUpdatedTime(), is("TEST_LASTUPDATE"));
assertThat(secret2.getNumUses(), is(678)); assertThat(secret2.getNumUses(), is(678));
assertThat(secret2.getTtl(), is(12345)); assertThat(secret2.getTtl(), is(12345));
} catch (IOException e) {
e.printStackTrace();
fail("Deserialization failed");
}
} }

View File

@ -21,13 +21,13 @@ import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.model.AppRole; import de.stklcode.jvault.connector.model.AppRole;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* JUnit Test for {@link AppRoleResponse} model. * JUnit Test for {@link AppRoleResponse} model.
@ -81,12 +81,11 @@ class AppRoleResponseTest {
assertThat("Initial data should be empty", res.getRole(), is(nullValue())); assertThat("Initial data should be empty", res.getRole(), is(nullValue()));
// Parsing invalid auth data map should fail. // Parsing invalid auth data map should fail.
try { assertThrows(
res.setData(INVALID_DATA); InvalidResponseException.class,
fail("Parsing invalid data succeeded"); () -> res.setData(INVALID_DATA),
} catch (Exception e) { "Parsing invalid data succeeded"
assertThat(e, is(instanceOf(InvalidResponseException.class))); );
}
} }
/** /**
@ -94,8 +93,10 @@ class AppRoleResponseTest {
*/ */
@Test @Test
void jsonRoundtrip() { void jsonRoundtrip() {
try { AppRoleResponse res = assertDoesNotThrow(
AppRoleResponse res = new ObjectMapper().readValue(RES_JSON, AppRoleResponse.class); () -> new ObjectMapper().readValue(RES_JSON, AppRoleResponse.class),
"AuthResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue())); assertThat("Parsed response is NULL", res, is(notNullValue()));
// Extract role data. // Extract role data.
AppRole role = res.getRole(); AppRole role = res.getRole();
@ -113,8 +114,5 @@ class AppRoleResponseTest {
assertThat("Incorrect role bind secret ID flag", role.getBindSecretId(), is(ROLE_BIND_SECRET)); assertThat("Incorrect role bind secret ID flag", role.getBindSecretId(), is(ROLE_BIND_SECRET));
assertThat("Incorrect bound CIDR list", role.getTokenBoundCidrs(), is(nullValue())); assertThat("Incorrect bound CIDR list", role.getTokenBoundCidrs(), is(nullValue()));
assertThat("Incorrect bound CIDR list string", role.getTokenBoundCidrsString(), is(emptyString())); assertThat("Incorrect bound CIDR list string", role.getTokenBoundCidrsString(), is(emptyString()));
} catch (IOException e) {
fail("AuthResponse deserialization failed: " + e.getMessage());
}
} }
} }

View File

@ -22,13 +22,13 @@ import de.stklcode.jvault.connector.model.AuthBackend;
import de.stklcode.jvault.connector.model.response.embedded.AuthMethod; import de.stklcode.jvault.connector.model.response.embedded.AuthMethod;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* JUnit Test for {@link AuthMethodsResponse} model. * JUnit Test for {@link AuthMethodsResponse} model.
@ -79,12 +79,11 @@ class AuthMethodsResponseTest {
assertThat("Initial method map should be empty", res.getSupportedMethods(), is(anEmptyMap())); assertThat("Initial method map should be empty", res.getSupportedMethods(), is(anEmptyMap()));
// Parsing invalid data map should fail. // Parsing invalid data map should fail.
try { assertThrows(
res.setData(INVALID_DATA); InvalidResponseException.class,
fail("Parsing invalid data succeeded"); () -> res.setData(INVALID_DATA),
} catch (Exception e) { "Parsing invalid data succeeded"
assertThat(e, is(instanceOf(InvalidResponseException.class))); );
}
} }
/** /**
@ -92,8 +91,10 @@ class AuthMethodsResponseTest {
*/ */
@Test @Test
void jsonRoundtrip() { void jsonRoundtrip() {
try { AuthMethodsResponse res = assertDoesNotThrow(
AuthMethodsResponse res = new ObjectMapper().readValue(RES_JSON, AuthMethodsResponse.class); () -> new ObjectMapper().readValue(RES_JSON, AuthMethodsResponse.class),
"AuthResponse deserialization failed"
);
assertThat("Parsed response is NULL", res, is(notNullValue())); assertThat("Parsed response is NULL", res, is(notNullValue()));
// Extract auth data. // Extract auth data.
Map<String, AuthMethod> supported = res.getSupportedMethods(); Map<String, AuthMethod> supported = res.getSupportedMethods();
@ -117,9 +118,6 @@ class AuthMethodsResponseTest {
assertThat("Unexpected config size for Token", method.getConfig().keySet(), hasSize(2)); assertThat("Unexpected config size for Token", method.getConfig().keySet(), hasSize(2));
assertThat("Incorrect lease TTL config", method.getConfig().get("default_lease_ttl"), is(TK_LEASE_TTL.toString())); assertThat("Incorrect lease TTL config", method.getConfig().get("default_lease_ttl"), is(TK_LEASE_TTL.toString()));
assertThat("Incorrect max lease TTL config", method.getConfig().get("max_lease_ttl"), is(TK_MAX_LEASE_TTL.toString())); assertThat("Incorrect max lease TTL config", method.getConfig().get("max_lease_ttl"), is(TK_MAX_LEASE_TTL.toString()));
} catch (IOException e) {
fail("AuthResponse deserialization failed: " + e.getMessage());
}
} }
private static class Dummy { private static class Dummy {

View File

@ -21,13 +21,13 @@ import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.model.response.embedded.AuthData; import de.stklcode.jvault.connector.model.response.embedded.AuthData;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* JUnit Test for {@link AuthResponse} model. * JUnit Test for {@link AuthResponse} model.
@ -87,12 +87,11 @@ class AuthResponseTest {
assertThat("Initial data should be empty", res.getData(), is(nullValue())); assertThat("Initial data should be empty", res.getData(), is(nullValue()));
// Parsing invalid auth data map should fail. // Parsing invalid auth data map should fail.
try { assertThrows(
res.setAuth(INVALID_AUTH_DATA); InvalidResponseException.class,
fail("Parsing invalid auth data succeeded"); () -> res.setAuth(INVALID_AUTH_DATA),
} catch (Exception e) { "Parsing invalid auth data succeeded"
assertThat(e, is(instanceOf(InvalidResponseException.class))); );
}
// Data method should be agnostic. // Data method should be agnostic.
res.setData(INVALID_AUTH_DATA); res.setData(INVALID_AUTH_DATA);
@ -104,8 +103,10 @@ class AuthResponseTest {
*/ */
@Test @Test
void jsonRoundtrip() { void jsonRoundtrip() {
try { AuthResponse res = assertDoesNotThrow(
AuthResponse res = new ObjectMapper().readValue(RES_JSON, AuthResponse.class); () -> new ObjectMapper().readValue(RES_JSON, AuthResponse.class),
"AuthResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue())); assertThat("Parsed response is NULL", res, is(notNullValue()));
// Extract auth data. // Extract auth data.
AuthData data = res.getAuth(); AuthData data = res.getAuth();
@ -123,9 +124,5 @@ class AuthResponseTest {
assertThat("Incorrect token policies", data.getTokenPolicies(), containsInRelativeOrder(AUTH_POLICY_2, AUTH_POLICY_1)); assertThat("Incorrect token policies", data.getTokenPolicies(), containsInRelativeOrder(AUTH_POLICY_2, AUTH_POLICY_1));
assertThat("Incorrect auth metadata size", data.getMetadata().entrySet(), hasSize(1)); assertThat("Incorrect auth metadata size", data.getMetadata().entrySet(), hasSize(1));
assertThat("Incorrect auth metadata", data.getMetadata().get(AUTH_META_KEY), is(AUTH_META_VALUE)); assertThat("Incorrect auth metadata", data.getMetadata().get(AUTH_META_KEY), is(AUTH_META_VALUE));
} catch (IOException e) {
fail("AuthResponse deserialization failed: " + e.getMessage());
}
} }
} }

View File

@ -19,12 +19,10 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* JUnit Test for {@link AuthResponse} model. * JUnit Test for {@link AuthResponse} model.
@ -56,13 +54,16 @@ class HealthResponseTest {
" \"replication_dr_mode\": \"" + REPL_DR_MODE + "\",\n" + " \"replication_dr_mode\": \"" + REPL_DR_MODE + "\",\n" +
" \"performance_standby\": " + PERF_STANDBY + "\n" + " \"performance_standby\": " + PERF_STANDBY + "\n" +
"}"; "}";
/** /**
* Test creation from JSON value as returned by Vault (JSON example copied from Vault documentation). * Test creation from JSON value as returned by Vault (JSON example copied from Vault documentation).
*/ */
@Test @Test
void jsonRoundtrip() { void jsonRoundtrip() {
try { HealthResponse res = assertDoesNotThrow(
HealthResponse res = new ObjectMapper().readValue(RES_JSON, HealthResponse.class); () -> new ObjectMapper().readValue(RES_JSON, HealthResponse.class),
"Health deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue())); assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Incorrect cluster ID", res.getClusterID(), is(CLUSTER_ID)); assertThat("Incorrect cluster ID", res.getClusterID(), is(CLUSTER_ID));
assertThat("Incorrect cluster name", res.getClusterName(), is(CLUSTER_NAME)); assertThat("Incorrect cluster name", res.getClusterName(), is(CLUSTER_NAME));
@ -74,8 +75,5 @@ class HealthResponseTest {
assertThat("Incorrect performance standby state", res.isPerformanceStandby(), is(PERF_STANDBY)); assertThat("Incorrect performance standby state", res.isPerformanceStandby(), is(PERF_STANDBY));
assertThat("Incorrect replication perf mode", res.getReplicationPerfMode(), is(REPL_PERF_MODE)); assertThat("Incorrect replication perf mode", res.getReplicationPerfMode(), is(REPL_PERF_MODE));
assertThat("Incorrect replication DR mode", res.getReplicationDrMode(), is(REPL_DR_MODE)); assertThat("Incorrect replication DR mode", res.getReplicationDrMode(), is(REPL_DR_MODE));
} catch (IOException e) {
fail("Health deserialization failed: " + e.getMessage());
}
} }
} }

View File

@ -17,16 +17,12 @@
package de.stklcode.jvault.connector.model.response; package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.fail; import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* JUnit Test for {@link MetadataResponse} model. * JUnit Test for {@link MetadataResponse} model.
@ -74,8 +70,10 @@ class MetadataResponseTest {
*/ */
@Test @Test
void jsonRoundtrip() { void jsonRoundtrip() {
try { MetadataResponse res = assertDoesNotThrow(
MetadataResponse res = new ObjectMapper().readValue(META_JSON, MetadataResponse.class); () -> new ObjectMapper().readValue(META_JSON, MetadataResponse.class),
"MetadataResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue())); assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Parsed metadata is NULL", res.getMetadata(), is(notNullValue())); assertThat("Parsed metadata is NULL", res.getMetadata(), is(notNullValue()));
assertThat("Incorrect created time", res.getMetadata().getCreatedTimeString(), is(V1_TIME)); assertThat("Incorrect created time", res.getMetadata().getCreatedTimeString(), is(V1_TIME));
@ -92,9 +90,5 @@ class MetadataResponseTest {
assertThat("Incorrect version 2 created time", res.getMetadata().getVersions().get(2).getCreatedTimeString(), is(V2_TIME)); assertThat("Incorrect version 2 created time", res.getMetadata().getVersions().get(2).getCreatedTimeString(), is(V2_TIME));
assertThat("Parsing version created failed", res.getMetadata().getVersions().get(2).getCreatedTime(), is(notNullValue())); assertThat("Parsing version created failed", res.getMetadata().getVersions().get(2).getCreatedTime(), is(notNullValue()));
assertThat("Incorrect version 3 destroyed state", res.getMetadata().getVersions().get(3).isDestroyed(), is(false)); assertThat("Incorrect version 3 destroyed state", res.getMetadata().getVersions().get(3).isDestroyed(), is(false));
} catch (IOException e) {
fail("MetadataResponse deserialization failed: " + e.getMessage());
}
} }
} }

View File

@ -19,11 +19,9 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* JUnit Test for {@link SealResponse} model. * JUnit Test for {@link SealResponse} model.
@ -72,8 +70,10 @@ class SealResponseTest {
@Test @Test
void jsonRoundtripSealed() { void jsonRoundtripSealed() {
// First test sealed Vault's response. // First test sealed Vault's response.
try { SealResponse res = assertDoesNotThrow(
SealResponse res = new ObjectMapper().readValue(RES_SEALED, SealResponse.class); () -> new ObjectMapper().readValue(RES_SEALED, SealResponse.class),
"TokenResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue())); assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Incorrect seal type", res.getType(), is(TYPE)); assertThat("Incorrect seal type", res.getType(), is(TYPE));
assertThat("Incorrect seal status", res.isSealed(), is(true)); assertThat("Incorrect seal status", res.isSealed(), is(true));
@ -86,14 +86,13 @@ class SealResponseTest {
// And the fields, that should not be filled. // And the fields, that should not be filled.
assertThat("Cluster name should not be populated", res.getClusterName(), is(nullValue())); assertThat("Cluster name should not be populated", res.getClusterName(), is(nullValue()));
assertThat("Cluster ID should not be populated", res.getClusterId(), is(nullValue())); assertThat("Cluster ID should not be populated", res.getClusterId(), is(nullValue()));
} catch (IOException e) {
fail("TokenResponse deserialization failed: " + e.getMessage());
}
// Not test unsealed Vault's response. // Not test unsealed Vault's response.
try { res = assertDoesNotThrow(
SealResponse res = new ObjectMapper().readValue(RES_UNSEALED, SealResponse.class); () -> new ObjectMapper().readValue(RES_UNSEALED, SealResponse.class),
"TokenResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue())); assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Incorrect seal type", res.getType(), is(TYPE)); assertThat("Incorrect seal type", res.getType(), is(TYPE));
assertThat("Incorrect seal status", res.isSealed(), is(false)); assertThat("Incorrect seal status", res.isSealed(), is(false));
@ -105,8 +104,5 @@ class SealResponseTest {
assertThat("Incorrect version", res.getVersion(), is(VERSION)); assertThat("Incorrect version", res.getVersion(), is(VERSION));
assertThat("Incorrect cluster name", res.getClusterName(), is(CLUSTER_NAME)); assertThat("Incorrect cluster name", res.getClusterName(), is(CLUSTER_NAME));
assertThat("Incorrect cluster ID", res.getClusterId(), is(CLUSTER_ID)); assertThat("Incorrect cluster ID", res.getClusterId(), is(CLUSTER_ID));
} catch (IOException e) {
fail("TokenResponse deserialization failed: " + e.getMessage());
}
} }
} }

View File

@ -26,7 +26,7 @@ import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* JUnit Test for {@link SecretListResponse} model. * JUnit Test for {@link SecretListResponse} model.
@ -56,14 +56,13 @@ class SecretListResponseTest {
assertThat("Keys should be null without initialization", res.getKeys(), is(nullValue())); assertThat("Keys should be null without initialization", res.getKeys(), is(nullValue()));
// Provoke internal ClassCastException. // Provoke internal ClassCastException.
try {
Map<String, Object> invalidData = new HashMap<>(); Map<String, Object> invalidData = new HashMap<>();
invalidData.put("keys", "some string"); invalidData.put("keys", "some string");
res.setData(invalidData); assertThrows(
fail("Setting incorrect class succeeded"); InvalidResponseException.class,
} catch (Exception e) { () -> res.setData(invalidData),
assertThat("Unexpected exception type", e, instanceOf(InvalidResponseException.class)); "Setting incorrect class succeeded"
} );
// Fill correct data. // Fill correct data.
res.setData(DATA); res.setData(DATA);

View File

@ -20,14 +20,14 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.InvalidResponseException; import de.stklcode.jvault.connector.exception.InvalidResponseException;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* JUnit Test for {@link SecretResponse} model. * JUnit Test for {@link SecretResponse} model.
@ -137,19 +137,18 @@ class SecretResponseTest {
assertThat("Non-Null returned on unknown key", res.get(KEY_UNKNOWN), is(nullValue())); assertThat("Non-Null returned on unknown key", res.get(KEY_UNKNOWN), is(nullValue()));
// Try explicit JSON conversion. // Try explicit JSON conversion.
final List list = res.get(KEY_LIST, List.class); final List<?> list = res.get(KEY_LIST, List.class);
assertThat("JSON parsing of list failed", list, is(notNullValue())); assertThat("JSON parsing of list failed", list, is(notNullValue()));
assertThat("JSON parsing of list returned incorrect size", list.size(), is(2)); assertThat("JSON parsing of list returned incorrect size", list.size(), is(2));
assertThat("JSON parsing of list returned incorrect elements", (List<Object>)list, contains("first", "second")); assertThat("JSON parsing of list returned incorrect elements", list, contains("first", "second"));
assertThat("Non-Null returned on unknown key", res.get(KEY_UNKNOWN, Object.class), is(nullValue())); assertThat("Non-Null returned on unknown key", res.get(KEY_UNKNOWN, Object.class), is(nullValue()));
// Requesting invalid class should result in Exception. // Requesting invalid class should result in Exception.
try { assertThrows(
res.get(KEY_LIST, Double.class); InvalidResponseException.class,
fail("JSON parsing to incorrect type succeeded."); () -> res.get(KEY_LIST, Double.class),
} catch (Exception e) { "JSON parsing to incorrect type succeeded."
assertThat(e, is(instanceOf(InvalidResponseException.class))); );
}
} }
/** /**
@ -157,15 +156,17 @@ class SecretResponseTest {
*/ */
@Test @Test
void jsonRoundtrip() { void jsonRoundtrip() {
try { SecretResponse res = assertDoesNotThrow(
assertSecretData(new ObjectMapper().readValue(SECRET_JSON, SecretResponse.class)); () -> new ObjectMapper().readValue(SECRET_JSON, SecretResponse.class),
} catch (IOException e) { "SecretResponse deserialization failed."
fail("SecretResponse deserialization failed: " + e.getMessage()); );
} assertSecretData(res);
// KV v2 secret. // KV v2 secret.
try { res = assertDoesNotThrow(
SecretResponse res = new ObjectMapper().readValue(SECRET_JSON_V2, SecretResponse.class); () -> new ObjectMapper().readValue(SECRET_JSON_V2, SecretResponse.class),
"SecretResponse deserialization failed."
);
assertSecretData(res); assertSecretData(res);
assertThat("SecretResponse does not contain metadata", res.getMetadata(), is(notNullValue())); assertThat("SecretResponse does not contain metadata", res.getMetadata(), is(notNullValue()));
assertThat("Incorrect creation date string", res.getMetadata().getCreatedTimeString(), is(SECRET_META_CREATED)); assertThat("Incorrect creation date string", res.getMetadata().getCreatedTimeString(), is(SECRET_META_CREATED));
@ -174,13 +175,12 @@ class SecretResponseTest {
assertThat("Incorrect deletion date", res.getMetadata().getDeletionTime(), is(nullValue())); assertThat("Incorrect deletion date", res.getMetadata().getDeletionTime(), is(nullValue()));
assertThat("Secret destroyed when not expected", res.getMetadata().isDestroyed(), is(false)); assertThat("Secret destroyed when not expected", res.getMetadata().isDestroyed(), is(false));
assertThat("Incorrect secret version", res.getMetadata().getVersion(), is(1)); assertThat("Incorrect secret version", res.getMetadata().getVersion(), is(1));
} catch (IOException e) {
fail("SecretResponse deserialization failed: " + e.getMessage());
}
// Deleted KV v2 secret. // Deleted KV v2 secret.
try { res = assertDoesNotThrow(
SecretResponse res = new ObjectMapper().readValue(SECRET_JSON_V2_2, SecretResponse.class); () -> new ObjectMapper().readValue(SECRET_JSON_V2_2, SecretResponse.class),
"SecretResponse deserialization failed."
);
assertSecretData(res); assertSecretData(res);
assertThat("SecretResponse does not contain metadata", res.getMetadata(), is(notNullValue())); assertThat("SecretResponse does not contain metadata", res.getMetadata(), is(notNullValue()));
assertThat("Incorrect creation date string", res.getMetadata().getCreatedTimeString(), is(SECRET_META_CREATED)); assertThat("Incorrect creation date string", res.getMetadata().getCreatedTimeString(), is(SECRET_META_CREATED));
@ -189,9 +189,6 @@ class SecretResponseTest {
assertThat("Incorrect deletion date", res.getMetadata().getDeletionTime(), is(notNullValue())); assertThat("Incorrect deletion date", res.getMetadata().getDeletionTime(), is(notNullValue()));
assertThat("Secret destroyed when not expected", res.getMetadata().isDestroyed(), is(true)); assertThat("Secret destroyed when not expected", res.getMetadata().isDestroyed(), is(true));
assertThat("Incorrect secret version", res.getMetadata().getVersion(), is(2)); assertThat("Incorrect secret version", res.getMetadata().getVersion(), is(2));
} catch (IOException e) {
fail("SecretResponse deserialization failed: " + e.getMessage());
}
} }
private void assertSecretData(SecretResponse res) { private void assertSecretData(SecretResponse res) {

View File

@ -19,12 +19,10 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* JUnit Test for {@link SecretVersionResponse} model. * JUnit Test for {@link SecretVersionResponse} model.
@ -51,16 +49,15 @@ class SecretVersionResponseTest {
*/ */
@Test @Test
void jsonRoundtrip() { void jsonRoundtrip() {
try { SecretVersionResponse res = assertDoesNotThrow(
SecretVersionResponse res = new ObjectMapper().readValue(META_JSON, SecretVersionResponse.class); () -> new ObjectMapper().readValue(META_JSON, SecretVersionResponse.class),
"SecretVersionResponse deserialization failed"
);
assertThat("Parsed response is NULL", res, is(notNullValue())); assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Parsed metadata is NULL", res.getMetadata(), is(notNullValue())); assertThat("Parsed metadata is NULL", res.getMetadata(), is(notNullValue()));
assertThat("Incorrect created time", res.getMetadata().getCreatedTimeString(), is(CREATION_TIME)); assertThat("Incorrect created time", res.getMetadata().getCreatedTimeString(), is(CREATION_TIME));
assertThat("Incorrect deletion time", res.getMetadata().getDeletionTimeString(), is(DELETION_TIME)); assertThat("Incorrect deletion time", res.getMetadata().getDeletionTimeString(), is(DELETION_TIME));
assertThat("Incorrect destroyed state", res.getMetadata().isDestroyed(), is(false)); assertThat("Incorrect destroyed state", res.getMetadata().isDestroyed(), is(false));
assertThat("Incorrect version", res.getMetadata().getVersion(), is(VERSION)); assertThat("Incorrect version", res.getMetadata().getVersion(), is(VERSION));
} catch (IOException e) {
fail("SecretVersionResponse deserialization failed: " + e.getMessage());
}
} }
} }

View File

@ -21,14 +21,14 @@ import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.model.response.embedded.TokenData; import de.stklcode.jvault.connector.model.response.embedded.TokenData;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* JUnit Test for {@link TokenResponse} model. * JUnit Test for {@link TokenResponse} model.
@ -107,12 +107,11 @@ class TokenResponseTest {
assertThat("Initial data should be empty", res.getData(), is(nullValue())); assertThat("Initial data should be empty", res.getData(), is(nullValue()));
// Parsing invalid data map should fail. // Parsing invalid data map should fail.
try { assertThrows(
res.setData(INVALID_TOKEN_DATA); InvalidResponseException.class,
fail("Parsing invalid token data succeeded"); () -> res.setData(INVALID_TOKEN_DATA),
} catch (Exception e) { "Parsing invalid token data succeeded"
assertThat(e, is(instanceOf(InvalidResponseException.class))); );
}
} }
/** /**
@ -120,8 +119,10 @@ class TokenResponseTest {
*/ */
@Test @Test
void jsonRoundtrip() { void jsonRoundtrip() {
try { TokenResponse res = assertDoesNotThrow(
TokenResponse res = new ObjectMapper().readValue(RES_JSON, TokenResponse.class); () -> new ObjectMapper().readValue(RES_JSON, TokenResponse.class),
"TokenResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue())); assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Incorrect lease duration", res.getLeaseDuration(), is(RES_LEASE_DURATION)); assertThat("Incorrect lease duration", res.getLeaseDuration(), is(RES_LEASE_DURATION));
assertThat("Incorrect response renewable flag", res.isRenewable(), is(RES_RENEWABLE)); assertThat("Incorrect response renewable flag", res.isRenewable(), is(RES_RENEWABLE));
@ -150,8 +151,5 @@ class TokenResponseTest {
assertThat("Incorrect token renewable flag", data.isRenewable(), is(TOKEN_RENEWABLE)); assertThat("Incorrect token renewable flag", data.isRenewable(), is(TOKEN_RENEWABLE));
assertThat("Incorrect token TTL", data.getTtl(), is(RES_TTL)); assertThat("Incorrect token TTL", data.getTtl(), is(RES_TTL));
assertThat("Incorrect token type", data.getType(), is(TOKEN_TYPE)); assertThat("Incorrect token type", data.getType(), is(TOKEN_TYPE));
} catch (IOException e) {
fail("TokenResponse deserialization failed: " + e.getMessage());
}
} }
} }