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> <version>5.7.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>

View File

@ -49,14 +49,14 @@ class HTTPVaultConnectorBuilderTest {
*/ */
@Test @Test
void builderTest() throws Exception { void builderTest() throws Exception {
/* Minimal configuration */ // Minimal configuration.
HTTPVaultConnector connector = HTTPVaultConnector.builder().withHost("vault.example.com").build(); HTTPVaultConnector connector = HTTPVaultConnector.builder().withHost("vault.example.com").build();
assertEquals("https://vault.example.com:8200/v1/", getRequestHelperPrivate(connector, "baseURL"), "URL not set correctly"); 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"); assertNull(getRequestHelperPrivate(connector, "trustedCaCert"), "Trusted CA cert set when no cert provided");
assertEquals(0, getRequestHelperPrivate(connector, "retries"), "Number of retries unexpectedly set"); assertEquals(0, getRequestHelperPrivate(connector, "retries"), "Number of retries unexpectedly set");
/* Specify all options */ // Specify all options.
HTTPVaultConnectorBuilder builder = HTTPVaultConnector.builder() HTTPVaultConnectorBuilder builder = HTTPVaultConnector.builder()
.withHost("vault2.example.com") .withHost("vault2.example.com")
.withoutTLS() .withoutTLS()
@ -72,7 +72,7 @@ class HTTPVaultConnectorBuilderTest {
assertEquals(5678, getRequestHelperPrivate(connector, "timeout"), "Number timeout value"); assertEquals(5678, getRequestHelperPrivate(connector, "timeout"), "Number timeout value");
assertThrows(ConnectionException.class, builder::buildAndAuth, "Immediate authentication should throw exception without token"); assertThrows(ConnectionException.class, builder::buildAndAuth, "Immediate authentication should throw exception without token");
/* Initialization from URL */ // Initialization from URL.
assertThrows( assertThrows(
URISyntaxException.class, URISyntaxException.class,
() -> HTTPVaultConnector.builder().withBaseURL("foo:/\\1nv4l1d_UrL"), () -> 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"); 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(65536), "Too large port number should throw an exception");
assertThrows(IllegalArgumentException.class, () -> HTTPVaultConnector.builder().withPort(0), "Port number 0 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"); builder = assertDoesNotThrow(() -> HTTPVaultConnector.builder().withPort(-1), "Port number -1 should not throw an exception");
@ -96,7 +96,7 @@ class HTTPVaultConnectorBuilderTest {
*/ */
@Test @Test
void testFromEnv() throws Exception { void testFromEnv() throws Exception {
/* Provide address only should be enough */ // Provide address only should be enough.
withVaultEnv(VAULT_ADDR, null, null, null).execute(() -> { withVaultEnv(VAULT_ADDR, null, null, null).execute(() -> {
HTTPVaultConnectorBuilder builder = assertDoesNotThrow( HTTPVaultConnectorBuilder builder = assertDoesNotThrow(
() -> HTTPVaultConnector.builder().fromEnv(), () -> HTTPVaultConnector.builder().fromEnv(),
@ -111,7 +111,7 @@ class HTTPVaultConnectorBuilderTest {
return null; return null;
}); });
/* Provide address and number of retries */ // Provide address and number of retries.
withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null).execute(() -> { withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null).execute(() -> {
HTTPVaultConnectorBuilder builder = assertDoesNotThrow( HTTPVaultConnectorBuilder builder = assertDoesNotThrow(
() -> HTTPVaultConnector.builder().fromEnv(), () -> HTTPVaultConnector.builder().fromEnv(),
@ -126,7 +126,7 @@ class HTTPVaultConnectorBuilderTest {
return null; return null;
}); });
/* Provide CA certificate */ // Provide CA certificate.
String VAULT_CACERT = tempDir.toString() + "/doesnotexist"; String VAULT_CACERT = tempDir.toString() + "/doesnotexist";
withVaultEnv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null).execute(() -> { withVaultEnv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null).execute(() -> {
TlsException e = assertThrows( TlsException e = assertThrows(
@ -140,7 +140,7 @@ class HTTPVaultConnectorBuilderTest {
return null; return null;
}); });
/* Automatic authentication */ // Automatic authentication.
withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN).execute(() -> { withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN).execute(() -> {
HTTPVaultConnectorBuilder builder = assertDoesNotThrow( HTTPVaultConnectorBuilder builder = assertDoesNotThrow(
() -> HTTPVaultConnector.builder().fromEnv(), () -> HTTPVaultConnector.builder().fromEnv(),
@ -151,7 +151,7 @@ class HTTPVaultConnectorBuilderTest {
return null; return null;
}); });
/* Invalid URL */ // Invalid URL.
withVaultEnv("This is not a valid URL!", null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN).execute(() -> { withVaultEnv("This is not a valid URL!", null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN).execute(() -> {
assertThrows( assertThrows(
ConnectionException.class, 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.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.jupiter.api.Assertions.*;
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;
/** /**
* JUnit test for HTTP Vault connector. * JUnit test for HTTP Vault connector.
@ -86,9 +81,9 @@ class HTTPVaultConnectorOfflineTest {
connector::getHealth, connector::getHealth,
"Querying health status succeeded on invalid instance" "Querying health status succeeded on invalid instance"
); );
assertThat("Unexpected exception message", e.getMessage(), is("Invalid response code")); assertEquals("Invalid response code", e.getMessage(), "Unexpected exception message");
assertThat("Unexpected status code in exception", ((InvalidResponseException) e).getStatusCode(), is(responseCode)); assertEquals(responseCode, ((InvalidResponseException) e).getStatusCode(), "Unexpected status code in exception");
assertThat("Response message where none was expected", ((InvalidResponseException) e).getResponse(), is(nullValue())); assertNull(((InvalidResponseException) e).getResponse(), "Response message where none was expected");
// Simulate permission denied response. // Simulate permission denied response.
mockHttpResponse(responseCode, "{\"errors\":[\"permission denied\"]}", "application/json"); mockHttpResponse(responseCode, "{\"errors\":[\"permission denied\"]}", "application/json");
@ -107,8 +102,8 @@ class HTTPVaultConnectorOfflineTest {
connector::getHealth, connector::getHealth,
"Querying health status succeeded on invalid instance" "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");
assertThat("Unexpected cause", e.getCause(), instanceOf(IOException.class)); assertTrue(e.getCause() instanceof IOException, "Unexpected cause");
// Now simulate a failing request that succeeds on second try. // Now simulate a failing request that succeeds on second try.
connector = HTTPVaultConnector.builder(wireMock.url("/")).withNumberOfRetries(1).withTimeout(250).build(); connector = HTTPVaultConnector.builder(wireMock.url("/")).withNumberOfRetries(1).withTimeout(250).build();
@ -144,30 +139,30 @@ class HTTPVaultConnectorOfflineTest {
// Most basic constructor expects complete URL. // Most basic constructor expects complete URL.
HTTPVaultConnector connector = HTTPVaultConnector.builder(url).build(); 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. // Now override TLS usage.
connector = HTTPVaultConnector.builder().withHost(hostname).withoutTLS().build(); 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. // Specify custom port.
connector = HTTPVaultConnector.builder().withHost(hostname).withTLS().withPort(port).build(); 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. // Specify custom prefix.
connector = HTTPVaultConnector.builder().withHost(hostname).withTLS().withPort(port).withPrefix(prefix).build(); connector = HTTPVaultConnector.builder().withHost(hostname).withTLS().withPort(port).withPrefix(prefix).build();
assertThat("Unexpected base URL with custom prefix", getRequestHelperPrivate(connector, "baseURL"), is(expectedCustomPrefix)); assertEquals(expectedCustomPrefix, getRequestHelperPrivate(connector, "baseURL"), "Unexpected base URL with custom prefix");
assertThat("Trusted CA cert set, but not specified", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue())); assertNull(getRequestHelperPrivate(connector, "trustedCaCert"), "Trusted CA cert set, but not specified");
// Specify number of retries. // Specify number of retries.
connector = HTTPVaultConnector.builder(url).withTrustedCA(trustedCaCert).withNumberOfRetries(retries).build(); 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). // 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. // Now override.
connector = HTTPVaultConnector.builder(url).withTrustedCA(trustedCaCert).withNumberOfRetries(retries).withTLS("TLSv1.1").build(); 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, connector::sealStatus,
"Querying seal status succeeded on invalid instance" "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, connector::getHealth,
"Querying health status succeeded on invalid instance" "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) { private void assertParseError(Executable executable, String message) {
InvalidResponseException e = assertThrows(InvalidResponseException.class, executable, 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 org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.hamcrest.Matchers.instanceOf; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
/** /**
* Common JUnit test for Exceptions extending {@link VaultConnectorException}. * Common JUnit test for Exceptions extending {@link VaultConnectorException}.
@ -65,42 +63,39 @@ class VaultConnectorExceptionTest {
// Constructor with message and status code. // Constructor with message and status code.
InvalidResponseException e = new InvalidResponseException(MSG, STATUS_CODE); InvalidResponseException e = new InvalidResponseException(MSG, STATUS_CODE);
assertThat(e.getMessage(), is(MSG)); assertEquals(MSG, e.getMessage());
assertThat(e.getCause(), is(nullValue())); assertNull(e.getCause());
assertThat(e.getStatusCode(), is(STATUS_CODE)); assertEquals(STATUS_CODE, e.getStatusCode());
assertThat(e.getResponse(), is(nullValue())); assertNull(e.getResponse());
// Constructor with message, status code and cause. // Constructor with message, status code and cause.
e = new InvalidResponseException(MSG, STATUS_CODE, CAUSE); e = new InvalidResponseException(MSG, STATUS_CODE, CAUSE);
assertThat(e.getMessage(), is(MSG)); assertEquals(MSG, e.getMessage());
assertThat(e.getCause(), is(CAUSE)); assertEquals(CAUSE, e.getCause());
assertThat(e.getStatusCode(), is(STATUS_CODE)); assertEquals(STATUS_CODE, e.getStatusCode());
assertThat(e.getResponse(), is(nullValue())); assertNull(e.getResponse());
// Constructor with message, status code and response. // Constructor with message, status code and response.
e = new InvalidResponseException(MSG, STATUS_CODE, RESPONSE); e = new InvalidResponseException(MSG, STATUS_CODE, RESPONSE);
assertThat(e.getMessage(), is(MSG)); assertEquals(MSG, e.getMessage());
assertThat(e.getCause(), is(nullValue())); assertNull(e.getCause());
assertThat(e.getStatusCode(), is(STATUS_CODE)); assertEquals(STATUS_CODE, e.getStatusCode());
assertThat(e.getResponse(), is(RESPONSE)); assertEquals(RESPONSE, e.getResponse());
// Constructor with message, status code, response and cause. // Constructor with message, status code, response and cause.
e = new InvalidResponseException(MSG, STATUS_CODE, RESPONSE, CAUSE); e = new InvalidResponseException(MSG, STATUS_CODE, RESPONSE, CAUSE);
assertThat(e.getMessage(), is(MSG)); assertEquals(MSG, e.getMessage());
assertThat(e.getCause(), is(CAUSE)); assertEquals(CAUSE, e.getCause());
assertThat(e.getStatusCode(), is(STATUS_CODE)); assertEquals(STATUS_CODE, e.getStatusCode());
assertThat(e.getResponse(), is(RESPONSE)); assertEquals(RESPONSE, e.getResponse());
} }
@Test @Test
void permissionDeniedExceptionTest() { void permissionDeniedExceptionTest() {
// Default message overwritten. // Default message overwritten.
PermissionDeniedException e = new PermissionDeniedException(); PermissionDeniedException e = new PermissionDeniedException();
assertThat(e, is(instanceOf(VaultConnectorException.class))); assertEquals("Permission denied", e.getMessage());
assertThat(e, is(instanceOf(Exception.class))); assertNull(e.getCause());
assertThat(e, is(instanceOf(Throwable.class)));
assertThat(e.getMessage(), is("Permission denied"));
assertThat(e.getCause(), is(nullValue()));
assertMsgConstructor(new PermissionDeniedException(MSG)); assertMsgConstructor(new PermissionDeniedException(MSG));
assertCauseConstructor(new PermissionDeniedException(CAUSE)); assertCauseConstructor(new PermissionDeniedException(CAUSE));
@ -121,11 +116,8 @@ class VaultConnectorExceptionTest {
* @param e the exception * @param e the exception
*/ */
private void assertEmptyConstructor(VaultConnectorException e) { private void assertEmptyConstructor(VaultConnectorException e) {
assertThat(e, is(instanceOf(VaultConnectorException.class))); assertNull(e.getMessage());
assertThat(e, is(instanceOf(Exception.class))); assertNull(e.getCause());
assertThat(e, is(instanceOf(Throwable.class)));
assertThat(e.getMessage(), is(nullValue()));
assertThat(e.getCause(), is(nullValue()));
} }
/** /**
@ -134,8 +126,8 @@ class VaultConnectorExceptionTest {
* @param e the exception * @param e the exception
*/ */
private void assertMsgConstructor(VaultConnectorException e) { private void assertMsgConstructor(VaultConnectorException e) {
assertThat(e.getMessage(), is(MSG)); assertEquals(MSG, e.getMessage());
assertThat(e.getCause(), is(nullValue())); assertNull(e.getCause());
} }
/** /**
@ -144,8 +136,8 @@ class VaultConnectorExceptionTest {
* @param e the exception * @param e the exception
*/ */
private void assertCauseConstructor(VaultConnectorException e) { private void assertCauseConstructor(VaultConnectorException e) {
assertThat(e.getMessage(), is(CAUSE.toString())); assertEquals(CAUSE.toString(), e.getMessage());
assertThat(e.getCause(), is(CAUSE)); assertEquals(CAUSE, e.getCause());
} }
/** /**
@ -154,7 +146,7 @@ class VaultConnectorExceptionTest {
* @param e the exception * @param e the exception
*/ */
private void assertMsgCauseConstructor(VaultConnectorException e) { private void assertMsgCauseConstructor(VaultConnectorException e) {
assertThat(e.getMessage(), is(MSG)); assertEquals(MSG, e.getMessage());
assertThat(e.getCause(), is(CAUSE)); assertEquals(CAUSE, e.getCause());
} }
} }

View File

@ -25,9 +25,7 @@ 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.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue;
@ -38,7 +36,6 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue;
* @since 0.5.0 * @since 0.5.0
*/ */
class AppRoleSecretTest { class AppRoleSecretTest {
private static final String TEST_ID = "abc123"; private static final String TEST_ID = "abc123";
private static final Map<String, Object> TEST_META = new HashMap<>(); 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"); 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 @Test
void constructorTest() { void constructorTest() {
/* Empty constructor */ // Empty constructor.
AppRoleSecret secret = new AppRoleSecret(); AppRoleSecret secret = new AppRoleSecret();
assertThat(secret.getId(), is(nullValue())); assertNull(secret.getId());
assertThat(secret.getAccessor(), is(nullValue())); assertNull(secret.getAccessor());
assertThat(secret.getMetadata(), is(nullValue())); assertNull(secret.getMetadata());
assertThat(secret.getCidrList(), is(nullValue())); assertNull(secret.getCidrList());
assertThat(secret.getCidrListString(), is(emptyString())); assertEquals("", secret.getCidrListString());
assertThat(secret.getCreationTime(), is(nullValue())); assertNull(secret.getCreationTime());
assertThat(secret.getExpirationTime(), is(nullValue())); assertNull(secret.getExpirationTime());
assertThat(secret.getLastUpdatedTime(), is(nullValue())); assertNull(secret.getLastUpdatedTime());
assertThat(secret.getNumUses(), is(nullValue())); assertNull(secret.getNumUses());
assertThat(secret.getTtl(), is(nullValue())); assertNull(secret.getTtl());
/* Constructor with ID */ // Constructor with ID.
secret = new AppRoleSecret(TEST_ID); secret = new AppRoleSecret(TEST_ID);
assertThat(secret.getId(), is(TEST_ID)); assertEquals(TEST_ID, secret.getId());
assertThat(secret.getAccessor(), is(nullValue())); assertNull(secret.getAccessor());
assertThat(secret.getMetadata(), is(nullValue())); assertNull(secret.getMetadata());
assertThat(secret.getCidrList(), is(nullValue())); assertNull(secret.getCidrList());
assertThat(secret.getCidrListString(), is(emptyString())); assertEquals("", secret.getCidrListString());
assertThat(secret.getCreationTime(), is(nullValue())); assertNull(secret.getCreationTime());
assertThat(secret.getExpirationTime(), is(nullValue())); assertNull(secret.getExpirationTime());
assertThat(secret.getLastUpdatedTime(), is(nullValue())); assertNull(secret.getLastUpdatedTime());
assertThat(secret.getNumUses(), is(nullValue())); assertNull(secret.getNumUses());
assertThat(secret.getTtl(), is(nullValue())); assertNull(secret.getTtl());
/* Constructor with Metadata and CIDR bindings */ // Constructor with Metadata and CIDR bindings.
secret = new AppRoleSecret(TEST_ID, TEST_META, TEST_CIDR); secret = new AppRoleSecret(TEST_ID, TEST_META, TEST_CIDR);
assertThat(secret.getId(), is(TEST_ID)); assertEquals(TEST_ID, secret.getId());
assertThat(secret.getAccessor(), is(nullValue())); assertNull(secret.getAccessor());
assertThat(secret.getMetadata(), is(TEST_META)); assertEquals(TEST_META, secret.getMetadata());
assertThat(secret.getCidrList(), is(TEST_CIDR)); assertEquals(TEST_CIDR, secret.getCidrList());
assertThat(secret.getCidrListString(), is(String.join(",", TEST_CIDR))); assertEquals(String.join(",", TEST_CIDR), secret.getCidrListString());
assertThat(secret.getCreationTime(), is(nullValue())); assertNull(secret.getCreationTime());
assertThat(secret.getExpirationTime(), is(nullValue())); assertNull(secret.getExpirationTime());
assertThat(secret.getLastUpdatedTime(), is(nullValue())); assertNull(secret.getLastUpdatedTime());
assertThat(secret.getNumUses(), is(nullValue())); assertNull(secret.getNumUses());
assertThat(secret.getTtl(), is(nullValue())); assertNull(secret.getTtl());
} }
/** /**
@ -99,14 +96,14 @@ class AppRoleSecretTest {
@Test @Test
void setterTest() { void setterTest() {
AppRoleSecret secret = new AppRoleSecret(TEST_ID); AppRoleSecret secret = new AppRoleSecret(TEST_ID);
assertThat(secret.getCidrList(), is(nullValue())); assertNull(secret.getCidrList());
assertThat(secret.getCidrListString(), is(emptyString())); assertEquals("", secret.getCidrListString());
secret.setCidrList(TEST_CIDR); secret.setCidrList(TEST_CIDR);
assertThat(secret.getCidrList(), is(TEST_CIDR)); assertEquals(TEST_CIDR, secret.getCidrList());
assertThat(secret.getCidrListString(), is(String.join(",", TEST_CIDR))); assertEquals(String.join(",", TEST_CIDR), secret.getCidrListString());
secret.setCidrList(null); secret.setCidrList(null);
assertThat(secret.getCidrList(), is(nullValue())); assertNull(secret.getCidrList());
assertThat(secret.getCidrListString(), is(emptyString())); assertEquals("", secret.getCidrListString());
} }
/** /**
@ -116,21 +113,21 @@ class AppRoleSecretTest {
void jsonTest() throws NoSuchFieldException, IllegalAccessException { void jsonTest() throws NoSuchFieldException, IllegalAccessException {
ObjectMapper mapper = new ObjectMapper(); 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); AppRoleSecret secret = new AppRoleSecret(TEST_ID, TEST_META, TEST_CIDR);
String secretJson = assertDoesNotThrow(() -> mapper.writeValueAsString(secret), "Serialization failed"); 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); String secretJson2 = commaSeparatedToList(secretJson);
AppRoleSecret secret2 = assertDoesNotThrow( AppRoleSecret secret2 = assertDoesNotThrow(
() -> mapper.readValue(secretJson2, AppRoleSecret.class), () -> mapper.readValue(secretJson2, AppRoleSecret.class),
"Deserialization failed" "Deserialization failed"
); );
assertThat(secret.getId(), is(secret2.getId())); assertEquals(secret2.getId(), secret.getId());
assertThat(secret.getMetadata(), is(secret2.getMetadata())); assertEquals(secret2.getMetadata(), secret.getMetadata());
assertThat(secret.getCidrList(), is(secret2.getCidrList())); 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"); setPrivateField(secret, "accessor", "TEST_ACCESSOR");
assumeTrue("TEST_ACCESSOR".equals(secret.getAccessor())); assumeTrue("TEST_ACCESSOR".equals(secret.getAccessor()));
setPrivateField(secret, "creationTime", "TEST_CREATION"); setPrivateField(secret, "creationTime", "TEST_CREATION");
@ -148,28 +145,28 @@ class AppRoleSecretTest {
() -> mapper.readValue(commaSeparatedToList(secretJson3), AppRoleSecret.class), () -> mapper.readValue(commaSeparatedToList(secretJson3), AppRoleSecret.class),
"Deserialization failed" "Deserialization failed"
); );
assertThat(secret.getId(), is(secret2.getId())); assertEquals(secret2.getId(), secret.getId());
assertThat(secret.getMetadata(), is(secret2.getMetadata())); assertEquals(secret2.getMetadata(), secret.getMetadata());
assertThat(secret.getCidrList(), is(secret2.getCidrList())); assertEquals(secret2.getCidrList(), secret.getCidrList());
assertThat(secret2.getAccessor(), is(nullValue())); assertNull(secret2.getAccessor());
assertThat(secret2.getCreationTime(), is(nullValue())); assertNull(secret2.getCreationTime());
assertThat(secret2.getExpirationTime(), is(nullValue())); assertNull(secret2.getExpirationTime());
assertThat(secret2.getLastUpdatedTime(), is(nullValue())); assertNull(secret2.getLastUpdatedTime());
assertThat(secret2.getNumUses(), is(nullValue())); assertNull(secret2.getNumUses());
assertThat(secret2.getTtl(), is(nullValue())); 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\"}," + 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}";
secret2 = assertDoesNotThrow(() -> mapper.readValue(secretJson4, AppRoleSecret.class), "Deserialization failed"); secret2 = assertDoesNotThrow(() -> mapper.readValue(secretJson4, AppRoleSecret.class), "Deserialization failed");
assertThat(secret2.getAccessor(), is("TEST_ACCESSOR")); assertEquals("TEST_ACCESSOR", secret2.getAccessor());
assertThat(secret2.getCreationTime(), is("TEST_CREATION")); assertEquals("TEST_CREATION", secret2.getCreationTime());
assertThat(secret2.getExpirationTime(), is("TEST_EXPIRATION")); assertEquals("TEST_EXPIRATION", secret2.getExpirationTime());
assertThat(secret2.getLastUpdatedTime(), is("TEST_LASTUPDATE")); assertEquals("TEST_LASTUPDATE", secret2.getLastUpdatedTime());
assertThat(secret2.getNumUses(), is(678)); assertEquals(678, secret2.getNumUses());
assertThat(secret2.getTtl(), is(12345)); assertEquals(12345, secret2.getTtl());
} }

View File

@ -24,8 +24,7 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
/** /**
* JUnit Test for {@link AppRole} and {@link AppRole.Builder}. * JUnit Test for {@link AppRole} and {@link AppRole.Builder}.
@ -69,24 +68,24 @@ class AppRoleTest {
@Test @Test
void buildDefaultTest() throws JsonProcessingException { void buildDefaultTest() throws JsonProcessingException {
AppRole role = AppRole.builder(NAME).build(); AppRole role = AppRole.builder(NAME).build();
assertThat(role.getId(), is(nullValue())); assertNull(role.getId());
assertThat(role.getBindSecretId(), is(nullValue())); assertNull(role.getBindSecretId());
assertThat(role.getSecretIdBoundCidrs(), is(nullValue())); assertNull(role.getSecretIdBoundCidrs());
assertThat(role.getTokenPolicies(), is(nullValue())); assertNull(role.getTokenPolicies());
assertThat(role.getSecretIdNumUses(), is(nullValue())); assertNull(role.getSecretIdNumUses());
assertThat(role.getSecretIdTtl(), is(nullValue())); assertNull(role.getSecretIdTtl());
assertThat(role.getEnableLocalSecretIds(), is(nullValue())); assertNull(role.getEnableLocalSecretIds());
assertThat(role.getTokenTtl(), is(nullValue())); assertNull(role.getTokenTtl());
assertThat(role.getTokenMaxTtl(), is(nullValue())); assertNull(role.getTokenMaxTtl());
assertThat(role.getTokenBoundCidrs(), is(nullValue())); assertNull(role.getTokenBoundCidrs());
assertThat(role.getTokenExplicitMaxTtl(), is(nullValue())); assertNull(role.getTokenExplicitMaxTtl());
assertThat(role.getTokenNoDefaultPolicy(), is(nullValue())); assertNull(role.getTokenNoDefaultPolicy());
assertThat(role.getTokenNumUses(), is(nullValue())); assertNull(role.getTokenNumUses());
assertThat(role.getTokenPeriod(), is(nullValue())); assertNull(role.getTokenPeriod());
assertThat(role.getTokenType(), is(nullValue())); assertNull(role.getTokenType());
/* optional fields should be ignored, so JSON string should only contain role_name */ // Optional fields should be ignored, so JSON string should only contain role_name.
assertThat(new ObjectMapper().writeValueAsString(role), is(JSON_MIN)); assertEquals(JSON_MIN, new ObjectMapper().writeValueAsString(role));
} }
/** /**
@ -111,25 +110,25 @@ class AppRoleTest {
.withTokenPeriod(TOKEN_PERIOD) .withTokenPeriod(TOKEN_PERIOD)
.withTokenType(TOKEN_TYPE) .withTokenType(TOKEN_TYPE)
.build(); .build();
assertThat(role.getName(), is(NAME)); assertEquals(NAME, role.getName());
assertThat(role.getId(), is(ID)); assertEquals(ID, role.getId());
assertThat(role.getBindSecretId(), is(BIND_SECRET_ID)); assertEquals(BIND_SECRET_ID, role.getBindSecretId());
assertThat(role.getSecretIdBoundCidrs(), is(BOUND_CIDR_LIST)); assertEquals(BOUND_CIDR_LIST, role.getSecretIdBoundCidrs());
assertThat(role.getTokenPolicies(), is(POLICIES)); assertEquals(POLICIES, role.getTokenPolicies());
assertThat(role.getSecretIdNumUses(), is(SECRET_ID_NUM_USES)); assertEquals(SECRET_ID_NUM_USES, role.getSecretIdNumUses());
assertThat(role.getSecretIdTtl(), is(SECRET_ID_TTL)); assertEquals(SECRET_ID_TTL, role.getSecretIdTtl());
assertThat(role.getEnableLocalSecretIds(), is(ENABLE_LOCAL_SECRET_IDS)); assertEquals(ENABLE_LOCAL_SECRET_IDS, role.getEnableLocalSecretIds());
assertThat(role.getTokenTtl(), is(TOKEN_TTL)); assertEquals(TOKEN_TTL, role.getTokenTtl());
assertThat(role.getTokenMaxTtl(), is(TOKEN_MAX_TTL)); assertEquals(TOKEN_MAX_TTL, role.getTokenMaxTtl());
assertThat(role.getTokenBoundCidrs(), is(BOUND_CIDR_LIST)); assertEquals(BOUND_CIDR_LIST, role.getTokenBoundCidrs());
assertThat(role.getTokenExplicitMaxTtl(), is(TOKEN_EXPLICIT_MAX_TTL)); assertEquals(TOKEN_EXPLICIT_MAX_TTL, role.getTokenExplicitMaxTtl());
assertThat(role.getTokenNoDefaultPolicy(), is(TOKEN_NO_DEFAULT_POLICY)); assertEquals(TOKEN_NO_DEFAULT_POLICY, role.getTokenNoDefaultPolicy());
assertThat(role.getTokenNumUses(), is(TOKEN_NUM_USES)); assertEquals(TOKEN_NUM_USES, role.getTokenNumUses());
assertThat(role.getTokenPeriod(), is(TOKEN_PERIOD)); assertEquals(TOKEN_PERIOD, role.getTokenPeriod());
assertThat(role.getTokenType(), is(TOKEN_TYPE.value())); assertEquals(TOKEN_TYPE.value(), role.getTokenType());
/* Verify that all parameters are included in JSON string */ // Verify that all parameters are included in JSON string.
assertThat(new ObjectMapper().writeValueAsString(role), is(JSON_FULL)); assertEquals(JSON_FULL, new ObjectMapper().writeValueAsString(role));
} }
/** /**
@ -137,40 +136,40 @@ class AppRoleTest {
*/ */
@Test @Test
void convenienceMethodsTest() { void convenienceMethodsTest() {
/* bind_secret_id */ // bind_secret_id.
AppRole role = AppRole.builder(NAME).build(); AppRole role = AppRole.builder(NAME).build();
assertThat(role.getBindSecretId(), is(nullValue())); assertNull(role.getBindSecretId());
role = AppRole.builder(NAME).withBindSecretID().build(); role = AppRole.builder(NAME).withBindSecretID().build();
assertThat(role.getBindSecretId(), is(true)); assertEquals(true, role.getBindSecretId());
role = AppRole.builder(NAME).withoutBindSecretID().build(); 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(); role = AppRole.builder(NAME).withSecretBoundCidr(CIDR_2).withTokenBoundCidr(CIDR_2).build();
assertThat(role.getSecretIdBoundCidrs(), hasSize(1)); assertEquals(1, role.getSecretIdBoundCidrs().size());
assertThat(role.getSecretIdBoundCidrs(), contains(CIDR_2)); assertEquals(CIDR_2, role.getSecretIdBoundCidrs().get(0));
assertThat(role.getTokenBoundCidrs(), hasSize(1)); assertEquals(1, role.getTokenBoundCidrs().size());
assertThat(role.getTokenBoundCidrs(), contains(CIDR_2)); assertEquals(CIDR_2, role.getTokenBoundCidrs().get(0));
role = AppRole.builder(NAME) role = AppRole.builder(NAME)
.withSecretIdBoundCidrs(BOUND_CIDR_LIST) .withSecretIdBoundCidrs(BOUND_CIDR_LIST)
.withSecretBoundCidr(CIDR_2) .withSecretBoundCidr(CIDR_2)
.withTokenBoundCidrs(BOUND_CIDR_LIST) .withTokenBoundCidrs(BOUND_CIDR_LIST)
.withTokenBoundCidr(CIDR_2) .withTokenBoundCidr(CIDR_2)
.build(); .build();
assertThat(role.getSecretIdBoundCidrs(), hasSize(2)); assertEquals(2, role.getSecretIdBoundCidrs().size());
assertThat(role.getSecretIdBoundCidrs(), contains(CIDR_1, CIDR_2)); assertTrue(role.getSecretIdBoundCidrs().containsAll(List.of(CIDR_1, CIDR_2)));
assertThat(role.getTokenBoundCidrs(), hasSize(2)); assertEquals(2, role.getTokenBoundCidrs().size());
assertThat(role.getSecretIdBoundCidrs(), contains(CIDR_1, CIDR_2)); assertTrue(role.getSecretIdBoundCidrs().containsAll(List.of(CIDR_1, CIDR_2)));
/* Add single policy */ // Add single policy.
role = AppRole.builder(NAME).withTokenPolicy(POLICY_2).build(); role = AppRole.builder(NAME).withTokenPolicy(POLICY_2).build();
assertThat(role.getTokenPolicies(), hasSize(1)); assertEquals(1, role.getTokenPolicies().size());
assertThat(role.getTokenPolicies(), contains(POLICY_2)); assertEquals(POLICY_2, role.getTokenPolicies().get(0));
role = AppRole.builder(NAME) role = AppRole.builder(NAME)
.withTokenPolicies(POLICIES) .withTokenPolicies(POLICIES)
.withTokenPolicy(POLICY_2) .withTokenPolicy(POLICY_2)
.build(); .build();
assertThat(role.getTokenPolicies(), hasSize(2)); assertEquals(2, role.getTokenPolicies().size());
assertThat(role.getTokenPolicies(), contains(POLICY, POLICY_2)); 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 org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.hamcrest.Matchers.is;
/** /**
* JUnit Test for AuthBackend model. * JUnit Test for AuthBackend model.
@ -34,12 +34,11 @@ class AuthBackendTest {
*/ */
@Test @Test
void forTypeTest() { void forTypeTest() {
assertThat(AuthBackend.forType("token"), is(AuthBackend.TOKEN)); assertEquals(AuthBackend.TOKEN, AuthBackend.forType("token"));
assertThat(AuthBackend.forType("app-id"), is(AuthBackend.APPID)); assertEquals(AuthBackend.APPID, AuthBackend.forType("app-id"));
assertThat(AuthBackend.forType("userpass"), is(AuthBackend.USERPASS)); assertEquals(AuthBackend.USERPASS, AuthBackend.forType("userpass"));
assertThat(AuthBackend.forType("github"), is(AuthBackend.GITHUB)); assertEquals(AuthBackend.GITHUB, AuthBackend.forType("github"));
assertThat(AuthBackend.forType(""), is(AuthBackend.UNKNOWN)); assertEquals(AuthBackend.UNKNOWN, AuthBackend.forType(""));
assertThat(AuthBackend.forType("foobar"), is(AuthBackend.UNKNOWN)); 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.Arrays;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
/** /**
* Unit Test for {@link Token.Builder} * Unit Test for {@link Token.Builder}
@ -80,20 +79,20 @@ class TokenRoleBuilderTest {
@Test @Test
void buildDefaultTest() throws JsonProcessingException { void buildDefaultTest() throws JsonProcessingException {
TokenRole role = TokenRole.builder().build(); TokenRole role = TokenRole.builder().build();
assertThat(role.getAllowedPolicies(), is(nullValue())); assertNull(role.getAllowedPolicies());
assertThat(role.getDisallowedPolicies(), is(nullValue())); assertNull(role.getDisallowedPolicies());
assertThat(role.getOrphan(), is(nullValue())); assertNull(role.getOrphan());
assertThat(role.getRenewable(), is(nullValue())); assertNull(role.getRenewable());
assertThat(role.getAllowedEntityAliases(), is(nullValue())); assertNull(role.getAllowedEntityAliases());
assertThat(role.getTokenBoundCidrs(), is(nullValue())); assertNull(role.getTokenBoundCidrs());
assertThat(role.getTokenExplicitMaxTtl(), is(nullValue())); assertNull(role.getTokenExplicitMaxTtl());
assertThat(role.getTokenNoDefaultPolicy(), is(nullValue())); assertNull(role.getTokenNoDefaultPolicy());
assertThat(role.getTokenNumUses(), is(nullValue())); assertNull(role.getTokenNumUses());
assertThat(role.getTokenPeriod(), is(nullValue())); assertNull(role.getTokenPeriod());
assertThat(role.getTokenType(), is(nullValue())); assertNull(role.getTokenType());
/* optional fields should be ignored, so JSON string should be empty */ // Optional fields should be ignored, so JSON string should be empty.
assertThat(new ObjectMapper().writeValueAsString(role), is("{}")); assertEquals("{}", new ObjectMapper().writeValueAsString(role));
} }
/** /**
@ -121,20 +120,20 @@ class TokenRoleBuilderTest {
.withTokenType(null) .withTokenType(null)
.build(); .build();
assertThat(role.getAllowedPolicies(), is(nullValue())); assertNull(role.getAllowedPolicies());
assertThat(role.getDisallowedPolicies(), is(nullValue())); assertNull(role.getDisallowedPolicies());
assertThat(role.getOrphan(), is(nullValue())); assertNull(role.getOrphan());
assertThat(role.getRenewable(), is(nullValue())); assertNull(role.getRenewable());
assertThat(role.getAllowedEntityAliases(), is(nullValue())); assertNull(role.getAllowedEntityAliases());
assertThat(role.getTokenBoundCidrs(), is(nullValue())); assertNull(role.getTokenBoundCidrs());
assertThat(role.getTokenExplicitMaxTtl(), is(nullValue())); assertNull(role.getTokenExplicitMaxTtl());
assertThat(role.getTokenNoDefaultPolicy(), is(nullValue())); assertNull(role.getTokenNoDefaultPolicy());
assertThat(role.getTokenNumUses(), is(nullValue())); assertNull(role.getTokenNumUses());
assertThat(role.getTokenPeriod(), is(nullValue())); assertNull(role.getTokenPeriod());
assertThat(role.getTokenType(), is(nullValue())); assertNull(role.getTokenType());
/* optional fields should be ignored, so JSON string should be empty */ // Optional fields should be ignored, so JSON string should be empty.
assertThat(new ObjectMapper().writeValueAsString(role), is("{}")); assertEquals("{}", new ObjectMapper().writeValueAsString(role));
} }
/** /**
@ -161,24 +160,24 @@ class TokenRoleBuilderTest {
.withTokenPeriod(TOKEN_PERIOD) .withTokenPeriod(TOKEN_PERIOD)
.withTokenType(TOKEN_TYPE) .withTokenType(TOKEN_TYPE)
.build(); .build();
assertThat(role.getName(), is(NAME)); assertEquals(NAME, role.getName());
assertThat(role.getAllowedPolicies(), hasSize(ALLOWED_POLICIES.size() + 1)); assertEquals(ALLOWED_POLICIES.size() + 1, role.getAllowedPolicies().size());
assertThat(role.getAllowedPolicies(), containsInAnyOrder(ALLOWED_POLICY_1, ALLOWED_POLICY_2, ALLOWED_POLICY_3)); assertTrue(role.getAllowedPolicies().containsAll(List.of(ALLOWED_POLICY_1, ALLOWED_POLICY_2, ALLOWED_POLICY_3)));
assertThat(role.getDisallowedPolicies(), hasSize(DISALLOWED_POLICIES.size() + 1)); assertEquals(DISALLOWED_POLICIES.size() + 1, role.getDisallowedPolicies().size());
assertThat(role.getDisallowedPolicies(), containsInAnyOrder(DISALLOWED_POLICY_1, DISALLOWED_POLICY_2, DISALLOWED_POLICY_3)); assertTrue(role.getDisallowedPolicies().containsAll(List.of(DISALLOWED_POLICY_1, DISALLOWED_POLICY_2, DISALLOWED_POLICY_3)));
assertThat(role.getOrphan(), is(ORPHAN)); assertEquals(ORPHAN, role.getOrphan());
assertThat(role.getRenewable(), is(RENEWABLE)); assertEquals(RENEWABLE, role.getRenewable());
assertThat(role.getPathSuffix(), is(PATH_SUFFIX)); assertEquals(PATH_SUFFIX, role.getPathSuffix());
assertThat(role.getAllowedEntityAliases(), hasSize(ALLOWED_ENTITY_ALIASES.size() + 1)); assertEquals(ALLOWED_ENTITY_ALIASES.size() + 1, role.getAllowedEntityAliases().size());
assertThat(role.getAllowedEntityAliases(), containsInAnyOrder(ALLOWED_ENTITY_ALIAS_1, ALLOWED_ENTITY_ALIAS_2, ALLOWED_ENTITY_ALIAS_3)); assertTrue(role.getAllowedEntityAliases().containsAll(List.of(ALLOWED_ENTITY_ALIAS_1, ALLOWED_ENTITY_ALIAS_2, ALLOWED_ENTITY_ALIAS_3)));
assertThat(role.getTokenBoundCidrs(), hasSize(TOKEN_BOUND_CIDRS.size() + 1)); assertEquals(TOKEN_BOUND_CIDRS.size() + 1, role.getTokenBoundCidrs().size());
assertThat(role.getTokenBoundCidrs(), containsInAnyOrder(TOKEN_BOUND_CIDR_1, TOKEN_BOUND_CIDR_2, TOKEN_BOUND_CIDR_3)); assertTrue(role.getTokenBoundCidrs().containsAll(List.of(TOKEN_BOUND_CIDR_1, TOKEN_BOUND_CIDR_2, TOKEN_BOUND_CIDR_3)));
assertThat(role.getTokenNoDefaultPolicy(), is(TOKEN_NO_DEFAULT_POLICY)); assertEquals(TOKEN_NO_DEFAULT_POLICY, role.getTokenNoDefaultPolicy());
assertThat(role.getTokenNumUses(), is(TOKEN_NUM_USES)); assertEquals(TOKEN_NUM_USES, role.getTokenNumUses());
assertThat(role.getTokenPeriod(), is(TOKEN_PERIOD)); assertEquals(TOKEN_PERIOD, role.getTokenPeriod());
assertThat(role.getTokenType(), is(TOKEN_TYPE.value())); assertEquals(TOKEN_TYPE.value(), role.getTokenType());
/* Verify that all parameters are included in JSON string */ // Verify that all parameters are included in JSON string.
assertThat(new ObjectMapper().writeValueAsString(role), is(JSON_FULL)); 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.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
/** /**
* JUnit Test for {@link Token} and {@link Token.Builder}. * JUnit Test for {@link Token} and {@link Token.Builder}.
@ -55,7 +51,6 @@ class TokenTest {
private static final Boolean RENEWABLE = true; private static final Boolean RENEWABLE = true;
private static final Integer PERIOD = 3600; private static final Integer PERIOD = 3600;
private static final String ENTITY_ALIAS = "alias-value"; 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\"}"; 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 @BeforeAll
@ -70,22 +65,22 @@ class TokenTest {
@Test @Test
void buildDefaultTest() throws JsonProcessingException { void buildDefaultTest() throws JsonProcessingException {
Token token = Token.builder().build(); Token token = Token.builder().build();
assertThat(token.getId(), is(nullValue())); assertNull(token.getId());
assertThat(token.getType(), is(nullValue())); assertNull(token.getType());
assertThat(token.getDisplayName(), is(nullValue())); assertNull(token.getDisplayName());
assertThat(token.getNoParent(), is(nullValue())); assertNull(token.getNoParent());
assertThat(token.getNoDefaultPolicy(), is(nullValue())); assertNull(token.getNoDefaultPolicy());
assertThat(token.getTtl(), is(nullValue())); assertNull(token.getTtl());
assertThat(token.getExplicitMaxTtl(), is(nullValue())); assertNull(token.getExplicitMaxTtl());
assertThat(token.getNumUses(), is(nullValue())); assertNull(token.getNumUses());
assertThat(token.getPolicies(), is(nullValue())); assertNull(token.getPolicies());
assertThat(token.getMeta(), is(nullValue())); assertNull(token.getMeta());
assertThat(token.isRenewable(), is(nullValue())); assertNull(token.isRenewable());
assertThat(token.getPeriod(), is(nullValue())); assertNull(token.getPeriod());
assertThat(token.getEntityAlias(), is(nullValue())); assertNull(token.getEntityAlias());
/* optional fields should be ignored, so JSON string should be empty */ // Optional fields should be ignored, so JSON string should be empty.
assertThat(new ObjectMapper().writeValueAsString(token), is("{}")); assertEquals("{}", new ObjectMapper().writeValueAsString(token));
} }
/** /**
@ -108,21 +103,21 @@ class TokenTest {
.withPeriod(PERIOD) .withPeriod(PERIOD)
.withEntityAlias(ENTITY_ALIAS) .withEntityAlias(ENTITY_ALIAS)
.build(); .build();
assertThat(token.getId(), is(ID)); assertEquals(ID, token.getId());
assertThat(token.getType(), is(Token.Type.SERVICE.value())); assertEquals(Token.Type.SERVICE.value(), token.getType());
assertThat(token.getDisplayName(), is(DISPLAY_NAME)); assertEquals(DISPLAY_NAME, token.getDisplayName());
assertThat(token.getNoParent(), is(NO_PARENT)); assertEquals(NO_PARENT, token.getNoParent());
assertThat(token.getNoDefaultPolicy(), is(NO_DEFAULT_POLICY)); assertEquals(NO_DEFAULT_POLICY, token.getNoDefaultPolicy());
assertThat(token.getTtl(), is(TTL)); assertEquals(TTL, token.getTtl());
assertThat(token.getExplicitMaxTtl(), is(EXPLICIT_MAX_TTL)); assertEquals(EXPLICIT_MAX_TTL, token.getExplicitMaxTtl());
assertThat(token.getNumUses(), is(NUM_USES)); assertEquals(NUM_USES, token.getNumUses());
assertThat(token.getPolicies(), is(POLICIES)); assertEquals(POLICIES, token.getPolicies());
assertThat(token.getMeta(), is(META)); assertEquals(META, token.getMeta());
assertThat(token.isRenewable(), is(RENEWABLE)); assertEquals(RENEWABLE, token.isRenewable());
assertThat(token.getPeriod(), is(PERIOD)); assertEquals(PERIOD, token.getPeriod());
/* Verify that all parameters are included in JSON string */ // Verify that all parameters are included in JSON string.
assertThat(new ObjectMapper().writeValueAsString(token), is(JSON_FULL)); assertEquals(JSON_FULL, new ObjectMapper().writeValueAsString(token));
} }
/** /**
@ -130,46 +125,46 @@ class TokenTest {
*/ */
@Test @Test
void convenienceMethodsTest() { void convenienceMethodsTest() {
/* Parent */ // Parent.
Token token = Token.builder().asOrphan().build(); Token token = Token.builder().asOrphan().build();
assertThat(token.getNoParent(), is(true)); assertEquals(true, token.getNoParent());
token = Token.builder().withParent().build(); token = Token.builder().withParent().build();
assertThat(token.getNoParent(), is(false)); assertEquals(false, token.getNoParent());
/* Default policy */ // Default policy.
token = Token.builder().withDefaultPolicy().build(); token = Token.builder().withDefaultPolicy().build();
assertThat(token.getNoDefaultPolicy(), is(false)); assertEquals(false, token.getNoDefaultPolicy());
token = Token.builder().withoutDefaultPolicy().build(); token = Token.builder().withoutDefaultPolicy().build();
assertThat(token.getNoDefaultPolicy(), is(true)); assertEquals(true, token.getNoDefaultPolicy());
/* Renewability */ // Renewability.
token = Token.builder().renewable().build(); token = Token.builder().renewable().build();
assertThat(token.isRenewable(), is(true)); assertEquals(true, token.isRenewable());
token = Token.builder().notRenewable().build(); 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(); token = Token.builder().withPolicy(POLICY_2).build();
assertThat(token.getPolicies(), hasSize(1)); assertEquals(1, token.getPolicies().size());
assertThat(token.getPolicies(), contains(POLICY_2)); assertEquals(List.of(POLICY_2), token.getPolicies());
token = Token.builder() token = Token.builder()
.withPolicies(POLICY, POLICY_2) .withPolicies(POLICY, POLICY_2)
.withPolicy(POLICY_3) .withPolicy(POLICY_3)
.build(); .build();
assertThat(token.getPolicies(), hasSize(3)); assertEquals(3, token.getPolicies().size());
assertThat(token.getPolicies(), contains(POLICY, POLICY_2, POLICY_3)); 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(); token = Token.builder().withMeta(META_KEY_2, META_VALUE_2).build();
assertThat(token.getMeta().size(), is(1)); assertEquals(1, token.getMeta().size());
assertThat(token.getMeta().keySet(), contains(META_KEY_2)); assertEquals(Set.of(META_KEY_2), token.getMeta().keySet());
assertThat(token.getMeta().get(META_KEY_2), is(META_VALUE_2)); assertEquals(META_VALUE_2, token.getMeta().get(META_KEY_2));
token = Token.builder() token = Token.builder()
.withMeta(META) .withMeta(META)
.withMeta(META_KEY_2, META_VALUE_2) .withMeta(META_KEY_2, META_VALUE_2)
.build(); .build();
assertThat(token.getMeta().size(), is(2)); assertEquals(2, token.getMeta().size());
assertThat(token.getMeta().get(META_KEY), is(META_VALUE)); assertEquals(META_VALUE, token.getMeta().get(META_KEY));
assertThat(token.getMeta().get(META_KEY_2), is(META_VALUE_2)); 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.HashMap;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
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.
@ -78,7 +75,7 @@ class AppRoleResponseTest {
void getDataRoundtrip() { void getDataRoundtrip() {
// Create empty Object. // Create empty Object.
AppRoleResponse res = new AppRoleResponse(); 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. // Parsing invalid auth data map should fail.
assertThrows( assertThrows(
@ -97,19 +94,19 @@ class AppRoleResponseTest {
() -> new ObjectMapper().readValue(RES_JSON, AppRoleResponse.class), () -> new ObjectMapper().readValue(RES_JSON, AppRoleResponse.class),
"AuthResponse deserialization failed." "AuthResponse deserialization failed."
); );
assertThat("Parsed response is NULL", res, is(notNullValue())); assertNotNull(res, "Parsed response is NULL");
// Extract role data. // Extract role data.
AppRole role = res.getRole(); AppRole role = res.getRole();
assertThat("Role data is NULL", role, is(notNullValue())); assertNotNull(role, "Role data is NULL");
assertThat("Incorrect token TTL", role.getTokenTtl(), is(ROLE_TOKEN_TTL)); assertEquals(ROLE_TOKEN_TTL, role.getTokenTtl(), "Incorrect token TTL");
assertThat("Incorrect token max TTL", role.getTokenMaxTtl(), is(ROLE_TOKEN_MAX_TTL)); assertEquals(ROLE_TOKEN_MAX_TTL, role.getTokenMaxTtl(), "Incorrect token max TTL");
assertThat("Incorrect secret ID TTL", role.getSecretIdTtl(), is(ROLE_SECRET_TTL)); assertEquals(ROLE_SECRET_TTL, role.getSecretIdTtl(), "Incorrect secret ID TTL");
assertThat("Incorrect secret ID umber of uses", role.getSecretIdNumUses(), is(ROLE_SECRET_NUM_USES)); assertEquals(ROLE_SECRET_NUM_USES, role.getSecretIdNumUses(), "Incorrect secret ID umber of uses");
assertThat("Incorrect number of policies", role.getTokenPolicies(), hasSize(1)); assertEquals(1, role.getTokenPolicies().size(), "Incorrect number of policies");
assertThat("Incorrect role policies", role.getTokenPolicies(), contains(ROLE_POLICY)); assertEquals(ROLE_POLICY, role.getTokenPolicies().get(0), "Incorrect role policies");
assertThat("Incorrect role period", role.getTokenPeriod(), is(ROLE_PERIOD)); assertEquals(ROLE_PERIOD, role.getTokenPeriod(), "Incorrect role period");
assertThat("Incorrect role bind secret ID flag", role.getBindSecretId(), is(ROLE_BIND_SECRET)); assertEquals(ROLE_BIND_SECRET, role.getBindSecretId(), "Incorrect role bind secret ID flag");
assertThat("Incorrect bound CIDR list", role.getTokenBoundCidrs(), is(nullValue())); assertNull(role.getTokenBoundCidrs(), "Incorrect bound CIDR list");
assertThat("Incorrect bound CIDR list string", role.getTokenBoundCidrsString(), is(emptyString())); 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 de.stklcode.jvault.connector.model.response.embedded.AuthMethod;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
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.
@ -76,7 +75,7 @@ class AuthMethodsResponseTest {
void getDataRoundtrip() { void getDataRoundtrip() {
// Create empty Object. // Create empty Object.
AuthMethodsResponse res = new AuthMethodsResponse(); 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. // Parsing invalid data map should fail.
assertThrows( assertThrows(
@ -95,29 +94,29 @@ class AuthMethodsResponseTest {
() -> new ObjectMapper().readValue(RES_JSON, AuthMethodsResponse.class), () -> new ObjectMapper().readValue(RES_JSON, AuthMethodsResponse.class),
"AuthResponse deserialization failed" "AuthResponse deserialization failed"
); );
assertThat("Parsed response is NULL", res, is(notNullValue())); assertNotNull(res, "Parsed response is NULL");
// Extract auth data. // Extract auth data.
Map<String, AuthMethod> supported = res.getSupportedMethods(); Map<String, AuthMethod> supported = res.getSupportedMethods();
assertThat("Auth data is NULL", supported, is(notNullValue())); assertNotNull(supported, "Auth data is NULL");
assertThat("Incorrect number of supported methods", supported.entrySet(), hasSize(2)); assertEquals(2, supported.size(), "Incorrect number of supported methods");
assertThat("Incorrect method paths", supported.keySet(), containsInAnyOrder(GH_PATH, TK_PATH)); assertTrue(supported.keySet().containsAll(Set.of(GH_PATH, TK_PATH)), "Incorrect method paths");
// Verify first method. // Verify first method.
AuthMethod method = supported.get(GH_PATH); AuthMethod method = supported.get(GH_PATH);
assertThat("Incorrect raw type for GitHub", method.getRawType(), is(GH_TYPE)); assertEquals(GH_TYPE, method.getRawType(), "Incorrect raw type for GitHub");
assertThat("Incorrect parsed type for GitHub", method.getType(), is(AuthBackend.GITHUB)); assertEquals(AuthBackend.GITHUB, method.getType(), "Incorrect parsed type for GitHub");
assertThat("Incorrect description for GitHub", method.getDescription(), is(GH_DESCR)); assertEquals(GH_DESCR, method.getDescription(), "Incorrect description for GitHub");
assertThat("Unexpected config for GitHub", method.getConfig(), is(nullValue())); assertNull(method.getConfig(), "Unexpected config for GitHub");
// Verify first method. // Verify first method.
method = supported.get(TK_PATH); method = supported.get(TK_PATH);
assertThat("Incorrect raw type for Token", method.getRawType(), is(TK_TYPE)); assertEquals(TK_TYPE, method.getRawType(), "Incorrect raw type for Token");
assertThat("Incorrect parsed type for Token", method.getType(), is(AuthBackend.TOKEN)); assertEquals(AuthBackend.TOKEN, method.getType(), "Incorrect parsed type for Token");
assertThat("Incorrect description for Token", method.getDescription(), is(TK_DESCR)); assertEquals(TK_DESCR, method.getDescription(), "Incorrect description for Token");
assertThat("Missing config for Token", method.getConfig(), is(notNullValue())); assertNotNull(method.getConfig(), "Missing config for Token");
assertThat("Unexpected config size for Token", method.getConfig().keySet(), hasSize(2)); assertEquals(2, method.getConfig().size(), "Unexpected config size for Token");
assertThat("Incorrect lease TTL config", method.getConfig().get("default_lease_ttl"), is(TK_LEASE_TTL.toString())); assertEquals(TK_LEASE_TTL.toString(), method.getConfig().get("default_lease_ttl"), "Incorrect lease TTL config");
assertThat("Incorrect max lease TTL config", method.getConfig().get("max_lease_ttl"), is(TK_MAX_LEASE_TTL.toString())); assertEquals(TK_MAX_LEASE_TTL.toString(), method.getConfig().get("max_lease_ttl"), "Incorrect max lease TTL config");
} }
private static class Dummy { private static class Dummy {

View File

@ -23,11 +23,9 @@ import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
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.
@ -84,7 +82,7 @@ class AuthResponseTest {
void getDataRoundtrip() { void getDataRoundtrip() {
// Create empty Object. // Create empty Object.
AuthResponse res = new AuthResponse(); 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. // Parsing invalid auth data map should fail.
assertThrows( assertThrows(
@ -95,7 +93,7 @@ class AuthResponseTest {
// Data method should be agnostic. // Data method should be agnostic.
res.setData(INVALID_AUTH_DATA); 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 @Test
void jsonRoundtrip() { void jsonRoundtrip() {
AuthResponse res = assertDoesNotThrow( AuthResponse res = assertDoesNotThrow(
() -> new ObjectMapper().readValue(RES_JSON, AuthResponse.class), () -> new ObjectMapper().readValue(RES_JSON, AuthResponse.class),
"AuthResponse deserialization failed." "AuthResponse deserialization failed."
); );
assertThat("Parsed response is NULL", res, is(notNullValue())); assertNotNull(res, "Parsed response is NULL");
// Extract auth data. // Extract auth data.
AuthData data = res.getAuth(); AuthData data = res.getAuth();
assertThat("Auth data is NULL", data, is(notNullValue())); assertNotNull(data, "Auth data is NULL");
assertThat("Incorrect auth accessor", data.getAccessor(), is(AUTH_ACCESSOR)); assertEquals(AUTH_ACCESSOR, data.getAccessor(), "Incorrect auth accessor");
assertThat("Incorrect auth client token", data.getClientToken(), is(AUTH_CLIENT_TOKEN)); assertEquals(AUTH_CLIENT_TOKEN, data.getClientToken(), "Incorrect auth client token");
assertThat("Incorrect auth lease duration", data.getLeaseDuration(), is(AUTH_LEASE_DURATION)); assertEquals(AUTH_LEASE_DURATION, data.getLeaseDuration(), "Incorrect auth lease duration");
assertThat("Incorrect auth renewable flag", data.isRenewable(), is(AUTH_RENEWABLE)); assertEquals(AUTH_RENEWABLE, data.isRenewable(), "Incorrect auth renewable flag");
assertThat("Incorrect auth orphan flag", data.isOrphan(), is(AUTH_ORPHAN)); assertEquals(AUTH_ORPHAN, data.isOrphan(), "Incorrect auth orphan flag");
assertThat("Incorrect auth token type", data.getTokenType(), is(AUTH_TOKEN_TYPE)); assertEquals(AUTH_TOKEN_TYPE, data.getTokenType(), "Incorrect auth token type");
assertThat("Incorrect auth entity id", data.getEntityId(), is(AUTH_ENTITY_ID)); assertEquals(AUTH_ENTITY_ID, data.getEntityId(), "Incorrect auth entity id");
assertThat("Incorrect number of policies", data.getPolicies(), hasSize(2)); assertEquals(2, data.getPolicies().size(), "Incorrect number of policies");
assertThat("Incorrect auth policies", data.getPolicies(), containsInRelativeOrder(AUTH_POLICY_1, AUTH_POLICY_2)); assertTrue(data.getPolicies().containsAll(Set.of(AUTH_POLICY_1, AUTH_POLICY_2)));
assertThat("Incorrect number of token policies", data.getTokenPolicies(), hasSize(2)); assertEquals(2, data.getTokenPolicies().size(), "Incorrect number of token policies");
assertThat("Incorrect token policies", data.getTokenPolicies(), containsInRelativeOrder(AUTH_POLICY_2, AUTH_POLICY_1)); assertTrue(data.getTokenPolicies().containsAll(Set.of(AUTH_POLICY_2, AUTH_POLICY_1)), "Incorrect token policies");
assertThat("Incorrect auth metadata size", data.getMetadata().entrySet(), hasSize(1)); assertEquals(1, data.getMetadata().size(), "Incorrect auth metadata size");
assertThat("Incorrect auth metadata", data.getMetadata().get(AUTH_META_KEY), is(AUTH_META_VALUE)); 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; package de.stklcode.jvault.connector.model.response;
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.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
/** /**
* JUnit Test for {@link CredentialsResponse} model. * JUnit Test for {@link CredentialsResponse} model.
@ -55,12 +51,12 @@ class CredentialsResponseTest {
void getCredentialsTest() throws InvalidResponseException { void getCredentialsTest() throws InvalidResponseException {
// Create empty Object. // Create empty Object.
CredentialsResponse res = new CredentialsResponse(); CredentialsResponse res = new CredentialsResponse();
assertThat("Username not present in data map should not return anything", res.getUsername(), is(nullValue())); assertNull(res.getUsername(), "Username not present in data map should not return anything");
assertThat("Password not present in data map should not return anything", res.getPassword(), is(nullValue())); assertNull(res.getPassword(), "Password not present in data map should not return anything");
// Fill data map. // Fill data map.
res.setData(DATA); res.setData(DATA);
assertThat("Incorrect username", res.getUsername(), is(VAL_USER)); assertEquals(VAL_USER, res.getUsername(), "Incorrect username");
assertThat("Incorrect password", res.getPassword(), is(VAL_PASS)); 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 com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* JUnit Test for {@link AuthResponse} model. * JUnit Test for {@link AuthResponse} model.
@ -64,16 +61,16 @@ class HealthResponseTest {
() -> new ObjectMapper().readValue(RES_JSON, HealthResponse.class), () -> new ObjectMapper().readValue(RES_JSON, HealthResponse.class),
"Health deserialization failed." "Health deserialization failed."
); );
assertThat("Parsed response is NULL", res, is(notNullValue())); assertNotNull(res, "Parsed response is NULL");
assertThat("Incorrect cluster ID", res.getClusterID(), is(CLUSTER_ID)); assertEquals(CLUSTER_ID, res.getClusterID(), "Incorrect cluster ID");
assertThat("Incorrect cluster name", res.getClusterName(), is(CLUSTER_NAME)); assertEquals(CLUSTER_NAME, res.getClusterName(), "Incorrect cluster name");
assertThat("Incorrect version", res.getVersion(), is(VERSION)); assertEquals(VERSION, res.getVersion(), "Incorrect version");
assertThat("Incorrect server time", res.getServerTimeUTC(), is(SERVER_TIME_UTC)); assertEquals(SERVER_TIME_UTC, res.getServerTimeUTC(), "Incorrect server time");
assertThat("Incorrect standby state", res.isStandby(), is(STANDBY)); assertEquals(STANDBY, res.isStandby(), "Incorrect standby state");
assertThat("Incorrect seal state", res.isSealed(), is(SEALED)); assertEquals(SEALED, res.isSealed(), "Incorrect seal state");
assertThat("Incorrect initialization state", res.isInitialized(), is(INITIALIZED)); assertEquals(INITIALIZED, res.isInitialized(), "Incorrect initialization state");
assertThat("Incorrect performance standby state", res.isPerformanceStandby(), is(PERF_STANDBY)); assertEquals(PERF_STANDBY, res.isPerformanceStandby(), "Incorrect performance standby state");
assertThat("Incorrect replication perf mode", res.getReplicationPerfMode(), is(REPL_PERF_MODE)); assertEquals(REPL_PERF_MODE, res.getReplicationPerfMode(), "Incorrect replication perf mode");
assertThat("Incorrect replication DR mode", res.getReplicationDrMode(), is(REPL_DR_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 com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.is;
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,21 +71,21 @@ class MetadataResponseTest {
() -> new ObjectMapper().readValue(META_JSON, MetadataResponse.class), () -> new ObjectMapper().readValue(META_JSON, MetadataResponse.class),
"MetadataResponse deserialization failed." "MetadataResponse deserialization failed."
); );
assertThat("Parsed response is NULL", res, is(notNullValue())); assertNotNull(res, "Parsed response is NULL");
assertThat("Parsed metadata is NULL", res.getMetadata(), is(notNullValue())); assertNotNull(res.getMetadata(), "Parsed metadata is NULL");
assertThat("Incorrect created time", res.getMetadata().getCreatedTimeString(), is(V1_TIME)); assertEquals(V1_TIME, res.getMetadata().getCreatedTimeString(), "Incorrect created time");
assertThat("Parting created time failed", res.getMetadata().getCreatedTime(), is(notNullValue())); assertNotNull(res.getMetadata().getCreatedTime(), "Parting created time failed");
assertThat("Incorrect current version", res.getMetadata().getCurrentVersion(), is(CURRENT_VERSION)); assertEquals(CURRENT_VERSION, res.getMetadata().getCurrentVersion(), "Incorrect current version");
assertThat("Incorrect max versions", res.getMetadata().getMaxVersions(), is(MAX_VERSIONS)); assertEquals(MAX_VERSIONS, res.getMetadata().getMaxVersions(), "Incorrect max versions");
assertThat("Incorrect oldest version", res.getMetadata().getOldestVersion(), is(OLDEST_VERSION)); assertEquals(OLDEST_VERSION, res.getMetadata().getOldestVersion(), "Incorrect oldest version");
assertThat("Incorrect updated time", res.getMetadata().getUpdatedTimeString(), is(V3_TIME)); assertEquals(V3_TIME, res.getMetadata().getUpdatedTimeString(), "Incorrect updated time");
assertThat("Parting updated time failed", res.getMetadata().getUpdatedTime(), is(notNullValue())); assertNotNull(res.getMetadata().getUpdatedTime(), "Parting updated time failed");
assertThat("Incorrect number of versions", res.getMetadata().getVersions().size(), is(3)); assertEquals(3, res.getMetadata().getVersions().size(), "Incorrect number of versions");
assertThat("Incorrect version 1 delete time", res.getMetadata().getVersions().get(1).getDeletionTimeString(), is(V2_TIME)); assertEquals(V2_TIME, res.getMetadata().getVersions().get(1).getDeletionTimeString(), "Incorrect version 1 delete time");
assertThat("Parsing version delete time failed", res.getMetadata().getVersions().get(1).getDeletionTime(), is(notNullValue())); assertNotNull(res.getMetadata().getVersions().get(1).getDeletionTime(), "Parsing version delete time failed");
assertThat("Incorrect version 1 destroyed state", res.getMetadata().getVersions().get(1).isDestroyed(), is(true)); assertTrue(res.getMetadata().getVersions().get(1).isDestroyed(), "Incorrect version 1 destroyed state");
assertThat("Incorrect version 2 created time", res.getMetadata().getVersions().get(2).getCreatedTimeString(), is(V2_TIME)); assertEquals(V2_TIME, res.getMetadata().getVersions().get(2).getCreatedTimeString(), "Incorrect version 2 created time");
assertThat("Parsing version created failed", res.getMetadata().getVersions().get(2).getCreatedTime(), is(notNullValue())); assertNotNull(res.getMetadata().getVersions().get(2).getCreatedTime(), "Parsing version created failed");
assertThat("Incorrect version 3 destroyed state", res.getMetadata().getVersions().get(3).isDestroyed(), is(false)); 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 com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* JUnit Test for {@link SealResponse} model. * JUnit Test for {@link SealResponse} model.
@ -74,18 +72,18 @@ class SealResponseTest {
() -> new ObjectMapper().readValue(RES_SEALED, SealResponse.class), () -> new ObjectMapper().readValue(RES_SEALED, SealResponse.class),
"TokenResponse deserialization failed." "TokenResponse deserialization failed."
); );
assertThat("Parsed response is NULL", res, is(notNullValue())); assertNotNull(res, "Parsed response is NULL");
assertThat("Incorrect seal type", res.getType(), is(TYPE)); assertEquals(TYPE, res.getType(), "Incorrect seal type");
assertThat("Incorrect seal status", res.isSealed(), is(true)); assertTrue(res.isSealed(), "Incorrect seal status");
assertThat("Incorrect initialization status", res.isInitialized(), is(true)); assertTrue(res.isInitialized(), "Incorrect initialization status");
assertThat("Incorrect threshold", res.getThreshold(), is(THRESHOLD)); assertEquals(THRESHOLD, res.getThreshold(), "Incorrect threshold");
assertThat("Incorrect number of shares", res.getNumberOfShares(), is(SHARES)); assertEquals(SHARES, res.getNumberOfShares(), "Incorrect number of shares");
assertThat("Incorrect progress", res.getProgress(), is(PROGRESS_SEALED)); assertEquals(PROGRESS_SEALED, res.getProgress(), "Incorrect progress");
assertThat("Nonce not empty", res.getNonce(), is("")); assertEquals("", res.getNonce(), "Nonce not empty");
assertThat("Incorrect version", res.getVersion(), is(VERSION)); assertEquals(VERSION, res.getVersion(), "Incorrect version");
// 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())); assertNull(res.getClusterName(), "Cluster name should not be populated");
assertThat("Cluster ID should not be populated", res.getClusterId(), is(nullValue())); assertNull(res.getClusterId(), "Cluster ID should not be populated");
// Not test unsealed Vault's response. // Not test unsealed Vault's response.
@ -93,16 +91,16 @@ class SealResponseTest {
() -> new ObjectMapper().readValue(RES_UNSEALED, SealResponse.class), () -> new ObjectMapper().readValue(RES_UNSEALED, SealResponse.class),
"TokenResponse deserialization failed." "TokenResponse deserialization failed."
); );
assertThat("Parsed response is NULL", res, is(notNullValue())); assertNotNull(res, "Parsed response is NULL");
assertThat("Incorrect seal type", res.getType(), is(TYPE)); assertEquals(TYPE, res.getType(), "Incorrect seal type");
assertThat("Incorrect seal status", res.isSealed(), is(false)); assertFalse(res.isSealed(), "Incorrect seal status");
assertThat("Incorrect initialization status", res.isInitialized(), is(true)); assertTrue(res.isInitialized(), "Incorrect initialization status");
assertThat("Incorrect threshold", res.getThreshold(), is(THRESHOLD)); assertEquals(THRESHOLD, res.getThreshold(), "Incorrect threshold");
assertThat("Incorrect number of shares", res.getNumberOfShares(), is(SHARES)); assertEquals(SHARES, res.getNumberOfShares(), "Incorrect number of shares");
assertThat("Incorrect progress", res.getProgress(), is(PROGRESS_UNSEALED)); assertEquals(PROGRESS_UNSEALED, res.getProgress(), "Incorrect progress");
assertThat("Incorrect nonce", res.getNonce(), is(NONCE)); assertEquals(NONCE, res.getNonce(), "Incorrect nonce");
assertThat("Incorrect version", res.getVersion(), is(VERSION)); assertEquals(VERSION, res.getVersion(), "Incorrect version");
assertThat("Incorrect cluster name", res.getClusterName(), is(CLUSTER_NAME)); assertEquals(CLUSTER_NAME, res.getClusterName(), "Incorrect cluster name");
assertThat("Incorrect cluster ID", res.getClusterId(), is(CLUSTER_ID)); 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 de.stklcode.jvault.connector.exception.InvalidResponseException;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* JUnit Test for {@link SecretListResponse} model. * JUnit Test for {@link SecretListResponse} model.
@ -53,7 +48,7 @@ class SecretListResponseTest {
void getKeysTest() throws InvalidResponseException { void getKeysTest() throws InvalidResponseException {
// Create empty Object. // Create empty Object.
SecretListResponse res = new SecretListResponse(); 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. // Provoke internal ClassCastException.
Map<String, Object> invalidData = new HashMap<>(); Map<String, Object> invalidData = new HashMap<>();
@ -66,8 +61,8 @@ class SecretListResponseTest {
// Fill correct data. // Fill correct data.
res.setData(DATA); res.setData(DATA);
assertThat("Keys should be filled here", res.getKeys(), is(notNullValue())); assertNotNull(res.getKeys(), "Keys should be filled here");
assertThat("Unexpected number of keys", res.getKeys(), hasSize(2)); assertEquals(2, res.getKeys().size(), "Unexpected number of keys");
assertThat("Unexpected keys", res.getKeys(), contains(KEY1, KEY2)); 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.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
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.
@ -123,25 +121,25 @@ class SecretResponseTest {
void getDataRoundtrip() throws InvalidResponseException { void getDataRoundtrip() throws InvalidResponseException {
// Create empty Object. // Create empty Object.
SecretResponse res = new SecretResponse(); SecretResponse res = new SecretResponse();
assertThat("Initial data should be Map", res.getData(), is(instanceOf(Map.class))); assertNotNull(res.getData(), "Initial data should be Map");
assertThat("Initial data should be empty", res.getData().entrySet(), empty()); assertTrue(res.getData().isEmpty(), "Initial data should be empty");
assertThat("Getter should return NULL on empty data map", res.get(KEY_STRING), is(nullValue())); assertNull(res.get(KEY_STRING), "Getter should return NULL on empty data map");
// Fill data map. // Fill data map.
res.setData(DATA); res.setData(DATA);
assertThat("Data setter/getter not transparent", res.getData(), is(DATA)); assertEquals(DATA, res.getData(), "Data setter/getter not transparent");
assertThat("Data size modified", res.getData().keySet(), hasSize(DATA.size())); assertEquals(DATA.size(), res.getData().keySet().size(), "Data size modified");
assertThat("Data keys not passed correctly", res.getData().keySet(), containsInAnyOrder(KEY_STRING, KEY_INTEGER, KEY_LIST)); assertTrue(res.getData().keySet().containsAll(Set.of(KEY_STRING, KEY_INTEGER, KEY_LIST)), "Data keys not passed correctly");
assertThat("Data values not passed correctly", res.get(KEY_STRING), is(VAL_STRING)); assertEquals(VAL_STRING, res.get(KEY_STRING), "Data values not passed correctly");
assertThat("Data values not passed correctly", res.get(KEY_INTEGER), is(VAL_INTEGER)); assertEquals(VAL_INTEGER, res.get(KEY_INTEGER), "Data values not passed correctly");
assertThat("Non-Null returned on unknown key", res.get(KEY_UNKNOWN), is(nullValue())); assertNull(res.get(KEY_UNKNOWN), "Non-Null returned on unknown key");
// 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())); assertNotNull(list, "JSON parsing of list failed");
assertThat("JSON parsing of list returned incorrect size", list.size(), is(2)); assertEquals(2, list.size(), "JSON parsing of list returned incorrect size");
assertThat("JSON parsing of list returned incorrect elements", list, contains("first", "second")); assertTrue(list.containsAll(List.of("first", "second")), "JSON parsing of list returned incorrect elements");
assertThat("Non-Null returned on unknown key", res.get(KEY_UNKNOWN, Object.class), is(nullValue())); assertNull(res.get(KEY_UNKNOWN, Object.class), "Non-Null returned on unknown key");
// Requesting invalid class should result in Exception. // Requesting invalid class should result in Exception.
assertThrows( assertThrows(
@ -168,13 +166,13 @@ class SecretResponseTest {
"SecretResponse deserialization failed." "SecretResponse deserialization failed."
); );
assertSecretData(res); assertSecretData(res);
assertThat("SecretResponse does not contain metadata", res.getMetadata(), is(notNullValue())); assertNotNull(res.getMetadata(), "SecretResponse does not contain metadata");
assertThat("Incorrect creation date string", res.getMetadata().getCreatedTimeString(), is(SECRET_META_CREATED)); assertEquals(SECRET_META_CREATED, res.getMetadata().getCreatedTimeString(), "Incorrect creation date string");
assertThat("Creation date parsing failed", res.getMetadata().getCreatedTime(), is(notNullValue())); assertNotNull(res.getMetadata().getCreatedTime(), "Creation date parsing failed");
assertThat("Incorrect deletion date string", res.getMetadata().getDeletionTimeString(), is(emptyString())); assertEquals("", res.getMetadata().getDeletionTimeString(), "Incorrect deletion date string");
assertThat("Incorrect deletion date", res.getMetadata().getDeletionTime(), is(nullValue())); assertNull(res.getMetadata().getDeletionTime(), "Incorrect deletion date");
assertThat("Secret destroyed when not expected", res.getMetadata().isDestroyed(), is(false)); assertEquals(false, res.getMetadata().isDestroyed(), "Secret destroyed when not expected");
assertThat("Incorrect secret version", res.getMetadata().getVersion(), is(1)); assertEquals(1, res.getMetadata().getVersion(), "Incorrect secret version");
// Deleted KV v2 secret. // Deleted KV v2 secret.
res = assertDoesNotThrow( res = assertDoesNotThrow(
@ -182,22 +180,22 @@ class SecretResponseTest {
"SecretResponse deserialization failed." "SecretResponse deserialization failed."
); );
assertSecretData(res); assertSecretData(res);
assertThat("SecretResponse does not contain metadata", res.getMetadata(), is(notNullValue())); assertNotNull(res.getMetadata(), "SecretResponse does not contain metadata");
assertThat("Incorrect creation date string", res.getMetadata().getCreatedTimeString(), is(SECRET_META_CREATED)); assertEquals(SECRET_META_CREATED, res.getMetadata().getCreatedTimeString(), "Incorrect creation date string");
assertThat("Creation date parsing failed", res.getMetadata().getCreatedTime(), is(notNullValue())); assertNotNull(res.getMetadata().getCreatedTime(), "Creation date parsing failed");
assertThat("Incorrect deletion date string", res.getMetadata().getDeletionTimeString(), is(SECRET_META_DELETED)); assertEquals(SECRET_META_DELETED, res.getMetadata().getDeletionTimeString(), "Incorrect deletion date string");
assertThat("Incorrect deletion date", res.getMetadata().getDeletionTime(), is(notNullValue())); assertNotNull(res.getMetadata().getDeletionTime(), "Incorrect deletion date");
assertThat("Secret destroyed when not expected", res.getMetadata().isDestroyed(), is(true)); assertEquals(true, res.getMetadata().isDestroyed(), "Secret destroyed when not expected");
assertThat("Incorrect secret version", res.getMetadata().getVersion(), is(2)); assertEquals(2, res.getMetadata().getVersion(), "Incorrect secret version");
} }
private void assertSecretData(SecretResponse res) { private void assertSecretData(SecretResponse res) {
assertThat("Parsed response is NULL", res, is(notNullValue())); assertNotNull(res, "Parsed response is NULL");
assertThat("Incorrect lease ID", res.getLeaseId(), is(SECRET_LEASE_ID)); assertEquals(SECRET_LEASE_ID, res.getLeaseId(), "Incorrect lease ID");
assertThat("Incorrect lease duration", res.getLeaseDuration(), is(SECRET_LEASE_DURATION)); assertEquals(SECRET_LEASE_DURATION, res.getLeaseDuration(), "Incorrect lease duration");
assertThat("Incorrect renewable status", res.isRenewable(), is(SECRET_RENEWABLE)); assertEquals(SECRET_RENEWABLE, res.isRenewable(), "Incorrect renewable status");
assertThat("Incorrect warnings", res.getWarnings(), is(SECRET_WARNINGS)); assertEquals(SECRET_WARNINGS, res.getWarnings(), "Incorrect warnings");
assertThat("Response does not contain correct data", res.get(SECRET_DATA_K1), is(SECRET_DATA_V1)); assertEquals(SECRET_DATA_V1, res.get(SECRET_DATA_K1), "Response does not contain correct data");
assertThat("Response does not contain correct data", res.get(SECRET_DATA_K2), is(SECRET_DATA_V2)); 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 com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* JUnit Test for {@link SecretVersionResponse} model. * JUnit Test for {@link SecretVersionResponse} model.
@ -53,11 +50,11 @@ class SecretVersionResponseTest {
() -> new ObjectMapper().readValue(META_JSON, SecretVersionResponse.class), () -> new ObjectMapper().readValue(META_JSON, SecretVersionResponse.class),
"SecretVersionResponse deserialization failed" "SecretVersionResponse deserialization failed"
); );
assertThat("Parsed response is NULL", res, is(notNullValue())); assertNotNull(res, "Parsed response is NULL");
assertThat("Parsed metadata is NULL", res.getMetadata(), is(notNullValue())); assertNotNull(res.getMetadata(), "Parsed metadata is NULL");
assertThat("Incorrect created time", res.getMetadata().getCreatedTimeString(), is(CREATION_TIME)); assertEquals(CREATION_TIME, res.getMetadata().getCreatedTimeString(), "Incorrect created time");
assertThat("Incorrect deletion time", res.getMetadata().getDeletionTimeString(), is(DELETION_TIME)); assertEquals(DELETION_TIME, res.getMetadata().getDeletionTimeString(), "Incorrect deletion time");
assertThat("Incorrect destroyed state", res.getMetadata().isDestroyed(), is(false)); assertEquals(false, res.getMetadata().isDestroyed(), "Incorrect destroyed state");
assertThat("Incorrect version", res.getMetadata().getVersion(), is(VERSION)); 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.time.ZonedDateTime;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.Matchers.*;
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.
@ -104,7 +102,7 @@ class TokenResponseTest {
void getDataRoundtrip() { void getDataRoundtrip() {
// Create empty Object. // Create empty Object.
TokenResponse res = new TokenResponse(); 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. // Parsing invalid data map should fail.
assertThrows( assertThrows(
@ -123,33 +121,33 @@ class TokenResponseTest {
() -> new ObjectMapper().readValue(RES_JSON, TokenResponse.class), () -> new ObjectMapper().readValue(RES_JSON, TokenResponse.class),
"TokenResponse deserialization failed." "TokenResponse deserialization failed."
); );
assertThat("Parsed response is NULL", res, is(notNullValue())); assertNotNull(res, "Parsed response is NULL");
assertThat("Incorrect lease duration", res.getLeaseDuration(), is(RES_LEASE_DURATION)); assertEquals(RES_LEASE_DURATION, res.getLeaseDuration(), "Incorrect lease duration");
assertThat("Incorrect response renewable flag", res.isRenewable(), is(RES_RENEWABLE)); assertEquals(RES_RENEWABLE, res.isRenewable(), "Incorrect response renewable flag");
assertThat("Incorrect response lease duration", res.getLeaseDuration(), is(RES_LEASE_DURATION)); assertEquals(RES_LEASE_DURATION, res.getLeaseDuration(), "Incorrect response lease duration");
// Extract token data. // Extract token data.
TokenData data = res.getData(); TokenData data = res.getData();
assertThat("Token data is NULL", data, is(notNullValue())); assertNotNull(data, "Token data is NULL");
assertThat("Incorrect token accessor", data.getAccessor(), is(TOKEN_ACCESSOR)); assertEquals(TOKEN_ACCESSOR, data.getAccessor(), "Incorrect token accessor");
assertThat("Incorrect token creation time", data.getCreationTime(), is(TOKEN_CREATION_TIME)); assertEquals(TOKEN_CREATION_TIME, data.getCreationTime(), "Incorrect token creation time");
assertThat("Incorrect token creation TTL", data.getCreationTtl(), is(TOKEN_TTL)); assertEquals(TOKEN_TTL, data.getCreationTtl(), "Incorrect token creation TTL");
assertThat("Incorrect token display name", data.getName(), is(TOKEN_DISPLAY_NAME)); assertEquals(TOKEN_DISPLAY_NAME, data.getName(), "Incorrect token display name");
assertThat("Incorrect token entity ID", data.getEntityId(), is(TOKEN_ENTITY_ID)); assertEquals(TOKEN_ENTITY_ID, data.getEntityId(), "Incorrect token entity ID");
assertThat("Incorrect token expire time", data.getExpireTimeString(), is(TOKEN_EXPIRE_TIME)); assertEquals(TOKEN_EXPIRE_TIME, data.getExpireTimeString(), "Incorrect token expire time");
assertThat("Incorrect parsed token expire time", data.getExpireTime(), is(ZonedDateTime.parse(TOKEN_EXPIRE_TIME))); assertEquals(ZonedDateTime.parse(TOKEN_EXPIRE_TIME), data.getExpireTime(), "Incorrect parsed token expire time");
assertThat("Incorrect token explicit max TTL", data.getExplicitMaxTtl(), is(TOKEN_EXPLICIT_MAX_TTL)); assertEquals(TOKEN_EXPLICIT_MAX_TTL, data.getExplicitMaxTtl(), "Incorrect token explicit max TTL");
assertThat("Incorrect token ID", data.getId(), is(TOKEN_ID)); assertEquals(TOKEN_ID, data.getId(), "Incorrect token ID");
assertThat("Incorrect token issue time", data.getIssueTimeString(), is(TOKEN_ISSUE_TIME)); assertEquals(TOKEN_ISSUE_TIME, data.getIssueTimeString(), "Incorrect token issue time");
assertThat("Incorrect parsed token issue time", data.getIssueTime(), is(ZonedDateTime.parse(TOKEN_ISSUE_TIME))); assertEquals(ZonedDateTime.parse(TOKEN_ISSUE_TIME), data.getIssueTime(), "Incorrect parsed token issue time");
assertThat("Incorrect token metadata size", data.getMeta().entrySet(), hasSize(1)); assertEquals(1, data.getMeta().size(), "Incorrect token metadata size");
assertThat("Incorrect token metadata", data.getMeta().get(TOKEN_META_KEY), is(TOKEN_META_VALUE)); assertEquals(TOKEN_META_VALUE, data.getMeta().get(TOKEN_META_KEY), "Incorrect token metadata");
assertThat("Incorrect token number of uses", data.getNumUses(), is(TOKEN_NUM_USES)); assertEquals(TOKEN_NUM_USES, data.getNumUses(), "Incorrect token number of uses");
assertThat("Incorrect token orphan flag", data.isOrphan(), is(TOKEN_ORPHAN)); assertEquals(TOKEN_ORPHAN, data.isOrphan(), "Incorrect token orphan flag");
assertThat("Incorrect token path", data.getPath(), is(TOKEN_PATH)); assertEquals(TOKEN_PATH, data.getPath(), "Incorrect token path");
assertThat("Incorrect number of token policies", data.getPolicies(), hasSize(2)); assertEquals(2, data.getPolicies().size(), "Incorrect number of token policies");
assertThat("Incorrect token policies", data.getPolicies(), contains(TOKEN_POLICY_1, TOKEN_POLICY_2)); assertTrue(data.getPolicies().containsAll(List.of(TOKEN_POLICY_1, TOKEN_POLICY_2)), "Incorrect token policies");
assertThat("Incorrect token renewable flag", data.isRenewable(), is(TOKEN_RENEWABLE)); assertEquals(TOKEN_RENEWABLE, data.isRenewable(), "Incorrect token renewable flag");
assertThat("Incorrect token TTL", data.getTtl(), is(RES_TTL)); assertEquals(RES_TTL, data.getTtl(), "Incorrect token TTL");
assertThat("Incorrect token type", data.getType(), is(TOKEN_TYPE)); 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. * Simple credentials class for JSON testing.
* *
* @author Stefan Kalscheuer * @author Stefan Kalscheuer
* @since 0.1 * @since 0.1
*/ */
public class Credentials { public class Credentials {
@JsonProperty("username") @JsonProperty("username")