From 74092bba9a3946776d28022c4d2eadee1988fe44 Mon Sep 17 00:00:00 2001 From: Stefan Kalscheuer Date: Sat, 12 Jun 2021 13:09:45 +0200 Subject: [PATCH] use plain JUnit for test assertions Hamcrest is a beautiful library, but we try to keep things simple here and switch to plain JUnit 5 assertions for testing. --- pom.xml | 6 - .../HTTPVaultConnectorBuilderTest.java | 18 +- .../HTTPVaultConnectorOfflineTest.java | 39 +- .../connector/HTTPVaultConnectorTest.java | 488 +++++++++--------- .../VaultConnectorExceptionTest.java | 64 +-- .../connector/model/AppRoleSecretTest.java | 127 +++-- .../jvault/connector/model/AppRoleTest.java | 109 ++-- .../connector/model/AuthBackendTest.java | 17 +- .../connector/model/TokenRoleBuilderTest.java | 91 ++-- .../jvault/connector/model/TokenTest.java | 109 ++-- .../model/response/AppRoleResponseTest.java | 31 +- .../response/AuthMethodsResponseTest.java | 39 +- .../model/response/AuthResponseTest.java | 52 +- .../response/CredentialsResponseTest.java | 16 +- .../model/response/HealthResponseTest.java | 27 +- .../model/response/MetadataResponseTest.java | 37 +- .../model/response/SealResponseTest.java | 48 +- .../response/SecretListResponseTest.java | 17 +- .../model/response/SecretResponseTest.java | 74 ++- .../response/SecretVersionResponseTest.java | 17 +- .../model/response/TokenResponseTest.java | 60 ++- .../jvault/connector/test/Credentials.java | 4 +- 22 files changed, 712 insertions(+), 778 deletions(-) diff --git a/pom.xml b/pom.xml index 81aec77..e031f01 100644 --- a/pom.xml +++ b/pom.xml @@ -117,12 +117,6 @@ 5.7.2 test - - org.hamcrest - hamcrest - 2.2 - test - org.mockito mockito-core diff --git a/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorBuilderTest.java b/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorBuilderTest.java index d678bb0..dd0706b 100644 --- a/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorBuilderTest.java +++ b/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorBuilderTest.java @@ -49,14 +49,14 @@ class HTTPVaultConnectorBuilderTest { */ @Test void builderTest() throws Exception { - /* Minimal configuration */ + // Minimal configuration. HTTPVaultConnector connector = HTTPVaultConnector.builder().withHost("vault.example.com").build(); assertEquals("https://vault.example.com:8200/v1/", getRequestHelperPrivate(connector, "baseURL"), "URL not set correctly"); assertNull(getRequestHelperPrivate(connector, "trustedCaCert"), "Trusted CA cert set when no cert provided"); assertEquals(0, getRequestHelperPrivate(connector, "retries"), "Number of retries unexpectedly set"); - /* Specify all options */ + // Specify all options. HTTPVaultConnectorBuilder builder = HTTPVaultConnector.builder() .withHost("vault2.example.com") .withoutTLS() @@ -72,7 +72,7 @@ class HTTPVaultConnectorBuilderTest { assertEquals(5678, getRequestHelperPrivate(connector, "timeout"), "Number timeout value"); assertThrows(ConnectionException.class, builder::buildAndAuth, "Immediate authentication should throw exception without token"); - /* Initialization from URL */ + // Initialization from URL. assertThrows( URISyntaxException.class, () -> HTTPVaultConnector.builder().withBaseURL("foo:/\\1nv4l1d_UrL"), @@ -84,7 +84,7 @@ class HTTPVaultConnectorBuilderTest { ); assertEquals("https://vault3.example.com:5678/bar/", getRequestHelperPrivate(connector, "baseURL"), "URL not set correctly"); - /* Port numbers */ + // Port numbers. assertThrows(IllegalArgumentException.class, () -> HTTPVaultConnector.builder().withPort(65536), "Too large port number should throw an exception"); assertThrows(IllegalArgumentException.class, () -> HTTPVaultConnector.builder().withPort(0), "Port number 0 should throw an exception"); builder = assertDoesNotThrow(() -> HTTPVaultConnector.builder().withPort(-1), "Port number -1 should not throw an exception"); @@ -96,7 +96,7 @@ class HTTPVaultConnectorBuilderTest { */ @Test void testFromEnv() throws Exception { - /* Provide address only should be enough */ + // Provide address only should be enough. withVaultEnv(VAULT_ADDR, null, null, null).execute(() -> { HTTPVaultConnectorBuilder builder = assertDoesNotThrow( () -> HTTPVaultConnector.builder().fromEnv(), @@ -111,7 +111,7 @@ class HTTPVaultConnectorBuilderTest { return null; }); - /* Provide address and number of retries */ + // Provide address and number of retries. withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), null).execute(() -> { HTTPVaultConnectorBuilder builder = assertDoesNotThrow( () -> HTTPVaultConnector.builder().fromEnv(), @@ -126,7 +126,7 @@ class HTTPVaultConnectorBuilderTest { return null; }); - /* Provide CA certificate */ + // Provide CA certificate. String VAULT_CACERT = tempDir.toString() + "/doesnotexist"; withVaultEnv(VAULT_ADDR, VAULT_CACERT, VAULT_MAX_RETRIES.toString(), null).execute(() -> { TlsException e = assertThrows( @@ -140,7 +140,7 @@ class HTTPVaultConnectorBuilderTest { return null; }); - /* Automatic authentication */ + // Automatic authentication. withVaultEnv(VAULT_ADDR, null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN).execute(() -> { HTTPVaultConnectorBuilder builder = assertDoesNotThrow( () -> HTTPVaultConnector.builder().fromEnv(), @@ -151,7 +151,7 @@ class HTTPVaultConnectorBuilderTest { return null; }); - /* Invalid URL */ + // Invalid URL. withVaultEnv("This is not a valid URL!", null, VAULT_MAX_RETRIES.toString(), VAULT_TOKEN).execute(() -> { assertThrows( ConnectionException.class, diff --git a/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorOfflineTest.java b/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorOfflineTest.java index 70016c3..0c888fc 100644 --- a/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorOfflineTest.java +++ b/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorOfflineTest.java @@ -40,12 +40,7 @@ import java.util.Collections; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit test for HTTP Vault connector. @@ -86,9 +81,9 @@ class HTTPVaultConnectorOfflineTest { connector::getHealth, "Querying health status succeeded on invalid instance" ); - assertThat("Unexpected exception message", e.getMessage(), is("Invalid response code")); - assertThat("Unexpected status code in exception", ((InvalidResponseException) e).getStatusCode(), is(responseCode)); - assertThat("Response message where none was expected", ((InvalidResponseException) e).getResponse(), is(nullValue())); + assertEquals("Invalid response code", e.getMessage(), "Unexpected exception message"); + assertEquals(responseCode, ((InvalidResponseException) e).getStatusCode(), "Unexpected status code in exception"); + assertNull(((InvalidResponseException) e).getResponse(), "Response message where none was expected"); // Simulate permission denied response. mockHttpResponse(responseCode, "{\"errors\":[\"permission denied\"]}", "application/json"); @@ -107,8 +102,8 @@ class HTTPVaultConnectorOfflineTest { connector::getHealth, "Querying health status succeeded on invalid instance" ); - assertThat("Unexpected exception message", e.getMessage(), is("Unable to connect to Vault server")); - assertThat("Unexpected cause", e.getCause(), instanceOf(IOException.class)); + assertEquals("Unable to connect to Vault server", e.getMessage(), "Unexpected exception message"); + assertTrue(e.getCause() instanceof IOException, "Unexpected cause"); // Now simulate a failing request that succeeds on second try. connector = HTTPVaultConnector.builder(wireMock.url("/")).withNumberOfRetries(1).withTimeout(250).build(); @@ -144,30 +139,30 @@ class HTTPVaultConnectorOfflineTest { // Most basic constructor expects complete URL. HTTPVaultConnector connector = HTTPVaultConnector.builder(url).build(); - assertThat("Unexpected base URL", getRequestHelperPrivate(connector, "baseURL"), is(url)); + assertEquals(url, getRequestHelperPrivate(connector, "baseURL"), "Unexpected base URL"); // Now override TLS usage. connector = HTTPVaultConnector.builder().withHost(hostname).withoutTLS().build(); - assertThat("Unexpected base URL with TLS disabled", getRequestHelperPrivate(connector, "baseURL"), is(expectedNoTls)); + assertEquals(expectedNoTls, getRequestHelperPrivate(connector, "baseURL"), "Unexpected base URL with TLS disabled"); // Specify custom port. connector = HTTPVaultConnector.builder().withHost(hostname).withTLS().withPort(port).build(); - assertThat("Unexpected base URL with custom port", getRequestHelperPrivate(connector, "baseURL"), is(expectedCustomPort)); + assertEquals(expectedCustomPort, getRequestHelperPrivate(connector, "baseURL"), "Unexpected base URL with custom port"); // Specify custom prefix. connector = HTTPVaultConnector.builder().withHost(hostname).withTLS().withPort(port).withPrefix(prefix).build(); - assertThat("Unexpected base URL with custom prefix", getRequestHelperPrivate(connector, "baseURL"), is(expectedCustomPrefix)); - assertThat("Trusted CA cert set, but not specified", getRequestHelperPrivate(connector, "trustedCaCert"), is(nullValue())); + assertEquals(expectedCustomPrefix, getRequestHelperPrivate(connector, "baseURL"), "Unexpected base URL with custom prefix"); + assertNull(getRequestHelperPrivate(connector, "trustedCaCert"), "Trusted CA cert set, but not specified"); // Specify number of retries. connector = HTTPVaultConnector.builder(url).withTrustedCA(trustedCaCert).withNumberOfRetries(retries).build(); - assertThat("Number of retries not set correctly", getRequestHelperPrivate(connector, "retries"), is(retries)); + assertEquals(retries, getRequestHelperPrivate(connector, "retries"), "Number of retries not set correctly"); // Test TLS version (#22). - assertThat("TLS version should be 1.2 if not specified", getRequestHelperPrivate(connector, "tlsVersion"), is("TLSv1.2")); + assertEquals("TLSv1.2", getRequestHelperPrivate(connector, "tlsVersion"), "TLS version should be 1.2 if not specified"); // Now override. connector = HTTPVaultConnector.builder(url).withTrustedCA(trustedCaCert).withNumberOfRetries(retries).withTLS("TLSv1.1").build(); - assertThat("Overridden TLS version 1.1 not correct", getRequestHelperPrivate(connector, "tlsVersion"), is("TLSv1.1")); + assertEquals("TLSv1.1", getRequestHelperPrivate(connector, "tlsVersion"), "Overridden TLS version 1.1 not correct"); } /** @@ -185,7 +180,7 @@ class HTTPVaultConnectorOfflineTest { connector::sealStatus, "Querying seal status succeeded on invalid instance" ); - assertThat("Unexpected exception message", e.getMessage(), is("Unable to connect to Vault server")); + assertEquals("Unable to connect to Vault server", e.getMessage(), "Unexpected exception message"); } /** @@ -203,7 +198,7 @@ class HTTPVaultConnectorOfflineTest { connector::getHealth, "Querying health status succeeded on invalid instance" ); - assertThat("Unexpected exception message", e.getMessage(), is("Unable to connect to Vault server")); + assertEquals("Unable to connect to Vault server", e.getMessage(), "Unexpected exception message"); } /** @@ -237,7 +232,7 @@ class HTTPVaultConnectorOfflineTest { private void assertParseError(Executable executable, String message) { InvalidResponseException e = assertThrows(InvalidResponseException.class, executable, message); - assertThat("Unexpected exception message", e.getMessage(), is("Unable to parse response")); + assertEquals("Unable to parse response", e.getMessage(), "Unexpected exception message"); } /** diff --git a/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorTest.java b/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorTest.java index f8a7de9..0598c6d 100644 --- a/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorTest.java +++ b/src/test/java/de/stklcode/jvault/connector/HTTPVaultConnectorTest.java @@ -33,12 +33,10 @@ import java.net.ServerSocket; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; import static java.util.Collections.singletonMap; import static org.apache.commons.io.FileUtils.copyDirectory; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.core.Is.is; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -52,7 +50,7 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; */ @Tag("online") class HTTPVaultConnectorTest { - private static String VAULT_VERSION = "1.7.2"; // the vault version this test is supposed to run against + private static String VAULT_VERSION = "1.7.2"; // The vault version this test is supposed to run against. private static final String KEY1 = "E38bkCm0VhUvpdCKGQpcohhD9XmcHJ/2hreOSY019Lho"; private static final String KEY2 = "O5OHwDleY3IiPdgw61cgHlhsrEm6tVJkrxhF6QAnILd1"; private static final String KEY3 = "mw7Bm3nbt/UWa/juDjjL2EPQ04kiJ0saC5JEXwJvXYsB"; @@ -78,10 +76,10 @@ class HTTPVaultConnectorTest { */ @BeforeEach void setUp(TestInfo testInfo, @TempDir File tempDir) throws VaultConnectorException, IOException { - /* Determine, if TLS is required */ + // Determine, if TLS is required. boolean isTls = testInfo.getTags().contains("tls"); - /* Initialize Vault */ + // Initialize Vault. VaultConfiguration config = initializeVault(tempDir, isTls); try { TimeUnit.SECONDS.sleep(1); @@ -89,7 +87,7 @@ class HTTPVaultConnectorTest { e.printStackTrace(); } - /* Initialize connector */ + // Initialize connector. HTTPVaultConnectorBuilder builder = HTTPVaultConnector.builder() .withHost(config.getHost()) .withPort(config.getPort()) @@ -99,7 +97,7 @@ class HTTPVaultConnectorTest { } connector = builder.build(); - /* Unseal Vault and check result */ + // Unseal Vault and check result. SealResponse sealStatus = connector.unseal(KEY1); assumeTrue(sealStatus != null, "Seal status could not be determined after startup"); assumeTrue(sealStatus.isSealed(), "Vault is not sealed after startup"); @@ -136,7 +134,7 @@ class HTTPVaultConnectorTest { authUser(); assumeTrue(connector.isAuthorized()); - /* Try to read path user has no permission to read */ + // Try to read path user has no permission to read. SecretResponse res = null; final String invalidPath = "secret/invalid/path"; @@ -146,54 +144,54 @@ class HTTPVaultConnectorTest { "Invalid secret path should raise an exception" ); - /* Assert that the exception does not reveal secret or credentials */ - assertThat(stackTrace(e), not(stringContainsInOrder(invalidPath))); - assertThat(stackTrace(e), not(stringContainsInOrder(USER_VALID))); - assertThat(stackTrace(e), not(stringContainsInOrder(PASS_VALID))); - assertThat(stackTrace(e), not(matchesPattern("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}"))); + // Assert that the exception does not reveal secret or credentials. + assertFalse(stackTrace(e).contains(invalidPath)); + assertFalse(stackTrace(e).contains(USER_VALID)); + assertFalse(stackTrace(e).contains(PASS_VALID)); + assertFalse(Pattern.compile("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}").matcher(stackTrace(e)).find()); - /* Try to read accessible path with known value */ + // Try to read accessible path with known value. res = assertDoesNotThrow( () -> connector.read(SECRET_PATH + "/" + SECRET_KEY), "Valid secret path could not be read" ); - assertThat("Known secret returned invalid value.", res.get("value"), is(SECRET_VALUE)); + assertEquals(SECRET_VALUE, res.get("value"), "Known secret returned invalid value"); - /* Try to read accessible path with JSON value */ + // Try to read accessible path with JSON value. res = assertDoesNotThrow( () -> connector.read(SECRET_PATH + "/" + SECRET_KEY_JSON), "Valid secret path could not be read" ); - assertThat("Known secret returned null value.", res.get("value"), notNullValue()); + assertNotNull(res.get("value"), "Known secret returned null value"); SecretResponse finalRes = res; Credentials parsedRes = assertDoesNotThrow(() -> finalRes.get("value", Credentials.class), "JSON response could not be parsed"); - assertThat("JSON response was null", parsedRes, notNullValue()); - assertThat("JSON response incorrect", parsedRes.getUsername(), is("user")); - assertThat("JSON response incorrect", parsedRes.getPassword(), is("password")); + assertNotNull(parsedRes, "JSON response was null"); + assertEquals("user", parsedRes.getUsername(), "JSON response incorrect"); + assertEquals("password", parsedRes.getPassword(), "JSON response incorrect"); - /* Try to read accessible path with JSON value */ + // Try to read accessible path with JSON value. res = assertDoesNotThrow( () -> connector.read(SECRET_PATH + "/" + SECRET_KEY_JSON), "Valid secret path could not be read" ); - assertThat("Known secret returned null value.", res.get("value"), notNullValue()); + assertNotNull(res.get("value"), "Known secret returned null value"); SecretResponse finalRes1 = res; parsedRes = assertDoesNotThrow(() -> finalRes1.get("value", Credentials.class), "JSON response could not be parsed"); - assertThat("JSON response was null", parsedRes, notNullValue()); - assertThat("JSON response incorrect", parsedRes.getUsername(), is("user")); - assertThat("JSON response incorrect", parsedRes.getPassword(), is("password")); + assertNotNull(parsedRes, "JSON response was null"); + assertEquals("user", parsedRes.getUsername(), "JSON response incorrect"); + assertEquals("password", parsedRes.getPassword(), "JSON response incorrect"); - /* Try to read accessible complex secret */ + // Try to read accessible complex secret. res = assertDoesNotThrow( () -> connector.read(SECRET_PATH + "/" + SECRET_KEY_COMPLEX), "Valid secret path could not be read" ); - assertThat("Known secret returned null value.", res.getData(), notNullValue()); - assertThat("Unexpected value size", res.getData().keySet(), hasSize(2)); - assertThat("Unexpected value", res.get("key1"), is("value1")); - assertThat("Unexpected value", res.get("key2"), is("value2")); + assertNotNull(res.getData(), "Known secret returned null value"); + assertEquals(2, res.getData().keySet().size(), "Unexpected value size"); + assertEquals("value1", res.get("key1"), "Unexpected value"); + assertEquals("value2", res.get("key2"), "Unexpected value"); } /** @@ -205,13 +203,13 @@ class HTTPVaultConnectorTest { void listSecretsTest() { authRoot(); assumeTrue(connector.isAuthorized()); - /* Try to list secrets from valid path */ + // Try to list secrets from valid path. List secrets = assertDoesNotThrow( () -> connector.list(SECRET_PATH), "Secrets could not be listed" ); - assertThat("Invalid nmber of secrets.", secrets.size(), greaterThan(0)); - assertThat("Known secret key not found", secrets, hasItem(SECRET_KEY)); + assertNotEquals(0, secrets.size(), "Invalid number of secrets"); + assertTrue(secrets.contains(SECRET_KEY), "Known secret key not found"); } /** @@ -225,28 +223,28 @@ class HTTPVaultConnectorTest { authUser(); assumeTrue(connector.isAuthorized()); - /* Try to write to null path */ + // Try to write to null path. assertThrows( InvalidRequestException.class, () -> connector.write(null, "someValue"), "Secret written to null path." ); - /* Try to write to invalid path */ + // Try to write to invalid path. assertThrows( InvalidRequestException.class, () -> connector.write("", "someValue"), "Secret written to invalid path." ); - /* Try to write to a path the user has no access for */ + // Try to write to a path the user has no access for. assertThrows( PermissionDeniedException.class, () -> connector.write("invalid/path", "someValue"), "Secret written to inaccessible path." ); - /* Perform a valid write/read roundtrip to valid path. Also check UTF8-encoding. */ + // Perform a valid write/read roundtrip to valid path. Also check UTF8-encoding. assertDoesNotThrow( () -> connector.write(SECRET_PATH + "/temp", "Abc123äöü,!"), "Failed to write secret to accessible path." @@ -255,7 +253,7 @@ class HTTPVaultConnectorTest { () -> connector.read(SECRET_PATH + "/temp"), "Written secret could not be read." ); - assertThat(res.get("value"), is("Abc123äöü,!")); + assertEquals("Abc123äöü,!", res.get("value")); } /** @@ -268,7 +266,7 @@ class HTTPVaultConnectorTest { authUser(); assumeTrue(connector.isAuthorized()); - /* Write a test secret to vault */ + // Write a test secret to vault. assertDoesNotThrow( () -> connector.write(SECRET_PATH + "/toDelete", "secret content"), "Secret written to inaccessible path." @@ -279,19 +277,19 @@ class HTTPVaultConnectorTest { ); assumeTrue(res != null); - /* Delete secret */ + // Delete secret. assertDoesNotThrow( () -> connector.delete(SECRET_PATH + "/toDelete"), "Revocation threw unexpected exception." ); - /* Try to read again */ + // Try to read again. InvalidResponseException e = assertThrows( InvalidResponseException.class, () -> connector.read(SECRET_PATH + "/toDelete"), "Successfully read deleted secret." ); - assertThat(e.getStatusCode(), is(404)); + assertEquals(404, e.getStatusCode()); } /** @@ -304,7 +302,7 @@ class HTTPVaultConnectorTest { authRoot(); assumeTrue(connector.isAuthorized()); - /* Write a test secret to vault */ + // Write a test secret to vault. assertDoesNotThrow( () -> connector.write(SECRET_PATH + "/toRevoke", "secret content"), "Secret written to inaccessible path." @@ -315,7 +313,7 @@ class HTTPVaultConnectorTest { ); assumeTrue(res != null); - /* Revoke secret */ + // Revoke secret. assertDoesNotThrow( () -> connector.revoke(SECRET_PATH + "/toRevoke"), "Revocation threw unexpected exception." @@ -350,17 +348,17 @@ class HTTPVaultConnectorTest { () -> connector.readSecretData(MOUNT_KV2, SECRET2_KEY), "Valid secret path could not be read." ); - assertThat("Metadata not populated for KV v2 secret", res.getMetadata(), is(notNullValue())); - assertThat("Unexpected secret version", res.getMetadata().getVersion(), is(2)); - assertThat("Known secret returned invalid value.", res.get("value"), is(SECRET2_VALUE2)); + assertNotNull(res.getMetadata(), "Metadata not populated for KV v2 secret"); + assertEquals(2, res.getMetadata().getVersion(), "Unexpected secret version"); + assertEquals(SECRET2_VALUE2, res.get("value"), "Known secret returned invalid value"); // Try to read different version of same secret. res = assertDoesNotThrow( () -> connector.readSecretVersion(MOUNT_KV2, SECRET2_KEY, 1), "Valid secret version could not be read." ); - assertThat("Unexpected secret version", res.getMetadata().getVersion(), is(1)); - assertThat("Known secret returned invalid value.", res.get("value"), is(SECRET2_VALUE1)); + assertEquals(1, res.getMetadata().getVersion(), "Unexpected secret version"); + assertEquals(SECRET2_VALUE1, res.get("value"), "Known secret returned invalid value"); } /** @@ -387,7 +385,7 @@ class HTTPVaultConnectorTest { () -> connector.writeSecretData(MOUNT_KV2, SECRET2_KEY, data), "Writing secret to KV v2 store failed." ); - assertThat("Version not updated after writing secret", res2.getMetadata().getVersion(), is(currentVersion + 1)); + assertEquals(currentVersion + 1, res2.getMetadata().getVersion(), "Version not updated after writing secret"); int currentVersion2 = res2.getMetadata().getVersion(); // Verify the content. @@ -395,7 +393,7 @@ class HTTPVaultConnectorTest { () -> connector.readSecretData(MOUNT_KV2, SECRET2_KEY), "Reading secret from KV v2 store failed." ); - assertThat("Data not updated correctly", res3.get("value"), is(SECRET2_VALUE3)); + assertEquals(SECRET2_VALUE3, res3.get("value"), "Data not updated correctly"); // Now try with explicit CAS value (invalid). Map data4 = singletonMap("value", SECRET2_VALUE4); @@ -439,7 +437,7 @@ class HTTPVaultConnectorTest { () -> connector.readSecretMetadata(MOUNT_KV2, SECRET2_KEY), "Reading secret metadata failed." ); - assertThat("Unexpected maximum number of versions", res.getMetadata().getMaxVersions(), is(maxVersions + 1)); + assertEquals(maxVersions + 1, res.getMetadata().getMaxVersions(), "Unexpected maximum number of versions"); } /** @@ -457,12 +455,12 @@ class HTTPVaultConnectorTest { () -> connector.readSecretMetadata(MOUNT_KV2, SECRET2_KEY), "Valid secret path could not be read." ); - assertThat("Metadata not populated for KV v2 secret", res.getMetadata(), is(notNullValue())); - assertThat("Unexpected secret version", res.getMetadata().getCurrentVersion(), is(2)); - assertThat("Unexpected number of secret versions", res.getMetadata().getVersions().size(), is(2)); - assertThat("Creation date should be present", res.getMetadata().getCreatedTime(), is(notNullValue())); - assertThat("Update date should be present", res.getMetadata().getUpdatedTime(), is(notNullValue())); - assertThat("Unexpected maximum number of versions", res.getMetadata().getMaxVersions(), is(10)); + assertNotNull(res.getMetadata(), "Metadata not populated for KV v2 secret"); + assertEquals(2, res.getMetadata().getCurrentVersion(), "Unexpected secret version"); + assertEquals(2, res.getMetadata().getVersions().size(), "Unexpected number of secret versions"); + assertNotNull(res.getMetadata().getCreatedTime(), "Creation date should be present"); + assertNotNull(res.getMetadata().getUpdatedTime(), "Update date should be present"); + assertEquals(10, res.getMetadata().getMaxVersions(), "Unexpected maximum number of versions"); } /** @@ -494,10 +492,9 @@ class HTTPVaultConnectorTest { () -> connector.readSecretMetadata(MOUNT_KV2, SECRET2_KEY), "Reading deleted secret metadata failed" ); - assertThat( - "Expected deletion time for secret 1", + assertNotNull( meta.getMetadata().getVersions().get(1).getDeletionTime(), - is(notNullValue()) + "Expected deletion time for secret 1" ); // Undelete the just deleted version. @@ -509,10 +506,9 @@ class HTTPVaultConnectorTest { () -> connector.readSecretMetadata(MOUNT_KV2, SECRET2_KEY), "Reading deleted secret metadata failed" ); - assertThat( - "Expected deletion time for secret 1 to be reset", + assertNull( meta.getMetadata().getVersions().get(1).getDeletionTime(), - is(nullValue()) + "Expected deletion time for secret 1 to be reset" ); // Now destroy it. @@ -524,10 +520,9 @@ class HTTPVaultConnectorTest { () -> connector.readSecretMetadata(MOUNT_KV2, SECRET2_KEY), "Reading destroyed secret metadata failed" ); - assertThat( - "Expected secret 1 to be marked destroyed", + assertTrue( meta.getMetadata().getVersions().get(1).isDestroyed(), - is(true) + "Expected secret 1 to be marked destroyed" ); // Delete latest version. @@ -539,10 +534,9 @@ class HTTPVaultConnectorTest { () -> connector.readSecretMetadata(MOUNT_KV2, SECRET2_KEY), "Reading deleted secret metadata failed" ); - assertThat( - "Expected secret 2 to be deleted", + assertNotNull( meta.getMetadata().getVersions().get(2).getDeletionTime(), - is(notNullValue()) + "Expected secret 2 to be deleted" ); // Delete all versions. @@ -572,7 +566,7 @@ class HTTPVaultConnectorTest { @DisplayName("Authenticate with App-ID") @SuppressWarnings("deprecation") void authAppIdTest() { - /* Try unauthorized access first. */ + // Try unauthorized access first. assumeFalse(connector.isAuthorized()); assertThrows( @@ -595,33 +589,33 @@ class HTTPVaultConnectorTest { @DisplayName("Register App-ID") @SuppressWarnings("deprecation") void registerAppIdTest() { - /* Authorize. */ + // Authorize. authRoot(); assumeTrue(connector.isAuthorized()); - /* Register App-ID */ + // Register App-ID. boolean res = assertDoesNotThrow( () -> connector.registerAppId(APP_ID, "user", "App Name"), "Failed to register App-ID" ); - assertThat("Failed to register App-ID", res, is(true)); + assertTrue(res, "Failed to register App-ID"); - /* Register User-ID */ + // Register User-ID. res = assertDoesNotThrow( () -> connector.registerUserId(APP_ID, USER_ID), "Failed to register App-ID" ); - assertThat("Failed to register App-ID", res, is(true)); + assertTrue(res, "Failed to register App-ID"); connector.resetAuth(); assumeFalse(connector.isAuthorized()); - /* Authenticate with created credentials */ + // Authenticate with created credentials. AuthResponse resp = assertDoesNotThrow( () -> connector.authAppId(APP_ID, USER_ID), "Failed to authenticate using App-ID" ); - assertThat("Authorization flag not set after App-ID login.", connector.isAuthorized(), is(true)); + assertTrue(connector.isAuthorized(), "Authorization flag not set after App-ID login"); } } @@ -629,11 +623,11 @@ class HTTPVaultConnectorTest { @DisplayName("AppRole Tests") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class AppRoleTests { - private static final String APPROLE_ROLE_NAME = "testrole1"; // role with secret ID + private static final String APPROLE_ROLE_NAME = "testrole1"; // Role with secret ID. private static final String APPROLE_ROLE = "06eae026-7d4b-e4f8-0ec4-4107eb483975"; private static final String APPROLE_SECRET = "20320293-c1c1-3b22-20f8-e5c960da0b5b"; private static final String APPROLE_SECRET_ACCESSOR = "3b45a7c2-8d1c-abcf-c732-ecf6db16a8e1"; - private static final String APPROLE_ROLE2_NAME = "testrole2"; // role with CIDR subnet + private static final String APPROLE_ROLE2_NAME = "testrole2"; // Role with CIDR subnet. private static final String APPROLE_ROLE2 = "40224890-1563-5193-be4b-0b4f9f573b7f"; /** @@ -645,50 +639,50 @@ class HTTPVaultConnectorTest { void authAppRole() { assumeFalse(connector.isAuthorized()); - /* Authenticate with correct credentials */ + // Authenticate with correct credentials. assertDoesNotThrow( () -> connector.authAppRole(APPROLE_ROLE, APPROLE_SECRET), "Failed to authenticate using AppRole." ); - assertThat("Authorization flag not set after AppRole login.", connector.isAuthorized(), is(true)); + assertTrue(connector.isAuthorized(), "Authorization flag not set after AppRole login"); - /* Authenticate with valid secret ID against unknown role */ + // Authenticate with valid secret ID against unknown role. final String invalidRole = "foo"; InvalidResponseException e = assertThrows( InvalidResponseException.class, () -> connector.authAppRole(invalidRole, APPROLE_SECRET), "Successfully logged in with unknown role" ); - /* Assert that the exception does not reveal role ID or secret */ - assertThat(stackTrace(e), not(stringContainsInOrder(invalidRole))); - assertThat(stackTrace(e), not(stringContainsInOrder(APPROLE_SECRET))); + // Assert that the exception does not reveal role ID or secret. + assertFalse(stackTrace(e).contains(invalidRole)); + assertFalse(stackTrace(e).contains(APPROLE_SECRET)); - /* Authenticate without wrong secret ID */ + // Authenticate without wrong secret ID. final String invalidSecret = "foo"; e = assertThrows( InvalidResponseException.class, () -> connector.authAppRole(APPROLE_ROLE, "foo"), "Successfully logged in without secret ID" ); - /* Assert that the exception does not reveal role ID or secret */ - assertThat(stackTrace(e), not(stringContainsInOrder(APPROLE_ROLE))); - assertThat(stackTrace(e), not(stringContainsInOrder(invalidSecret))); + // Assert that the exception does not reveal role ID or secret. + assertFalse(stackTrace(e).contains(APPROLE_ROLE)); + assertFalse(stackTrace(e).contains(invalidSecret)); - /* Authenticate without secret ID */ + // Authenticate without secret ID. e = assertThrows( InvalidResponseException.class, () -> connector.authAppRole(APPROLE_ROLE), "Successfully logged in without secret ID" ); - /* Assert that the exception does not reveal role ID */ - assertThat(stackTrace(e), not(stringContainsInOrder(APPROLE_ROLE))); + // Assert that the exception does not reveal role ID. + assertFalse(stackTrace(e).contains(APPROLE_ROLE)); - /* Authenticate with secret ID on role with CIDR whitelist */ + // Authenticate with secret ID on role with CIDR whitelist. assertDoesNotThrow( () -> connector.authAppRole(APPROLE_ROLE2, APPROLE_SECRET), "Failed to log in without secret ID" ); - assertThat("Authorization flag not set after AppRole login.", connector.isAuthorized(), is(true)); + assertTrue(connector.isAuthorized(), "Authorization flag not set after AppRole login"); } /** @@ -698,26 +692,26 @@ class HTTPVaultConnectorTest { @Order(20) @DisplayName("List AppRoles") void listAppRoleTest() { - /* Try unauthorized access first. */ + // Try unauthorized access first. assumeFalse(connector.isAuthorized()); assertThrows(AuthorizationRequiredException.class, () -> connector.listAppRoles()); assertThrows(AuthorizationRequiredException.class, () -> connector.listAppRoleSecrets("")); - /* Authorize. */ + // Authorize. authRoot(); assumeTrue(connector.isAuthorized()); - /* Verify pre-existing rules */ - List res = assertDoesNotThrow(() -> connector.listAppRoles(), "Role listing failed."); - assertThat("Unexpected number of AppRoles", res, hasSize(2)); - assertThat("Pre-configured roles not listed", res, containsInAnyOrder(APPROLE_ROLE_NAME, APPROLE_ROLE2_NAME)); + // Verify pre-existing rules. + List res = assertDoesNotThrow(() -> connector.listAppRoles(), "Role listing failed"); + assertEquals(2, res.size(), "Unexpected number of AppRoles"); + assertTrue(res.containsAll(List.of(APPROLE_ROLE_NAME, APPROLE_ROLE2_NAME)), "Pre-configured roles not listed"); - /* Check secret IDs */ - res = assertDoesNotThrow(() -> connector.listAppRoleSecrets(APPROLE_ROLE_NAME), "AppRole secret listing failed."); - assertThat("Unexpected number of AppRole secrets", res, hasSize(1)); - assertThat("Pre-configured AppRole secret not listed", res, contains(APPROLE_SECRET_ACCESSOR)); + // Check secret IDs. + res = assertDoesNotThrow(() -> connector.listAppRoleSecrets(APPROLE_ROLE_NAME), "AppRole secret listing failed"); + assertEquals(1, res.size(), "Unexpected number of AppRole secrets"); + assertEquals(List.of(APPROLE_SECRET_ACCESSOR), res, "Pre-configured AppRole secret not listed"); } /** @@ -727,7 +721,7 @@ class HTTPVaultConnectorTest { @Order(30) @DisplayName("Create AppRole") void createAppRoleTest() { - /* Try unauthorized access first. */ + // Try unauthorized access first. assumeFalse(connector.isAuthorized()); assertThrows(AuthorizationRequiredException.class, () -> connector.createAppRole(new AppRole())); assertThrows(AuthorizationRequiredException.class, () -> connector.lookupAppRole("")); @@ -738,77 +732,77 @@ class HTTPVaultConnectorTest { assertThrows(AuthorizationRequiredException.class, () -> connector.lookupAppRoleSecret("", "")); assertThrows(AuthorizationRequiredException.class, () -> connector.destroyAppRoleSecret("", "")); - /* Authorize. */ + // Authorize. authRoot(); assumeTrue(connector.isAuthorized()); String roleName = "TestRole"; - /* Create role model */ + // Create role model. AppRole role = AppRole.builder(roleName).build(); - /* Create role */ - boolean createRes = assertDoesNotThrow(() -> connector.createAppRole(role), "Role creation failed."); - assertThat("Role creation failed.", createRes, is(true)); + // Create role. + boolean createRes = assertDoesNotThrow(() -> connector.createAppRole(role), "Role creation failed"); + assertTrue(createRes, "Role creation failed"); - /* Lookup role */ - AppRoleResponse res = assertDoesNotThrow(() -> connector.lookupAppRole(roleName), "Role lookup failed."); - assertThat("Role lookup returned no role.", res.getRole(), is(notNullValue())); + // Lookup role. + AppRoleResponse res = assertDoesNotThrow(() -> connector.lookupAppRole(roleName), "Role lookup failed"); + assertNotNull(res.getRole(), "Role lookup returned no role"); - /* Lookup role ID */ - String roleID = assertDoesNotThrow(() -> connector.getAppRoleID(roleName), "Role ID lookup failed."); - assertThat("Role ID lookup returned empty ID.", roleID, is(not(emptyString()))); + // Lookup role ID. + String roleID = assertDoesNotThrow(() -> connector.getAppRoleID(roleName), "Role ID lookup failed"); + assertNotEquals("", roleID, "Role ID lookup returned empty ID"); - /* Set custom role ID */ + // Set custom role ID. String roleID2 = "custom-role-id"; - assertDoesNotThrow(() -> connector.setAppRoleID(roleName, roleID2), "Setting custom role ID failed."); + assertDoesNotThrow(() -> connector.setAppRoleID(roleName, roleID2), "Setting custom role ID failed"); - /* Verify role ID */ - String res2 = assertDoesNotThrow(() -> connector.getAppRoleID(roleName), "Role ID lookup failed."); - assertThat("Role ID lookup returned wrong ID.", res2, is(roleID2)); + // Verify role ID. + String res2 = assertDoesNotThrow(() -> connector.getAppRoleID(roleName), "Role ID lookup failed"); + assertEquals(roleID2, res2, "Role ID lookup returned wrong ID"); - /* Update role model with custom flags */ + // Update role model with custom flags. AppRole role2 = AppRole.builder(roleName) .withTokenPeriod(321) .build(); - /* Create role */ - boolean res3 = assertDoesNotThrow(() -> connector.createAppRole(role2), "Role creation failed."); - assertThat("No result given.", res3, is(notNullValue())); + // Create role. + boolean res3 = assertDoesNotThrow(() -> connector.createAppRole(role2), "Role creation failed"); + assertTrue(res3, "No result given"); - /* Lookup updated role */ - res = assertDoesNotThrow(() -> connector.lookupAppRole(roleName), "Role lookup failed."); - assertThat("Role lookup returned no role.", res.getRole(), is(notNullValue())); - assertThat("Token period not set for role.", res.getRole().getTokenPeriod(), is(321)); + // Lookup updated role. + res = assertDoesNotThrow(() -> connector.lookupAppRole(roleName), "Role lookup failed"); + assertNotNull(res.getRole(), "Role lookup returned no role"); + assertEquals(321, res.getRole().getTokenPeriod(), "Token period not set for role"); - /* Create role by name */ + // Create role by name. String roleName2 = "RoleByName"; - assertDoesNotThrow(() -> connector.createAppRole(roleName2), "Creation of role by name failed."); - res = assertDoesNotThrow(() -> connector.lookupAppRole(roleName2), "Creation of role by name failed."); - assertThat("Role lookuo returned not value", res.getRole(), is(notNullValue())); + assertDoesNotThrow(() -> connector.createAppRole(roleName2), "Creation of role by name failed"); + res = assertDoesNotThrow(() -> connector.lookupAppRole(roleName2), "Creation of role by name failed"); + assertNotNull(res.getRole(), "Role lookuo returned not value"); - /* Create role by name with custom ID */ + // Create role by name with custom ID. String roleName3 = "RoleByName"; String roleID3 = "RolyByNameID"; - assertDoesNotThrow(() -> connector.createAppRole(roleName3, roleID3), "Creation of role by name failed."); - res = assertDoesNotThrow(() -> connector.lookupAppRole(roleName3), "Creation of role by name failed."); - assertThat("Role lookuo returned not value", res.getRole(), is(notNullValue())); + assertDoesNotThrow(() -> connector.createAppRole(roleName3, roleID3), "Creation of role by name failed"); + res = assertDoesNotThrow(() -> connector.lookupAppRole(roleName3), "Creation of role by name failed"); + assertNotNull(res.getRole(), "Role lookuo returned not value"); - res2 = assertDoesNotThrow(() -> connector.getAppRoleID(roleName3), "Creation of role by name failed."); - assertThat("Role lookuo returned wrong ID", res2, is(roleID3)); + res2 = assertDoesNotThrow(() -> connector.getAppRoleID(roleName3), "Creation of role by name failed"); + assertEquals(roleID3, res2, "Role lookuo returned wrong ID"); - /* Create role by name with policies */ + // Create role by name with policies. assertDoesNotThrow( () -> connector.createAppRole(roleName3, Collections.singletonList("testpolicy")), "Creation of role by name failed." ); - res = assertDoesNotThrow(() -> connector.lookupAppRole(roleName3), "Creation of role by name failed."); + res = assertDoesNotThrow(() -> connector.lookupAppRole(roleName3), "Creation of role by name failed"); // Note: As of Vault 0.8.3 default policy is not added automatically, so this test should return 1, not 2. - assertThat("Role lookup returned wrong policy count (before Vault 0.8.3 is should be 2)", res.getRole().getTokenPolicies(), hasSize(1)); - assertThat("Role lookup returned wrong policies", res.getRole().getTokenPolicies(), hasItem("testpolicy")); + assertEquals(1, res.getRole().getTokenPolicies().size(), "Role lookup returned wrong policy count (before Vault 0.8.3 is should be 2)"); + assertTrue(res.getRole().getTokenPolicies().contains("testpolicy"), "Role lookup returned wrong policies"); - /* Delete role */ - assertDoesNotThrow(() -> connector.deleteAppRole(roleName3), "Deletion of role failed."); + // Delete role. + assertDoesNotThrow(() -> connector.deleteAppRole(roleName3), "Deletion of role failed"); assertThrows( InvalidResponseException.class, () -> connector.lookupAppRole(roleName3), @@ -826,29 +820,29 @@ class HTTPVaultConnectorTest { authRoot(); assumeTrue(connector.isAuthorized()); - /* Create default (random) secret for existing role */ + // Create default (random) secret for existing role. AppRoleSecretResponse res = assertDoesNotThrow( () -> connector.createAppRoleSecret(APPROLE_ROLE_NAME), "AppRole secret creation failed." ); - assertThat("No secret returned", res.getSecret(), is(notNullValue())); + assertNotNull(res.getSecret(), "No secret returned"); - /* Create secret with custom ID */ + // Create secret with custom ID. String secretID = "customSecretId"; res = assertDoesNotThrow( () -> connector.createAppRoleSecret(APPROLE_ROLE_NAME, secretID), "AppRole secret creation failed." ); - assertThat("Unexpected secret ID returned", res.getSecret().getId(), is(secretID)); + assertEquals(secretID, res.getSecret().getId(), "Unexpected secret ID returned"); - /* Lookup secret */ + // Lookup secret. res = assertDoesNotThrow( () -> connector.lookupAppRoleSecret(APPROLE_ROLE_NAME, secretID), "AppRole secret lookup failed." ); - assertThat("No secret information returned", res.getSecret(), is(notNullValue())); + assertNotNull(res.getSecret(), "No secret information returned"); - /* Destroy secret */ + // Destroy secret. assertDoesNotThrow( () -> connector.destroyAppRoleSecret(APPROLE_ROLE_NAME, secretID), "AppRole secret destruction failed." @@ -878,8 +872,8 @@ class HTTPVaultConnectorTest { () -> connector.authToken(invalidToken), "Logged in with invalid token" ); - /* Assert that the exception does not reveal the token */ - assertThat(stackTrace(e), not(stringContainsInOrder(invalidToken))); + // Assert that the exception does not reveal the token. + assertFalse(stackTrace(e).contains(invalidToken)); TokenResponse res = assertDoesNotThrow( @@ -887,7 +881,7 @@ class HTTPVaultConnectorTest { "Login failed with valid token" ); assertNotNull(res, "Login failed with valid token"); - assertThat("Login failed with valid token", connector.isAuthorized(), is(true)); + assertTrue(connector.isAuthorized(), "Login failed with valid token"); } /** @@ -900,34 +894,34 @@ class HTTPVaultConnectorTest { authRoot(); assumeTrue(connector.isAuthorized()); - /* Create token */ + // Create token. Token token = Token.builder() .withId("test-id") .withType(Token.Type.SERVICE) .withDisplayName("test name") .build(); - /* Create token */ + // Create token. AuthResponse res = assertDoesNotThrow(() -> connector.createToken(token), "Token creation failed"); - assertThat("No result given.", res, is(notNullValue())); - assertThat("Invalid token ID returned.", res.getAuth().getClientToken(), is("test-id")); - assertThat("Invalid number of policies returned.", res.getAuth().getPolicies(), hasSize(1)); - assertThat("Root policy not inherited.", res.getAuth().getPolicies(), contains("root")); - assertThat("Invalid number of token policies returned.", res.getAuth().getTokenPolicies(), hasSize(1)); - assertThat("Root policy not inherited for token.", res.getAuth().getTokenPolicies(), contains("root")); - assertThat("Unexpected token type.", res.getAuth().getTokenType(), is(Token.Type.SERVICE.value())); - assertThat("Metadata unexpected.", res.getAuth().getMetadata(), is(nullValue())); - assertThat("Root token should not be renewable", res.getAuth().isRenewable(), is(false)); - assertThat("Root token should not be orphan", res.getAuth().isOrphan(), is(false)); + assertNotNull(res, "No result given"); + assertEquals("test-id", res.getAuth().getClientToken(), "Invalid token ID returned"); + assertEquals(1, res.getAuth().getPolicies().size(), "Invalid number of policies returned"); + assertTrue(res.getAuth().getPolicies().contains("root"), "Root policy not inherited"); + assertEquals(1, res.getAuth().getTokenPolicies().size(), "Invalid number of token policies returned"); + assertTrue(res.getAuth().getTokenPolicies().contains("root"), "Root policy not inherited for token"); + assertEquals(Token.Type.SERVICE.value(), res.getAuth().getTokenType(), "Unexpected token type"); + assertNull(res.getAuth().getMetadata(), "Metadata unexpected"); + assertFalse(res.getAuth().isRenewable(), "Root token should not be renewable"); + assertFalse(res.getAuth().isOrphan(), "Root token should not be orphan"); // Starting with Vault 1.0 a warning "custom ID uses weaker SHA1..." is given. if (VAULT_VERSION.startsWith("1.")) { - assertThat("Token creation did not return expected warning.", res.getWarnings(), hasSize(1)); + assertEquals(1, res.getWarnings().size(), "Token creation did not return expected warning"); } else { - assertThat("Token creation returned warnings.", res.getWarnings(), is(nullValue())); + assertNull(res.getWarnings(), "Token creation returned warnings"); } - /* Create token with attributes */ + // Create token with attributes. Token token2 = Token.builder() .withId("test-id2") .withDisplayName("test name 2") @@ -936,14 +930,14 @@ class HTTPVaultConnectorTest { .withMeta("foo", "bar") .build(); res = assertDoesNotThrow(() -> connector.createToken(token2), "Token creation failed"); - assertThat("Invalid token ID returned.", res.getAuth().getClientToken(), is("test-id2")); - assertThat("Invalid number of policies returned.", res.getAuth().getPolicies(), hasSize(1)); - assertThat("Custom policy not set.", res.getAuth().getPolicies(), contains("testpolicy")); - assertThat("Metadata not given.", res.getAuth().getMetadata(), is(notNullValue())); - assertThat("Metadata not correct.", res.getAuth().getMetadata().get("foo"), is("bar")); - assertThat("Token should be renewable", res.getAuth().isRenewable(), is(true)); + assertEquals("test-id2", res.getAuth().getClientToken(), "Invalid token ID returned"); + assertEquals(1, res.getAuth().getPolicies().size(), "Invalid number of policies returned"); + assertTrue(res.getAuth().getPolicies().contains("testpolicy"), "Custom policy not set"); + assertNotNull(res.getAuth().getMetadata(), "Metadata not given"); + assertEquals("bar", res.getAuth().getMetadata().get("foo"), "Metadata not correct"); + assertTrue(res.getAuth().isRenewable(), "Token should be renewable"); - /* Overwrite token should fail as of Vault 0.8.0 */ + // Overwrite token should fail as of Vault 0.8.0. Token token3 = Token.builder() .withId("test-id2") .withDisplayName("test name 3") @@ -958,11 +952,11 @@ class HTTPVaultConnectorTest { () -> connector.createToken(token3), "Overwriting token should fail as of Vault 0.8.0" ); - assertThat(e.getStatusCode(), is(400)); - /* Assert that the exception does not reveal token ID */ - assertThat(stackTrace(e), not(stringContainsInOrder(token3.getId()))); + assertEquals(400, e.getStatusCode()); + // Assert that the exception does not reveal token ID. + assertFalse(stackTrace(e).contains(token3.getId())); - /* Create token with batch type */ + // Create token with batch type. Token token4 = Token.builder() .withDisplayName("test name 3") .withPolicy("batchpolicy") @@ -970,12 +964,12 @@ class HTTPVaultConnectorTest { .withType(Token.Type.BATCH) .build(); res = assertDoesNotThrow(() -> connector.createToken(token4), "Token creation failed"); - assertThat("Unexpected token prefix", res.getAuth().getClientToken(), startsWith("b.")); - assertThat("Invalid number of policies returned.", res.getAuth().getPolicies(), hasSize(1)); - assertThat("Custom policy policy not set.", res.getAuth().getPolicies(), contains("batchpolicy")); - assertThat("Token should not be renewable", res.getAuth().isRenewable(), is(false)); - assertThat("Token should not be orphan", res.getAuth().isOrphan(), is(false)); - assertThat("Specified token Type not set", res.getAuth().getTokenType(), is(Token.Type.BATCH.value())); + assertTrue(res.getAuth().getClientToken().startsWith("b."), "Unexpected token prefix"); + assertEquals(1, res.getAuth().getPolicies().size(), "Invalid number of policies returned"); + assertTrue(res.getAuth().getPolicies().contains("batchpolicy"), "Custom policy policy not set"); + assertFalse(res.getAuth().isRenewable(), "Token should not be renewable"); + assertFalse(res.getAuth().isOrphan(), "Token should not be orphan"); + assertEquals(Token.Type.BATCH.value(), res.getAuth().getTokenType(), "Specified token Type not set"); } /** @@ -988,22 +982,22 @@ class HTTPVaultConnectorTest { authRoot(); assumeTrue(connector.isAuthorized()); - /* Create token with attributes */ + // Create token with attributes. Token token = Token.builder() .withId("my-token") .withType(Token.Type.SERVICE) .build(); - assertDoesNotThrow(() -> connector.createToken(token), "Token creation failed."); + assertDoesNotThrow(() -> connector.createToken(token), "Token creation failed"); authRoot(); assumeTrue(connector.isAuthorized()); - TokenResponse res = assertDoesNotThrow(() -> connector.lookupToken("my-token"), "Token creation failed."); - assertThat("Unexpected token ID", res.getData().getId(), is(token.getId())); - assertThat("Unexpected number of policies", res.getData().getPolicies(), hasSize(1)); - assertThat("Unexpected policy", res.getData().getPolicies(), contains("root")); - assertThat("Unexpected token type", res.getData().getType(), is(token.getType())); - assertThat("Issue time expected to be filled", res.getData().getIssueTime(), is(notNullValue())); + TokenResponse res = assertDoesNotThrow(() -> connector.lookupToken("my-token"), "Token creation failed"); + assertEquals(token.getId(), res.getData().getId(), "Unexpected token ID"); + assertEquals(1, res.getData().getPolicies().size(), "Unexpected number of policies"); + assertTrue(res.getData().getPolicies().contains("root"), "Unexpected policy"); + assertEquals(token.getType(), res.getData().getType(), "Unexpected token type"); + assertNotNull(res.getData().getIssueTime(), "Issue time expected to be filled"); } /** @@ -1024,19 +1018,19 @@ class HTTPVaultConnectorTest { () -> connector.createOrUpdateTokenRole(roleName, role), "Token role creation failed." ); - assertThat("Token role creation failed.", creationRes, is(true)); + assertTrue(creationRes, "Token role creation failed"); // Read the role. TokenRoleResponse res = assertDoesNotThrow( () -> connector.readTokenRole(roleName), "Reading token role failed." ); - assertThat("Token role response must not be null", res, is(notNullValue())); - assertThat("Token role must not be null", res.getData(), is(notNullValue())); - assertThat("Token role name not as expected", res.getData().getName(), is(roleName)); - assertThat("Token role expected to be renewable by default", res.getData().getRenewable(), is(true)); - assertThat("Token role not expected to be orphan by default", res.getData().getOrphan(), is(false)); - assertThat("Unexpected default token type", res.getData().getTokenType(), is(Token.Type.DEFAULT_SERVICE.value())); + assertNotNull(res, "Token role response must not be null"); + assertNotNull(res.getData(), "Token role must not be null"); + assertEquals(roleName, res.getData().getName(), "Token role name not as expected"); + assertTrue(res.getData().getRenewable(), "Token role expected to be renewable by default"); + assertFalse(res.getData().getOrphan(), "Token role not expected to be orphan by default"); + assertEquals(Token.Type.DEFAULT_SERVICE.value(), res.getData().getTokenType(), "Unexpected default token type"); // Update the role, i.e. change some attributes. final TokenRole role2 = TokenRole.builder() @@ -1051,25 +1045,25 @@ class HTTPVaultConnectorTest { () -> connector.createOrUpdateTokenRole(role2), "Token role update failed." ); - assertThat("Token role update failed.", creationRes, is(true)); + assertTrue(creationRes, "Token role update failed"); - res = assertDoesNotThrow(() -> connector.readTokenRole(roleName), "Reading token role failed."); - assertThat("Token role response must not be null", res, is(notNullValue())); - assertThat("Token role must not be null", res.getData(), is(notNullValue())); - assertThat("Token role name not as expected", res.getData().getName(), is(roleName)); - assertThat("Token role not expected to be renewable after update", res.getData().getRenewable(), is(false)); - assertThat("Token role expected to be orphan after update", res.getData().getOrphan(), is(true)); - assertThat("Unexpected number of token uses after update", res.getData().getTokenNumUses(), is(42)); + res = assertDoesNotThrow(() -> connector.readTokenRole(roleName), "Reading token role failed"); + assertNotNull(res, "Token role response must not be null"); + assertNotNull(res.getData(), "Token role must not be null"); + assertEquals(roleName, res.getData().getName(), "Token role name not as expected"); + assertFalse(res.getData().getRenewable(), "Token role not expected to be renewable after update"); + assertTrue(res.getData().getOrphan(), "Token role expected to be orphan after update"); + assertEquals(42, res.getData().getTokenNumUses(), "Unexpected number of token uses after update"); // List roles. - List listRes = assertDoesNotThrow(() -> connector.listTokenRoles(), "Listing token roles failed."); - assertThat("Token role list must not be null", listRes, is(notNullValue())); - assertThat("Unexpected number of token roles", listRes, hasSize(1)); - assertThat("Unexpected token role in list", listRes, contains(roleName)); + List listRes = assertDoesNotThrow(() -> connector.listTokenRoles(), "Listing token roles failed"); + assertNotNull(listRes, "Token role list must not be null"); + assertEquals(1, listRes.size(), "Unexpected number of token roles"); + assertTrue(listRes.contains(roleName), "Unexpected token role in list"); // Delete the role. - creationRes = assertDoesNotThrow(() -> connector.deleteTokenRole(roleName), "Token role deletion failed."); - assertThat("Token role deletion failed.", creationRes, is(true)); + creationRes = assertDoesNotThrow(() -> connector.deleteTokenRole(roleName), "Token role deletion failed"); + assertTrue(creationRes, "Token role deletion failed"); assertThrows(InvalidResponseException.class, () -> connector.readTokenRole(roleName), "Reading nonexistent token role should fail"); assertThrows(InvalidResponseException.class, () -> connector.listTokenRoles(), "Listing nonexistent token roles should fail"); } @@ -1084,7 +1078,7 @@ class HTTPVaultConnectorTest { @Test @DisplayName("List auth methods") void authMethodsTest() { - /* Authenticate as valid user */ + // Authenticate as valid user. assertDoesNotThrow(() -> connector.authToken(TOKEN_ROOT)); assumeTrue(connector.isAuthorized()); @@ -1092,8 +1086,8 @@ class HTTPVaultConnectorTest { () -> connector.getAuthBackends(), "Could not list supported auth backends." ); - assertThat(supportedBackends, hasSize(4)); - assertThat(supportedBackends, hasItems(AuthBackend.TOKEN, AuthBackend.USERPASS, AuthBackend.APPID, AuthBackend.APPROLE)); + assertEquals(4, supportedBackends.size()); + assertTrue(supportedBackends.containsAll(List.of(AuthBackend.TOKEN, AuthBackend.USERPASS, AuthBackend.APPID, AuthBackend.APPROLE))); } /** @@ -1109,16 +1103,16 @@ class HTTPVaultConnectorTest { () -> connector.authUserPass(invalidUser, invalidPass), "Logged in with invalid credentials" ); - /* Assert that the exception does not reveal credentials */ - assertThat(stackTrace(e), not(stringContainsInOrder(invalidUser))); - assertThat(stackTrace(e), not(stringContainsInOrder(invalidPass))); + // Assert that the exception does not reveal credentials. + assertFalse(stackTrace(e).contains(invalidUser)); + assertFalse(stackTrace(e).contains(invalidPass)); AuthResponse res = assertDoesNotThrow( () -> connector.authUserPass(USER_VALID, PASS_VALID), "Login failed with valid credentials: Exception thrown" ); assertNotNull(res.getAuth(), "Login failed with valid credentials: Response not available"); - assertThat("Login failed with valid credentials: Connector not authorized", connector.isAuthorized(), is(true)); + assertTrue(connector.isAuthorized(), "Login failed with valid credentials: Connector not authorized"); } /** @@ -1139,7 +1133,7 @@ class HTTPVaultConnectorTest { "Login failed with valid token" ); assertNotNull(res, "Login failed with valid token"); - assertThat("Login failed with valid token", connector.isAuthorized(), is(true)); + assertTrue(connector.isAuthorized(), "Login failed with valid token"); } /** @@ -1151,20 +1145,20 @@ class HTTPVaultConnectorTest { SealResponse sealStatus = connector.sealStatus(); assumeFalse(sealStatus.isSealed()); - /* Unauthorized sealing should fail */ + // Unauthorized sealing should fail. assertThrows(VaultConnectorException.class, connector::seal, "Unauthorized sealing succeeded"); - assertThat("Vault sealed, although sealing failed", sealStatus.isSealed(), is(false)); + assertFalse(sealStatus.isSealed(), "Vault sealed, although sealing failed"); - /* Root user should be able to seal */ + // Root user should be able to seal. authRoot(); assumeTrue(connector.isAuthorized()); assertDoesNotThrow(connector::seal, "Sealing failed"); sealStatus = connector.sealStatus(); - assertThat("Vault not sealed", sealStatus.isSealed(), is(true)); + assertTrue(sealStatus.isSealed(), "Vault not sealed"); sealStatus = connector.unseal(KEY2); - assertThat("Vault unsealed with only 1 key", sealStatus.isSealed(), is(true)); + assertTrue(sealStatus.isSealed(), "Vault unsealed with only 1 key"); sealStatus = connector.unseal(KEY3); - assertThat("Vault not unsealed", sealStatus.isSealed(), is(false)); + assertFalse(sealStatus.isSealed(), "Vault not unsealed"); } /** @@ -1173,12 +1167,12 @@ class HTTPVaultConnectorTest { @Test @DisplayName("Health test") void healthTest() { - HealthResponse res = assertDoesNotThrow(connector::getHealth, "Retrieving health status failed."); - assertThat("Health response should be set", res, is(notNullValue())); - assertThat("Unexpected version", res.getVersion(), is(VAULT_VERSION)); - assertThat("Unexpected init status", res.isInitialized(), is(true)); - assertThat("Unexpected seal status", res.isSealed(), is(false)); - assertThat("Unexpected standby status", res.isStandby(), is(false)); + HealthResponse res = assertDoesNotThrow(connector::getHealth, "Retrieving health status failed"); + assertNotNull(res, "Health response should be set"); + assertEquals(VAULT_VERSION, res.getVersion(), "Unexpected version"); + assertTrue(res.isInitialized(), "Unexpected init status"); + assertFalse(res.isSealed(), "Unexpected seal status"); + assertFalse(res.isStandby(), "Unexpected standby status"); // No seal vault and verify correct status. authRoot(); @@ -1187,7 +1181,7 @@ class HTTPVaultConnectorTest { assumeTrue(sealStatus.isSealed()); connector.resetAuth(); // Should work unauthenticated res = assertDoesNotThrow(connector::getHealth, "Retrieving health status failed when sealed"); - assertThat("Unexpected seal status", res.isSealed(), is(true)); + assertTrue(res.isSealed(), "Unexpected seal status"); } /** @@ -1200,12 +1194,12 @@ class HTTPVaultConnectorTest { assumeTrue(connector.isAuthorized()); assertDoesNotThrow(connector::close, "Closing the connector failed"); - assertThat("Not unauthorized after close().", connector.isAuthorized(), is(false)); + assertFalse(connector.isAuthorized(), "Not unauthorized after close()"); - /* Verify that (private) token has indeed been removed */ + // Verify that (private) token has indeed been removed. Field tokenField = HTTPVaultConnector.class.getDeclaredField("token"); tokenField.setAccessible(true); - assertThat("Token not removed after close().", tokenField.get(connector), is(nullValue())); + assertNull(tokenField.get(connector), "Token not removed after close()"); } } @@ -1221,21 +1215,21 @@ class HTTPVaultConnectorTest { File dataDir = new File(dir, "data"); copyDirectory(new File(getClass().getResource("/data_dir").getPath()), dataDir); - /* Generate vault local unencrypted configuration */ + // Generate vault local unencrypted configuration. VaultConfiguration config = new VaultConfiguration() .withHost("localhost") .withPort(getFreePort()) .withDataLocation(dataDir.toPath()) .disableMlock(); - /* Enable TLS with custom certificate and key, if required */ + // Enable TLS with custom certificate and key, if required. if (tls) { config.enableTLS() .withCert(getClass().getResource("/tls/server.pem").getPath()) .withKey(getClass().getResource("/tls/server.key").getPath()); } - /* Write configuration file */ + // Write configuration file. BufferedWriter bw = null; File configFile; try { @@ -1253,7 +1247,7 @@ class HTTPVaultConnectorTest { } } - /* Start vault process */ + // Start vault process. try { vaultProcess = Runtime.getRuntime().exec("vault server -config " + configFile.toString()); } catch (IOException e) { @@ -1267,7 +1261,7 @@ class HTTPVaultConnectorTest { * Authenticate with root token. */ private void authRoot() { - /* Authenticate as valid user */ + // Authenticate as valid user. assertDoesNotThrow(() -> connector.authToken(TOKEN_ROOT)); } diff --git a/src/test/java/de/stklcode/jvault/connector/exception/VaultConnectorExceptionTest.java b/src/test/java/de/stklcode/jvault/connector/exception/VaultConnectorExceptionTest.java index 8d2f433..ae67976 100644 --- a/src/test/java/de/stklcode/jvault/connector/exception/VaultConnectorExceptionTest.java +++ b/src/test/java/de/stklcode/jvault/connector/exception/VaultConnectorExceptionTest.java @@ -18,10 +18,8 @@ package de.stklcode.jvault.connector.exception; import org.junit.jupiter.api.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.core.Is.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Common JUnit test for Exceptions extending {@link VaultConnectorException}. @@ -65,42 +63,39 @@ class VaultConnectorExceptionTest { // Constructor with message and status code. InvalidResponseException e = new InvalidResponseException(MSG, STATUS_CODE); - assertThat(e.getMessage(), is(MSG)); - assertThat(e.getCause(), is(nullValue())); - assertThat(e.getStatusCode(), is(STATUS_CODE)); - assertThat(e.getResponse(), is(nullValue())); + assertEquals(MSG, e.getMessage()); + assertNull(e.getCause()); + assertEquals(STATUS_CODE, e.getStatusCode()); + assertNull(e.getResponse()); // Constructor with message, status code and cause. e = new InvalidResponseException(MSG, STATUS_CODE, CAUSE); - assertThat(e.getMessage(), is(MSG)); - assertThat(e.getCause(), is(CAUSE)); - assertThat(e.getStatusCode(), is(STATUS_CODE)); - assertThat(e.getResponse(), is(nullValue())); + assertEquals(MSG, e.getMessage()); + assertEquals(CAUSE, e.getCause()); + assertEquals(STATUS_CODE, e.getStatusCode()); + assertNull(e.getResponse()); // Constructor with message, status code and response. e = new InvalidResponseException(MSG, STATUS_CODE, RESPONSE); - assertThat(e.getMessage(), is(MSG)); - assertThat(e.getCause(), is(nullValue())); - assertThat(e.getStatusCode(), is(STATUS_CODE)); - assertThat(e.getResponse(), is(RESPONSE)); + assertEquals(MSG, e.getMessage()); + assertNull(e.getCause()); + assertEquals(STATUS_CODE, e.getStatusCode()); + assertEquals(RESPONSE, e.getResponse()); // Constructor with message, status code, response and cause. e = new InvalidResponseException(MSG, STATUS_CODE, RESPONSE, CAUSE); - assertThat(e.getMessage(), is(MSG)); - assertThat(e.getCause(), is(CAUSE)); - assertThat(e.getStatusCode(), is(STATUS_CODE)); - assertThat(e.getResponse(), is(RESPONSE)); + assertEquals(MSG, e.getMessage()); + assertEquals(CAUSE, e.getCause()); + assertEquals(STATUS_CODE, e.getStatusCode()); + assertEquals(RESPONSE, e.getResponse()); } @Test void permissionDeniedExceptionTest() { // Default message overwritten. PermissionDeniedException e = new PermissionDeniedException(); - assertThat(e, is(instanceOf(VaultConnectorException.class))); - assertThat(e, is(instanceOf(Exception.class))); - assertThat(e, is(instanceOf(Throwable.class))); - assertThat(e.getMessage(), is("Permission denied")); - assertThat(e.getCause(), is(nullValue())); + assertEquals("Permission denied", e.getMessage()); + assertNull(e.getCause()); assertMsgConstructor(new PermissionDeniedException(MSG)); assertCauseConstructor(new PermissionDeniedException(CAUSE)); @@ -121,11 +116,8 @@ class VaultConnectorExceptionTest { * @param e the exception */ private void assertEmptyConstructor(VaultConnectorException e) { - assertThat(e, is(instanceOf(VaultConnectorException.class))); - assertThat(e, is(instanceOf(Exception.class))); - assertThat(e, is(instanceOf(Throwable.class))); - assertThat(e.getMessage(), is(nullValue())); - assertThat(e.getCause(), is(nullValue())); + assertNull(e.getMessage()); + assertNull(e.getCause()); } /** @@ -134,8 +126,8 @@ class VaultConnectorExceptionTest { * @param e the exception */ private void assertMsgConstructor(VaultConnectorException e) { - assertThat(e.getMessage(), is(MSG)); - assertThat(e.getCause(), is(nullValue())); + assertEquals(MSG, e.getMessage()); + assertNull(e.getCause()); } /** @@ -144,8 +136,8 @@ class VaultConnectorExceptionTest { * @param e the exception */ private void assertCauseConstructor(VaultConnectorException e) { - assertThat(e.getMessage(), is(CAUSE.toString())); - assertThat(e.getCause(), is(CAUSE)); + assertEquals(CAUSE.toString(), e.getMessage()); + assertEquals(CAUSE, e.getCause()); } /** @@ -154,7 +146,7 @@ class VaultConnectorExceptionTest { * @param e the exception */ private void assertMsgCauseConstructor(VaultConnectorException e) { - assertThat(e.getMessage(), is(MSG)); - assertThat(e.getCause(), is(CAUSE)); + assertEquals(MSG, e.getMessage()); + assertEquals(CAUSE, e.getCause()); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/AppRoleSecretTest.java b/src/test/java/de/stklcode/jvault/connector/model/AppRoleSecretTest.java index 693569c..79fd8c3 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/AppRoleSecretTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/AppRoleSecretTest.java @@ -25,9 +25,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -38,7 +36,6 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; * @since 0.5.0 */ class AppRoleSecretTest { - private static final String TEST_ID = "abc123"; private static final Map TEST_META = new HashMap<>(); private static final List TEST_CIDR = Arrays.asList("203.0.113.0/24", "198.51.100.0/24"); @@ -53,44 +50,44 @@ class AppRoleSecretTest { */ @Test void constructorTest() { - /* Empty constructor */ + // Empty constructor. AppRoleSecret secret = new AppRoleSecret(); - assertThat(secret.getId(), is(nullValue())); - assertThat(secret.getAccessor(), is(nullValue())); - assertThat(secret.getMetadata(), is(nullValue())); - assertThat(secret.getCidrList(), is(nullValue())); - assertThat(secret.getCidrListString(), is(emptyString())); - assertThat(secret.getCreationTime(), is(nullValue())); - assertThat(secret.getExpirationTime(), is(nullValue())); - assertThat(secret.getLastUpdatedTime(), is(nullValue())); - assertThat(secret.getNumUses(), is(nullValue())); - assertThat(secret.getTtl(), is(nullValue())); + assertNull(secret.getId()); + assertNull(secret.getAccessor()); + assertNull(secret.getMetadata()); + assertNull(secret.getCidrList()); + assertEquals("", secret.getCidrListString()); + assertNull(secret.getCreationTime()); + assertNull(secret.getExpirationTime()); + assertNull(secret.getLastUpdatedTime()); + assertNull(secret.getNumUses()); + assertNull(secret.getTtl()); - /* Constructor with ID */ + // Constructor with ID. secret = new AppRoleSecret(TEST_ID); - assertThat(secret.getId(), is(TEST_ID)); - assertThat(secret.getAccessor(), is(nullValue())); - assertThat(secret.getMetadata(), is(nullValue())); - assertThat(secret.getCidrList(), is(nullValue())); - assertThat(secret.getCidrListString(), is(emptyString())); - assertThat(secret.getCreationTime(), is(nullValue())); - assertThat(secret.getExpirationTime(), is(nullValue())); - assertThat(secret.getLastUpdatedTime(), is(nullValue())); - assertThat(secret.getNumUses(), is(nullValue())); - assertThat(secret.getTtl(), is(nullValue())); + assertEquals(TEST_ID, secret.getId()); + assertNull(secret.getAccessor()); + assertNull(secret.getMetadata()); + assertNull(secret.getCidrList()); + assertEquals("", secret.getCidrListString()); + assertNull(secret.getCreationTime()); + assertNull(secret.getExpirationTime()); + assertNull(secret.getLastUpdatedTime()); + assertNull(secret.getNumUses()); + assertNull(secret.getTtl()); - /* Constructor with Metadata and CIDR bindings */ + // Constructor with Metadata and CIDR bindings. secret = new AppRoleSecret(TEST_ID, TEST_META, TEST_CIDR); - assertThat(secret.getId(), is(TEST_ID)); - assertThat(secret.getAccessor(), is(nullValue())); - assertThat(secret.getMetadata(), is(TEST_META)); - assertThat(secret.getCidrList(), is(TEST_CIDR)); - assertThat(secret.getCidrListString(), is(String.join(",", TEST_CIDR))); - assertThat(secret.getCreationTime(), is(nullValue())); - assertThat(secret.getExpirationTime(), is(nullValue())); - assertThat(secret.getLastUpdatedTime(), is(nullValue())); - assertThat(secret.getNumUses(), is(nullValue())); - assertThat(secret.getTtl(), is(nullValue())); + assertEquals(TEST_ID, secret.getId()); + assertNull(secret.getAccessor()); + assertEquals(TEST_META, secret.getMetadata()); + assertEquals(TEST_CIDR, secret.getCidrList()); + assertEquals(String.join(",", TEST_CIDR), secret.getCidrListString()); + assertNull(secret.getCreationTime()); + assertNull(secret.getExpirationTime()); + assertNull(secret.getLastUpdatedTime()); + assertNull(secret.getNumUses()); + assertNull(secret.getTtl()); } /** @@ -99,14 +96,14 @@ class AppRoleSecretTest { @Test void setterTest() { AppRoleSecret secret = new AppRoleSecret(TEST_ID); - assertThat(secret.getCidrList(), is(nullValue())); - assertThat(secret.getCidrListString(), is(emptyString())); + assertNull(secret.getCidrList()); + assertEquals("", secret.getCidrListString()); secret.setCidrList(TEST_CIDR); - assertThat(secret.getCidrList(), is(TEST_CIDR)); - assertThat(secret.getCidrListString(), is(String.join(",", TEST_CIDR))); + assertEquals(TEST_CIDR, secret.getCidrList()); + assertEquals(String.join(",", TEST_CIDR), secret.getCidrListString()); secret.setCidrList(null); - assertThat(secret.getCidrList(), is(nullValue())); - assertThat(secret.getCidrListString(), is(emptyString())); + assertNull(secret.getCidrList()); + assertEquals("", secret.getCidrListString()); } /** @@ -116,21 +113,21 @@ class AppRoleSecretTest { void jsonTest() throws NoSuchFieldException, IllegalAccessException { ObjectMapper mapper = new ObjectMapper(); - /* A simple roundtrip first. All set fields should be present afterwards. */ + // A simple roundtrip first. All set fields should be present afterwards.. AppRoleSecret secret = new AppRoleSecret(TEST_ID, TEST_META, TEST_CIDR); String secretJson = assertDoesNotThrow(() -> mapper.writeValueAsString(secret), "Serialization failed"); - /* CIDR list is comma-separated when used as input, but List otherwise, hence convert string to list */ + // CIDR list is comma-separated when used as input, but List otherwise, hence convert string to list. String secretJson2 = commaSeparatedToList(secretJson); AppRoleSecret secret2 = assertDoesNotThrow( () -> mapper.readValue(secretJson2, AppRoleSecret.class), "Deserialization failed" ); - assertThat(secret.getId(), is(secret2.getId())); - assertThat(secret.getMetadata(), is(secret2.getMetadata())); - assertThat(secret.getCidrList(), is(secret2.getCidrList())); + assertEquals(secret2.getId(), secret.getId()); + assertEquals(secret2.getMetadata(), secret.getMetadata()); + assertEquals(secret2.getCidrList(), secret.getCidrList()); - /* Test fields, that should not be written to JSON */ + // Test fields, that should not be written to JSON. setPrivateField(secret, "accessor", "TEST_ACCESSOR"); assumeTrue("TEST_ACCESSOR".equals(secret.getAccessor())); setPrivateField(secret, "creationTime", "TEST_CREATION"); @@ -148,28 +145,28 @@ class AppRoleSecretTest { () -> mapper.readValue(commaSeparatedToList(secretJson3), AppRoleSecret.class), "Deserialization failed" ); - assertThat(secret.getId(), is(secret2.getId())); - assertThat(secret.getMetadata(), is(secret2.getMetadata())); - assertThat(secret.getCidrList(), is(secret2.getCidrList())); - assertThat(secret2.getAccessor(), is(nullValue())); - assertThat(secret2.getCreationTime(), is(nullValue())); - assertThat(secret2.getExpirationTime(), is(nullValue())); - assertThat(secret2.getLastUpdatedTime(), is(nullValue())); - assertThat(secret2.getNumUses(), is(nullValue())); - assertThat(secret2.getTtl(), is(nullValue())); + assertEquals(secret2.getId(), secret.getId()); + assertEquals(secret2.getMetadata(), secret.getMetadata()); + assertEquals(secret2.getCidrList(), secret.getCidrList()); + assertNull(secret2.getAccessor()); + assertNull(secret2.getCreationTime()); + assertNull(secret2.getExpirationTime()); + assertNull(secret2.getLastUpdatedTime()); + assertNull(secret2.getNumUses()); + assertNull(secret2.getTtl()); - /* Those fields should be deserialized from JSON though */ + // Those fields should be deserialized from JSON though. String secretJson4 = "{\"secret_id\":\"abc123\",\"metadata\":{\"number\":1337,\"foo\":\"bar\"}," + "\"cidr_list\":[\"203.0.113.0/24\",\"198.51.100.0/24\"],\"secret_id_accessor\":\"TEST_ACCESSOR\"," + "\"creation_time\":\"TEST_CREATION\",\"expiration_time\":\"TEST_EXPIRATION\"," + "\"last_updated_time\":\"TEST_LASTUPDATE\",\"secret_id_num_uses\":678,\"secret_id_ttl\":12345}"; secret2 = assertDoesNotThrow(() -> mapper.readValue(secretJson4, AppRoleSecret.class), "Deserialization failed"); - assertThat(secret2.getAccessor(), is("TEST_ACCESSOR")); - assertThat(secret2.getCreationTime(), is("TEST_CREATION")); - assertThat(secret2.getExpirationTime(), is("TEST_EXPIRATION")); - assertThat(secret2.getLastUpdatedTime(), is("TEST_LASTUPDATE")); - assertThat(secret2.getNumUses(), is(678)); - assertThat(secret2.getTtl(), is(12345)); + assertEquals("TEST_ACCESSOR", secret2.getAccessor()); + assertEquals("TEST_CREATION", secret2.getCreationTime()); + assertEquals("TEST_EXPIRATION", secret2.getExpirationTime()); + assertEquals("TEST_LASTUPDATE", secret2.getLastUpdatedTime()); + assertEquals(678, secret2.getNumUses()); + assertEquals(12345, secret2.getTtl()); } diff --git a/src/test/java/de/stklcode/jvault/connector/model/AppRoleTest.java b/src/test/java/de/stklcode/jvault/connector/model/AppRoleTest.java index 50a0296..d92c5b1 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/AppRoleTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/AppRoleTest.java @@ -24,8 +24,7 @@ import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link AppRole} and {@link AppRole.Builder}. @@ -69,24 +68,24 @@ class AppRoleTest { @Test void buildDefaultTest() throws JsonProcessingException { AppRole role = AppRole.builder(NAME).build(); - assertThat(role.getId(), is(nullValue())); - assertThat(role.getBindSecretId(), is(nullValue())); - assertThat(role.getSecretIdBoundCidrs(), is(nullValue())); - assertThat(role.getTokenPolicies(), is(nullValue())); - assertThat(role.getSecretIdNumUses(), is(nullValue())); - assertThat(role.getSecretIdTtl(), is(nullValue())); - assertThat(role.getEnableLocalSecretIds(), is(nullValue())); - assertThat(role.getTokenTtl(), is(nullValue())); - assertThat(role.getTokenMaxTtl(), is(nullValue())); - assertThat(role.getTokenBoundCidrs(), is(nullValue())); - assertThat(role.getTokenExplicitMaxTtl(), is(nullValue())); - assertThat(role.getTokenNoDefaultPolicy(), is(nullValue())); - assertThat(role.getTokenNumUses(), is(nullValue())); - assertThat(role.getTokenPeriod(), is(nullValue())); - assertThat(role.getTokenType(), is(nullValue())); + assertNull(role.getId()); + assertNull(role.getBindSecretId()); + assertNull(role.getSecretIdBoundCidrs()); + assertNull(role.getTokenPolicies()); + assertNull(role.getSecretIdNumUses()); + assertNull(role.getSecretIdTtl()); + assertNull(role.getEnableLocalSecretIds()); + assertNull(role.getTokenTtl()); + assertNull(role.getTokenMaxTtl()); + assertNull(role.getTokenBoundCidrs()); + assertNull(role.getTokenExplicitMaxTtl()); + assertNull(role.getTokenNoDefaultPolicy()); + assertNull(role.getTokenNumUses()); + assertNull(role.getTokenPeriod()); + assertNull(role.getTokenType()); - /* optional fields should be ignored, so JSON string should only contain role_name */ - assertThat(new ObjectMapper().writeValueAsString(role), is(JSON_MIN)); + // Optional fields should be ignored, so JSON string should only contain role_name. + assertEquals(JSON_MIN, new ObjectMapper().writeValueAsString(role)); } /** @@ -111,25 +110,25 @@ class AppRoleTest { .withTokenPeriod(TOKEN_PERIOD) .withTokenType(TOKEN_TYPE) .build(); - assertThat(role.getName(), is(NAME)); - assertThat(role.getId(), is(ID)); - assertThat(role.getBindSecretId(), is(BIND_SECRET_ID)); - assertThat(role.getSecretIdBoundCidrs(), is(BOUND_CIDR_LIST)); - assertThat(role.getTokenPolicies(), is(POLICIES)); - assertThat(role.getSecretIdNumUses(), is(SECRET_ID_NUM_USES)); - assertThat(role.getSecretIdTtl(), is(SECRET_ID_TTL)); - assertThat(role.getEnableLocalSecretIds(), is(ENABLE_LOCAL_SECRET_IDS)); - assertThat(role.getTokenTtl(), is(TOKEN_TTL)); - assertThat(role.getTokenMaxTtl(), is(TOKEN_MAX_TTL)); - assertThat(role.getTokenBoundCidrs(), is(BOUND_CIDR_LIST)); - assertThat(role.getTokenExplicitMaxTtl(), is(TOKEN_EXPLICIT_MAX_TTL)); - assertThat(role.getTokenNoDefaultPolicy(), is(TOKEN_NO_DEFAULT_POLICY)); - assertThat(role.getTokenNumUses(), is(TOKEN_NUM_USES)); - assertThat(role.getTokenPeriod(), is(TOKEN_PERIOD)); - assertThat(role.getTokenType(), is(TOKEN_TYPE.value())); + assertEquals(NAME, role.getName()); + assertEquals(ID, role.getId()); + assertEquals(BIND_SECRET_ID, role.getBindSecretId()); + assertEquals(BOUND_CIDR_LIST, role.getSecretIdBoundCidrs()); + assertEquals(POLICIES, role.getTokenPolicies()); + assertEquals(SECRET_ID_NUM_USES, role.getSecretIdNumUses()); + assertEquals(SECRET_ID_TTL, role.getSecretIdTtl()); + assertEquals(ENABLE_LOCAL_SECRET_IDS, role.getEnableLocalSecretIds()); + assertEquals(TOKEN_TTL, role.getTokenTtl()); + assertEquals(TOKEN_MAX_TTL, role.getTokenMaxTtl()); + assertEquals(BOUND_CIDR_LIST, role.getTokenBoundCidrs()); + assertEquals(TOKEN_EXPLICIT_MAX_TTL, role.getTokenExplicitMaxTtl()); + assertEquals(TOKEN_NO_DEFAULT_POLICY, role.getTokenNoDefaultPolicy()); + assertEquals(TOKEN_NUM_USES, role.getTokenNumUses()); + assertEquals(TOKEN_PERIOD, role.getTokenPeriod()); + assertEquals(TOKEN_TYPE.value(), role.getTokenType()); - /* Verify that all parameters are included in JSON string */ - assertThat(new ObjectMapper().writeValueAsString(role), is(JSON_FULL)); + // Verify that all parameters are included in JSON string. + assertEquals(JSON_FULL, new ObjectMapper().writeValueAsString(role)); } /** @@ -137,40 +136,40 @@ class AppRoleTest { */ @Test void convenienceMethodsTest() { - /* bind_secret_id */ + // bind_secret_id. AppRole role = AppRole.builder(NAME).build(); - assertThat(role.getBindSecretId(), is(nullValue())); + assertNull(role.getBindSecretId()); role = AppRole.builder(NAME).withBindSecretID().build(); - assertThat(role.getBindSecretId(), is(true)); + assertEquals(true, role.getBindSecretId()); role = AppRole.builder(NAME).withoutBindSecretID().build(); - assertThat(role.getBindSecretId(), is(false)); + assertEquals(false, role.getBindSecretId()); - /* Add single CIDR subnet */ + // Add single CIDR subnet. role = AppRole.builder(NAME).withSecretBoundCidr(CIDR_2).withTokenBoundCidr(CIDR_2).build(); - assertThat(role.getSecretIdBoundCidrs(), hasSize(1)); - assertThat(role.getSecretIdBoundCidrs(), contains(CIDR_2)); - assertThat(role.getTokenBoundCidrs(), hasSize(1)); - assertThat(role.getTokenBoundCidrs(), contains(CIDR_2)); + assertEquals(1, role.getSecretIdBoundCidrs().size()); + assertEquals(CIDR_2, role.getSecretIdBoundCidrs().get(0)); + assertEquals(1, role.getTokenBoundCidrs().size()); + assertEquals(CIDR_2, role.getTokenBoundCidrs().get(0)); role = AppRole.builder(NAME) .withSecretIdBoundCidrs(BOUND_CIDR_LIST) .withSecretBoundCidr(CIDR_2) .withTokenBoundCidrs(BOUND_CIDR_LIST) .withTokenBoundCidr(CIDR_2) .build(); - assertThat(role.getSecretIdBoundCidrs(), hasSize(2)); - assertThat(role.getSecretIdBoundCidrs(), contains(CIDR_1, CIDR_2)); - assertThat(role.getTokenBoundCidrs(), hasSize(2)); - assertThat(role.getSecretIdBoundCidrs(), contains(CIDR_1, CIDR_2)); + assertEquals(2, role.getSecretIdBoundCidrs().size()); + assertTrue(role.getSecretIdBoundCidrs().containsAll(List.of(CIDR_1, CIDR_2))); + assertEquals(2, role.getTokenBoundCidrs().size()); + assertTrue(role.getSecretIdBoundCidrs().containsAll(List.of(CIDR_1, CIDR_2))); - /* Add single policy */ + // Add single policy. role = AppRole.builder(NAME).withTokenPolicy(POLICY_2).build(); - assertThat(role.getTokenPolicies(), hasSize(1)); - assertThat(role.getTokenPolicies(), contains(POLICY_2)); + assertEquals(1, role.getTokenPolicies().size()); + assertEquals(POLICY_2, role.getTokenPolicies().get(0)); role = AppRole.builder(NAME) .withTokenPolicies(POLICIES) .withTokenPolicy(POLICY_2) .build(); - assertThat(role.getTokenPolicies(), hasSize(2)); - assertThat(role.getTokenPolicies(), contains(POLICY, POLICY_2)); + assertEquals(2, role.getTokenPolicies().size()); + assertTrue(role.getTokenPolicies().containsAll(List.of(POLICY, POLICY_2))); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/AuthBackendTest.java b/src/test/java/de/stklcode/jvault/connector/model/AuthBackendTest.java index 8cd1fcc..245a0dc 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/AuthBackendTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/AuthBackendTest.java @@ -18,8 +18,8 @@ package de.stklcode.jvault.connector.model; import org.junit.jupiter.api.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * JUnit Test for AuthBackend model. @@ -34,12 +34,11 @@ class AuthBackendTest { */ @Test void forTypeTest() { - assertThat(AuthBackend.forType("token"), is(AuthBackend.TOKEN)); - assertThat(AuthBackend.forType("app-id"), is(AuthBackend.APPID)); - assertThat(AuthBackend.forType("userpass"), is(AuthBackend.USERPASS)); - assertThat(AuthBackend.forType("github"), is(AuthBackend.GITHUB)); - assertThat(AuthBackend.forType(""), is(AuthBackend.UNKNOWN)); - assertThat(AuthBackend.forType("foobar"), is(AuthBackend.UNKNOWN)); + assertEquals(AuthBackend.TOKEN, AuthBackend.forType("token")); + assertEquals(AuthBackend.APPID, AuthBackend.forType("app-id")); + assertEquals(AuthBackend.USERPASS, AuthBackend.forType("userpass")); + assertEquals(AuthBackend.GITHUB, AuthBackend.forType("github")); + assertEquals(AuthBackend.UNKNOWN, AuthBackend.forType("")); + assertEquals(AuthBackend.UNKNOWN, AuthBackend.forType("foobar")); } - } diff --git a/src/test/java/de/stklcode/jvault/connector/model/TokenRoleBuilderTest.java b/src/test/java/de/stklcode/jvault/connector/model/TokenRoleBuilderTest.java index 448c33a..4d4fae6 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/TokenRoleBuilderTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/TokenRoleBuilderTest.java @@ -23,8 +23,7 @@ import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.*; /** * Unit Test for {@link Token.Builder} @@ -80,20 +79,20 @@ class TokenRoleBuilderTest { @Test void buildDefaultTest() throws JsonProcessingException { TokenRole role = TokenRole.builder().build(); - assertThat(role.getAllowedPolicies(), is(nullValue())); - assertThat(role.getDisallowedPolicies(), is(nullValue())); - assertThat(role.getOrphan(), is(nullValue())); - assertThat(role.getRenewable(), is(nullValue())); - assertThat(role.getAllowedEntityAliases(), is(nullValue())); - assertThat(role.getTokenBoundCidrs(), is(nullValue())); - assertThat(role.getTokenExplicitMaxTtl(), is(nullValue())); - assertThat(role.getTokenNoDefaultPolicy(), is(nullValue())); - assertThat(role.getTokenNumUses(), is(nullValue())); - assertThat(role.getTokenPeriod(), is(nullValue())); - assertThat(role.getTokenType(), is(nullValue())); + assertNull(role.getAllowedPolicies()); + assertNull(role.getDisallowedPolicies()); + assertNull(role.getOrphan()); + assertNull(role.getRenewable()); + assertNull(role.getAllowedEntityAliases()); + assertNull(role.getTokenBoundCidrs()); + assertNull(role.getTokenExplicitMaxTtl()); + assertNull(role.getTokenNoDefaultPolicy()); + assertNull(role.getTokenNumUses()); + assertNull(role.getTokenPeriod()); + assertNull(role.getTokenType()); - /* optional fields should be ignored, so JSON string should be empty */ - assertThat(new ObjectMapper().writeValueAsString(role), is("{}")); + // Optional fields should be ignored, so JSON string should be empty. + assertEquals("{}", new ObjectMapper().writeValueAsString(role)); } /** @@ -121,20 +120,20 @@ class TokenRoleBuilderTest { .withTokenType(null) .build(); - assertThat(role.getAllowedPolicies(), is(nullValue())); - assertThat(role.getDisallowedPolicies(), is(nullValue())); - assertThat(role.getOrphan(), is(nullValue())); - assertThat(role.getRenewable(), is(nullValue())); - assertThat(role.getAllowedEntityAliases(), is(nullValue())); - assertThat(role.getTokenBoundCidrs(), is(nullValue())); - assertThat(role.getTokenExplicitMaxTtl(), is(nullValue())); - assertThat(role.getTokenNoDefaultPolicy(), is(nullValue())); - assertThat(role.getTokenNumUses(), is(nullValue())); - assertThat(role.getTokenPeriod(), is(nullValue())); - assertThat(role.getTokenType(), is(nullValue())); + assertNull(role.getAllowedPolicies()); + assertNull(role.getDisallowedPolicies()); + assertNull(role.getOrphan()); + assertNull(role.getRenewable()); + assertNull(role.getAllowedEntityAliases()); + assertNull(role.getTokenBoundCidrs()); + assertNull(role.getTokenExplicitMaxTtl()); + assertNull(role.getTokenNoDefaultPolicy()); + assertNull(role.getTokenNumUses()); + assertNull(role.getTokenPeriod()); + assertNull(role.getTokenType()); - /* optional fields should be ignored, so JSON string should be empty */ - assertThat(new ObjectMapper().writeValueAsString(role), is("{}")); + // Optional fields should be ignored, so JSON string should be empty. + assertEquals("{}", new ObjectMapper().writeValueAsString(role)); } /** @@ -161,24 +160,24 @@ class TokenRoleBuilderTest { .withTokenPeriod(TOKEN_PERIOD) .withTokenType(TOKEN_TYPE) .build(); - assertThat(role.getName(), is(NAME)); - assertThat(role.getAllowedPolicies(), hasSize(ALLOWED_POLICIES.size() + 1)); - assertThat(role.getAllowedPolicies(), containsInAnyOrder(ALLOWED_POLICY_1, ALLOWED_POLICY_2, ALLOWED_POLICY_3)); - assertThat(role.getDisallowedPolicies(), hasSize(DISALLOWED_POLICIES.size() + 1)); - assertThat(role.getDisallowedPolicies(), containsInAnyOrder(DISALLOWED_POLICY_1, DISALLOWED_POLICY_2, DISALLOWED_POLICY_3)); - assertThat(role.getOrphan(), is(ORPHAN)); - assertThat(role.getRenewable(), is(RENEWABLE)); - assertThat(role.getPathSuffix(), is(PATH_SUFFIX)); - assertThat(role.getAllowedEntityAliases(), hasSize(ALLOWED_ENTITY_ALIASES.size() + 1)); - assertThat(role.getAllowedEntityAliases(), containsInAnyOrder(ALLOWED_ENTITY_ALIAS_1, ALLOWED_ENTITY_ALIAS_2, ALLOWED_ENTITY_ALIAS_3)); - assertThat(role.getTokenBoundCidrs(), hasSize(TOKEN_BOUND_CIDRS.size() + 1)); - assertThat(role.getTokenBoundCidrs(), containsInAnyOrder(TOKEN_BOUND_CIDR_1, TOKEN_BOUND_CIDR_2, TOKEN_BOUND_CIDR_3)); - assertThat(role.getTokenNoDefaultPolicy(), is(TOKEN_NO_DEFAULT_POLICY)); - assertThat(role.getTokenNumUses(), is(TOKEN_NUM_USES)); - assertThat(role.getTokenPeriod(), is(TOKEN_PERIOD)); - assertThat(role.getTokenType(), is(TOKEN_TYPE.value())); + assertEquals(NAME, role.getName()); + assertEquals(ALLOWED_POLICIES.size() + 1, role.getAllowedPolicies().size()); + assertTrue(role.getAllowedPolicies().containsAll(List.of(ALLOWED_POLICY_1, ALLOWED_POLICY_2, ALLOWED_POLICY_3))); + assertEquals(DISALLOWED_POLICIES.size() + 1, role.getDisallowedPolicies().size()); + assertTrue(role.getDisallowedPolicies().containsAll(List.of(DISALLOWED_POLICY_1, DISALLOWED_POLICY_2, DISALLOWED_POLICY_3))); + assertEquals(ORPHAN, role.getOrphan()); + assertEquals(RENEWABLE, role.getRenewable()); + assertEquals(PATH_SUFFIX, role.getPathSuffix()); + assertEquals(ALLOWED_ENTITY_ALIASES.size() + 1, role.getAllowedEntityAliases().size()); + assertTrue(role.getAllowedEntityAliases().containsAll(List.of(ALLOWED_ENTITY_ALIAS_1, ALLOWED_ENTITY_ALIAS_2, ALLOWED_ENTITY_ALIAS_3))); + assertEquals(TOKEN_BOUND_CIDRS.size() + 1, role.getTokenBoundCidrs().size()); + assertTrue(role.getTokenBoundCidrs().containsAll(List.of(TOKEN_BOUND_CIDR_1, TOKEN_BOUND_CIDR_2, TOKEN_BOUND_CIDR_3))); + assertEquals(TOKEN_NO_DEFAULT_POLICY, role.getTokenNoDefaultPolicy()); + assertEquals(TOKEN_NUM_USES, role.getTokenNumUses()); + assertEquals(TOKEN_PERIOD, role.getTokenPeriod()); + assertEquals(TOKEN_TYPE.value(), role.getTokenType()); - /* Verify that all parameters are included in JSON string */ - assertThat(new ObjectMapper().writeValueAsString(role), is(JSON_FULL)); + // Verify that all parameters are included in JSON string. + assertEquals(JSON_FULL, new ObjectMapper().writeValueAsString(role)); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/TokenTest.java b/src/test/java/de/stklcode/jvault/connector/model/TokenTest.java index ae592d4..d2b3be1 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/TokenTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/TokenTest.java @@ -21,13 +21,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link Token} and {@link Token.Builder}. @@ -55,7 +51,6 @@ class TokenTest { private static final Boolean RENEWABLE = true; private static final Integer PERIOD = 3600; private static final String ENTITY_ALIAS = "alias-value"; - private static final String LEGACY_JSON_FULL = "{\"id\":\"test-id\",\"type\":\"service\",\"display_name\":\"display-name\",\"no_parent\":false,\"no_default_policy\":false,\"ttl\":123,\"num_uses\":4,\"policies\":[\"policy\"],\"meta\":{\"key\":\"value\"},\"renewable\":true}"; private static final String JSON_FULL = "{\"id\":\"test-id\",\"type\":\"service\",\"display_name\":\"display-name\",\"no_parent\":false,\"no_default_policy\":false,\"ttl\":123,\"explicit_max_ttl\":456,\"num_uses\":4,\"policies\":[\"policy\"],\"meta\":{\"key\":\"value\"},\"renewable\":true,\"period\":3600,\"entity_alias\":\"alias-value\"}"; @BeforeAll @@ -70,22 +65,22 @@ class TokenTest { @Test void buildDefaultTest() throws JsonProcessingException { Token token = Token.builder().build(); - assertThat(token.getId(), is(nullValue())); - assertThat(token.getType(), is(nullValue())); - assertThat(token.getDisplayName(), is(nullValue())); - assertThat(token.getNoParent(), is(nullValue())); - assertThat(token.getNoDefaultPolicy(), is(nullValue())); - assertThat(token.getTtl(), is(nullValue())); - assertThat(token.getExplicitMaxTtl(), is(nullValue())); - assertThat(token.getNumUses(), is(nullValue())); - assertThat(token.getPolicies(), is(nullValue())); - assertThat(token.getMeta(), is(nullValue())); - assertThat(token.isRenewable(), is(nullValue())); - assertThat(token.getPeriod(), is(nullValue())); - assertThat(token.getEntityAlias(), is(nullValue())); + assertNull(token.getId()); + assertNull(token.getType()); + assertNull(token.getDisplayName()); + assertNull(token.getNoParent()); + assertNull(token.getNoDefaultPolicy()); + assertNull(token.getTtl()); + assertNull(token.getExplicitMaxTtl()); + assertNull(token.getNumUses()); + assertNull(token.getPolicies()); + assertNull(token.getMeta()); + assertNull(token.isRenewable()); + assertNull(token.getPeriod()); + assertNull(token.getEntityAlias()); - /* optional fields should be ignored, so JSON string should be empty */ - assertThat(new ObjectMapper().writeValueAsString(token), is("{}")); + // Optional fields should be ignored, so JSON string should be empty. + assertEquals("{}", new ObjectMapper().writeValueAsString(token)); } /** @@ -108,21 +103,21 @@ class TokenTest { .withPeriod(PERIOD) .withEntityAlias(ENTITY_ALIAS) .build(); - assertThat(token.getId(), is(ID)); - assertThat(token.getType(), is(Token.Type.SERVICE.value())); - assertThat(token.getDisplayName(), is(DISPLAY_NAME)); - assertThat(token.getNoParent(), is(NO_PARENT)); - assertThat(token.getNoDefaultPolicy(), is(NO_DEFAULT_POLICY)); - assertThat(token.getTtl(), is(TTL)); - assertThat(token.getExplicitMaxTtl(), is(EXPLICIT_MAX_TTL)); - assertThat(token.getNumUses(), is(NUM_USES)); - assertThat(token.getPolicies(), is(POLICIES)); - assertThat(token.getMeta(), is(META)); - assertThat(token.isRenewable(), is(RENEWABLE)); - assertThat(token.getPeriod(), is(PERIOD)); + assertEquals(ID, token.getId()); + assertEquals(Token.Type.SERVICE.value(), token.getType()); + assertEquals(DISPLAY_NAME, token.getDisplayName()); + assertEquals(NO_PARENT, token.getNoParent()); + assertEquals(NO_DEFAULT_POLICY, token.getNoDefaultPolicy()); + assertEquals(TTL, token.getTtl()); + assertEquals(EXPLICIT_MAX_TTL, token.getExplicitMaxTtl()); + assertEquals(NUM_USES, token.getNumUses()); + assertEquals(POLICIES, token.getPolicies()); + assertEquals(META, token.getMeta()); + assertEquals(RENEWABLE, token.isRenewable()); + assertEquals(PERIOD, token.getPeriod()); - /* Verify that all parameters are included in JSON string */ - assertThat(new ObjectMapper().writeValueAsString(token), is(JSON_FULL)); + // Verify that all parameters are included in JSON string. + assertEquals(JSON_FULL, new ObjectMapper().writeValueAsString(token)); } /** @@ -130,46 +125,46 @@ class TokenTest { */ @Test void convenienceMethodsTest() { - /* Parent */ + // Parent. Token token = Token.builder().asOrphan().build(); - assertThat(token.getNoParent(), is(true)); + assertEquals(true, token.getNoParent()); token = Token.builder().withParent().build(); - assertThat(token.getNoParent(), is(false)); + assertEquals(false, token.getNoParent()); - /* Default policy */ + // Default policy. token = Token.builder().withDefaultPolicy().build(); - assertThat(token.getNoDefaultPolicy(), is(false)); + assertEquals(false, token.getNoDefaultPolicy()); token = Token.builder().withoutDefaultPolicy().build(); - assertThat(token.getNoDefaultPolicy(), is(true)); + assertEquals(true, token.getNoDefaultPolicy()); - /* Renewability */ + // Renewability. token = Token.builder().renewable().build(); - assertThat(token.isRenewable(), is(true)); + assertEquals(true, token.isRenewable()); token = Token.builder().notRenewable().build(); - assertThat(token.isRenewable(), is(false)); + assertEquals(false, token.isRenewable()); - /* Add single policy */ + // Add single policy. token = Token.builder().withPolicy(POLICY_2).build(); - assertThat(token.getPolicies(), hasSize(1)); - assertThat(token.getPolicies(), contains(POLICY_2)); + assertEquals(1, token.getPolicies().size()); + assertEquals(List.of(POLICY_2), token.getPolicies()); token = Token.builder() .withPolicies(POLICY, POLICY_2) .withPolicy(POLICY_3) .build(); - assertThat(token.getPolicies(), hasSize(3)); - assertThat(token.getPolicies(), contains(POLICY, POLICY_2, POLICY_3)); + assertEquals(3, token.getPolicies().size()); + assertTrue(token.getPolicies().containsAll(List.of(POLICY, POLICY_2, POLICY_3))); - /* Add single metadata */ + // Add single metadata. token = Token.builder().withMeta(META_KEY_2, META_VALUE_2).build(); - assertThat(token.getMeta().size(), is(1)); - assertThat(token.getMeta().keySet(), contains(META_KEY_2)); - assertThat(token.getMeta().get(META_KEY_2), is(META_VALUE_2)); + assertEquals(1, token.getMeta().size()); + assertEquals(Set.of(META_KEY_2), token.getMeta().keySet()); + assertEquals(META_VALUE_2, token.getMeta().get(META_KEY_2)); token = Token.builder() .withMeta(META) .withMeta(META_KEY_2, META_VALUE_2) .build(); - assertThat(token.getMeta().size(), is(2)); - assertThat(token.getMeta().get(META_KEY), is(META_VALUE)); - assertThat(token.getMeta().get(META_KEY_2), is(META_VALUE_2)); + assertEquals(2, token.getMeta().size()); + assertEquals(META_VALUE, token.getMeta().get(META_KEY)); + assertEquals(META_VALUE_2, token.getMeta().get(META_KEY_2)); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/AppRoleResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/AppRoleResponseTest.java index 74f6175..ed2a6e2 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/AppRoleResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/AppRoleResponseTest.java @@ -24,10 +24,7 @@ import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link AppRoleResponse} model. @@ -78,7 +75,7 @@ class AppRoleResponseTest { void getDataRoundtrip() { // Create empty Object. AppRoleResponse res = new AppRoleResponse(); - assertThat("Initial data should be empty", res.getRole(), is(nullValue())); + assertNull(res.getRole(), "Initial data should be empty"); // Parsing invalid auth data map should fail. assertThrows( @@ -97,19 +94,19 @@ class AppRoleResponseTest { () -> new ObjectMapper().readValue(RES_JSON, AppRoleResponse.class), "AuthResponse deserialization failed." ); - assertThat("Parsed response is NULL", res, is(notNullValue())); + assertNotNull(res, "Parsed response is NULL"); // Extract role data. AppRole role = res.getRole(); - assertThat("Role data is NULL", role, is(notNullValue())); - assertThat("Incorrect token TTL", role.getTokenTtl(), is(ROLE_TOKEN_TTL)); - assertThat("Incorrect token max TTL", role.getTokenMaxTtl(), is(ROLE_TOKEN_MAX_TTL)); - assertThat("Incorrect secret ID TTL", role.getSecretIdTtl(), is(ROLE_SECRET_TTL)); - assertThat("Incorrect secret ID umber of uses", role.getSecretIdNumUses(), is(ROLE_SECRET_NUM_USES)); - assertThat("Incorrect number of policies", role.getTokenPolicies(), hasSize(1)); - assertThat("Incorrect role policies", role.getTokenPolicies(), contains(ROLE_POLICY)); - assertThat("Incorrect role period", role.getTokenPeriod(), is(ROLE_PERIOD)); - assertThat("Incorrect role bind secret ID flag", role.getBindSecretId(), is(ROLE_BIND_SECRET)); - assertThat("Incorrect bound CIDR list", role.getTokenBoundCidrs(), is(nullValue())); - assertThat("Incorrect bound CIDR list string", role.getTokenBoundCidrsString(), is(emptyString())); + assertNotNull(role, "Role data is NULL"); + assertEquals(ROLE_TOKEN_TTL, role.getTokenTtl(), "Incorrect token TTL"); + assertEquals(ROLE_TOKEN_MAX_TTL, role.getTokenMaxTtl(), "Incorrect token max TTL"); + assertEquals(ROLE_SECRET_TTL, role.getSecretIdTtl(), "Incorrect secret ID TTL"); + assertEquals(ROLE_SECRET_NUM_USES, role.getSecretIdNumUses(), "Incorrect secret ID umber of uses"); + assertEquals(1, role.getTokenPolicies().size(), "Incorrect number of policies"); + assertEquals(ROLE_POLICY, role.getTokenPolicies().get(0), "Incorrect role policies"); + assertEquals(ROLE_PERIOD, role.getTokenPeriod(), "Incorrect role period"); + assertEquals(ROLE_BIND_SECRET, role.getBindSecretId(), "Incorrect role bind secret ID flag"); + assertNull(role.getTokenBoundCidrs(), "Incorrect bound CIDR list"); + assertEquals("", role.getTokenBoundCidrsString(), "Incorrect bound CIDR list string"); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/AuthMethodsResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/AuthMethodsResponseTest.java index bb357bf..9f99ad6 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/AuthMethodsResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/AuthMethodsResponseTest.java @@ -22,13 +22,12 @@ import de.stklcode.jvault.connector.model.AuthBackend; import de.stklcode.jvault.connector.model.response.embedded.AuthMethod; import org.junit.jupiter.api.Test; +import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Set; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link AuthMethodsResponse} model. @@ -76,7 +75,7 @@ class AuthMethodsResponseTest { void getDataRoundtrip() { // Create empty Object. AuthMethodsResponse res = new AuthMethodsResponse(); - assertThat("Initial method map should be empty", res.getSupportedMethods(), is(anEmptyMap())); + assertEquals(Collections.emptyMap(), res.getSupportedMethods(), "Initial method map should be empty"); // Parsing invalid data map should fail. assertThrows( @@ -95,29 +94,29 @@ class AuthMethodsResponseTest { () -> new ObjectMapper().readValue(RES_JSON, AuthMethodsResponse.class), "AuthResponse deserialization failed" ); - assertThat("Parsed response is NULL", res, is(notNullValue())); + assertNotNull(res, "Parsed response is NULL"); // Extract auth data. Map supported = res.getSupportedMethods(); - assertThat("Auth data is NULL", supported, is(notNullValue())); - assertThat("Incorrect number of supported methods", supported.entrySet(), hasSize(2)); - assertThat("Incorrect method paths", supported.keySet(), containsInAnyOrder(GH_PATH, TK_PATH)); + assertNotNull(supported, "Auth data is NULL"); + assertEquals(2, supported.size(), "Incorrect number of supported methods"); + assertTrue(supported.keySet().containsAll(Set.of(GH_PATH, TK_PATH)), "Incorrect method paths"); // Verify first method. AuthMethod method = supported.get(GH_PATH); - assertThat("Incorrect raw type for GitHub", method.getRawType(), is(GH_TYPE)); - assertThat("Incorrect parsed type for GitHub", method.getType(), is(AuthBackend.GITHUB)); - assertThat("Incorrect description for GitHub", method.getDescription(), is(GH_DESCR)); - assertThat("Unexpected config for GitHub", method.getConfig(), is(nullValue())); + assertEquals(GH_TYPE, method.getRawType(), "Incorrect raw type for GitHub"); + assertEquals(AuthBackend.GITHUB, method.getType(), "Incorrect parsed type for GitHub"); + assertEquals(GH_DESCR, method.getDescription(), "Incorrect description for GitHub"); + assertNull(method.getConfig(), "Unexpected config for GitHub"); // Verify first method. method = supported.get(TK_PATH); - assertThat("Incorrect raw type for Token", method.getRawType(), is(TK_TYPE)); - assertThat("Incorrect parsed type for Token", method.getType(), is(AuthBackend.TOKEN)); - assertThat("Incorrect description for Token", method.getDescription(), is(TK_DESCR)); - assertThat("Missing config for Token", method.getConfig(), is(notNullValue())); - assertThat("Unexpected config size for Token", method.getConfig().keySet(), hasSize(2)); - assertThat("Incorrect lease TTL config", method.getConfig().get("default_lease_ttl"), is(TK_LEASE_TTL.toString())); - assertThat("Incorrect max lease TTL config", method.getConfig().get("max_lease_ttl"), is(TK_MAX_LEASE_TTL.toString())); + assertEquals(TK_TYPE, method.getRawType(), "Incorrect raw type for Token"); + assertEquals(AuthBackend.TOKEN, method.getType(), "Incorrect parsed type for Token"); + assertEquals(TK_DESCR, method.getDescription(), "Incorrect description for Token"); + assertNotNull(method.getConfig(), "Missing config for Token"); + assertEquals(2, method.getConfig().size(), "Unexpected config size for Token"); + assertEquals(TK_LEASE_TTL.toString(), method.getConfig().get("default_lease_ttl"), "Incorrect lease TTL config"); + assertEquals(TK_MAX_LEASE_TTL.toString(), method.getConfig().get("max_lease_ttl"), "Incorrect max lease TTL config"); } private static class Dummy { diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/AuthResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/AuthResponseTest.java index 460a33a..65b4b7a 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/AuthResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/AuthResponseTest.java @@ -23,11 +23,9 @@ import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; +import java.util.Set; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link AuthResponse} model. @@ -84,7 +82,7 @@ class AuthResponseTest { void getDataRoundtrip() { // Create empty Object. AuthResponse res = new AuthResponse(); - assertThat("Initial data should be empty", res.getData(), is(nullValue())); + assertNull(res.getData(), "Initial data should be empty"); // Parsing invalid auth data map should fail. assertThrows( @@ -95,7 +93,7 @@ class AuthResponseTest { // Data method should be agnostic. res.setData(INVALID_AUTH_DATA); - assertThat("Data not passed through", res.getData(), is(INVALID_AUTH_DATA)); + assertEquals(INVALID_AUTH_DATA, res.getData(), "Data not passed through"); } /** @@ -103,26 +101,26 @@ class AuthResponseTest { */ @Test void jsonRoundtrip() { - AuthResponse res = assertDoesNotThrow( - () -> new ObjectMapper().readValue(RES_JSON, AuthResponse.class), - "AuthResponse deserialization failed." - ); - assertThat("Parsed response is NULL", res, is(notNullValue())); - // Extract auth data. - AuthData data = res.getAuth(); - assertThat("Auth data is NULL", data, is(notNullValue())); - assertThat("Incorrect auth accessor", data.getAccessor(), is(AUTH_ACCESSOR)); - assertThat("Incorrect auth client token", data.getClientToken(), is(AUTH_CLIENT_TOKEN)); - assertThat("Incorrect auth lease duration", data.getLeaseDuration(), is(AUTH_LEASE_DURATION)); - assertThat("Incorrect auth renewable flag", data.isRenewable(), is(AUTH_RENEWABLE)); - assertThat("Incorrect auth orphan flag", data.isOrphan(), is(AUTH_ORPHAN)); - assertThat("Incorrect auth token type", data.getTokenType(), is(AUTH_TOKEN_TYPE)); - assertThat("Incorrect auth entity id", data.getEntityId(), is(AUTH_ENTITY_ID)); - assertThat("Incorrect number of policies", data.getPolicies(), hasSize(2)); - assertThat("Incorrect auth policies", data.getPolicies(), containsInRelativeOrder(AUTH_POLICY_1, AUTH_POLICY_2)); - assertThat("Incorrect number of token policies", data.getTokenPolicies(), hasSize(2)); - assertThat("Incorrect token policies", data.getTokenPolicies(), containsInRelativeOrder(AUTH_POLICY_2, AUTH_POLICY_1)); - assertThat("Incorrect auth metadata size", data.getMetadata().entrySet(), hasSize(1)); - assertThat("Incorrect auth metadata", data.getMetadata().get(AUTH_META_KEY), is(AUTH_META_VALUE)); + AuthResponse res = assertDoesNotThrow( + () -> new ObjectMapper().readValue(RES_JSON, AuthResponse.class), + "AuthResponse deserialization failed." + ); + assertNotNull(res, "Parsed response is NULL"); + // Extract auth data. + AuthData data = res.getAuth(); + assertNotNull(data, "Auth data is NULL"); + assertEquals(AUTH_ACCESSOR, data.getAccessor(), "Incorrect auth accessor"); + assertEquals(AUTH_CLIENT_TOKEN, data.getClientToken(), "Incorrect auth client token"); + assertEquals(AUTH_LEASE_DURATION, data.getLeaseDuration(), "Incorrect auth lease duration"); + assertEquals(AUTH_RENEWABLE, data.isRenewable(), "Incorrect auth renewable flag"); + assertEquals(AUTH_ORPHAN, data.isOrphan(), "Incorrect auth orphan flag"); + assertEquals(AUTH_TOKEN_TYPE, data.getTokenType(), "Incorrect auth token type"); + assertEquals(AUTH_ENTITY_ID, data.getEntityId(), "Incorrect auth entity id"); + assertEquals(2, data.getPolicies().size(), "Incorrect number of policies"); + assertTrue(data.getPolicies().containsAll(Set.of(AUTH_POLICY_1, AUTH_POLICY_2))); + assertEquals(2, data.getTokenPolicies().size(), "Incorrect number of token policies"); + assertTrue(data.getTokenPolicies().containsAll(Set.of(AUTH_POLICY_2, AUTH_POLICY_1)), "Incorrect token policies"); + assertEquals(1, data.getMetadata().size(), "Incorrect auth metadata size"); + assertEquals(AUTH_META_VALUE, data.getMetadata().get(AUTH_META_KEY), "Incorrect auth metadata"); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/CredentialsResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/CredentialsResponseTest.java index ee193b3..130d5fb 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/CredentialsResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/CredentialsResponseTest.java @@ -16,18 +16,14 @@ package de.stklcode.jvault.connector.model.response; -import com.fasterxml.jackson.databind.ObjectMapper; import de.stklcode.jvault.connector.exception.InvalidResponseException; import org.junit.jupiter.api.Test; -import java.io.IOException; import java.util.HashMap; -import java.util.List; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * JUnit Test for {@link CredentialsResponse} model. @@ -55,12 +51,12 @@ class CredentialsResponseTest { void getCredentialsTest() throws InvalidResponseException { // Create empty Object. CredentialsResponse res = new CredentialsResponse(); - assertThat("Username not present in data map should not return anything", res.getUsername(), is(nullValue())); - assertThat("Password not present in data map should not return anything", res.getPassword(), is(nullValue())); + assertNull(res.getUsername(), "Username not present in data map should not return anything"); + assertNull(res.getPassword(), "Password not present in data map should not return anything"); // Fill data map. res.setData(DATA); - assertThat("Incorrect username", res.getUsername(), is(VAL_USER)); - assertThat("Incorrect password", res.getPassword(), is(VAL_PASS)); + assertEquals(VAL_USER, res.getUsername(), "Incorrect username"); + assertEquals(VAL_PASS, res.getPassword(), "Incorrect password"); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/HealthResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/HealthResponseTest.java index c5a457b..32ed28e 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/HealthResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/HealthResponseTest.java @@ -19,10 +19,7 @@ package de.stklcode.jvault.connector.model.response; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link AuthResponse} model. @@ -64,16 +61,16 @@ class HealthResponseTest { () -> new ObjectMapper().readValue(RES_JSON, HealthResponse.class), "Health deserialization failed." ); - assertThat("Parsed response is NULL", res, is(notNullValue())); - assertThat("Incorrect cluster ID", res.getClusterID(), is(CLUSTER_ID)); - assertThat("Incorrect cluster name", res.getClusterName(), is(CLUSTER_NAME)); - assertThat("Incorrect version", res.getVersion(), is(VERSION)); - assertThat("Incorrect server time", res.getServerTimeUTC(), is(SERVER_TIME_UTC)); - assertThat("Incorrect standby state", res.isStandby(), is(STANDBY)); - assertThat("Incorrect seal state", res.isSealed(), is(SEALED)); - assertThat("Incorrect initialization state", res.isInitialized(), is(INITIALIZED)); - assertThat("Incorrect performance standby state", res.isPerformanceStandby(), is(PERF_STANDBY)); - assertThat("Incorrect replication perf mode", res.getReplicationPerfMode(), is(REPL_PERF_MODE)); - assertThat("Incorrect replication DR mode", res.getReplicationDrMode(), is(REPL_DR_MODE)); + assertNotNull(res, "Parsed response is NULL"); + assertEquals(CLUSTER_ID, res.getClusterID(), "Incorrect cluster ID"); + assertEquals(CLUSTER_NAME, res.getClusterName(), "Incorrect cluster name"); + assertEquals(VERSION, res.getVersion(), "Incorrect version"); + assertEquals(SERVER_TIME_UTC, res.getServerTimeUTC(), "Incorrect server time"); + assertEquals(STANDBY, res.isStandby(), "Incorrect standby state"); + assertEquals(SEALED, res.isSealed(), "Incorrect seal state"); + assertEquals(INITIALIZED, res.isInitialized(), "Incorrect initialization state"); + assertEquals(PERF_STANDBY, res.isPerformanceStandby(), "Incorrect performance standby state"); + assertEquals(REPL_PERF_MODE, res.getReplicationPerfMode(), "Incorrect replication perf mode"); + assertEquals(REPL_DR_MODE, res.getReplicationDrMode(), "Incorrect replication DR mode"); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/MetadataResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/MetadataResponseTest.java index d4522f0..7c96272 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/MetadataResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/MetadataResponseTest.java @@ -19,10 +19,7 @@ package de.stklcode.jvault.connector.model.response; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link MetadataResponse} model. @@ -74,21 +71,21 @@ class MetadataResponseTest { () -> new ObjectMapper().readValue(META_JSON, MetadataResponse.class), "MetadataResponse deserialization failed." ); - assertThat("Parsed response is NULL", res, is(notNullValue())); - assertThat("Parsed metadata is NULL", res.getMetadata(), is(notNullValue())); - assertThat("Incorrect created time", res.getMetadata().getCreatedTimeString(), is(V1_TIME)); - assertThat("Parting created time failed", res.getMetadata().getCreatedTime(), is(notNullValue())); - assertThat("Incorrect current version", res.getMetadata().getCurrentVersion(), is(CURRENT_VERSION)); - assertThat("Incorrect max versions", res.getMetadata().getMaxVersions(), is(MAX_VERSIONS)); - assertThat("Incorrect oldest version", res.getMetadata().getOldestVersion(), is(OLDEST_VERSION)); - assertThat("Incorrect updated time", res.getMetadata().getUpdatedTimeString(), is(V3_TIME)); - assertThat("Parting updated time failed", res.getMetadata().getUpdatedTime(), is(notNullValue())); - assertThat("Incorrect number of versions", res.getMetadata().getVersions().size(), is(3)); - assertThat("Incorrect version 1 delete time", res.getMetadata().getVersions().get(1).getDeletionTimeString(), is(V2_TIME)); - assertThat("Parsing version delete time failed", res.getMetadata().getVersions().get(1).getDeletionTime(), is(notNullValue())); - assertThat("Incorrect version 1 destroyed state", res.getMetadata().getVersions().get(1).isDestroyed(), is(true)); - assertThat("Incorrect version 2 created time", res.getMetadata().getVersions().get(2).getCreatedTimeString(), is(V2_TIME)); - assertThat("Parsing version created failed", res.getMetadata().getVersions().get(2).getCreatedTime(), is(notNullValue())); - assertThat("Incorrect version 3 destroyed state", res.getMetadata().getVersions().get(3).isDestroyed(), is(false)); + assertNotNull(res, "Parsed response is NULL"); + assertNotNull(res.getMetadata(), "Parsed metadata is NULL"); + assertEquals(V1_TIME, res.getMetadata().getCreatedTimeString(), "Incorrect created time"); + assertNotNull(res.getMetadata().getCreatedTime(), "Parting created time failed"); + assertEquals(CURRENT_VERSION, res.getMetadata().getCurrentVersion(), "Incorrect current version"); + assertEquals(MAX_VERSIONS, res.getMetadata().getMaxVersions(), "Incorrect max versions"); + assertEquals(OLDEST_VERSION, res.getMetadata().getOldestVersion(), "Incorrect oldest version"); + assertEquals(V3_TIME, res.getMetadata().getUpdatedTimeString(), "Incorrect updated time"); + assertNotNull(res.getMetadata().getUpdatedTime(), "Parting updated time failed"); + assertEquals(3, res.getMetadata().getVersions().size(), "Incorrect number of versions"); + assertEquals(V2_TIME, res.getMetadata().getVersions().get(1).getDeletionTimeString(), "Incorrect version 1 delete time"); + assertNotNull(res.getMetadata().getVersions().get(1).getDeletionTime(), "Parsing version delete time failed"); + assertTrue(res.getMetadata().getVersions().get(1).isDestroyed(), "Incorrect version 1 destroyed state"); + assertEquals(V2_TIME, res.getMetadata().getVersions().get(2).getCreatedTimeString(), "Incorrect version 2 created time"); + assertNotNull(res.getMetadata().getVersions().get(2).getCreatedTime(), "Parsing version created failed"); + assertFalse(res.getMetadata().getVersions().get(3).isDestroyed(), "Incorrect version 3 destroyed state"); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/SealResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/SealResponseTest.java index 762cbaa..dc85e62 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/SealResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/SealResponseTest.java @@ -19,9 +19,7 @@ package de.stklcode.jvault.connector.model.response; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link SealResponse} model. @@ -74,18 +72,18 @@ class SealResponseTest { () -> new ObjectMapper().readValue(RES_SEALED, SealResponse.class), "TokenResponse deserialization failed." ); - assertThat("Parsed response is NULL", res, is(notNullValue())); - assertThat("Incorrect seal type", res.getType(), is(TYPE)); - assertThat("Incorrect seal status", res.isSealed(), is(true)); - assertThat("Incorrect initialization status", res.isInitialized(), is(true)); - assertThat("Incorrect threshold", res.getThreshold(), is(THRESHOLD)); - assertThat("Incorrect number of shares", res.getNumberOfShares(), is(SHARES)); - assertThat("Incorrect progress", res.getProgress(), is(PROGRESS_SEALED)); - assertThat("Nonce not empty", res.getNonce(), is("")); - assertThat("Incorrect version", res.getVersion(), is(VERSION)); + assertNotNull(res, "Parsed response is NULL"); + assertEquals(TYPE, res.getType(), "Incorrect seal type"); + assertTrue(res.isSealed(), "Incorrect seal status"); + assertTrue(res.isInitialized(), "Incorrect initialization status"); + assertEquals(THRESHOLD, res.getThreshold(), "Incorrect threshold"); + assertEquals(SHARES, res.getNumberOfShares(), "Incorrect number of shares"); + assertEquals(PROGRESS_SEALED, res.getProgress(), "Incorrect progress"); + assertEquals("", res.getNonce(), "Nonce not empty"); + assertEquals(VERSION, res.getVersion(), "Incorrect version"); // And the fields, that should not be filled. - assertThat("Cluster name should not be populated", res.getClusterName(), is(nullValue())); - assertThat("Cluster ID should not be populated", res.getClusterId(), is(nullValue())); + assertNull(res.getClusterName(), "Cluster name should not be populated"); + assertNull(res.getClusterId(), "Cluster ID should not be populated"); // Not test unsealed Vault's response. @@ -93,16 +91,16 @@ class SealResponseTest { () -> new ObjectMapper().readValue(RES_UNSEALED, SealResponse.class), "TokenResponse deserialization failed." ); - assertThat("Parsed response is NULL", res, is(notNullValue())); - assertThat("Incorrect seal type", res.getType(), is(TYPE)); - assertThat("Incorrect seal status", res.isSealed(), is(false)); - assertThat("Incorrect initialization status", res.isInitialized(), is(true)); - assertThat("Incorrect threshold", res.getThreshold(), is(THRESHOLD)); - assertThat("Incorrect number of shares", res.getNumberOfShares(), is(SHARES)); - assertThat("Incorrect progress", res.getProgress(), is(PROGRESS_UNSEALED)); - assertThat("Incorrect nonce", res.getNonce(), is(NONCE)); - assertThat("Incorrect version", res.getVersion(), is(VERSION)); - assertThat("Incorrect cluster name", res.getClusterName(), is(CLUSTER_NAME)); - assertThat("Incorrect cluster ID", res.getClusterId(), is(CLUSTER_ID)); + assertNotNull(res, "Parsed response is NULL"); + assertEquals(TYPE, res.getType(), "Incorrect seal type"); + assertFalse(res.isSealed(), "Incorrect seal status"); + assertTrue(res.isInitialized(), "Incorrect initialization status"); + assertEquals(THRESHOLD, res.getThreshold(), "Incorrect threshold"); + assertEquals(SHARES, res.getNumberOfShares(), "Incorrect number of shares"); + assertEquals(PROGRESS_UNSEALED, res.getProgress(), "Incorrect progress"); + assertEquals(NONCE, res.getNonce(), "Incorrect nonce"); + assertEquals(VERSION, res.getVersion(), "Incorrect version"); + assertEquals(CLUSTER_NAME, res.getClusterName(), "Incorrect cluster name"); + assertEquals(CLUSTER_ID, res.getClusterId(), "Incorrect cluster ID"); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/SecretListResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/SecretListResponseTest.java index 8f10c13..5dd793c 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/SecretListResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/SecretListResponseTest.java @@ -19,14 +19,9 @@ package de.stklcode.jvault.connector.model.response; import de.stklcode.jvault.connector.exception.InvalidResponseException; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link SecretListResponse} model. @@ -53,7 +48,7 @@ class SecretListResponseTest { void getKeysTest() throws InvalidResponseException { // Create empty Object. SecretListResponse res = new SecretListResponse(); - assertThat("Keys should be null without initialization", res.getKeys(), is(nullValue())); + assertNull(res.getKeys(), "Keys should be null without initialization"); // Provoke internal ClassCastException. Map invalidData = new HashMap<>(); @@ -66,8 +61,8 @@ class SecretListResponseTest { // Fill correct data. res.setData(DATA); - assertThat("Keys should be filled here", res.getKeys(), is(notNullValue())); - assertThat("Unexpected number of keys", res.getKeys(), hasSize(2)); - assertThat("Unexpected keys", res.getKeys(), contains(KEY1, KEY2)); + assertNotNull(res.getKeys(), "Keys should be filled here"); + assertEquals(2, res.getKeys().size(), "Unexpected number of keys"); + assertTrue(res.getKeys().containsAll(Set.of(KEY1, KEY2)), "Unexpected keys"); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/SecretResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/SecretResponseTest.java index 2538a68..30230cc 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/SecretResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/SecretResponseTest.java @@ -23,11 +23,9 @@ import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link SecretResponse} model. @@ -123,25 +121,25 @@ class SecretResponseTest { void getDataRoundtrip() throws InvalidResponseException { // Create empty Object. SecretResponse res = new SecretResponse(); - assertThat("Initial data should be Map", res.getData(), is(instanceOf(Map.class))); - assertThat("Initial data should be empty", res.getData().entrySet(), empty()); - assertThat("Getter should return NULL on empty data map", res.get(KEY_STRING), is(nullValue())); + assertNotNull(res.getData(), "Initial data should be Map"); + assertTrue(res.getData().isEmpty(), "Initial data should be empty"); + assertNull(res.get(KEY_STRING), "Getter should return NULL on empty data map"); // Fill data map. res.setData(DATA); - assertThat("Data setter/getter not transparent", res.getData(), is(DATA)); - assertThat("Data size modified", res.getData().keySet(), hasSize(DATA.size())); - assertThat("Data keys not passed correctly", res.getData().keySet(), containsInAnyOrder(KEY_STRING, KEY_INTEGER, KEY_LIST)); - assertThat("Data values not passed correctly", res.get(KEY_STRING), is(VAL_STRING)); - assertThat("Data values not passed correctly", res.get(KEY_INTEGER), is(VAL_INTEGER)); - assertThat("Non-Null returned on unknown key", res.get(KEY_UNKNOWN), is(nullValue())); + assertEquals(DATA, res.getData(), "Data setter/getter not transparent"); + assertEquals(DATA.size(), res.getData().keySet().size(), "Data size modified"); + assertTrue(res.getData().keySet().containsAll(Set.of(KEY_STRING, KEY_INTEGER, KEY_LIST)), "Data keys not passed correctly"); + assertEquals(VAL_STRING, res.get(KEY_STRING), "Data values not passed correctly"); + assertEquals(VAL_INTEGER, res.get(KEY_INTEGER), "Data values not passed correctly"); + assertNull(res.get(KEY_UNKNOWN), "Non-Null returned on unknown key"); // Try explicit JSON conversion. final List list = res.get(KEY_LIST, List.class); - assertThat("JSON parsing of list failed", list, is(notNullValue())); - assertThat("JSON parsing of list returned incorrect size", list.size(), is(2)); - assertThat("JSON parsing of list returned incorrect elements", list, contains("first", "second")); - assertThat("Non-Null returned on unknown key", res.get(KEY_UNKNOWN, Object.class), is(nullValue())); + assertNotNull(list, "JSON parsing of list failed"); + assertEquals(2, list.size(), "JSON parsing of list returned incorrect size"); + assertTrue(list.containsAll(List.of("first", "second")), "JSON parsing of list returned incorrect elements"); + assertNull(res.get(KEY_UNKNOWN, Object.class), "Non-Null returned on unknown key"); // Requesting invalid class should result in Exception. assertThrows( @@ -168,13 +166,13 @@ class SecretResponseTest { "SecretResponse deserialization failed." ); assertSecretData(res); - assertThat("SecretResponse does not contain metadata", res.getMetadata(), is(notNullValue())); - assertThat("Incorrect creation date string", res.getMetadata().getCreatedTimeString(), is(SECRET_META_CREATED)); - assertThat("Creation date parsing failed", res.getMetadata().getCreatedTime(), is(notNullValue())); - assertThat("Incorrect deletion date string", res.getMetadata().getDeletionTimeString(), is(emptyString())); - assertThat("Incorrect deletion date", res.getMetadata().getDeletionTime(), is(nullValue())); - assertThat("Secret destroyed when not expected", res.getMetadata().isDestroyed(), is(false)); - assertThat("Incorrect secret version", res.getMetadata().getVersion(), is(1)); + assertNotNull(res.getMetadata(), "SecretResponse does not contain metadata"); + assertEquals(SECRET_META_CREATED, res.getMetadata().getCreatedTimeString(), "Incorrect creation date string"); + assertNotNull(res.getMetadata().getCreatedTime(), "Creation date parsing failed"); + assertEquals("", res.getMetadata().getDeletionTimeString(), "Incorrect deletion date string"); + assertNull(res.getMetadata().getDeletionTime(), "Incorrect deletion date"); + assertEquals(false, res.getMetadata().isDestroyed(), "Secret destroyed when not expected"); + assertEquals(1, res.getMetadata().getVersion(), "Incorrect secret version"); // Deleted KV v2 secret. res = assertDoesNotThrow( @@ -182,22 +180,22 @@ class SecretResponseTest { "SecretResponse deserialization failed." ); assertSecretData(res); - assertThat("SecretResponse does not contain metadata", res.getMetadata(), is(notNullValue())); - assertThat("Incorrect creation date string", res.getMetadata().getCreatedTimeString(), is(SECRET_META_CREATED)); - assertThat("Creation date parsing failed", res.getMetadata().getCreatedTime(), is(notNullValue())); - assertThat("Incorrect deletion date string", res.getMetadata().getDeletionTimeString(), is(SECRET_META_DELETED)); - assertThat("Incorrect deletion date", res.getMetadata().getDeletionTime(), is(notNullValue())); - assertThat("Secret destroyed when not expected", res.getMetadata().isDestroyed(), is(true)); - assertThat("Incorrect secret version", res.getMetadata().getVersion(), is(2)); + assertNotNull(res.getMetadata(), "SecretResponse does not contain metadata"); + assertEquals(SECRET_META_CREATED, res.getMetadata().getCreatedTimeString(), "Incorrect creation date string"); + assertNotNull(res.getMetadata().getCreatedTime(), "Creation date parsing failed"); + assertEquals(SECRET_META_DELETED, res.getMetadata().getDeletionTimeString(), "Incorrect deletion date string"); + assertNotNull(res.getMetadata().getDeletionTime(), "Incorrect deletion date"); + assertEquals(true, res.getMetadata().isDestroyed(), "Secret destroyed when not expected"); + assertEquals(2, res.getMetadata().getVersion(), "Incorrect secret version"); } private void assertSecretData(SecretResponse res) { - assertThat("Parsed response is NULL", res, is(notNullValue())); - assertThat("Incorrect lease ID", res.getLeaseId(), is(SECRET_LEASE_ID)); - assertThat("Incorrect lease duration", res.getLeaseDuration(), is(SECRET_LEASE_DURATION)); - assertThat("Incorrect renewable status", res.isRenewable(), is(SECRET_RENEWABLE)); - assertThat("Incorrect warnings", res.getWarnings(), is(SECRET_WARNINGS)); - assertThat("Response does not contain correct data", res.get(SECRET_DATA_K1), is(SECRET_DATA_V1)); - assertThat("Response does not contain correct data", res.get(SECRET_DATA_K2), is(SECRET_DATA_V2)); + assertNotNull(res, "Parsed response is NULL"); + assertEquals(SECRET_LEASE_ID, res.getLeaseId(), "Incorrect lease ID"); + assertEquals(SECRET_LEASE_DURATION, res.getLeaseDuration(), "Incorrect lease duration"); + assertEquals(SECRET_RENEWABLE, res.isRenewable(), "Incorrect renewable status"); + assertEquals(SECRET_WARNINGS, res.getWarnings(), "Incorrect warnings"); + assertEquals(SECRET_DATA_V1, res.get(SECRET_DATA_K1), "Response does not contain correct data"); + assertEquals(SECRET_DATA_V2, res.get(SECRET_DATA_K2), "Response does not contain correct data"); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/SecretVersionResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/SecretVersionResponseTest.java index 97dcda3..6efe767 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/SecretVersionResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/SecretVersionResponseTest.java @@ -19,10 +19,7 @@ package de.stklcode.jvault.connector.model.response; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link SecretVersionResponse} model. @@ -53,11 +50,11 @@ class SecretVersionResponseTest { () -> new ObjectMapper().readValue(META_JSON, SecretVersionResponse.class), "SecretVersionResponse deserialization failed" ); - assertThat("Parsed response is NULL", res, is(notNullValue())); - assertThat("Parsed metadata is NULL", res.getMetadata(), is(notNullValue())); - assertThat("Incorrect created time", res.getMetadata().getCreatedTimeString(), is(CREATION_TIME)); - assertThat("Incorrect deletion time", res.getMetadata().getDeletionTimeString(), is(DELETION_TIME)); - assertThat("Incorrect destroyed state", res.getMetadata().isDestroyed(), is(false)); - assertThat("Incorrect version", res.getMetadata().getVersion(), is(VERSION)); + assertNotNull(res, "Parsed response is NULL"); + assertNotNull(res.getMetadata(), "Parsed metadata is NULL"); + assertEquals(CREATION_TIME, res.getMetadata().getCreatedTimeString(), "Incorrect created time"); + assertEquals(DELETION_TIME, res.getMetadata().getDeletionTimeString(), "Incorrect deletion time"); + assertEquals(false, res.getMetadata().isDestroyed(), "Incorrect destroyed state"); + assertEquals(VERSION, res.getMetadata().getVersion(), "Incorrect version"); } } diff --git a/src/test/java/de/stklcode/jvault/connector/model/response/TokenResponseTest.java b/src/test/java/de/stklcode/jvault/connector/model/response/TokenResponseTest.java index ff2dc6c..9dc54f7 100644 --- a/src/test/java/de/stklcode/jvault/connector/model/response/TokenResponseTest.java +++ b/src/test/java/de/stklcode/jvault/connector/model/response/TokenResponseTest.java @@ -23,12 +23,10 @@ import org.junit.jupiter.api.Test; import java.time.ZonedDateTime; import java.util.HashMap; +import java.util.List; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for {@link TokenResponse} model. @@ -104,7 +102,7 @@ class TokenResponseTest { void getDataRoundtrip() { // Create empty Object. TokenResponse res = new TokenResponse(); - assertThat("Initial data should be empty", res.getData(), is(nullValue())); + assertNull(res.getData(), "Initial data should be empty"); // Parsing invalid data map should fail. assertThrows( @@ -123,33 +121,33 @@ class TokenResponseTest { () -> new ObjectMapper().readValue(RES_JSON, TokenResponse.class), "TokenResponse deserialization failed." ); - assertThat("Parsed response is NULL", res, is(notNullValue())); - assertThat("Incorrect lease duration", res.getLeaseDuration(), is(RES_LEASE_DURATION)); - assertThat("Incorrect response renewable flag", res.isRenewable(), is(RES_RENEWABLE)); - assertThat("Incorrect response lease duration", res.getLeaseDuration(), is(RES_LEASE_DURATION)); + assertNotNull(res, "Parsed response is NULL"); + assertEquals(RES_LEASE_DURATION, res.getLeaseDuration(), "Incorrect lease duration"); + assertEquals(RES_RENEWABLE, res.isRenewable(), "Incorrect response renewable flag"); + assertEquals(RES_LEASE_DURATION, res.getLeaseDuration(), "Incorrect response lease duration"); // Extract token data. TokenData data = res.getData(); - assertThat("Token data is NULL", data, is(notNullValue())); - assertThat("Incorrect token accessor", data.getAccessor(), is(TOKEN_ACCESSOR)); - assertThat("Incorrect token creation time", data.getCreationTime(), is(TOKEN_CREATION_TIME)); - assertThat("Incorrect token creation TTL", data.getCreationTtl(), is(TOKEN_TTL)); - assertThat("Incorrect token display name", data.getName(), is(TOKEN_DISPLAY_NAME)); - assertThat("Incorrect token entity ID", data.getEntityId(), is(TOKEN_ENTITY_ID)); - assertThat("Incorrect token expire time", data.getExpireTimeString(), is(TOKEN_EXPIRE_TIME)); - assertThat("Incorrect parsed token expire time", data.getExpireTime(), is(ZonedDateTime.parse(TOKEN_EXPIRE_TIME))); - assertThat("Incorrect token explicit max TTL", data.getExplicitMaxTtl(), is(TOKEN_EXPLICIT_MAX_TTL)); - assertThat("Incorrect token ID", data.getId(), is(TOKEN_ID)); - assertThat("Incorrect token issue time", data.getIssueTimeString(), is(TOKEN_ISSUE_TIME)); - assertThat("Incorrect parsed token issue time", data.getIssueTime(), is(ZonedDateTime.parse(TOKEN_ISSUE_TIME))); - assertThat("Incorrect token metadata size", data.getMeta().entrySet(), hasSize(1)); - assertThat("Incorrect token metadata", data.getMeta().get(TOKEN_META_KEY), is(TOKEN_META_VALUE)); - assertThat("Incorrect token number of uses", data.getNumUses(), is(TOKEN_NUM_USES)); - assertThat("Incorrect token orphan flag", data.isOrphan(), is(TOKEN_ORPHAN)); - assertThat("Incorrect token path", data.getPath(), is(TOKEN_PATH)); - assertThat("Incorrect number of token policies", data.getPolicies(), hasSize(2)); - assertThat("Incorrect token policies", data.getPolicies(), contains(TOKEN_POLICY_1, TOKEN_POLICY_2)); - assertThat("Incorrect token renewable flag", data.isRenewable(), is(TOKEN_RENEWABLE)); - assertThat("Incorrect token TTL", data.getTtl(), is(RES_TTL)); - assertThat("Incorrect token type", data.getType(), is(TOKEN_TYPE)); + assertNotNull(data, "Token data is NULL"); + assertEquals(TOKEN_ACCESSOR, data.getAccessor(), "Incorrect token accessor"); + assertEquals(TOKEN_CREATION_TIME, data.getCreationTime(), "Incorrect token creation time"); + assertEquals(TOKEN_TTL, data.getCreationTtl(), "Incorrect token creation TTL"); + assertEquals(TOKEN_DISPLAY_NAME, data.getName(), "Incorrect token display name"); + assertEquals(TOKEN_ENTITY_ID, data.getEntityId(), "Incorrect token entity ID"); + assertEquals(TOKEN_EXPIRE_TIME, data.getExpireTimeString(), "Incorrect token expire time"); + assertEquals(ZonedDateTime.parse(TOKEN_EXPIRE_TIME), data.getExpireTime(), "Incorrect parsed token expire time"); + assertEquals(TOKEN_EXPLICIT_MAX_TTL, data.getExplicitMaxTtl(), "Incorrect token explicit max TTL"); + assertEquals(TOKEN_ID, data.getId(), "Incorrect token ID"); + assertEquals(TOKEN_ISSUE_TIME, data.getIssueTimeString(), "Incorrect token issue time"); + assertEquals(ZonedDateTime.parse(TOKEN_ISSUE_TIME), data.getIssueTime(), "Incorrect parsed token issue time"); + assertEquals(1, data.getMeta().size(), "Incorrect token metadata size"); + assertEquals(TOKEN_META_VALUE, data.getMeta().get(TOKEN_META_KEY), "Incorrect token metadata"); + assertEquals(TOKEN_NUM_USES, data.getNumUses(), "Incorrect token number of uses"); + assertEquals(TOKEN_ORPHAN, data.isOrphan(), "Incorrect token orphan flag"); + assertEquals(TOKEN_PATH, data.getPath(), "Incorrect token path"); + assertEquals(2, data.getPolicies().size(), "Incorrect number of token policies"); + assertTrue(data.getPolicies().containsAll(List.of(TOKEN_POLICY_1, TOKEN_POLICY_2)), "Incorrect token policies"); + assertEquals(TOKEN_RENEWABLE, data.isRenewable(), "Incorrect token renewable flag"); + assertEquals(RES_TTL, data.getTtl(), "Incorrect token TTL"); + assertEquals(TOKEN_TYPE, data.getType(), "Incorrect token type"); } } diff --git a/src/test/java/de/stklcode/jvault/connector/test/Credentials.java b/src/test/java/de/stklcode/jvault/connector/test/Credentials.java index 683fb33..96ecbe9 100644 --- a/src/test/java/de/stklcode/jvault/connector/test/Credentials.java +++ b/src/test/java/de/stklcode/jvault/connector/test/Credentials.java @@ -21,8 +21,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * Simple credentials class for JSON testing. * - * @author Stefan Kalscheuer - * @since 0.1 + * @author Stefan Kalscheuer + * @since 0.1 */ public class Credentials { @JsonProperty("username")