use plain JUnit for test assertions
All checks were successful
continuous-integration/drone/push Build is passing

Hamcrest is a beautiful library, but we try to keep things simple here
and switch to plain JUnit 5 assertions for testing.
This commit is contained in:
Stefan Kalscheuer 2021-06-12 13:09:45 +02:00
parent 3c11fe912b
commit 74092bba9a
22 changed files with 712 additions and 778 deletions

View File

@ -117,12 +117,6 @@
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>

View File

@ -49,14 +49,14 @@ class HTTPVaultConnectorBuilderTest {
*/
@Test
void builderTest() throws Exception {
/* Minimal configuration */
// Minimal configuration.
HTTPVaultConnector connector = HTTPVaultConnector.builder().withHost("vault.example.com").build();
assertEquals("https://vault.example.com:8200/v1/", getRequestHelperPrivate(connector, "baseURL"), "URL not set correctly");
assertNull(getRequestHelperPrivate(connector, "trustedCaCert"), "Trusted CA cert set when no cert provided");
assertEquals(0, getRequestHelperPrivate(connector, "retries"), "Number of retries unexpectedly set");
/* Specify all options */
// Specify all options.
HTTPVaultConnectorBuilder builder = HTTPVaultConnector.builder()
.withHost("vault2.example.com")
.withoutTLS()
@ -72,7 +72,7 @@ class HTTPVaultConnectorBuilderTest {
assertEquals(5678, getRequestHelperPrivate(connector, "timeout"), "Number timeout value");
assertThrows(ConnectionException.class, builder::buildAndAuth, "Immediate authentication should throw exception without token");
/* Initialization from URL */
// Initialization from URL.
assertThrows(
URISyntaxException.class,
() -> HTTPVaultConnector.builder().withBaseURL("foo:/\\1nv4l1d_UrL"),
@ -84,7 +84,7 @@ class HTTPVaultConnectorBuilderTest {
);
assertEquals("https://vault3.example.com:5678/bar/", getRequestHelperPrivate(connector, "baseURL"), "URL not set correctly");
/* Port numbers */
// Port numbers.
assertThrows(IllegalArgumentException.class, () -> HTTPVaultConnector.builder().withPort(65536), "Too large port number should throw an exception");
assertThrows(IllegalArgumentException.class, () -> HTTPVaultConnector.builder().withPort(0), "Port number 0 should throw an exception");
builder = assertDoesNotThrow(() -> HTTPVaultConnector.builder().withPort(-1), "Port number -1 should not throw an exception");
@ -96,7 +96,7 @@ class HTTPVaultConnectorBuilderTest {
*/
@Test
void testFromEnv() throws Exception {
/* Provide address only should be enough */
// Provide address only should be enough.
withVaultEnv(VAULT_ADDR, null, null, null).execute(() -> {
HTTPVaultConnectorBuilder builder = assertDoesNotThrow(
() -> HTTPVaultConnector.builder().fromEnv(),
@ -111,7 +111,7 @@ class HTTPVaultConnectorBuilderTest {
return null;
});
/* Provide address and number of retries */
// Provide address and number of retries.
withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null).execute(() -> {
HTTPVaultConnectorBuilder builder = assertDoesNotThrow(
() -> HTTPVaultConnector.builder().fromEnv(),
@ -126,7 +126,7 @@ class HTTPVaultConnectorBuilderTest {
return null;
});
/* Provide CA certificate */
// Provide CA certificate.
String VAULT_CACERT = tempDir.toString() + "/doesnotexist";
withVaultEnv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null).execute(() -> {
TlsException e = assertThrows(
@ -140,7 +140,7 @@ class HTTPVaultConnectorBuilderTest {
return null;
});
/* Automatic authentication */
// Automatic authentication.
withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN).execute(() -> {
HTTPVaultConnectorBuilder builder = assertDoesNotThrow(
() -> HTTPVaultConnector.builder().fromEnv(),
@ -151,7 +151,7 @@ class HTTPVaultConnectorBuilderTest {
return null;
});
/* Invalid URL */
// Invalid URL.
withVaultEnv("This is not a valid URL!", null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN).execute(() -> {
assertThrows(
ConnectionException.class,

View File

@ -40,12 +40,7 @@ import java.util.Collections;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit test for HTTP Vault connector.
@ -86,9 +81,9 @@ class HTTPVaultConnectorOfflineTest {
connector::getHealth,
"Querying health status succeeded on invalid instance"
);
assertThat("Unexpected exception message", e.getMessage(), is("Invalid response code"));
assertThat("Unexpected status code in exception", ((InvalidResponseException) e).getStatusCode(), is(responseCode));
assertThat("Response message where none was expected", ((InvalidResponseException) e).getResponse(), is(nullValue()));
assertEquals("Invalid response code", e.getMessage(), "Unexpected exception message");
assertEquals(responseCode, ((InvalidResponseException) e).getStatusCode(), "Unexpected status code in exception");
assertNull(((InvalidResponseException) e).getResponse(), "Response message where none was expected");
// Simulate permission denied response.
mockHttpResponse(responseCode, "{\"errors\":[\"permission denied\"]}", "application/json");
@ -107,8 +102,8 @@ class HTTPVaultConnectorOfflineTest {
connector::getHealth,
"Querying health status succeeded on invalid instance"
);
assertThat("Unexpected exception message", e.getMessage(), is("Unable to connect to Vault server"));
assertThat("Unexpected cause", e.getCause(), instanceOf(IOException.class));
assertEquals("Unable to connect to Vault server", e.getMessage(), "Unexpected exception message");
assertTrue(e.getCause() instanceof IOException, "Unexpected cause");
// Now simulate a failing request that succeeds on second try.
connector = HTTPVaultConnector.builder(wireMock.url("/")).withNumberOfRetries(1).withTimeout(250).build();
@ -144,30 +139,30 @@ class HTTPVaultConnectorOfflineTest {
// Most basic constructor expects complete URL.
HTTPVaultConnector connector = HTTPVaultConnector.builder(url).build();
assertThat("Unexpected base URL", getRequestHelperPrivate(connector, "baseURL"), is(url));
assertEquals(url, getRequestHelperPrivate(connector, "baseURL"), "Unexpected base URL");
// Now override TLS usage.
connector = HTTPVaultConnector.builder().withHost(hostname).withoutTLS().build();
assertThat("Unexpected base URL with TLS disabled", getRequestHelperPrivate(connector, "baseURL"), is(expectedNoTls));
assertEquals(expectedNoTls, getRequestHelperPrivate(connector, "baseURL"), "Unexpected base URL with TLS disabled");
// Specify custom port.
connector = HTTPVaultConnector.builder().withHost(hostname).withTLS().withPort(port).build();
assertThat("Unexpected base URL with custom port", getRequestHelperPrivate(connector, "baseURL"), is(expectedCustomPort));
assertEquals(expectedCustomPort, getRequestHelperPrivate(connector, "baseURL"), "Unexpected base URL with custom port");
// Specify custom prefix.
connector = HTTPVaultConnector.builder().withHost(hostname).withTLS().withPort(port).withPrefix(prefix).build();
assertThat("Unexpected base URL with custom prefix", getRequestHelperPrivate(connector, "baseURL"), is(expectedCustomPrefix));
assertThat("Trusted CA cert set, but not specified", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue()));
assertEquals(expectedCustomPrefix, getRequestHelperPrivate(connector, "baseURL"), "Unexpected base URL with custom prefix");
assertNull(getRequestHelperPrivate(connector, "trustedCaCert"), "Trusted CA cert set, but not specified");
// Specify number of retries.
connector = HTTPVaultConnector.builder(url).withTrustedCA(trustedCaCert).withNumberOfRetries(retries).build();
assertThat("Number of retries not set correctly", getRequestHelperPrivate(connector, "retries"), is(retries));
assertEquals(retries, getRequestHelperPrivate(connector, "retries"), "Number of retries not set correctly");
// Test TLS version (#22).
assertThat("TLS version should be 1.2 if not specified", getRequestHelperPrivate(connector, "tlsVersion"), is("TLSv1.2"));
assertEquals("TLSv1.2", getRequestHelperPrivate(connector, "tlsVersion"), "TLS version should be 1.2 if not specified");
// Now override.
connector = HTTPVaultConnector.builder(url).withTrustedCA(trustedCaCert).withNumberOfRetries(retries).withTLS("TLSv1.1").build();
assertThat("Overridden TLS version 1.1 not correct", getRequestHelperPrivate(connector, "tlsVersion"), is("TLSv1.1"));
assertEquals("TLSv1.1", getRequestHelperPrivate(connector, "tlsVersion"), "Overridden TLS version 1.1 not correct");
}
/**
@ -185,7 +180,7 @@ class HTTPVaultConnectorOfflineTest {
connector::sealStatus,
"Querying seal status succeeded on invalid instance"
);
assertThat("Unexpected exception message", e.getMessage(), is("Unable to connect to Vault server"));
assertEquals("Unable to connect to Vault server", e.getMessage(), "Unexpected exception message");
}
/**
@ -203,7 +198,7 @@ class HTTPVaultConnectorOfflineTest {
connector::getHealth,
"Querying health status succeeded on invalid instance"
);
assertThat("Unexpected exception message", e.getMessage(), is("Unable to connect to Vault server"));
assertEquals("Unable to connect to Vault server", e.getMessage(), "Unexpected exception message");
}
/**
@ -237,7 +232,7 @@ class HTTPVaultConnectorOfflineTest {
private void assertParseError(Executable executable, String message) {
InvalidResponseException e = assertThrows(InvalidResponseException.class, executable, message);
assertThat("Unexpected exception message", e.getMessage(), is("Unable to parse response"));
assertEquals("Unable to parse response", e.getMessage(), "Unexpected exception message");
}
/**

View File

@ -18,10 +18,8 @@ package de.stklcode.jvault.connector.exception;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Common JUnit test for Exceptions extending {@link VaultConnectorException}.
@ -65,42 +63,39 @@ class VaultConnectorExceptionTest {
// Constructor with message and status code.
InvalidResponseException e = new InvalidResponseException(MSG, STATUS_CODE);
assertThat(e.getMessage(), is(MSG));
assertThat(e.getCause(), is(nullValue()));
assertThat(e.getStatusCode(), is(STATUS_CODE));
assertThat(e.getResponse(), is(nullValue()));
assertEquals(MSG, e.getMessage());
assertNull(e.getCause());
assertEquals(STATUS_CODE, e.getStatusCode());
assertNull(e.getResponse());
// Constructor with message, status code and cause.
e = new InvalidResponseException(MSG, STATUS_CODE, CAUSE);
assertThat(e.getMessage(), is(MSG));
assertThat(e.getCause(), is(CAUSE));
assertThat(e.getStatusCode(), is(STATUS_CODE));
assertThat(e.getResponse(), is(nullValue()));
assertEquals(MSG, e.getMessage());
assertEquals(CAUSE, e.getCause());
assertEquals(STATUS_CODE, e.getStatusCode());
assertNull(e.getResponse());
// Constructor with message, status code and response.
e = new InvalidResponseException(MSG, STATUS_CODE, RESPONSE);
assertThat(e.getMessage(), is(MSG));
assertThat(e.getCause(), is(nullValue()));
assertThat(e.getStatusCode(), is(STATUS_CODE));
assertThat(e.getResponse(), is(RESPONSE));
assertEquals(MSG, e.getMessage());
assertNull(e.getCause());
assertEquals(STATUS_CODE, e.getStatusCode());
assertEquals(RESPONSE, e.getResponse());
// Constructor with message, status code, response and cause.
e = new InvalidResponseException(MSG, STATUS_CODE, RESPONSE, CAUSE);
assertThat(e.getMessage(), is(MSG));
assertThat(e.getCause(), is(CAUSE));
assertThat(e.getStatusCode(), is(STATUS_CODE));
assertThat(e.getResponse(), is(RESPONSE));
assertEquals(MSG, e.getMessage());
assertEquals(CAUSE, e.getCause());
assertEquals(STATUS_CODE, e.getStatusCode());
assertEquals(RESPONSE, e.getResponse());
}
@Test
void permissionDeniedExceptionTest() {
// Default message overwritten.
PermissionDeniedException e = new PermissionDeniedException();
assertThat(e, is(instanceOf(VaultConnectorException.class)));
assertThat(e, is(instanceOf(Exception.class)));
assertThat(e, is(instanceOf(Throwable.class)));
assertThat(e.getMessage(), is("Permission denied"));
assertThat(e.getCause(), is(nullValue()));
assertEquals("Permission denied", e.getMessage());
assertNull(e.getCause());
assertMsgConstructor(new PermissionDeniedException(MSG));
assertCauseConstructor(new PermissionDeniedException(CAUSE));
@ -121,11 +116,8 @@ class VaultConnectorExceptionTest {
* @param e the exception
*/
private void assertEmptyConstructor(VaultConnectorException e) {
assertThat(e, is(instanceOf(VaultConnectorException.class)));
assertThat(e, is(instanceOf(Exception.class)));
assertThat(e, is(instanceOf(Throwable.class)));
assertThat(e.getMessage(), is(nullValue()));
assertThat(e.getCause(), is(nullValue()));
assertNull(e.getMessage());
assertNull(e.getCause());
}
/**
@ -134,8 +126,8 @@ class VaultConnectorExceptionTest {
* @param e the exception
*/
private void assertMsgConstructor(VaultConnectorException e) {
assertThat(e.getMessage(), is(MSG));
assertThat(e.getCause(), is(nullValue()));
assertEquals(MSG, e.getMessage());
assertNull(e.getCause());
}
/**
@ -144,8 +136,8 @@ class VaultConnectorExceptionTest {
* @param e the exception
*/
private void assertCauseConstructor(VaultConnectorException e) {
assertThat(e.getMessage(), is(CAUSE.toString()));
assertThat(e.getCause(), is(CAUSE));
assertEquals(CAUSE.toString(), e.getMessage());
assertEquals(CAUSE, e.getCause());
}
/**
@ -154,7 +146,7 @@ class VaultConnectorExceptionTest {
* @param e the exception
*/
private void assertMsgCauseConstructor(VaultConnectorException e) {
assertThat(e.getMessage(), is(MSG));
assertThat(e.getCause(), is(CAUSE));
assertEquals(MSG, e.getMessage());
assertEquals(CAUSE, e.getCause());
}
}

View File

@ -25,9 +25,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
@ -38,7 +36,6 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue;
* @since 0.5.0
*/
class AppRoleSecretTest {
private static final String TEST_ID = "abc123";
private static final Map<String, Object> TEST_META = new HashMap<>();
private static final List<String> TEST_CIDR = Arrays.asList("203.0.113.0/24", "198.51.100.0/24");
@ -53,44 +50,44 @@ class AppRoleSecretTest {
*/
@Test
void constructorTest() {
/* Empty constructor */
// Empty constructor.
AppRoleSecret secret = new AppRoleSecret();
assertThat(secret.getId(), is(nullValue()));
assertThat(secret.getAccessor(), is(nullValue()));
assertThat(secret.getMetadata(), is(nullValue()));
assertThat(secret.getCidrList(), is(nullValue()));
assertThat(secret.getCidrListString(), is(emptyString()));
assertThat(secret.getCreationTime(), is(nullValue()));
assertThat(secret.getExpirationTime(), is(nullValue()));
assertThat(secret.getLastUpdatedTime(), is(nullValue()));
assertThat(secret.getNumUses(), is(nullValue()));
assertThat(secret.getTtl(), is(nullValue()));
assertNull(secret.getId());
assertNull(secret.getAccessor());
assertNull(secret.getMetadata());
assertNull(secret.getCidrList());
assertEquals("", secret.getCidrListString());
assertNull(secret.getCreationTime());
assertNull(secret.getExpirationTime());
assertNull(secret.getLastUpdatedTime());
assertNull(secret.getNumUses());
assertNull(secret.getTtl());
/* Constructor with ID */
// Constructor with ID.
secret = new AppRoleSecret(TEST_ID);
assertThat(secret.getId(), is(TEST_ID));
assertThat(secret.getAccessor(), is(nullValue()));
assertThat(secret.getMetadata(), is(nullValue()));
assertThat(secret.getCidrList(), is(nullValue()));
assertThat(secret.getCidrListString(), is(emptyString()));
assertThat(secret.getCreationTime(), is(nullValue()));
assertThat(secret.getExpirationTime(), is(nullValue()));
assertThat(secret.getLastUpdatedTime(), is(nullValue()));
assertThat(secret.getNumUses(), is(nullValue()));
assertThat(secret.getTtl(), is(nullValue()));
assertEquals(TEST_ID, secret.getId());
assertNull(secret.getAccessor());
assertNull(secret.getMetadata());
assertNull(secret.getCidrList());
assertEquals("", secret.getCidrListString());
assertNull(secret.getCreationTime());
assertNull(secret.getExpirationTime());
assertNull(secret.getLastUpdatedTime());
assertNull(secret.getNumUses());
assertNull(secret.getTtl());
/* Constructor with Metadata and CIDR bindings */
// Constructor with Metadata and CIDR bindings.
secret = new AppRoleSecret(TEST_ID, TEST_META, TEST_CIDR);
assertThat(secret.getId(), is(TEST_ID));
assertThat(secret.getAccessor(), is(nullValue()));
assertThat(secret.getMetadata(), is(TEST_META));
assertThat(secret.getCidrList(), is(TEST_CIDR));
assertThat(secret.getCidrListString(), is(String.join(",", TEST_CIDR)));
assertThat(secret.getCreationTime(), is(nullValue()));
assertThat(secret.getExpirationTime(), is(nullValue()));
assertThat(secret.getLastUpdatedTime(), is(nullValue()));
assertThat(secret.getNumUses(), is(nullValue()));
assertThat(secret.getTtl(), is(nullValue()));
assertEquals(TEST_ID, secret.getId());
assertNull(secret.getAccessor());
assertEquals(TEST_META, secret.getMetadata());
assertEquals(TEST_CIDR, secret.getCidrList());
assertEquals(String.join(",", TEST_CIDR), secret.getCidrListString());
assertNull(secret.getCreationTime());
assertNull(secret.getExpirationTime());
assertNull(secret.getLastUpdatedTime());
assertNull(secret.getNumUses());
assertNull(secret.getTtl());
}
/**
@ -99,14 +96,14 @@ class AppRoleSecretTest {
@Test
void setterTest() {
AppRoleSecret secret = new AppRoleSecret(TEST_ID);
assertThat(secret.getCidrList(), is(nullValue()));
assertThat(secret.getCidrListString(), is(emptyString()));
assertNull(secret.getCidrList());
assertEquals("", secret.getCidrListString());
secret.setCidrList(TEST_CIDR);
assertThat(secret.getCidrList(), is(TEST_CIDR));
assertThat(secret.getCidrListString(), is(String.join(",", TEST_CIDR)));
assertEquals(TEST_CIDR, secret.getCidrList());
assertEquals(String.join(",", TEST_CIDR), secret.getCidrListString());
secret.setCidrList(null);
assertThat(secret.getCidrList(), is(nullValue()));
assertThat(secret.getCidrListString(), is(emptyString()));
assertNull(secret.getCidrList());
assertEquals("", secret.getCidrListString());
}
/**
@ -116,21 +113,21 @@ class AppRoleSecretTest {
void jsonTest() throws NoSuchFieldException, IllegalAccessException {
ObjectMapper mapper = new ObjectMapper();
/* 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);
String secretJson = assertDoesNotThrow(() -> mapper.writeValueAsString(secret), "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.
String secretJson2 = commaSeparatedToList(secretJson);
AppRoleSecret secret2 = assertDoesNotThrow(
() -> mapper.readValue(secretJson2, AppRoleSecret.class),
"Deserialization failed"
);
assertThat(secret.getId(), is(secret2.getId()));
assertThat(secret.getMetadata(), is(secret2.getMetadata()));
assertThat(secret.getCidrList(), is(secret2.getCidrList()));
assertEquals(secret2.getId(), secret.getId());
assertEquals(secret2.getMetadata(), secret.getMetadata());
assertEquals(secret2.getCidrList(), secret.getCidrList());
/* Test fields, that should not be written to JSON */
// Test fields, that should not be written to JSON.
setPrivateField(secret, "accessor", "TEST_ACCESSOR");
assumeTrue("TEST_ACCESSOR".equals(secret.getAccessor()));
setPrivateField(secret, "creationTime", "TEST_CREATION");
@ -148,28 +145,28 @@ class AppRoleSecretTest {
() -> mapper.readValue(commaSeparatedToList(secretJson3), AppRoleSecret.class),
"Deserialization failed"
);
assertThat(secret.getId(), is(secret2.getId()));
assertThat(secret.getMetadata(), is(secret2.getMetadata()));
assertThat(secret.getCidrList(), is(secret2.getCidrList()));
assertThat(secret2.getAccessor(), is(nullValue()));
assertThat(secret2.getCreationTime(), is(nullValue()));
assertThat(secret2.getExpirationTime(), is(nullValue()));
assertThat(secret2.getLastUpdatedTime(), is(nullValue()));
assertThat(secret2.getNumUses(), is(nullValue()));
assertThat(secret2.getTtl(), is(nullValue()));
assertEquals(secret2.getId(), secret.getId());
assertEquals(secret2.getMetadata(), secret.getMetadata());
assertEquals(secret2.getCidrList(), secret.getCidrList());
assertNull(secret2.getAccessor());
assertNull(secret2.getCreationTime());
assertNull(secret2.getExpirationTime());
assertNull(secret2.getLastUpdatedTime());
assertNull(secret2.getNumUses());
assertNull(secret2.getTtl());
/* Those fields should be deserialized from JSON though */
// Those fields should be deserialized from JSON though.
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\"," +
"\"creation_time\":\"TEST_CREATION\",\"expiration_time\":\"TEST_EXPIRATION\"," +
"\"last_updated_time\":\"TEST_LASTUPDATE\",\"secret_id_num_uses\":678,\"secret_id_ttl\":12345}";
secret2 = assertDoesNotThrow(() -> mapper.readValue(secretJson4, AppRoleSecret.class), "Deserialization failed");
assertThat(secret2.getAccessor(), is("TEST_ACCESSOR"));
assertThat(secret2.getCreationTime(), is("TEST_CREATION"));
assertThat(secret2.getExpirationTime(), is("TEST_EXPIRATION"));
assertThat(secret2.getLastUpdatedTime(), is("TEST_LASTUPDATE"));
assertThat(secret2.getNumUses(), is(678));
assertThat(secret2.getTtl(), is(12345));
assertEquals("TEST_ACCESSOR", secret2.getAccessor());
assertEquals("TEST_CREATION", secret2.getCreationTime());
assertEquals("TEST_EXPIRATION", secret2.getExpirationTime());
assertEquals("TEST_LASTUPDATE", secret2.getLastUpdatedTime());
assertEquals(678, secret2.getNumUses());
assertEquals(12345, secret2.getTtl());
}

View File

@ -24,8 +24,7 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link AppRole} and {@link AppRole.Builder}.
@ -69,24 +68,24 @@ class AppRoleTest {
@Test
void buildDefaultTest() throws JsonProcessingException {
AppRole role = AppRole.builder(NAME).build();
assertThat(role.getId(), is(nullValue()));
assertThat(role.getBindSecretId(), is(nullValue()));
assertThat(role.getSecretIdBoundCidrs(), is(nullValue()));
assertThat(role.getTokenPolicies(), is(nullValue()));
assertThat(role.getSecretIdNumUses(), is(nullValue()));
assertThat(role.getSecretIdTtl(), is(nullValue()));
assertThat(role.getEnableLocalSecretIds(), is(nullValue()));
assertThat(role.getTokenTtl(), is(nullValue()));
assertThat(role.getTokenMaxTtl(), is(nullValue()));
assertThat(role.getTokenBoundCidrs(), is(nullValue()));
assertThat(role.getTokenExplicitMaxTtl(), is(nullValue()));
assertThat(role.getTokenNoDefaultPolicy(), is(nullValue()));
assertThat(role.getTokenNumUses(), is(nullValue()));
assertThat(role.getTokenPeriod(), is(nullValue()));
assertThat(role.getTokenType(), is(nullValue()));
assertNull(role.getId());
assertNull(role.getBindSecretId());
assertNull(role.getSecretIdBoundCidrs());
assertNull(role.getTokenPolicies());
assertNull(role.getSecretIdNumUses());
assertNull(role.getSecretIdTtl());
assertNull(role.getEnableLocalSecretIds());
assertNull(role.getTokenTtl());
assertNull(role.getTokenMaxTtl());
assertNull(role.getTokenBoundCidrs());
assertNull(role.getTokenExplicitMaxTtl());
assertNull(role.getTokenNoDefaultPolicy());
assertNull(role.getTokenNumUses());
assertNull(role.getTokenPeriod());
assertNull(role.getTokenType());
/* optional fields should be ignored, so JSON string should only contain role_name */
assertThat(new ObjectMapper().writeValueAsString(role), is(JSON_MIN));
// Optional fields should be ignored, so JSON string should only contain role_name.
assertEquals(JSON_MIN, new ObjectMapper().writeValueAsString(role));
}
/**
@ -111,25 +110,25 @@ class AppRoleTest {
.withTokenPeriod(TOKEN_PERIOD)
.withTokenType(TOKEN_TYPE)
.build();
assertThat(role.getName(), is(NAME));
assertThat(role.getId(), is(ID));
assertThat(role.getBindSecretId(), is(BIND_SECRET_ID));
assertThat(role.getSecretIdBoundCidrs(), is(BOUND_CIDR_LIST));
assertThat(role.getTokenPolicies(), is(POLICIES));
assertThat(role.getSecretIdNumUses(), is(SECRET_ID_NUM_USES));
assertThat(role.getSecretIdTtl(), is(SECRET_ID_TTL));
assertThat(role.getEnableLocalSecretIds(), is(ENABLE_LOCAL_SECRET_IDS));
assertThat(role.getTokenTtl(), is(TOKEN_TTL));
assertThat(role.getTokenMaxTtl(), is(TOKEN_MAX_TTL));
assertThat(role.getTokenBoundCidrs(), is(BOUND_CIDR_LIST));
assertThat(role.getTokenExplicitMaxTtl(), is(TOKEN_EXPLICIT_MAX_TTL));
assertThat(role.getTokenNoDefaultPolicy(), is(TOKEN_NO_DEFAULT_POLICY));
assertThat(role.getTokenNumUses(), is(TOKEN_NUM_USES));
assertThat(role.getTokenPeriod(), is(TOKEN_PERIOD));
assertThat(role.getTokenType(), is(TOKEN_TYPE.value()));
assertEquals(NAME, role.getName());
assertEquals(ID, role.getId());
assertEquals(BIND_SECRET_ID, role.getBindSecretId());
assertEquals(BOUND_CIDR_LIST, role.getSecretIdBoundCidrs());
assertEquals(POLICIES, role.getTokenPolicies());
assertEquals(SECRET_ID_NUM_USES, role.getSecretIdNumUses());
assertEquals(SECRET_ID_TTL, role.getSecretIdTtl());
assertEquals(ENABLE_LOCAL_SECRET_IDS, role.getEnableLocalSecretIds());
assertEquals(TOKEN_TTL, role.getTokenTtl());
assertEquals(TOKEN_MAX_TTL, role.getTokenMaxTtl());
assertEquals(BOUND_CIDR_LIST, role.getTokenBoundCidrs());
assertEquals(TOKEN_EXPLICIT_MAX_TTL, role.getTokenExplicitMaxTtl());
assertEquals(TOKEN_NO_DEFAULT_POLICY, role.getTokenNoDefaultPolicy());
assertEquals(TOKEN_NUM_USES, role.getTokenNumUses());
assertEquals(TOKEN_PERIOD, role.getTokenPeriod());
assertEquals(TOKEN_TYPE.value(), role.getTokenType());
/* Verify that all parameters are included in JSON string */
assertThat(new ObjectMapper().writeValueAsString(role), is(JSON_FULL));
// Verify that all parameters are included in JSON string.
assertEquals(JSON_FULL, new ObjectMapper().writeValueAsString(role));
}
/**
@ -137,40 +136,40 @@ class AppRoleTest {
*/
@Test
void convenienceMethodsTest() {
/* bind_secret_id */
// bind_secret_id.
AppRole role = AppRole.builder(NAME).build();
assertThat(role.getBindSecretId(), is(nullValue()));
assertNull(role.getBindSecretId());
role = AppRole.builder(NAME).withBindSecretID().build();
assertThat(role.getBindSecretId(), is(true));
assertEquals(true, role.getBindSecretId());
role = AppRole.builder(NAME).withoutBindSecretID().build();
assertThat(role.getBindSecretId(), is(false));
assertEquals(false, role.getBindSecretId());
/* Add single CIDR subnet */
// Add single CIDR subnet.
role = AppRole.builder(NAME).withSecretBoundCidr(CIDR_2).withTokenBoundCidr(CIDR_2).build();
assertThat(role.getSecretIdBoundCidrs(), hasSize(1));
assertThat(role.getSecretIdBoundCidrs(), contains(CIDR_2));
assertThat(role.getTokenBoundCidrs(), hasSize(1));
assertThat(role.getTokenBoundCidrs(), contains(CIDR_2));
assertEquals(1, role.getSecretIdBoundCidrs().size());
assertEquals(CIDR_2, role.getSecretIdBoundCidrs().get(0));
assertEquals(1, role.getTokenBoundCidrs().size());
assertEquals(CIDR_2, role.getTokenBoundCidrs().get(0));
role = AppRole.builder(NAME)
.withSecretIdBoundCidrs(BOUND_CIDR_LIST)
.withSecretBoundCidr(CIDR_2)
.withTokenBoundCidrs(BOUND_CIDR_LIST)
.withTokenBoundCidr(CIDR_2)
.build();
assertThat(role.getSecretIdBoundCidrs(), hasSize(2));
assertThat(role.getSecretIdBoundCidrs(), contains(CIDR_1, CIDR_2));
assertThat(role.getTokenBoundCidrs(), hasSize(2));
assertThat(role.getSecretIdBoundCidrs(), contains(CIDR_1, CIDR_2));
assertEquals(2, role.getSecretIdBoundCidrs().size());
assertTrue(role.getSecretIdBoundCidrs().containsAll(List.of(CIDR_1, CIDR_2)));
assertEquals(2, role.getTokenBoundCidrs().size());
assertTrue(role.getSecretIdBoundCidrs().containsAll(List.of(CIDR_1, CIDR_2)));
/* Add single policy */
// Add single policy.
role = AppRole.builder(NAME).withTokenPolicy(POLICY_2).build();
assertThat(role.getTokenPolicies(), hasSize(1));
assertThat(role.getTokenPolicies(), contains(POLICY_2));
assertEquals(1, role.getTokenPolicies().size());
assertEquals(POLICY_2, role.getTokenPolicies().get(0));
role = AppRole.builder(NAME)
.withTokenPolicies(POLICIES)
.withTokenPolicy(POLICY_2)
.build();
assertThat(role.getTokenPolicies(), hasSize(2));
assertThat(role.getTokenPolicies(), contains(POLICY, POLICY_2));
assertEquals(2, role.getTokenPolicies().size());
assertTrue(role.getTokenPolicies().containsAll(List.of(POLICY, POLICY_2)));
}
}

View File

@ -18,8 +18,8 @@ package de.stklcode.jvault.connector.model;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* JUnit Test for AuthBackend model.
@ -34,12 +34,11 @@ class AuthBackendTest {
*/
@Test
void forTypeTest() {
assertThat(AuthBackend.forType("token"), is(AuthBackend.TOKEN));
assertThat(AuthBackend.forType("app-id"), is(AuthBackend.APPID));
assertThat(AuthBackend.forType("userpass"), is(AuthBackend.USERPASS));
assertThat(AuthBackend.forType("github"), is(AuthBackend.GITHUB));
assertThat(AuthBackend.forType(""), is(AuthBackend.UNKNOWN));
assertThat(AuthBackend.forType("foobar"), is(AuthBackend.UNKNOWN));
assertEquals(AuthBackend.TOKEN, AuthBackend.forType("token"));
assertEquals(AuthBackend.APPID, AuthBackend.forType("app-id"));
assertEquals(AuthBackend.USERPASS, AuthBackend.forType("userpass"));
assertEquals(AuthBackend.GITHUB, AuthBackend.forType("github"));
assertEquals(AuthBackend.UNKNOWN, AuthBackend.forType(""));
assertEquals(AuthBackend.UNKNOWN, AuthBackend.forType("foobar"));
}
}

View File

@ -23,8 +23,7 @@ import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* Unit Test for {@link Token.Builder}
@ -80,20 +79,20 @@ class TokenRoleBuilderTest {
@Test
void buildDefaultTest() throws JsonProcessingException {
TokenRole role = TokenRole.builder().build();
assertThat(role.getAllowedPolicies(), is(nullValue()));
assertThat(role.getDisallowedPolicies(), is(nullValue()));
assertThat(role.getOrphan(), is(nullValue()));
assertThat(role.getRenewable(), is(nullValue()));
assertThat(role.getAllowedEntityAliases(), is(nullValue()));
assertThat(role.getTokenBoundCidrs(), is(nullValue()));
assertThat(role.getTokenExplicitMaxTtl(), is(nullValue()));
assertThat(role.getTokenNoDefaultPolicy(), is(nullValue()));
assertThat(role.getTokenNumUses(), is(nullValue()));
assertThat(role.getTokenPeriod(), is(nullValue()));
assertThat(role.getTokenType(), is(nullValue()));
assertNull(role.getAllowedPolicies());
assertNull(role.getDisallowedPolicies());
assertNull(role.getOrphan());
assertNull(role.getRenewable());
assertNull(role.getAllowedEntityAliases());
assertNull(role.getTokenBoundCidrs());
assertNull(role.getTokenExplicitMaxTtl());
assertNull(role.getTokenNoDefaultPolicy());
assertNull(role.getTokenNumUses());
assertNull(role.getTokenPeriod());
assertNull(role.getTokenType());
/* optional fields should be ignored, so JSON string should be empty */
assertThat(new ObjectMapper().writeValueAsString(role), is("{}"));
// Optional fields should be ignored, so JSON string should be empty.
assertEquals("{}", new ObjectMapper().writeValueAsString(role));
}
/**
@ -121,20 +120,20 @@ class TokenRoleBuilderTest {
.withTokenType(null)
.build();
assertThat(role.getAllowedPolicies(), is(nullValue()));
assertThat(role.getDisallowedPolicies(), is(nullValue()));
assertThat(role.getOrphan(), is(nullValue()));
assertThat(role.getRenewable(), is(nullValue()));
assertThat(role.getAllowedEntityAliases(), is(nullValue()));
assertThat(role.getTokenBoundCidrs(), is(nullValue()));
assertThat(role.getTokenExplicitMaxTtl(), is(nullValue()));
assertThat(role.getTokenNoDefaultPolicy(), is(nullValue()));
assertThat(role.getTokenNumUses(), is(nullValue()));
assertThat(role.getTokenPeriod(), is(nullValue()));
assertThat(role.getTokenType(), is(nullValue()));
assertNull(role.getAllowedPolicies());
assertNull(role.getDisallowedPolicies());
assertNull(role.getOrphan());
assertNull(role.getRenewable());
assertNull(role.getAllowedEntityAliases());
assertNull(role.getTokenBoundCidrs());
assertNull(role.getTokenExplicitMaxTtl());
assertNull(role.getTokenNoDefaultPolicy());
assertNull(role.getTokenNumUses());
assertNull(role.getTokenPeriod());
assertNull(role.getTokenType());
/* optional fields should be ignored, so JSON string should be empty */
assertThat(new ObjectMapper().writeValueAsString(role), is("{}"));
// Optional fields should be ignored, so JSON string should be empty.
assertEquals("{}", new ObjectMapper().writeValueAsString(role));
}
/**
@ -161,24 +160,24 @@ class TokenRoleBuilderTest {
.withTokenPeriod(TOKEN_PERIOD)
.withTokenType(TOKEN_TYPE)
.build();
assertThat(role.getName(), is(NAME));
assertThat(role.getAllowedPolicies(), hasSize(ALLOWED_POLICIES.size() + 1));
assertThat(role.getAllowedPolicies(), containsInAnyOrder(ALLOWED_POLICY_1, ALLOWED_POLICY_2, ALLOWED_POLICY_3));
assertThat(role.getDisallowedPolicies(), hasSize(DISALLOWED_POLICIES.size() + 1));
assertThat(role.getDisallowedPolicies(), containsInAnyOrder(DISALLOWED_POLICY_1, DISALLOWED_POLICY_2, DISALLOWED_POLICY_3));
assertThat(role.getOrphan(), is(ORPHAN));
assertThat(role.getRenewable(), is(RENEWABLE));
assertThat(role.getPathSuffix(), is(PATH_SUFFIX));
assertThat(role.getAllowedEntityAliases(), hasSize(ALLOWED_ENTITY_ALIASES.size() + 1));
assertThat(role.getAllowedEntityAliases(), containsInAnyOrder(ALLOWED_ENTITY_ALIAS_1, ALLOWED_ENTITY_ALIAS_2, ALLOWED_ENTITY_ALIAS_3));
assertThat(role.getTokenBoundCidrs(), hasSize(TOKEN_BOUND_CIDRS.size() + 1));
assertThat(role.getTokenBoundCidrs(), containsInAnyOrder(TOKEN_BOUND_CIDR_1, TOKEN_BOUND_CIDR_2, TOKEN_BOUND_CIDR_3));
assertThat(role.getTokenNoDefaultPolicy(), is(TOKEN_NO_DEFAULT_POLICY));
assertThat(role.getTokenNumUses(), is(TOKEN_NUM_USES));
assertThat(role.getTokenPeriod(), is(TOKEN_PERIOD));
assertThat(role.getTokenType(), is(TOKEN_TYPE.value()));
assertEquals(NAME, role.getName());
assertEquals(ALLOWED_POLICIES.size() + 1, role.getAllowedPolicies().size());
assertTrue(role.getAllowedPolicies().containsAll(List.of(ALLOWED_POLICY_1, ALLOWED_POLICY_2, ALLOWED_POLICY_3)));
assertEquals(DISALLOWED_POLICIES.size() + 1, role.getDisallowedPolicies().size());
assertTrue(role.getDisallowedPolicies().containsAll(List.of(DISALLOWED_POLICY_1, DISALLOWED_POLICY_2, DISALLOWED_POLICY_3)));
assertEquals(ORPHAN, role.getOrphan());
assertEquals(RENEWABLE, role.getRenewable());
assertEquals(PATH_SUFFIX, role.getPathSuffix());
assertEquals(ALLOWED_ENTITY_ALIASES.size() + 1, role.getAllowedEntityAliases().size());
assertTrue(role.getAllowedEntityAliases().containsAll(List.of(ALLOWED_ENTITY_ALIAS_1, ALLOWED_ENTITY_ALIAS_2, ALLOWED_ENTITY_ALIAS_3)));
assertEquals(TOKEN_BOUND_CIDRS.size() + 1, role.getTokenBoundCidrs().size());
assertTrue(role.getTokenBoundCidrs().containsAll(List.of(TOKEN_BOUND_CIDR_1, TOKEN_BOUND_CIDR_2, TOKEN_BOUND_CIDR_3)));
assertEquals(TOKEN_NO_DEFAULT_POLICY, role.getTokenNoDefaultPolicy());
assertEquals(TOKEN_NUM_USES, role.getTokenNumUses());
assertEquals(TOKEN_PERIOD, role.getTokenPeriod());
assertEquals(TOKEN_TYPE.value(), role.getTokenType());
/* Verify that all parameters are included in JSON string */
assertThat(new ObjectMapper().writeValueAsString(role), is(JSON_FULL));
// Verify that all parameters are included in JSON string.
assertEquals(JSON_FULL, new ObjectMapper().writeValueAsString(role));
}
}

View File

@ -21,13 +21,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link Token} and {@link Token.Builder}.
@ -55,7 +51,6 @@ class TokenTest {
private static final Boolean RENEWABLE = true;
private static final Integer PERIOD = 3600;
private static final String ENTITY_ALIAS = "alias-value";
private static final String LEGACY_JSON_FULL = "{\"id\":\"test-id\",\"type\":\"service\",\"display_name\":\"display-name\",\"no_parent\":false,\"no_default_policy\":false,\"ttl\":123,\"num_uses\":4,\"policies\":[\"policy\"],\"meta\":{\"key\":\"value\"},\"renewable\":true}";
private static final String JSON_FULL = "{\"id\":\"test-id\",\"type\":\"service\",\"display_name\":\"display-name\",\"no_parent\":false,\"no_default_policy\":false,\"ttl\":123,\"explicit_max_ttl\":456,\"num_uses\":4,\"policies\":[\"policy\"],\"meta\":{\"key\":\"value\"},\"renewable\":true,\"period\":3600,\"entity_alias\":\"alias-value\"}";
@BeforeAll
@ -70,22 +65,22 @@ class TokenTest {
@Test
void buildDefaultTest() throws JsonProcessingException {
Token token = Token.builder().build();
assertThat(token.getId(), is(nullValue()));
assertThat(token.getType(), is(nullValue()));
assertThat(token.getDisplayName(), is(nullValue()));
assertThat(token.getNoParent(), is(nullValue()));
assertThat(token.getNoDefaultPolicy(), is(nullValue()));
assertThat(token.getTtl(), is(nullValue()));
assertThat(token.getExplicitMaxTtl(), is(nullValue()));
assertThat(token.getNumUses(), is(nullValue()));
assertThat(token.getPolicies(), is(nullValue()));
assertThat(token.getMeta(), is(nullValue()));
assertThat(token.isRenewable(), is(nullValue()));
assertThat(token.getPeriod(), is(nullValue()));
assertThat(token.getEntityAlias(), is(nullValue()));
assertNull(token.getId());
assertNull(token.getType());
assertNull(token.getDisplayName());
assertNull(token.getNoParent());
assertNull(token.getNoDefaultPolicy());
assertNull(token.getTtl());
assertNull(token.getExplicitMaxTtl());
assertNull(token.getNumUses());
assertNull(token.getPolicies());
assertNull(token.getMeta());
assertNull(token.isRenewable());
assertNull(token.getPeriod());
assertNull(token.getEntityAlias());
/* optional fields should be ignored, so JSON string should be empty */
assertThat(new ObjectMapper().writeValueAsString(token), is("{}"));
// Optional fields should be ignored, so JSON string should be empty.
assertEquals("{}", new ObjectMapper().writeValueAsString(token));
}
/**
@ -108,21 +103,21 @@ class TokenTest {
.withPeriod(PERIOD)
.withEntityAlias(ENTITY_ALIAS)
.build();
assertThat(token.getId(), is(ID));
assertThat(token.getType(), is(Token.Type.SERVICE.value()));
assertThat(token.getDisplayName(), is(DISPLAY_NAME));
assertThat(token.getNoParent(), is(NO_PARENT));
assertThat(token.getNoDefaultPolicy(), is(NO_DEFAULT_POLICY));
assertThat(token.getTtl(), is(TTL));
assertThat(token.getExplicitMaxTtl(), is(EXPLICIT_MAX_TTL));
assertThat(token.getNumUses(), is(NUM_USES));
assertThat(token.getPolicies(), is(POLICIES));
assertThat(token.getMeta(), is(META));
assertThat(token.isRenewable(), is(RENEWABLE));
assertThat(token.getPeriod(), is(PERIOD));
assertEquals(ID, token.getId());
assertEquals(Token.Type.SERVICE.value(), token.getType());
assertEquals(DISPLAY_NAME, token.getDisplayName());
assertEquals(NO_PARENT, token.getNoParent());
assertEquals(NO_DEFAULT_POLICY, token.getNoDefaultPolicy());
assertEquals(TTL, token.getTtl());
assertEquals(EXPLICIT_MAX_TTL, token.getExplicitMaxTtl());
assertEquals(NUM_USES, token.getNumUses());
assertEquals(POLICIES, token.getPolicies());
assertEquals(META, token.getMeta());
assertEquals(RENEWABLE, token.isRenewable());
assertEquals(PERIOD, token.getPeriod());
/* Verify that all parameters are included in JSON string */
assertThat(new ObjectMapper().writeValueAsString(token), is(JSON_FULL));
// Verify that all parameters are included in JSON string.
assertEquals(JSON_FULL, new ObjectMapper().writeValueAsString(token));
}
/**
@ -130,46 +125,46 @@ class TokenTest {
*/
@Test
void convenienceMethodsTest() {
/* Parent */
// Parent.
Token token = Token.builder().asOrphan().build();
assertThat(token.getNoParent(), is(true));
assertEquals(true, token.getNoParent());
token = Token.builder().withParent().build();
assertThat(token.getNoParent(), is(false));
assertEquals(false, token.getNoParent());
/* Default policy */
// Default policy.
token = Token.builder().withDefaultPolicy().build();
assertThat(token.getNoDefaultPolicy(), is(false));
assertEquals(false, token.getNoDefaultPolicy());
token = Token.builder().withoutDefaultPolicy().build();
assertThat(token.getNoDefaultPolicy(), is(true));
assertEquals(true, token.getNoDefaultPolicy());
/* Renewability */
// Renewability.
token = Token.builder().renewable().build();
assertThat(token.isRenewable(), is(true));
assertEquals(true, token.isRenewable());
token = Token.builder().notRenewable().build();
assertThat(token.isRenewable(), is(false));
assertEquals(false, token.isRenewable());
/* Add single policy */
// Add single policy.
token = Token.builder().withPolicy(POLICY_2).build();
assertThat(token.getPolicies(), hasSize(1));
assertThat(token.getPolicies(), contains(POLICY_2));
assertEquals(1, token.getPolicies().size());
assertEquals(List.of(POLICY_2), token.getPolicies());
token = Token.builder()
.withPolicies(POLICY, POLICY_2)
.withPolicy(POLICY_3)
.build();
assertThat(token.getPolicies(), hasSize(3));
assertThat(token.getPolicies(), contains(POLICY, POLICY_2, POLICY_3));
assertEquals(3, token.getPolicies().size());
assertTrue(token.getPolicies().containsAll(List.of(POLICY, POLICY_2, POLICY_3)));
/* Add single metadata */
// Add single metadata.
token = Token.builder().withMeta(META_KEY_2, META_VALUE_2).build();
assertThat(token.getMeta().size(), is(1));
assertThat(token.getMeta().keySet(), contains(META_KEY_2));
assertThat(token.getMeta().get(META_KEY_2), is(META_VALUE_2));
assertEquals(1, token.getMeta().size());
assertEquals(Set.of(META_KEY_2), token.getMeta().keySet());
assertEquals(META_VALUE_2, token.getMeta().get(META_KEY_2));
token = Token.builder()
.withMeta(META)
.withMeta(META_KEY_2, META_VALUE_2)
.build();
assertThat(token.getMeta().size(), is(2));
assertThat(token.getMeta().get(META_KEY), is(META_VALUE));
assertThat(token.getMeta().get(META_KEY_2), is(META_VALUE_2));
assertEquals(2, token.getMeta().size());
assertEquals(META_VALUE, token.getMeta().get(META_KEY));
assertEquals(META_VALUE_2, token.getMeta().get(META_KEY_2));
}
}

View File

@ -24,10 +24,7 @@ import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link AppRoleResponse} model.
@ -78,7 +75,7 @@ class AppRoleResponseTest {
void getDataRoundtrip() {
// Create empty Object.
AppRoleResponse res = new AppRoleResponse();
assertThat("Initial data should be empty", res.getRole(), is(nullValue()));
assertNull(res.getRole(), "Initial data should be empty");
// Parsing invalid auth data map should fail.
assertThrows(
@ -97,19 +94,19 @@ class AppRoleResponseTest {
() -> new ObjectMapper().readValue(RES_JSON, AppRoleResponse.class),
"AuthResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue()));
assertNotNull(res, "Parsed response is NULL");
// Extract role data.
AppRole role = res.getRole();
assertThat("Role data is NULL", role, is(notNullValue()));
assertThat("Incorrect token TTL", role.getTokenTtl(), is(ROLE_TOKEN_TTL));
assertThat("Incorrect token max TTL", role.getTokenMaxTtl(), is(ROLE_TOKEN_MAX_TTL));
assertThat("Incorrect secret ID TTL", role.getSecretIdTtl(), is(ROLE_SECRET_TTL));
assertThat("Incorrect secret ID umber of uses", role.getSecretIdNumUses(), is(ROLE_SECRET_NUM_USES));
assertThat("Incorrect number of policies", role.getTokenPolicies(), hasSize(1));
assertThat("Incorrect role policies", role.getTokenPolicies(), contains(ROLE_POLICY));
assertThat("Incorrect role period", role.getTokenPeriod(), is(ROLE_PERIOD));
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 string", role.getTokenBoundCidrsString(), is(emptyString()));
assertNotNull(role, "Role data is NULL");
assertEquals(ROLE_TOKEN_TTL, role.getTokenTtl(), "Incorrect token TTL");
assertEquals(ROLE_TOKEN_MAX_TTL, role.getTokenMaxTtl(), "Incorrect token max TTL");
assertEquals(ROLE_SECRET_TTL, role.getSecretIdTtl(), "Incorrect secret ID TTL");
assertEquals(ROLE_SECRET_NUM_USES, role.getSecretIdNumUses(), "Incorrect secret ID umber of uses");
assertEquals(1, role.getTokenPolicies().size(), "Incorrect number of policies");
assertEquals(ROLE_POLICY, role.getTokenPolicies().get(0), "Incorrect role policies");
assertEquals(ROLE_PERIOD, role.getTokenPeriod(), "Incorrect role period");
assertEquals(ROLE_BIND_SECRET, role.getBindSecretId(), "Incorrect role bind secret ID flag");
assertNull(role.getTokenBoundCidrs(), "Incorrect bound CIDR list");
assertEquals("", role.getTokenBoundCidrsString(), "Incorrect bound CIDR list string");
}
}

View File

@ -22,13 +22,12 @@ import de.stklcode.jvault.connector.model.AuthBackend;
import de.stklcode.jvault.connector.model.response.embedded.AuthMethod;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link AuthMethodsResponse} model.
@ -76,7 +75,7 @@ class AuthMethodsResponseTest {
void getDataRoundtrip() {
// Create empty Object.
AuthMethodsResponse res = new AuthMethodsResponse();
assertThat("Initial method map should be empty", res.getSupportedMethods(), is(anEmptyMap()));
assertEquals(Collections.emptyMap(), res.getSupportedMethods(), "Initial method map should be empty");
// Parsing invalid data map should fail.
assertThrows(
@ -95,29 +94,29 @@ class AuthMethodsResponseTest {
() -> new ObjectMapper().readValue(RES_JSON, AuthMethodsResponse.class),
"AuthResponse deserialization failed"
);
assertThat("Parsed response is NULL", res, is(notNullValue()));
assertNotNull(res, "Parsed response is NULL");
// Extract auth data.
Map<String, AuthMethod> supported = res.getSupportedMethods();
assertThat("Auth data is NULL", supported, is(notNullValue()));
assertThat("Incorrect number of supported methods", supported.entrySet(), hasSize(2));
assertThat("Incorrect method paths", supported.keySet(), containsInAnyOrder(GH_PATH, TK_PATH));
assertNotNull(supported, "Auth data is NULL");
assertEquals(2, supported.size(), "Incorrect number of supported methods");
assertTrue(supported.keySet().containsAll(Set.of(GH_PATH, TK_PATH)), "Incorrect method paths");
// Verify first method.
AuthMethod method = supported.get(GH_PATH);
assertThat("Incorrect raw type for GitHub", method.getRawType(), is(GH_TYPE));
assertThat("Incorrect parsed type for GitHub", method.getType(), is(AuthBackend.GITHUB));
assertThat("Incorrect description for GitHub", method.getDescription(), is(GH_DESCR));
assertThat("Unexpected config for GitHub", method.getConfig(), is(nullValue()));
assertEquals(GH_TYPE, method.getRawType(), "Incorrect raw type for GitHub");
assertEquals(AuthBackend.GITHUB, method.getType(), "Incorrect parsed type for GitHub");
assertEquals(GH_DESCR, method.getDescription(), "Incorrect description for GitHub");
assertNull(method.getConfig(), "Unexpected config for GitHub");
// Verify first method.
method = supported.get(TK_PATH);
assertThat("Incorrect raw type for Token", method.getRawType(), is(TK_TYPE));
assertThat("Incorrect parsed type for Token", method.getType(), is(AuthBackend.TOKEN));
assertThat("Incorrect description for Token", method.getDescription(), is(TK_DESCR));
assertThat("Missing config for Token", method.getConfig(), is(notNullValue()));
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 max lease TTL config", method.getConfig().get("max_lease_ttl"), is(TK_MAX_LEASE_TTL.toString()));
assertEquals(TK_TYPE, method.getRawType(), "Incorrect raw type for Token");
assertEquals(AuthBackend.TOKEN, method.getType(), "Incorrect parsed type for Token");
assertEquals(TK_DESCR, method.getDescription(), "Incorrect description for Token");
assertNotNull(method.getConfig(), "Missing config for Token");
assertEquals(2, method.getConfig().size(), "Unexpected config size for Token");
assertEquals(TK_LEASE_TTL.toString(), method.getConfig().get("default_lease_ttl"), "Incorrect lease TTL config");
assertEquals(TK_MAX_LEASE_TTL.toString(), method.getConfig().get("max_lease_ttl"), "Incorrect max lease TTL config");
}
private static class Dummy {

View File

@ -23,11 +23,9 @@ import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link AuthResponse} model.
@ -84,7 +82,7 @@ class AuthResponseTest {
void getDataRoundtrip() {
// Create empty Object.
AuthResponse res = new AuthResponse();
assertThat("Initial data should be empty", res.getData(), is(nullValue()));
assertNull(res.getData(), "Initial data should be empty");
// Parsing invalid auth data map should fail.
assertThrows(
@ -95,7 +93,7 @@ class AuthResponseTest {
// Data method should be agnostic.
res.setData(INVALID_AUTH_DATA);
assertThat("Data not passed through", res.getData(), is(INVALID_AUTH_DATA));
assertEquals(INVALID_AUTH_DATA, res.getData(), "Data not passed through");
}
/**
@ -103,26 +101,26 @@ class AuthResponseTest {
*/
@Test
void jsonRoundtrip() {
AuthResponse res = assertDoesNotThrow(
() -> new ObjectMapper().readValue(RES_JSON, AuthResponse.class),
"AuthResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue()));
// Extract auth data.
AuthData data = res.getAuth();
assertThat("Auth data is NULL", data, is(notNullValue()));
assertThat("Incorrect auth accessor", data.getAccessor(), is(AUTH_ACCESSOR));
assertThat("Incorrect auth client token", data.getClientToken(), is(AUTH_CLIENT_TOKEN));
assertThat("Incorrect auth lease duration", data.getLeaseDuration(), is(AUTH_LEASE_DURATION));
assertThat("Incorrect auth renewable flag", data.isRenewable(), is(AUTH_RENEWABLE));
assertThat("Incorrect auth orphan flag", data.isOrphan(), is(AUTH_ORPHAN));
assertThat("Incorrect auth token type", data.getTokenType(), is(AUTH_TOKEN_TYPE));
assertThat("Incorrect auth entity id", data.getEntityId(), is(AUTH_ENTITY_ID));
assertThat("Incorrect number of policies", data.getPolicies(), hasSize(2));
assertThat("Incorrect auth policies", data.getPolicies(), containsInRelativeOrder(AUTH_POLICY_1, AUTH_POLICY_2));
assertThat("Incorrect number of token policies", data.getTokenPolicies(), hasSize(2));
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", data.getMetadata().get(AUTH_META_KEY), is(AUTH_META_VALUE));
AuthResponse res = assertDoesNotThrow(
() -> new ObjectMapper().readValue(RES_JSON, AuthResponse.class),
"AuthResponse deserialization failed."
);
assertNotNull(res, "Parsed response is NULL");
// Extract auth data.
AuthData data = res.getAuth();
assertNotNull(data, "Auth data is NULL");
assertEquals(AUTH_ACCESSOR, data.getAccessor(), "Incorrect auth accessor");
assertEquals(AUTH_CLIENT_TOKEN, data.getClientToken(), "Incorrect auth client token");
assertEquals(AUTH_LEASE_DURATION, data.getLeaseDuration(), "Incorrect auth lease duration");
assertEquals(AUTH_RENEWABLE, data.isRenewable(), "Incorrect auth renewable flag");
assertEquals(AUTH_ORPHAN, data.isOrphan(), "Incorrect auth orphan flag");
assertEquals(AUTH_TOKEN_TYPE, data.getTokenType(), "Incorrect auth token type");
assertEquals(AUTH_ENTITY_ID, data.getEntityId(), "Incorrect auth entity id");
assertEquals(2, data.getPolicies().size(), "Incorrect number of policies");
assertTrue(data.getPolicies().containsAll(Set.of(AUTH_POLICY_1, AUTH_POLICY_2)));
assertEquals(2, data.getTokenPolicies().size(), "Incorrect number of token policies");
assertTrue(data.getTokenPolicies().containsAll(Set.of(AUTH_POLICY_2, AUTH_POLICY_1)), "Incorrect token policies");
assertEquals(1, data.getMetadata().size(), "Incorrect auth metadata size");
assertEquals(AUTH_META_VALUE, data.getMetadata().get(AUTH_META_KEY), "Incorrect auth metadata");
}
}

View File

@ -16,18 +16,14 @@
package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* JUnit Test for {@link CredentialsResponse} model.
@ -55,12 +51,12 @@ class CredentialsResponseTest {
void getCredentialsTest() throws InvalidResponseException {
// Create empty Object.
CredentialsResponse res = new CredentialsResponse();
assertThat("Username not present in data map should not return anything", res.getUsername(), is(nullValue()));
assertThat("Password not present in data map should not return anything", res.getPassword(), is(nullValue()));
assertNull(res.getUsername(), "Username not present in data map should not return anything");
assertNull(res.getPassword(), "Password not present in data map should not return anything");
// Fill data map.
res.setData(DATA);
assertThat("Incorrect username", res.getUsername(), is(VAL_USER));
assertThat("Incorrect password", res.getPassword(), is(VAL_PASS));
assertEquals(VAL_USER, res.getUsername(), "Incorrect username");
assertEquals(VAL_PASS, res.getPassword(), "Incorrect password");
}
}

View File

@ -19,10 +19,7 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link AuthResponse} model.
@ -64,16 +61,16 @@ class HealthResponseTest {
() -> new ObjectMapper().readValue(RES_JSON, HealthResponse.class),
"Health deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Incorrect cluster ID", res.getClusterID(), is(CLUSTER_ID));
assertThat("Incorrect cluster name", res.getClusterName(), is(CLUSTER_NAME));
assertThat("Incorrect version", res.getVersion(), is(VERSION));
assertThat("Incorrect server time", res.getServerTimeUTC(), is(SERVER_TIME_UTC));
assertThat("Incorrect standby state", res.isStandby(), is(STANDBY));
assertThat("Incorrect seal state", res.isSealed(), is(SEALED));
assertThat("Incorrect initialization state", res.isInitialized(), is(INITIALIZED));
assertThat("Incorrect performance standby state", res.isPerformanceStandby(), is(PERF_STANDBY));
assertThat("Incorrect replication perf mode", res.getReplicationPerfMode(), is(REPL_PERF_MODE));
assertThat("Incorrect replication DR mode", res.getReplicationDrMode(), is(REPL_DR_MODE));
assertNotNull(res, "Parsed response is NULL");
assertEquals(CLUSTER_ID, res.getClusterID(), "Incorrect cluster ID");
assertEquals(CLUSTER_NAME, res.getClusterName(), "Incorrect cluster name");
assertEquals(VERSION, res.getVersion(), "Incorrect version");
assertEquals(SERVER_TIME_UTC, res.getServerTimeUTC(), "Incorrect server time");
assertEquals(STANDBY, res.isStandby(), "Incorrect standby state");
assertEquals(SEALED, res.isSealed(), "Incorrect seal state");
assertEquals(INITIALIZED, res.isInitialized(), "Incorrect initialization state");
assertEquals(PERF_STANDBY, res.isPerformanceStandby(), "Incorrect performance standby state");
assertEquals(REPL_PERF_MODE, res.getReplicationPerfMode(), "Incorrect replication perf mode");
assertEquals(REPL_DR_MODE, res.getReplicationDrMode(), "Incorrect replication DR mode");
}
}

View File

@ -19,10 +19,7 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link MetadataResponse} model.
@ -74,21 +71,21 @@ class MetadataResponseTest {
() -> new ObjectMapper().readValue(META_JSON, MetadataResponse.class),
"MetadataResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Parsed metadata is NULL", res.getMetadata(), is(notNullValue()));
assertThat("Incorrect created time", res.getMetadata().getCreatedTimeString(), is(V1_TIME));
assertThat("Parting created time failed", res.getMetadata().getCreatedTime(), is(notNullValue()));
assertThat("Incorrect current version", res.getMetadata().getCurrentVersion(), is(CURRENT_VERSION));
assertThat("Incorrect max versions", res.getMetadata().getMaxVersions(), is(MAX_VERSIONS));
assertThat("Incorrect oldest version", res.getMetadata().getOldestVersion(), is(OLDEST_VERSION));
assertThat("Incorrect updated time", res.getMetadata().getUpdatedTimeString(), is(V3_TIME));
assertThat("Parting updated time failed", res.getMetadata().getUpdatedTime(), is(notNullValue()));
assertThat("Incorrect number of versions", res.getMetadata().getVersions().size(), is(3));
assertThat("Incorrect version 1 delete time", res.getMetadata().getVersions().get(1).getDeletionTimeString(), is(V2_TIME));
assertThat("Parsing version delete time failed", res.getMetadata().getVersions().get(1).getDeletionTime(), is(notNullValue()));
assertThat("Incorrect version 1 destroyed state", res.getMetadata().getVersions().get(1).isDestroyed(), is(true));
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("Incorrect version 3 destroyed state", res.getMetadata().getVersions().get(3).isDestroyed(), is(false));
assertNotNull(res, "Parsed response is NULL");
assertNotNull(res.getMetadata(), "Parsed metadata is NULL");
assertEquals(V1_TIME, res.getMetadata().getCreatedTimeString(), "Incorrect created time");
assertNotNull(res.getMetadata().getCreatedTime(), "Parting created time failed");
assertEquals(CURRENT_VERSION, res.getMetadata().getCurrentVersion(), "Incorrect current version");
assertEquals(MAX_VERSIONS, res.getMetadata().getMaxVersions(), "Incorrect max versions");
assertEquals(OLDEST_VERSION, res.getMetadata().getOldestVersion(), "Incorrect oldest version");
assertEquals(V3_TIME, res.getMetadata().getUpdatedTimeString(), "Incorrect updated time");
assertNotNull(res.getMetadata().getUpdatedTime(), "Parting updated time failed");
assertEquals(3, res.getMetadata().getVersions().size(), "Incorrect number of versions");
assertEquals(V2_TIME, res.getMetadata().getVersions().get(1).getDeletionTimeString(), "Incorrect version 1 delete time");
assertNotNull(res.getMetadata().getVersions().get(1).getDeletionTime(), "Parsing version delete time failed");
assertTrue(res.getMetadata().getVersions().get(1).isDestroyed(), "Incorrect version 1 destroyed state");
assertEquals(V2_TIME, res.getMetadata().getVersions().get(2).getCreatedTimeString(), "Incorrect version 2 created time");
assertNotNull(res.getMetadata().getVersions().get(2).getCreatedTime(), "Parsing version created failed");
assertFalse(res.getMetadata().getVersions().get(3).isDestroyed(), "Incorrect version 3 destroyed state");
}
}

View File

@ -19,9 +19,7 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link SealResponse} model.
@ -74,18 +72,18 @@ class SealResponseTest {
() -> new ObjectMapper().readValue(RES_SEALED, SealResponse.class),
"TokenResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Incorrect seal type", res.getType(), is(TYPE));
assertThat("Incorrect seal status", res.isSealed(), is(true));
assertThat("Incorrect initialization status", res.isInitialized(), is(true));
assertThat("Incorrect threshold", res.getThreshold(), is(THRESHOLD));
assertThat("Incorrect number of shares", res.getNumberOfShares(), is(SHARES));
assertThat("Incorrect progress", res.getProgress(), is(PROGRESS_SEALED));
assertThat("Nonce not empty", res.getNonce(), is(""));
assertThat("Incorrect version", res.getVersion(), is(VERSION));
assertNotNull(res, "Parsed response is NULL");
assertEquals(TYPE, res.getType(), "Incorrect seal type");
assertTrue(res.isSealed(), "Incorrect seal status");
assertTrue(res.isInitialized(), "Incorrect initialization status");
assertEquals(THRESHOLD, res.getThreshold(), "Incorrect threshold");
assertEquals(SHARES, res.getNumberOfShares(), "Incorrect number of shares");
assertEquals(PROGRESS_SEALED, res.getProgress(), "Incorrect progress");
assertEquals("", res.getNonce(), "Nonce not empty");
assertEquals(VERSION, res.getVersion(), "Incorrect version");
// And the fields, that should not be filled.
assertThat("Cluster name should not be populated", res.getClusterName(), is(nullValue()));
assertThat("Cluster ID should not be populated", res.getClusterId(), is(nullValue()));
assertNull(res.getClusterName(), "Cluster name should not be populated");
assertNull(res.getClusterId(), "Cluster ID should not be populated");
// Not test unsealed Vault's response.
@ -93,16 +91,16 @@ class SealResponseTest {
() -> new ObjectMapper().readValue(RES_UNSEALED, SealResponse.class),
"TokenResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Incorrect seal type", res.getType(), is(TYPE));
assertThat("Incorrect seal status", res.isSealed(), is(false));
assertThat("Incorrect initialization status", res.isInitialized(), is(true));
assertThat("Incorrect threshold", res.getThreshold(), is(THRESHOLD));
assertThat("Incorrect number of shares", res.getNumberOfShares(), is(SHARES));
assertThat("Incorrect progress", res.getProgress(), is(PROGRESS_UNSEALED));
assertThat("Incorrect nonce", res.getNonce(), is(NONCE));
assertThat("Incorrect version", res.getVersion(), is(VERSION));
assertThat("Incorrect cluster name", res.getClusterName(), is(CLUSTER_NAME));
assertThat("Incorrect cluster ID", res.getClusterId(), is(CLUSTER_ID));
assertNotNull(res, "Parsed response is NULL");
assertEquals(TYPE, res.getType(), "Incorrect seal type");
assertFalse(res.isSealed(), "Incorrect seal status");
assertTrue(res.isInitialized(), "Incorrect initialization status");
assertEquals(THRESHOLD, res.getThreshold(), "Incorrect threshold");
assertEquals(SHARES, res.getNumberOfShares(), "Incorrect number of shares");
assertEquals(PROGRESS_UNSEALED, res.getProgress(), "Incorrect progress");
assertEquals(NONCE, res.getNonce(), "Incorrect nonce");
assertEquals(VERSION, res.getVersion(), "Incorrect version");
assertEquals(CLUSTER_NAME, res.getClusterName(), "Incorrect cluster name");
assertEquals(CLUSTER_ID, res.getClusterId(), "Incorrect cluster ID");
}
}

View File

@ -19,14 +19,9 @@ package de.stklcode.jvault.connector.model.response;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link SecretListResponse} model.
@ -53,7 +48,7 @@ class SecretListResponseTest {
void getKeysTest() throws InvalidResponseException {
// Create empty Object.
SecretListResponse res = new SecretListResponse();
assertThat("Keys should be null without initialization", res.getKeys(), is(nullValue()));
assertNull(res.getKeys(), "Keys should be null without initialization");
// Provoke internal ClassCastException.
Map<String, Object> invalidData = new HashMap<>();
@ -66,8 +61,8 @@ class SecretListResponseTest {
// Fill correct data.
res.setData(DATA);
assertThat("Keys should be filled here", res.getKeys(), is(notNullValue()));
assertThat("Unexpected number of keys", res.getKeys(), hasSize(2));
assertThat("Unexpected keys", res.getKeys(), contains(KEY1, KEY2));
assertNotNull(res.getKeys(), "Keys should be filled here");
assertEquals(2, res.getKeys().size(), "Unexpected number of keys");
assertTrue(res.getKeys().containsAll(Set.of(KEY1, KEY2)), "Unexpected keys");
}
}

View File

@ -23,11 +23,9 @@ import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link SecretResponse} model.
@ -123,25 +121,25 @@ class SecretResponseTest {
void getDataRoundtrip() throws InvalidResponseException {
// Create empty Object.
SecretResponse res = new SecretResponse();
assertThat("Initial data should be Map", res.getData(), is(instanceOf(Map.class)));
assertThat("Initial data should be empty", res.getData().entrySet(), empty());
assertThat("Getter should return NULL on empty data map", res.get(KEY_STRING), is(nullValue()));
assertNotNull(res.getData(), "Initial data should be Map");
assertTrue(res.getData().isEmpty(), "Initial data should be empty");
assertNull(res.get(KEY_STRING), "Getter should return NULL on empty data map");
// Fill data map.
res.setData(DATA);
assertThat("Data setter/getter not transparent", res.getData(), is(DATA));
assertThat("Data size modified", res.getData().keySet(), hasSize(DATA.size()));
assertThat("Data keys not passed correctly", res.getData().keySet(), containsInAnyOrder(KEY_STRING, KEY_INTEGER, KEY_LIST));
assertThat("Data values not passed correctly", res.get(KEY_STRING), is(VAL_STRING));
assertThat("Data values not passed correctly", res.get(KEY_INTEGER), is(VAL_INTEGER));
assertThat("Non-Null returned on unknown key", res.get(KEY_UNKNOWN), is(nullValue()));
assertEquals(DATA, res.getData(), "Data setter/getter not transparent");
assertEquals(DATA.size(), res.getData().keySet().size(), "Data size modified");
assertTrue(res.getData().keySet().containsAll(Set.of(KEY_STRING, KEY_INTEGER, KEY_LIST)), "Data keys not passed correctly");
assertEquals(VAL_STRING, res.get(KEY_STRING), "Data values not passed correctly");
assertEquals(VAL_INTEGER, res.get(KEY_INTEGER), "Data values not passed correctly");
assertNull(res.get(KEY_UNKNOWN), "Non-Null returned on unknown key");
// Try explicit JSON conversion.
final List<?> list = res.get(KEY_LIST, List.class);
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 elements", list, contains("first", "second"));
assertThat("Non-Null returned on unknown key", res.get(KEY_UNKNOWN, Object.class), is(nullValue()));
assertNotNull(list, "JSON parsing of list failed");
assertEquals(2, list.size(), "JSON parsing of list returned incorrect size");
assertTrue(list.containsAll(List.of("first", "second")), "JSON parsing of list returned incorrect elements");
assertNull(res.get(KEY_UNKNOWN, Object.class), "Non-Null returned on unknown key");
// Requesting invalid class should result in Exception.
assertThrows(
@ -168,13 +166,13 @@ class SecretResponseTest {
"SecretResponse deserialization failed."
);
assertSecretData(res);
assertThat("SecretResponse does not contain metadata", res.getMetadata(), is(notNullValue()));
assertThat("Incorrect creation date string", res.getMetadata().getCreatedTimeString(), is(SECRET_META_CREATED));
assertThat("Creation date parsing failed", res.getMetadata().getCreatedTime(), is(notNullValue()));
assertThat("Incorrect deletion date string", res.getMetadata().getDeletionTimeString(), is(emptyString()));
assertThat("Incorrect deletion date", res.getMetadata().getDeletionTime(), is(nullValue()));
assertThat("Secret destroyed when not expected", res.getMetadata().isDestroyed(), is(false));
assertThat("Incorrect secret version", res.getMetadata().getVersion(), is(1));
assertNotNull(res.getMetadata(), "SecretResponse does not contain metadata");
assertEquals(SECRET_META_CREATED, res.getMetadata().getCreatedTimeString(), "Incorrect creation date string");
assertNotNull(res.getMetadata().getCreatedTime(), "Creation date parsing failed");
assertEquals("", res.getMetadata().getDeletionTimeString(), "Incorrect deletion date string");
assertNull(res.getMetadata().getDeletionTime(), "Incorrect deletion date");
assertEquals(false, res.getMetadata().isDestroyed(), "Secret destroyed when not expected");
assertEquals(1, res.getMetadata().getVersion(), "Incorrect secret version");
// Deleted KV v2 secret.
res = assertDoesNotThrow(
@ -182,22 +180,22 @@ class SecretResponseTest {
"SecretResponse deserialization failed."
);
assertSecretData(res);
assertThat("SecretResponse does not contain metadata", res.getMetadata(), is(notNullValue()));
assertThat("Incorrect creation date string", res.getMetadata().getCreatedTimeString(), is(SECRET_META_CREATED));
assertThat("Creation date parsing failed", res.getMetadata().getCreatedTime(), is(notNullValue()));
assertThat("Incorrect deletion date string", res.getMetadata().getDeletionTimeString(), is(SECRET_META_DELETED));
assertThat("Incorrect deletion date", res.getMetadata().getDeletionTime(), is(notNullValue()));
assertThat("Secret destroyed when not expected", res.getMetadata().isDestroyed(), is(true));
assertThat("Incorrect secret version", res.getMetadata().getVersion(), is(2));
assertNotNull(res.getMetadata(), "SecretResponse does not contain metadata");
assertEquals(SECRET_META_CREATED, res.getMetadata().getCreatedTimeString(), "Incorrect creation date string");
assertNotNull(res.getMetadata().getCreatedTime(), "Creation date parsing failed");
assertEquals(SECRET_META_DELETED, res.getMetadata().getDeletionTimeString(), "Incorrect deletion date string");
assertNotNull(res.getMetadata().getDeletionTime(), "Incorrect deletion date");
assertEquals(true, res.getMetadata().isDestroyed(), "Secret destroyed when not expected");
assertEquals(2, res.getMetadata().getVersion(), "Incorrect secret version");
}
private void assertSecretData(SecretResponse res) {
assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Incorrect lease ID", res.getLeaseId(), is(SECRET_LEASE_ID));
assertThat("Incorrect lease duration", res.getLeaseDuration(), is(SECRET_LEASE_DURATION));
assertThat("Incorrect renewable status", res.isRenewable(), is(SECRET_RENEWABLE));
assertThat("Incorrect warnings", res.getWarnings(), is(SECRET_WARNINGS));
assertThat("Response does not contain correct data", res.get(SECRET_DATA_K1), is(SECRET_DATA_V1));
assertThat("Response does not contain correct data", res.get(SECRET_DATA_K2), is(SECRET_DATA_V2));
assertNotNull(res, "Parsed response is NULL");
assertEquals(SECRET_LEASE_ID, res.getLeaseId(), "Incorrect lease ID");
assertEquals(SECRET_LEASE_DURATION, res.getLeaseDuration(), "Incorrect lease duration");
assertEquals(SECRET_RENEWABLE, res.isRenewable(), "Incorrect renewable status");
assertEquals(SECRET_WARNINGS, res.getWarnings(), "Incorrect warnings");
assertEquals(SECRET_DATA_V1, res.get(SECRET_DATA_K1), "Response does not contain correct data");
assertEquals(SECRET_DATA_V2, res.get(SECRET_DATA_K2), "Response does not contain correct data");
}
}

View File

@ -19,10 +19,7 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link SecretVersionResponse} model.
@ -53,11 +50,11 @@ class SecretVersionResponseTest {
() -> new ObjectMapper().readValue(META_JSON, SecretVersionResponse.class),
"SecretVersionResponse deserialization failed"
);
assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Parsed metadata is NULL", res.getMetadata(), is(notNullValue()));
assertThat("Incorrect created time", res.getMetadata().getCreatedTimeString(), is(CREATION_TIME));
assertThat("Incorrect deletion time", res.getMetadata().getDeletionTimeString(), is(DELETION_TIME));
assertThat("Incorrect destroyed state", res.getMetadata().isDestroyed(), is(false));
assertThat("Incorrect version", res.getMetadata().getVersion(), is(VERSION));
assertNotNull(res, "Parsed response is NULL");
assertNotNull(res.getMetadata(), "Parsed metadata is NULL");
assertEquals(CREATION_TIME, res.getMetadata().getCreatedTimeString(), "Incorrect created time");
assertEquals(DELETION_TIME, res.getMetadata().getDeletionTimeString(), "Incorrect deletion time");
assertEquals(false, res.getMetadata().isDestroyed(), "Incorrect destroyed state");
assertEquals(VERSION, res.getMetadata().getVersion(), "Incorrect version");
}
}

View File

@ -23,12 +23,10 @@ import org.junit.jupiter.api.Test;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.*;
/**
* JUnit Test for {@link TokenResponse} model.
@ -104,7 +102,7 @@ class TokenResponseTest {
void getDataRoundtrip() {
// Create empty Object.
TokenResponse res = new TokenResponse();
assertThat("Initial data should be empty", res.getData(), is(nullValue()));
assertNull(res.getData(), "Initial data should be empty");
// Parsing invalid data map should fail.
assertThrows(
@ -123,33 +121,33 @@ class TokenResponseTest {
() -> new ObjectMapper().readValue(RES_JSON, TokenResponse.class),
"TokenResponse deserialization failed."
);
assertThat("Parsed response is NULL", res, is(notNullValue()));
assertThat("Incorrect lease duration", res.getLeaseDuration(), is(RES_LEASE_DURATION));
assertThat("Incorrect response renewable flag", res.isRenewable(), is(RES_RENEWABLE));
assertThat("Incorrect response lease duration", res.getLeaseDuration(), is(RES_LEASE_DURATION));
assertNotNull(res, "Parsed response is NULL");
assertEquals(RES_LEASE_DURATION, res.getLeaseDuration(), "Incorrect lease duration");
assertEquals(RES_RENEWABLE, res.isRenewable(), "Incorrect response renewable flag");
assertEquals(RES_LEASE_DURATION, res.getLeaseDuration(), "Incorrect response lease duration");
// Extract token data.
TokenData data = res.getData();
assertThat("Token data is NULL", data, is(notNullValue()));
assertThat("Incorrect token accessor", data.getAccessor(), is(TOKEN_ACCESSOR));
assertThat("Incorrect token creation time", data.getCreationTime(), is(TOKEN_CREATION_TIME));
assertThat("Incorrect token creation TTL", data.getCreationTtl(), is(TOKEN_TTL));
assertThat("Incorrect token display name", data.getName(), is(TOKEN_DISPLAY_NAME));
assertThat("Incorrect token entity ID", data.getEntityId(), is(TOKEN_ENTITY_ID));
assertThat("Incorrect token expire time", data.getExpireTimeString(), is(TOKEN_EXPIRE_TIME));
assertThat("Incorrect parsed token expire time", data.getExpireTime(), is(ZonedDateTime.parse(TOKEN_EXPIRE_TIME)));
assertThat("Incorrect token explicit max TTL", data.getExplicitMaxTtl(), is(TOKEN_EXPLICIT_MAX_TTL));
assertThat("Incorrect token ID", data.getId(), is(TOKEN_ID));
assertThat("Incorrect token issue time", data.getIssueTimeString(), is(TOKEN_ISSUE_TIME));
assertThat("Incorrect parsed token issue time", data.getIssueTime(), is(ZonedDateTime.parse(TOKEN_ISSUE_TIME)));
assertThat("Incorrect token metadata size", data.getMeta().entrySet(), hasSize(1));
assertThat("Incorrect token metadata", data.getMeta().get(TOKEN_META_KEY), is(TOKEN_META_VALUE));
assertThat("Incorrect token number of uses", data.getNumUses(), is(TOKEN_NUM_USES));
assertThat("Incorrect token orphan flag", data.isOrphan(), is(TOKEN_ORPHAN));
assertThat("Incorrect token path", data.getPath(), is(TOKEN_PATH));
assertThat("Incorrect number of token policies", data.getPolicies(), hasSize(2));
assertThat("Incorrect token policies", data.getPolicies(), contains(TOKEN_POLICY_1, TOKEN_POLICY_2));
assertThat("Incorrect token renewable flag", data.isRenewable(), is(TOKEN_RENEWABLE));
assertThat("Incorrect token TTL", data.getTtl(), is(RES_TTL));
assertThat("Incorrect token type", data.getType(), is(TOKEN_TYPE));
assertNotNull(data, "Token data is NULL");
assertEquals(TOKEN_ACCESSOR, data.getAccessor(), "Incorrect token accessor");
assertEquals(TOKEN_CREATION_TIME, data.getCreationTime(), "Incorrect token creation time");
assertEquals(TOKEN_TTL, data.getCreationTtl(), "Incorrect token creation TTL");
assertEquals(TOKEN_DISPLAY_NAME, data.getName(), "Incorrect token display name");
assertEquals(TOKEN_ENTITY_ID, data.getEntityId(), "Incorrect token entity ID");
assertEquals(TOKEN_EXPIRE_TIME, data.getExpireTimeString(), "Incorrect token expire time");
assertEquals(ZonedDateTime.parse(TOKEN_EXPIRE_TIME), data.getExpireTime(), "Incorrect parsed token expire time");
assertEquals(TOKEN_EXPLICIT_MAX_TTL, data.getExplicitMaxTtl(), "Incorrect token explicit max TTL");
assertEquals(TOKEN_ID, data.getId(), "Incorrect token ID");
assertEquals(TOKEN_ISSUE_TIME, data.getIssueTimeString(), "Incorrect token issue time");
assertEquals(ZonedDateTime.parse(TOKEN_ISSUE_TIME), data.getIssueTime(), "Incorrect parsed token issue time");
assertEquals(1, data.getMeta().size(), "Incorrect token metadata size");
assertEquals(TOKEN_META_VALUE, data.getMeta().get(TOKEN_META_KEY), "Incorrect token metadata");
assertEquals(TOKEN_NUM_USES, data.getNumUses(), "Incorrect token number of uses");
assertEquals(TOKEN_ORPHAN, data.isOrphan(), "Incorrect token orphan flag");
assertEquals(TOKEN_PATH, data.getPath(), "Incorrect token path");
assertEquals(2, data.getPolicies().size(), "Incorrect number of token policies");
assertTrue(data.getPolicies().containsAll(List.of(TOKEN_POLICY_1, TOKEN_POLICY_2)), "Incorrect token policies");
assertEquals(TOKEN_RENEWABLE, data.isRenewable(), "Incorrect token renewable flag");
assertEquals(RES_TTL, data.getTtl(), "Incorrect token TTL");
assertEquals(TOKEN_TYPE, data.getType(), "Incorrect token type");
}
}

View File

@ -21,8 +21,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Simple credentials class for JSON testing.
*
* @author Stefan Kalscheuer
* @since 0.1
* @author Stefan Kalscheuer
* @since 0.1
*/
public class Credentials {
@JsonProperty("username")