diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/AccountBuilderTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/AccountBuilderTest.java index 26851397..8fc89a97 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/AccountBuilderTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/AccountBuilderTest.java @@ -13,11 +13,10 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; import static org.shredzone.acme4j.toolbox.TestUtils.url; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.net.HttpURLConnection; import java.net.URL; @@ -56,19 +55,19 @@ public class AccountBuilderTest { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { - assertThat(login, is(notNullValue())); - assertThat(url, is(locationUrl)); - assertThat(isUpdate, is(false)); + assertThat(login).isNotNull(); + assertThat(url).isEqualTo(locationUrl); + assertThat(isUpdate).isFalse(); isUpdate = true; return HttpURLConnection.HTTP_OK; } @Override public int sendSignedRequest(URL url, JSONBuilder claims, Session session, KeyPair keypair) { - assertThat(session, is(notNullValue())); - assertThat(url, is(resourceUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("newAccount").toString())); - assertThat(keypair, is(accountKey)); + assertThat(session).isNotNull(); + assertThat(url).isEqualTo(resourceUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("newAccount").toString()); + assertThat(keypair).isEqualTo(accountKey); isUpdate = false; return HttpURLConnection.HTTP_CREATED; } @@ -94,13 +93,13 @@ public class AccountBuilderTest { Session session = provider.createSession(); Login login = builder.createLogin(session); - assertThat(login.getAccountLocation(), is(locationUrl)); + assertThat(login.getAccountLocation()).isEqualTo(locationUrl); Account account = login.getAccount(); - assertThat(account.getTermsOfServiceAgreed(), is(true)); - assertThat(account.getLocation(), is(locationUrl)); - assertThat(account.hasExternalAccountBinding(), is(false)); - assertThat(account.getKeyIdentifier(), is(nullValue())); + assertThat(account.getTermsOfServiceAgreed()).isTrue(); + assertThat(account.getLocation()).isEqualTo(locationUrl); + assertThat(account.hasExternalAccountBinding()).isFalse(); + assertThat(account.getKeyIdentifier()).isNull(); provider.close(); } @@ -117,9 +116,9 @@ public class AccountBuilderTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Session session, KeyPair keypair) { - assertThat(session, is(notNullValue())); - assertThat(url, is(resourceUrl)); - assertThat(keypair, is(accountKey)); + assertThat(session).isNotNull(); + assertThat(url).isEqualTo(resourceUrl); + assertThat(keypair).isEqualTo(accountKey); JSON binding = claims.toJSON() .get("externalAccountBinding") @@ -155,7 +154,7 @@ public class AccountBuilderTest { Session session = provider.createSession(); Login login = builder.createLogin(session); - assertThat(login.getAccountLocation(), is(locationUrl)); + assertThat(login.getAccountLocation()).isEqualTo(locationUrl); provider.close(); } @@ -170,10 +169,10 @@ public class AccountBuilderTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Session session, KeyPair keypair) { - assertThat(session, is(notNullValue())); - assertThat(url, is(resourceUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("newAccountOnlyExisting").toString())); - assertThat(keypair, is(accountKey)); + assertThat(session).isNotNull(); + assertThat(url).isEqualTo(resourceUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("newAccountOnlyExisting").toString()); + assertThat(keypair).isEqualTo(accountKey); return HttpURLConnection.HTTP_OK; } @@ -197,7 +196,7 @@ public class AccountBuilderTest { Session session = provider.createSession(); Login login = builder.createLogin(session); - assertThat(login.getAccountLocation(), is(locationUrl)); + assertThat(login.getAccountLocation()).isEqualTo(locationUrl); provider.close(); } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/AccountTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/AccountTest.java index 380d534c..0c6b900d 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/AccountTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/AccountTest.java @@ -15,13 +15,12 @@ package org.shredzone.acme4j; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; import static org.shredzone.acme4j.toolbox.TestUtils.url; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.io.IOException; import java.net.HttpURLConnection; @@ -66,9 +65,9 @@ public class AccountTest { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { - assertThat(url, is(locationUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("updateAccount").toString())); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(locationUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("updateAccount").toString()); + assertThat(login).isNotNull(); jsonResponse = getJSON("updateAccountResponse"); return HttpURLConnection.HTTP_OK; } @@ -110,19 +109,19 @@ public class AccountTest { Account account = new Account(login); account.update(); - assertThat(login.getAccountLocation(), is(locationUrl)); - assertThat(account.getLocation(), is(locationUrl)); - assertThat(account.getTermsOfServiceAgreed(), is(true)); - assertThat(account.getContacts(), hasSize(1)); - assertThat(account.getContacts().get(0), is(URI.create("mailto:foo2@example.com"))); - assertThat(account.getStatus(), is(Status.VALID)); - assertThat(account.hasExternalAccountBinding(), is(true)); - assertThat(account.getKeyIdentifier(), is("NCC-1701")); + assertThat(login.getAccountLocation()).isEqualTo(locationUrl); + assertThat(account.getLocation()).isEqualTo(locationUrl); + assertThat(account.getTermsOfServiceAgreed()).isTrue(); + assertThat(account.getContacts()).hasSize(1); + assertThat(account.getContacts().get(0)).isEqualTo(URI.create("mailto:foo2@example.com")); + assertThat(account.getStatus()).isEqualTo(Status.VALID); + assertThat(account.hasExternalAccountBinding()).isTrue(); + assertThat(account.getKeyIdentifier()).isEqualTo("NCC-1701"); Iterator orderIt = account.getOrders(); - assertThat(orderIt, not(nullValue())); - assertThat(orderIt.next().getLocation(), is(url("https://example.com/acme/order/1"))); - assertThat(orderIt.hasNext(), is(false)); + assertThat(orderIt).isNotNull(); + assertThat(orderIt.next().getLocation()).isEqualTo(url("https://example.com/acme/order/1")); + assertThat(orderIt.hasNext()).isFalse(); provider.close(); } @@ -138,7 +137,7 @@ public class AccountTest { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { requestWasSent.set(true); - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -169,15 +168,15 @@ public class AccountTest { Account account = new Account(provider.createLogin()); // Lazy loading - assertThat(requestWasSent.get(), is(false)); - assertThat(account.getTermsOfServiceAgreed(), is(true)); - assertThat(requestWasSent.get(), is(true)); + assertThat(requestWasSent.get()).isFalse(); + assertThat(account.getTermsOfServiceAgreed()).isTrue(); + assertThat(requestWasSent.get()).isTrue(); // Subsequent queries do not trigger another load requestWasSent.set(false); - assertThat(account.getTermsOfServiceAgreed(), is(true)); - assertThat(account.getStatus(), is(Status.VALID)); - assertThat(requestWasSent.get(), is(false)); + assertThat(account.getTermsOfServiceAgreed()).isTrue(); + assertThat(account.getStatus()).isEqualTo(Status.VALID); + assertThat(requestWasSent.get()).isFalse(); provider.close(); } @@ -190,9 +189,9 @@ public class AccountTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { - assertThat(url, is(resourceUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("newAuthorizationRequest").toString())); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(resourceUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("newAuthorizationRequest").toString()); + assertThat(login).isNotNull(); return HttpURLConnection.HTTP_CREATED; } @@ -218,14 +217,14 @@ public class AccountTest { Account account = new Account(login); Authorization auth = account.preAuthorizeDomain(domainName); - assertThat(auth.getIdentifier().getDomain(), is(domainName)); - assertThat(auth.getStatus(), is(Status.PENDING)); - assertThat(auth.getExpires(), is(nullValue())); - assertThat(auth.getLocation(), is(locationUrl)); + assertThat(auth.getIdentifier().getDomain()).isEqualTo(domainName); + assertThat(auth.getStatus()).isEqualTo(Status.PENDING); + assertThat(auth.getExpires()).isNull(); + assertThat(auth.getLocation()).isEqualTo(locationUrl); - assertThat(auth.getChallenges(), containsInAnyOrder( + assertThat(auth.getChallenges()).containsExactlyInAnyOrder( provider.getChallenge(Http01Challenge.TYPE), - provider.getChallenge(Dns01Challenge.TYPE))); + provider.getChallenge(Dns01Challenge.TYPE)); provider.close(); } @@ -241,9 +240,9 @@ public class AccountTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) throws AcmeException { - assertThat(url, is(resourceUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("newAuthorizationRequest").toString())); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(resourceUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("newAuthorizationRequest").toString()); + assertThat(login).isNotNull(); Problem problem = TestUtils.createProblem(problemType, problemDetail, resourceUrl); throw new AcmeServerException(problem); @@ -259,8 +258,8 @@ public class AccountTest { AcmeServerException ex = assertThrows(AcmeServerException.class, () -> account.preAuthorizeDomain("example.org") ); - assertThat(ex.getType(), is(problemType)); - assertThat(ex.getMessage(), is(problemDetail)); + assertThat(ex.getType()).isEqualTo(problemType); + assertThat(ex.getMessage()).isEqualTo(problemDetail); provider.close(); } @@ -296,9 +295,9 @@ public class AccountTest { @Override public int sendSignedRequest(URL url, JSONBuilder payload, Login login) { try { - assertThat(url, is(locationUrl)); - assertThat(login, is(notNullValue())); - assertThat(login.getKeyPair(), is(sameInstance(oldKeyPair))); + assertThat(url).isEqualTo(locationUrl); + assertThat(login).isNotNull(); + assertThat(login.getKeyPair()).isSameAs(oldKeyPair); JSON json = payload.toJSON(); String encodedHeader = json.get("protected").asString(); @@ -309,7 +308,7 @@ public class AccountTest { JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(serialized); jws.setKey(newKeyPair.getPublic()); - assertThat(jws.verifySignature(), is(true)); + assertThat(jws.verifySignature()).isTrue(); String decodedPayload = jws.getPayload(); @@ -321,7 +320,7 @@ public class AccountTest { expectedPayload.append("\"e\":\"").append(TestUtils.E).append("\","); expectedPayload.append("\"n\":\"").append(TestUtils.N).append("\""); expectedPayload.append("}}"); - assertThat(decodedPayload, sameJSONAs(expectedPayload.toString())); + assertThatJson(decodedPayload).isEqualTo(expectedPayload.toString()); } catch (JoseException ex) { fail(ex); } @@ -340,12 +339,12 @@ public class AccountTest { Session session = TestUtils.session(provider); Login login = new Login(locationUrl, oldKeyPair, session); - assertThat(login.getKeyPair(), is(sameInstance(oldKeyPair))); + assertThat(login.getKeyPair()).isSameAs(oldKeyPair); Account account = new Account(login); account.changeKey(newKeyPair); - assertThat(login.getKeyPair(), is(sameInstance(newKeyPair))); + assertThat(login.getKeyPair()).isSameAs(newKeyPair); } /** @@ -373,9 +372,9 @@ public class AccountTest { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { JSON json = claims.toJSON(); - assertThat(json.get("status").asString(), is("deactivated")); - assertThat(url, is(locationUrl)); - assertThat(login, is(notNullValue())); + assertThat(json.get("status").asString()).isEqualTo("deactivated"); + assertThat(url).isEqualTo(locationUrl); + assertThat(login).isNotNull(); return HttpURLConnection.HTTP_OK; } @@ -388,7 +387,7 @@ public class AccountTest { Account account = new Account(provider.createLogin()); account.deactivate(); - assertThat(account.getStatus(), is(Status.DEACTIVATED)); + assertThat(account.getStatus()).isEqualTo(Status.DEACTIVATED); provider.close(); } @@ -401,9 +400,9 @@ public class AccountTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { - assertThat(url, is(locationUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("modifyAccount").toString())); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(locationUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("modifyAccount").toString()); + assertThat(login).isNotNull(); return HttpURLConnection.HTTP_OK; } @@ -422,17 +421,17 @@ public class AccountTest { account.setJSON(getJSON("newAccount")); EditableAccount editable = account.modify(); - assertThat(editable, notNullValue()); + assertThat(editable).isNotNull(); editable.addContact("mailto:foo2@example.com"); editable.getContacts().add(URI.create("mailto:foo3@example.com")); editable.commit(); - assertThat(account.getLocation(), is(locationUrl)); - assertThat(account.getContacts().size(), is(3)); - assertThat(account.getContacts().get(0), is(URI.create("mailto:foo@example.com"))); - assertThat(account.getContacts().get(1), is(URI.create("mailto:foo2@example.com"))); - assertThat(account.getContacts().get(2), is(URI.create("mailto:foo3@example.com"))); + assertThat(account.getLocation()).isEqualTo(locationUrl); + assertThat(account.getContacts()).hasSize(3); + assertThat(account.getContacts()).element(0).isEqualTo(URI.create("mailto:foo@example.com")); + assertThat(account.getContacts()).element(1).isEqualTo(URI.create("mailto:foo2@example.com")); + assertThat(account.getContacts()).element(2).isEqualTo(URI.create("mailto:foo3@example.com")); provider.close(); } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/AcmeJsonResourceTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/AcmeJsonResourceTest.java index 3feea301..91ab2ec1 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/AcmeJsonResourceTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/AcmeJsonResourceTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; import static org.shredzone.acme4j.toolbox.TestUtils.url; @@ -41,14 +40,14 @@ public class AcmeJsonResourceTest { Login login = TestUtils.login(); AcmeJsonResource resource = new DummyJsonResource(login, LOCATION_URL); - assertThat(resource.getLogin(), is(login)); - assertThat(resource.getSession(), is(login.getSession())); - assertThat(resource.getLocation(), is(LOCATION_URL)); - assertThat(resource.isValid(), is(false)); + assertThat(resource.getLogin()).isEqualTo(login); + assertThat(resource.getSession()).isEqualTo(login.getSession()); + assertThat(resource.getLocation()).isEqualTo(LOCATION_URL); + assertThat(resource.isValid()).isFalse(); assertUpdateInvoked(resource, 0); - assertThat(resource.getJSON(), is(JSON_DATA)); - assertThat(resource.isValid(), is(true)); + assertThat(resource.getJSON()).isEqualTo(JSON_DATA); + assertThat(resource.isValid()).isTrue(); assertUpdateInvoked(resource, 1); } @@ -62,17 +61,17 @@ public class AcmeJsonResourceTest { JSON jsonData2 = getJSON("requestOrderResponse"); AcmeJsonResource resource = new DummyJsonResource(login, LOCATION_URL); - assertThat(resource.isValid(), is(false)); + assertThat(resource.isValid()).isFalse(); assertUpdateInvoked(resource, 0); resource.setJSON(JSON_DATA); - assertThat(resource.getJSON(), is(JSON_DATA)); - assertThat(resource.isValid(), is(true)); + assertThat(resource.getJSON()).isEqualTo(JSON_DATA); + assertThat(resource.isValid()).isTrue(); assertUpdateInvoked(resource, 0); resource.setJSON(jsonData2); - assertThat(resource.getJSON(), is(jsonData2)); - assertThat(resource.isValid(), is(true)); + assertThat(resource.getJSON()).isEqualTo(jsonData2); + assertThat(resource.isValid()).isTrue(); assertUpdateInvoked(resource, 0); } @@ -84,19 +83,19 @@ public class AcmeJsonResourceTest { Login login = TestUtils.login(); AcmeJsonResource resource = new DummyJsonResource(login, LOCATION_URL); - assertThat(resource.isValid(), is(false)); + assertThat(resource.isValid()).isFalse(); assertUpdateInvoked(resource, 0); resource.setJSON(JSON_DATA); - assertThat(resource.isValid(), is(true)); + assertThat(resource.isValid()).isTrue(); assertUpdateInvoked(resource, 0); resource.invalidate(); - assertThat(resource.isValid(), is(false)); + assertThat(resource.isValid()).isFalse(); assertUpdateInvoked(resource, 0); - assertThat(resource.getJSON(), is(JSON_DATA)); - assertThat(resource.isValid(), is(true)); + assertThat(resource.getJSON()).isEqualTo(JSON_DATA); + assertThat(resource.isValid()).isTrue(); assertUpdateInvoked(resource, 1); } @@ -111,7 +110,7 @@ public class AcmeJsonResourceTest { */ private static void assertUpdateInvoked(AcmeJsonResource resource, int count) { DummyJsonResource dummy = (DummyJsonResource) resource; - assertThat("update counter", dummy.updateCount, is(count)); + assertThat(dummy.updateCount).as("update counter").isEqualTo(count); } /** diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/AcmeResourceTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/AcmeResourceTest.java index efadc99a..a2d5812b 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/AcmeResourceTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/AcmeResourceTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.ByteArrayInputStream; @@ -43,8 +42,8 @@ public class AcmeResourceTest { assertThrows(NullPointerException.class, () -> new DummyResource(null, null)); AcmeResource resource = new DummyResource(login, location); - assertThat(resource.getLogin(), is(login)); - assertThat(resource.getLocation(), is(location)); + assertThat(resource.getLogin()).isEqualTo(login); + assertThat(resource.getLocation()).isEqualTo(location); } /** @@ -57,7 +56,7 @@ public class AcmeResourceTest { // Create a Challenge for testing DummyResource challenge = new DummyResource(login, location); - assertThat(challenge.getLogin(), is(login)); + assertThat(challenge.getLogin()).isEqualTo(login); // Serialize it byte[] serialized; @@ -70,18 +69,18 @@ public class AcmeResourceTest { // Make sure there is no PrivateKey in the stream String str = new String(serialized, StandardCharsets.ISO_8859_1); - assertThat("serialized stream contains a PrivateKey", - str, not(containsString("Ljava/security/PrivateKey"))); + assertThat(str).as("serialized stream contains a PrivateKey") + .doesNotContain("Ljava/security/PrivateKey"); // Deserialize to new object DummyResource restored; try (ByteArrayInputStream bais = new ByteArrayInputStream(serialized); ObjectInputStream in = new ObjectInputStream(bais)) { Object obj = in.readObject(); - assertThat(obj, instanceOf(DummyResource.class)); + assertThat(obj).isInstanceOf(DummyResource.class); restored = (DummyResource) obj; } - assertThat(restored, not(sameInstance(challenge))); + assertThat(restored).isNotSameAs(challenge); // Make sure the restored object is not attached to a login assertThrows(IllegalStateException.class, restored::getLogin); @@ -90,7 +89,7 @@ public class AcmeResourceTest { restored.rebind(login); // Make sure the new login is set - assertThat(restored.getLogin(), is(login)); + assertThat(restored.getLogin()).isEqualTo(login); } /** @@ -103,7 +102,7 @@ public class AcmeResourceTest { URL location = new URL("http://example.com/acme/resource"); AcmeResource resource = new DummyResource(login, location); - assertThat(resource.getLogin(), is(login)); + assertThat(resource.getLogin()).isEqualTo(login); Login login2 = TestUtils.login(); resource.rebind(login2); // fails to rebind to another login diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/AuthorizationTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/AuthorizationTest.java index 09673108..6c56c0cc 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/AuthorizationTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/AuthorizationTest.java @@ -13,10 +13,9 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.shredzone.acme4j.toolbox.AcmeUtils.parseTimestamp; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; import static org.shredzone.acme4j.toolbox.TestUtils.url; @@ -25,6 +24,7 @@ import java.net.HttpURLConnection; import java.net.URL; import java.time.Duration; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; @@ -58,22 +58,22 @@ public class AuthorizationTest { // A snail mail challenge is not available at all Challenge c1 = authorization.findChallenge(SNAILMAIL_TYPE); - assertThat(c1, is(nullValue())); + assertThat(c1).isNull(); // HttpChallenge is available Challenge c2 = authorization.findChallenge(Http01Challenge.TYPE); - assertThat(c2, is(notNullValue())); - assertThat(c2, is(instanceOf(Http01Challenge.class))); + assertThat(c2).isNotNull(); + assertThat(c2).isInstanceOf(Http01Challenge.class); // Dns01Challenge is available Challenge c3 = authorization.findChallenge(Dns01Challenge.TYPE); - assertThat(c3, is(notNullValue())); - assertThat(c3, is(instanceOf(Dns01Challenge.class))); + assertThat(c3).isNotNull(); + assertThat(c3).isInstanceOf(Dns01Challenge.class); // TlsAlpn01Challenge is available Challenge c4 = authorization.findChallenge(TlsAlpn01Challenge.TYPE); - assertThat(c4, is(notNullValue())); - assertThat(c4, is(instanceOf(TlsAlpn01Challenge.class))); + assertThat(c4).isNotNull(); + assertThat(c4).isInstanceOf(TlsAlpn01Challenge.class); } /** @@ -85,19 +85,19 @@ public class AuthorizationTest { // A snail mail challenge is not available at all NonExistingChallenge c1 = authorization.findChallenge(NonExistingChallenge.class); - assertThat(c1, is(nullValue())); + assertThat(c1).isNull(); // HttpChallenge is available Http01Challenge c2 = authorization.findChallenge(Http01Challenge.class); - assertThat(c2, is(notNullValue())); + assertThat(c2).isNotNull(); // Dns01Challenge is available Dns01Challenge c3 = authorization.findChallenge(Dns01Challenge.class); - assertThat(c3, is(notNullValue())); + assertThat(c3).isNotNull(); // TlsAlpn01Challenge is available TlsAlpn01Challenge c4 = authorization.findChallenge(TlsAlpn01Challenge.class); - assertThat(c4, is(notNullValue())); + assertThat(c4).isNotNull(); } /** @@ -120,7 +120,7 @@ public class AuthorizationTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -144,16 +144,16 @@ public class AuthorizationTest { Authorization auth = new Authorization(login, locationUrl); auth.update(); - assertThat(auth.getIdentifier().getDomain(), is("example.org")); - assertThat(auth.getStatus(), is(Status.VALID)); - assertThat(auth.isWildcard(), is(false)); - assertThat(auth.getExpires(), is(parseTimestamp("2016-01-02T17:12:40Z"))); - assertThat(auth.getLocation(), is(locationUrl)); + assertThat(auth.getIdentifier().getDomain()).isEqualTo("example.org"); + assertThat(auth.getStatus()).isEqualTo(Status.VALID); + assertThat(auth.isWildcard()).isFalse(); + assertThat(auth.getExpires()).isCloseTo("2016-01-02T17:12:40Z", within(1, ChronoUnit.SECONDS)); + assertThat(auth.getLocation()).isEqualTo(locationUrl); - assertThat(auth.getChallenges(), containsInAnyOrder( + assertThat(auth.getChallenges()).containsExactlyInAnyOrder( provider.getChallenge(Http01Challenge.TYPE), provider.getChallenge(Dns01Challenge.TYPE), - provider.getChallenge(TlsAlpn01Challenge.TYPE))); + provider.getChallenge(TlsAlpn01Challenge.TYPE)); provider.close(); } @@ -166,7 +166,7 @@ public class AuthorizationTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -188,14 +188,14 @@ public class AuthorizationTest { Authorization auth = new Authorization(login, locationUrl); auth.update(); - assertThat(auth.getIdentifier().getDomain(), is("example.org")); - assertThat(auth.getStatus(), is(Status.VALID)); - assertThat(auth.isWildcard(), is(true)); - assertThat(auth.getExpires(), is(parseTimestamp("2016-01-02T17:12:40Z"))); - assertThat(auth.getLocation(), is(locationUrl)); + assertThat(auth.getIdentifier().getDomain()).isEqualTo("example.org"); + assertThat(auth.getStatus()).isEqualTo(Status.VALID); + assertThat(auth.isWildcard()).isTrue(); + assertThat(auth.getExpires()).isCloseTo("2016-01-02T17:12:40Z", within(1, ChronoUnit.SECONDS)); + assertThat(auth.getLocation()).isEqualTo(locationUrl); - assertThat(auth.getChallenges(), containsInAnyOrder( - provider.getChallenge(Dns01Challenge.TYPE))); + assertThat(auth.getChallenges()).containsExactlyInAnyOrder( + provider.getChallenge(Dns01Challenge.TYPE)); provider.close(); } @@ -211,7 +211,7 @@ public class AuthorizationTest { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { requestWasSent.set(true); - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -235,17 +235,17 @@ public class AuthorizationTest { Authorization auth = new Authorization(login, locationUrl); // Lazy loading - assertThat(requestWasSent.get(), is(false)); - assertThat(auth.getIdentifier().getDomain(), is("example.org")); - assertThat(requestWasSent.get(), is(true)); + assertThat(requestWasSent).isFalse(); + assertThat(auth.getIdentifier().getDomain()).isEqualTo("example.org"); + assertThat(requestWasSent).isTrue(); // Subsequent queries do not trigger another load requestWasSent.set(false); - assertThat(auth.getIdentifier().getDomain(), is("example.org")); - assertThat(auth.getStatus(), is(Status.VALID)); - assertThat(auth.isWildcard(), is(false)); - assertThat(auth.getExpires(), is(parseTimestamp("2016-01-02T17:12:40Z"))); - assertThat(requestWasSent.get(), is(false)); + assertThat(auth.getIdentifier().getDomain()).isEqualTo("example.org"); + assertThat(auth.getStatus()).isEqualTo(Status.VALID); + assertThat(auth.isWildcard()).isFalse(); + assertThat(auth.getExpires()).isCloseTo("2016-01-02T17:12:40Z", within(1, ChronoUnit.SECONDS)); + assertThat(requestWasSent).isFalse(); provider.close(); } @@ -260,7 +260,7 @@ public class AuthorizationTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -283,18 +283,18 @@ public class AuthorizationTest { Authorization auth = new Authorization(login, locationUrl); AcmeRetryAfterException ex = assertThrows(AcmeRetryAfterException.class, auth::update); - assertThat(ex.getRetryAfter(), is(retryAfter)); + assertThat(ex.getRetryAfter()).isEqualTo(retryAfter); - assertThat(auth.getIdentifier().getDomain(), is("example.org")); - assertThat(auth.getStatus(), is(Status.VALID)); - assertThat(auth.isWildcard(), is(false)); - assertThat(auth.getExpires(), is(parseTimestamp("2016-01-02T17:12:40Z"))); - assertThat(auth.getLocation(), is(locationUrl)); + assertThat(auth.getIdentifier().getDomain()).isEqualTo("example.org"); + assertThat(auth.getStatus()).isEqualTo(Status.VALID); + assertThat(auth.isWildcard()).isFalse(); + assertThat(auth.getExpires()).isCloseTo("2016-01-02T17:12:40Z", within(1, ChronoUnit.SECONDS)); + assertThat(auth.getLocation()).isEqualTo(locationUrl); - assertThat(auth.getChallenges(), containsInAnyOrder( + assertThat(auth.getChallenges()).containsExactlyInAnyOrder( provider.getChallenge(Http01Challenge.TYPE), provider.getChallenge(Dns01Challenge.TYPE), - provider.getChallenge(TlsAlpn01Challenge.TYPE))); + provider.getChallenge(TlsAlpn01Challenge.TYPE)); provider.close(); } @@ -308,9 +308,9 @@ public class AuthorizationTest { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { JSON json = claims.toJSON(); - assertThat(json.get("status").asString(), is("deactivated")); - assertThat(url, is(locationUrl)); - assertThat(login, is(notNullValue())); + assertThat(json.get("status").asString()).isEqualTo("deactivated"); + assertThat(url).isEqualTo(locationUrl); + assertThat(login).isNotNull(); return HttpURLConnection.HTTP_OK; } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/CertificateTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/CertificateTest.java index c87ed5f7..77da3767 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/CertificateTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/CertificateTest.java @@ -13,12 +13,10 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; import static org.shredzone.acme4j.toolbox.TestUtils.url; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -58,8 +56,8 @@ public class CertificateTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendCertificateRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(locationUrl); + assertThat(login).isNotNull(); return HttpURLConnection.HTTP_OK; } @@ -70,7 +68,7 @@ public class CertificateTest { @Override public Collection getLinks(String relation) { - assertThat(relation, is("alternate")); + assertThat(relation).isEqualTo("alternate"); return Arrays.asList( url("https://example.com/acme/alt-cert/1"), url("https://example.com/acme/alt-cert/2")); @@ -81,12 +79,12 @@ public class CertificateTest { cert.download(); X509Certificate downloadedCert = cert.getCertificate(); - assertThat(downloadedCert.getEncoded(), is(originalCert.get(0).getEncoded())); + assertThat(downloadedCert.getEncoded()).isEqualTo(originalCert.get(0).getEncoded()); List downloadedChain = cert.getCertificateChain(); - assertThat(downloadedChain.size(), is(originalCert.size())); + assertThat(downloadedChain).hasSize(originalCert.size()); for (int ix = 0; ix < downloadedChain.size(); ix++) { - assertThat(downloadedChain.get(ix).getEncoded(), is(originalCert.get(ix).getEncoded())); + assertThat(downloadedChain.get(ix).getEncoded()).isEqualTo(originalCert.get(ix).getEncoded()); } byte[] writtenPem; @@ -106,17 +104,23 @@ public class CertificateTest { } originalPem = baos.toByteArray(); } - assertThat(writtenPem, is(originalPem)); + assertThat(writtenPem).isEqualTo(originalPem); - assertThat(cert.getAlternates(), is(notNullValue())); - assertThat(cert.getAlternates().size(), is(2)); - assertThat(cert.getAlternates().get(0), is(url("https://example.com/acme/alt-cert/1"))); - assertThat(cert.getAlternates().get(1), is(url("https://example.com/acme/alt-cert/2"))); + assertThat(cert.getAlternates()).isNotNull(); + assertThat(cert.getAlternates()).hasSize(2); + assertThat(cert.getAlternates()).element(0).isEqualTo(url("https://example.com/acme/alt-cert/1")); + assertThat(cert.getAlternates()).element(1).isEqualTo(url("https://example.com/acme/alt-cert/2")); - assertThat(cert.getAlternateCertificates(), is(notNullValue())); - assertThat(cert.getAlternateCertificates().size(), is(2)); - assertThat(cert.getAlternateCertificates().get(0).getLocation(), is(url("https://example.com/acme/alt-cert/1"))); - assertThat(cert.getAlternateCertificates().get(1).getLocation(), is(url("https://example.com/acme/alt-cert/2"))); + assertThat(cert.getAlternateCertificates()).isNotNull(); + assertThat(cert.getAlternateCertificates()).hasSize(2); + assertThat(cert.getAlternateCertificates()) + .element(0) + .extracting(Certificate::getLocation) + .isEqualTo(url("https://example.com/acme/alt-cert/1")); + assertThat(cert.getAlternateCertificates()) + .element(1) + .extracting(Certificate::getLocation) + .isEqualTo(url("https://example.com/acme/alt-cert/2")); provider.close(); } @@ -133,30 +137,30 @@ public class CertificateTest { @Override public int sendCertificateRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(locationUrl); + assertThat(login).isNotNull(); certRequested = true; return HttpURLConnection.HTTP_OK; } @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { - assertThat(url, is(resourceUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("revokeCertificateRequest").toString())); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(resourceUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("revokeCertificateRequest").toString()); + assertThat(login).isNotNull(); certRequested = false; return HttpURLConnection.HTTP_OK; } @Override public List readCertificates() { - assertThat(certRequested, is(true)); + assertThat(certRequested).isTrue(); return originalCert; } @Override public Collection getLinks(String relation) { - assertThat(relation, is("alternate")); + assertThat(relation).isEqualTo("alternate"); return Collections.emptyList(); } }; @@ -181,30 +185,30 @@ public class CertificateTest { @Override public int sendCertificateRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(locationUrl); + assertThat(login).isNotNull(); certRequested = true; return HttpURLConnection.HTTP_OK; } @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { - assertThat(url, is(resourceUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("revokeCertificateWithReasonRequest").toString())); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(resourceUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("revokeCertificateWithReasonRequest").toString()); + assertThat(login).isNotNull(); certRequested = false; return HttpURLConnection.HTTP_OK; } @Override public List readCertificates() { - assertThat(certRequested, is(true)); + assertThat(certRequested).isTrue(); return originalCert; } @Override public Collection getLinks(String relation) { - assertThat(relation, is("alternate")); + assertThat(relation).isEqualTo("alternate"); return Collections.emptyList(); } }; @@ -222,7 +226,7 @@ public class CertificateTest { */ @Test public void testRevocationReason() { - assertThat(RevocationReason.code(1), is(RevocationReason.KEY_COMPROMISE)); + assertThat(RevocationReason.code(1)).isEqualTo(RevocationReason.KEY_COMPROMISE); } /** @@ -236,10 +240,10 @@ public class CertificateTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Session session, KeyPair keypair) { - assertThat(url, is(resourceUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("revokeCertificateWithReasonRequest").toString())); - assertThat(session, is(notNullValue())); - assertThat(keypair, is(certKeyPair)); + assertThat(url).isEqualTo(resourceUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("revokeCertificateWithReasonRequest").toString()); + assertThat(session).isNotNull(); + assertThat(keypair).isEqualTo(certKeyPair); return HttpURLConnection.HTTP_OK; } }; diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/IdentifierTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/IdentifierTest.java index 666a5bbb..143e0b24 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/IdentifierTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/IdentifierTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.InetAddress; @@ -32,45 +31,45 @@ public class IdentifierTest { @Test public void testConstants() { - assertThat(Identifier.TYPE_DNS, is("dns")); - assertThat(Identifier.TYPE_IP, is("ip")); + assertThat(Identifier.TYPE_DNS).isEqualTo("dns"); + assertThat(Identifier.TYPE_IP).isEqualTo("ip"); } @Test public void testGetters() { Identifier id1 = new Identifier("foo", "123.456"); - assertThat(id1.getType(), is("foo")); - assertThat(id1.getValue(), is("123.456")); - assertThat(id1.toString(), is("foo=123.456")); + assertThat(id1.getType()).isEqualTo("foo"); + assertThat(id1.getValue()).isEqualTo("123.456"); + assertThat(id1.toString()).isEqualTo("foo=123.456"); Map map1 = id1.toMap(); - assertThat(map1.size(), is(2)); - assertThat(map1.get("type"), is("foo")); - assertThat(map1.get("value"), is("123.456")); + assertThat(map1).hasSize(2); + assertThat(map1.get("type")).isEqualTo("foo"); + assertThat(map1.get("value")).isEqualTo("123.456"); JSONBuilder jb = new JSONBuilder(); jb.put("type", "bar"); jb.put("value", "654.321"); Identifier id2 = new Identifier(jb.toJSON()); - assertThat(id2.getType(), is("bar")); - assertThat(id2.getValue(), is("654.321")); - assertThat(id2.toString(), is("bar=654.321")); + assertThat(id2.getType()).isEqualTo("bar"); + assertThat(id2.getValue()).isEqualTo("654.321"); + assertThat(id2.toString()).isEqualTo("bar=654.321"); Map map2 = id2.toMap(); - assertThat(map2.size(), is(2)); - assertThat(map2.get("type"), is("bar")); - assertThat(map2.get("value"), is("654.321")); + assertThat(map2).hasSize(2); + assertThat(map2.get("type")).isEqualTo("bar"); + assertThat(map2.get("value")).isEqualTo("654.321"); } @Test public void testDns() { Identifier id1 = Identifier.dns("example.com"); - assertThat(id1.getType(), is(Identifier.TYPE_DNS)); - assertThat(id1.getValue(), is("example.com")); - assertThat(id1.getDomain(), is("example.com")); + assertThat(id1.getType()).isEqualTo(Identifier.TYPE_DNS); + assertThat(id1.getValue()).isEqualTo("example.com"); + assertThat(id1.getDomain()).isEqualTo("example.com"); Identifier id2 = Identifier.dns("ëxämþlë.com"); - assertThat(id2.getType(), is(Identifier.TYPE_DNS)); - assertThat(id2.getValue(), is("xn--xml-qla7ae5k.com")); - assertThat(id2.getDomain(), is("xn--xml-qla7ae5k.com")); + assertThat(id2.getType()).isEqualTo(Identifier.TYPE_DNS); + assertThat(id2.getValue()).isEqualTo("xn--xml-qla7ae5k.com"); + assertThat(id2.getDomain()).isEqualTo("xn--xml-qla7ae5k.com"); } @Test @@ -83,19 +82,19 @@ public class IdentifierTest { @Test public void testIp() throws UnknownHostException { Identifier id1 = Identifier.ip(InetAddress.getByName("192.168.1.2")); - assertThat(id1.getType(), is(Identifier.TYPE_IP)); - assertThat(id1.getValue(), is("192.168.1.2")); - assertThat(id1.getIP().getHostAddress(), is("192.168.1.2")); + assertThat(id1.getType()).isEqualTo(Identifier.TYPE_IP); + assertThat(id1.getValue()).isEqualTo("192.168.1.2"); + assertThat(id1.getIP().getHostAddress()).isEqualTo("192.168.1.2"); Identifier id2 = Identifier.ip(InetAddress.getByName("2001:db8:85a3::8a2e:370:7334")); - assertThat(id2.getType(), is(Identifier.TYPE_IP)); - assertThat(id2.getValue(), is("2001:db8:85a3:0:0:8a2e:370:7334")); - assertThat(id2.getIP().getHostAddress(), is("2001:db8:85a3:0:0:8a2e:370:7334")); + assertThat(id2.getType()).isEqualTo(Identifier.TYPE_IP); + assertThat(id2.getValue()).isEqualTo("2001:db8:85a3:0:0:8a2e:370:7334"); + assertThat(id2.getIP().getHostAddress()).isEqualTo("2001:db8:85a3:0:0:8a2e:370:7334"); Identifier id3 = Identifier.ip("192.168.2.99"); - assertThat(id3.getType(), is(Identifier.TYPE_IP)); - assertThat(id3.getValue(), is("192.168.2.99")); - assertThat(id3.getIP().getHostAddress(), is("192.168.2.99")); + assertThat(id3.getType()).isEqualTo(Identifier.TYPE_IP); + assertThat(id3.getValue()).isEqualTo("192.168.2.99"); + assertThat(id3.getIP().getHostAddress()).isEqualTo("192.168.2.99"); } @Test @@ -110,19 +109,19 @@ public class IdentifierTest { Identifier idRef = new Identifier("foo", "123.456"); Identifier id1 = new Identifier("foo", "123.456"); - assertThat(idRef.equals(id1), is(true)); + assertThat(idRef.equals(id1)).isTrue(); Identifier id2 = new Identifier("bar", "654.321"); - assertThat(idRef.equals(id2), is(false)); + assertThat(idRef.equals(id2)).isFalse(); Identifier id3 = new Identifier("foo", "555.666"); - assertThat(idRef.equals(id3), is(false)); + assertThat(idRef.equals(id3)).isFalse(); Identifier id4 = new Identifier("sna", "123.456"); - assertThat(idRef.equals(id4), is(false)); + assertThat(idRef.equals(id4)).isFalse(); - assertThat(idRef.equals(new Object()), is(false)); - assertThat(idRef.equals(null), is(false)); + assertThat(idRef.equals(new Object())).isFalse(); + assertThat(idRef.equals(null)).isFalse(); } @Test diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/LoginTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/LoginTest.java index 9d0e72fa..06415836 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/LoginTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/LoginTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; @@ -54,14 +53,14 @@ public class LoginTest { Session session = TestUtils.session(); Login login = new Login(location, keypair, session); - assertThat(login.getAccountLocation(), is(location)); - assertThat(login.getKeyPair(), is(keypair)); - assertThat(login.getSession(), is(session)); + assertThat(login.getAccountLocation()).isEqualTo(location); + assertThat(login.getKeyPair()).isEqualTo(keypair); + assertThat(login.getSession()).isEqualTo(session); - assertThat(login.getAccount(), is(notNullValue())); - assertThat(login.getAccount().getLogin(), is(login)); - assertThat(login.getAccount().getLocation(), is(location)); - assertThat(login.getAccount().getSession(), is(session)); + assertThat(login.getAccount()).isNotNull(); + assertThat(login.getAccount().getLogin()).isEqualTo(login); + assertThat(login.getAccount().getLocation()).isEqualTo(location); + assertThat(login.getAccount().getSession()).isEqualTo(session); } /** @@ -76,19 +75,19 @@ public class LoginTest { Login login = new Login(location, keypair, session); Authorization auth = login.bindAuthorization(resourceUrl); - assertThat(auth, is(notNullValue())); - assertThat(auth.getLogin(), is(login)); - assertThat(auth.getLocation(), is(resourceUrl)); + assertThat(auth).isNotNull(); + assertThat(auth.getLogin()).isEqualTo(login); + assertThat(auth.getLocation()).isEqualTo(resourceUrl); Certificate cert = login.bindCertificate(resourceUrl); - assertThat(cert, is(notNullValue())); - assertThat(cert.getLogin(), is(login)); - assertThat(cert.getLocation(), is(resourceUrl)); + assertThat(cert).isNotNull(); + assertThat(cert.getLogin()).isEqualTo(login); + assertThat(cert.getLocation()).isEqualTo(resourceUrl); Order order = login.bindOrder(resourceUrl); - assertThat(order, is(notNullValue())); - assertThat(order.getLogin(), is(login)); - assertThat(order.getLocation(), is(resourceUrl)); + assertThat(order).isNotNull(); + assertThat(order.getLogin()).isEqualTo(login); + assertThat(order.getLocation()).isEqualTo(resourceUrl); } /** @@ -101,11 +100,11 @@ public class LoginTest { Session session = TestUtils.session(); Login login = new Login(location, keypair, session); - assertThat(login.getKeyPair(), is(keypair)); + assertThat(login.getKeyPair()).isEqualTo(keypair); KeyPair keypair2 = TestUtils.createKeyPair(); login.setKeyPair(keypair2); - assertThat(login.getKeyPair(), is(keypair2)); + assertThat(login.getKeyPair()).isEqualTo(keypair2); } /** @@ -135,8 +134,8 @@ public class LoginTest { Login login = new Login(location, keypair, session); Challenge challenge = login.createChallenge(data); - assertThat(challenge, is(instanceOf(Http01Challenge.class))); - assertThat(challenge, is(sameInstance(mockChallenge))); + assertThat(challenge).isInstanceOf(Http01Challenge.class); + assertThat(challenge).isSameAs(mockChallenge); verify(mockProvider).createChallenge(login, data); } @@ -154,7 +153,7 @@ public class LoginTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -165,23 +164,23 @@ public class LoginTest { @Override public Challenge createChallenge(Login login, JSON json) { - assertThat(json, is(httpChallenge)); + assertThat(json).isEqualTo(httpChallenge); return mockChallenge; } }; Login login = provider.createLogin(); Challenge challenge = login.bindChallenge(locationUrl); - assertThat(challenge, is(instanceOf(Http01Challenge.class))); - assertThat(challenge, is(sameInstance(mockChallenge))); + assertThat(challenge).isInstanceOf(Http01Challenge.class); + assertThat(challenge).isSameAs(mockChallenge); Http01Challenge challenge2 = login.bindChallenge(locationUrl, Http01Challenge.class); - assertThat(challenge2, is(sameInstance(mockChallenge))); + assertThat(challenge2).isSameAs(mockChallenge); AcmeProtocolException ex = assertThrows(AcmeProtocolException.class, () -> login.bindChallenge(locationUrl, Dns01Challenge.class)); - assertThat(ex.getMessage(), is("Challenge type http-01 does not match" + - " requested class class org.shredzone.acme4j.challenge.Dns01Challenge")); + assertThat(ex.getMessage()).isEqualTo("Challenge type http-01 does not match" + + " requested class class org.shredzone.acme4j.challenge.Dns01Challenge"); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/OrderBuilderTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/OrderBuilderTest.java index ee88f5f1..60e62e40 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/OrderBuilderTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/OrderBuilderTest.java @@ -13,13 +13,12 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.shredzone.acme4j.toolbox.AcmeUtils.parseTimestamp; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; import static org.shredzone.acme4j.toolbox.TestUtils.url; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.net.HttpURLConnection; import java.net.InetAddress; @@ -28,10 +27,10 @@ import java.time.Duration; import java.time.Instant; import java.util.Arrays; +import org.assertj.core.api.AutoCloseableSoftAssertions; import org.junit.jupiter.api.Test; import org.shredzone.acme4j.connector.Resource; import org.shredzone.acme4j.exception.AcmeException; -import org.shredzone.acme4j.exception.AcmeProtocolException; import org.shredzone.acme4j.provider.TestableConnectionProvider; import org.shredzone.acme4j.toolbox.JSON; import org.shredzone.acme4j.toolbox.JSONBuilder; @@ -56,9 +55,9 @@ public class OrderBuilderTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { - assertThat(url, is(resourceUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("requestOrderRequest").toString())); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(resourceUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("requestOrderRequest").toString()); + assertThat(login).isNotNull(); return HttpURLConnection.HTTP_CREATED; } @@ -90,7 +89,8 @@ public class OrderBuilderTest { .notAfter(notAfter) .create(); - assertThat(order.getIdentifiers(), containsInAnyOrder( + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(order.getIdentifiers()).containsExactlyInAnyOrder( Identifier.dns("example.com"), Identifier.dns("www.example.com"), Identifier.dns("example.org"), @@ -98,20 +98,21 @@ public class OrderBuilderTest { Identifier.dns("m.example.org"), Identifier.dns("d.example.com"), Identifier.dns("d2.example.com"), - Identifier.ip(InetAddress.getByName("192.168.1.2")))); - assertThat(order.getNotBefore(), is(parseTimestamp("2016-01-01T00:10:00Z"))); - assertThat(order.getNotAfter(), is(parseTimestamp("2016-01-08T00:10:00Z"))); - assertThat(order.getExpires(), is(parseTimestamp("2016-01-10T00:00:00Z"))); - assertThat(order.getStatus(), is(Status.PENDING)); - assertThat(order.isAutoRenewing(), is(false)); - assertThat(order.getAutoRenewalStartDate(), is(nullValue())); - assertThat(order.getAutoRenewalEndDate(), is(nullValue())); - assertThat(order.getAutoRenewalLifetime(), is(nullValue())); - assertThat(order.getAutoRenewalLifetimeAdjust(), is(nullValue())); - assertThat(order.isAutoRenewalGetEnabled(), is(false)); - assertThat(order.getLocation(), is(locationUrl)); - assertThat(order.getAuthorizations(), is(notNullValue())); - assertThat(order.getAuthorizations().size(), is(2)); + Identifier.ip(InetAddress.getByName("192.168.1.2"))); + softly.assertThat(order.getNotBefore()).isEqualTo("2016-01-01T00:10:00Z"); + softly.assertThat(order.getNotAfter()).isEqualTo("2016-01-08T00:10:00Z"); + softly.assertThat(order.getExpires()).isEqualTo("2016-01-10T00:00:00Z"); + softly.assertThat(order.getStatus()).isEqualTo(Status.PENDING); + softly.assertThat(order.isAutoRenewing()).isFalse(); + softly.assertThat(order.getAutoRenewalStartDate()).isNull(); + softly.assertThat(order.getAutoRenewalEndDate()).isNull(); + softly.assertThat(order.getAutoRenewalLifetime()).isNull(); + softly.assertThat(order.getAutoRenewalLifetimeAdjust()).isNull(); + softly.assertThat(order.isAutoRenewalGetEnabled()).isFalse(); + softly.assertThat(order.getLocation()).isEqualTo(locationUrl); + softly.assertThat(order.getAuthorizations()).isNotNull(); + softly.assertThat(order.getAuthorizations()).hasSize(2); + } provider.close(); } @@ -129,9 +130,9 @@ public class OrderBuilderTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { - assertThat(url, is(resourceUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("requestAutoRenewOrderRequest").toString())); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(resourceUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("requestAutoRenewOrderRequest").toString()); + assertThat(login).isNotNull(); return HttpURLConnection.HTTP_CREATED; } @@ -162,16 +163,18 @@ public class OrderBuilderTest { .autoRenewalEnableGet() .create(); - assertThat(order.getIdentifiers(), containsInAnyOrder(Identifier.dns("example.org"))); - assertThat(order.getNotBefore(), is(nullValue())); - assertThat(order.getNotAfter(), is(nullValue())); - assertThat(order.isAutoRenewing(), is(true)); - assertThat(order.getAutoRenewalStartDate(), is(autoRenewStart)); - assertThat(order.getAutoRenewalEndDate(), is(autoRenewEnd)); - assertThat(order.getAutoRenewalLifetime(), is(validity)); - assertThat(order.getAutoRenewalLifetimeAdjust(), is(predate)); - assertThat(order.isAutoRenewalGetEnabled(), is(true)); - assertThat(order.getLocation(), is(locationUrl)); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(order.getIdentifiers()).containsExactlyInAnyOrder(Identifier.dns("example.org")); + softly.assertThat(order.getNotBefore()).isNull(); + softly.assertThat(order.getNotAfter()).isNull(); + softly.assertThat(order.isAutoRenewing()).isTrue(); + softly.assertThat(order.getAutoRenewalStartDate()).isEqualTo(autoRenewStart); + softly.assertThat(order.getAutoRenewalEndDate()).isEqualTo(autoRenewEnd); + softly.assertThat(order.getAutoRenewalLifetime()).isEqualTo(validity); + softly.assertThat(order.getAutoRenewalLifetimeAdjust()).isEqualTo(predate); + softly.assertThat(order.isAutoRenewalGetEnabled()).isTrue(); + softly.assertThat(order.getLocation()).isEqualTo(locationUrl); + } provider.close(); } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/OrderTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/OrderTest.java index e3cb389f..a6b7369e 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/OrderTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/OrderTest.java @@ -13,12 +13,10 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.shredzone.acme4j.toolbox.AcmeUtils.parseTimestamp; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; import static org.shredzone.acme4j.toolbox.TestUtils.url; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.net.HttpURLConnection; import java.net.URI; @@ -27,6 +25,7 @@ import java.time.Duration; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; +import org.assertj.core.api.AutoCloseableSoftAssertions; import org.junit.jupiter.api.Test; import org.shredzone.acme4j.provider.TestableConnectionProvider; import org.shredzone.acme4j.toolbox.JSON; @@ -49,7 +48,7 @@ public class OrderTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -60,7 +59,7 @@ public class OrderTest { @Override public void handleRetryAfter(String message) { - assertThat(message, not(nullValue())); + assertThat(message).isNotNull(); } }; @@ -69,35 +68,41 @@ public class OrderTest { Order order = new Order(login, locationUrl); order.update(); - assertThat(order.getStatus(), is(Status.PENDING)); - assertThat(order.getExpires(), is(parseTimestamp("2015-03-01T14:09:00Z"))); - assertThat(order.getLocation(), is(locationUrl)); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(order.getStatus()).isEqualTo(Status.PENDING); + softly.assertThat(order.getExpires()).isEqualTo("2015-03-01T14:09:00Z"); + softly.assertThat(order.getLocation()).isEqualTo(locationUrl); - assertThat(order.getIdentifiers(), containsInAnyOrder( + softly.assertThat(order.getIdentifiers()).containsExactlyInAnyOrder( Identifier.dns("example.com"), - Identifier.dns("www.example.com"))); - assertThat(order.getNotBefore(), is(parseTimestamp("2016-01-01T00:00:00Z"))); - assertThat(order.getNotAfter(), is(parseTimestamp("2016-01-08T00:00:00Z"))); - assertThat(order.getCertificate().getLocation(), is(url("https://example.com/acme/cert/1234"))); - assertThat(order.getFinalizeLocation(), is(finalizeUrl)); + Identifier.dns("www.example.com")); + softly.assertThat(order.getNotBefore()).isEqualTo("2016-01-01T00:00:00Z"); + softly.assertThat(order.getNotAfter()).isEqualTo("2016-01-08T00:00:00Z"); + softly.assertThat(order.getCertificate().getLocation()) + .isEqualTo(url("https://example.com/acme/cert/1234")); + softly.assertThat(order.getFinalizeLocation()).isEqualTo(finalizeUrl); - assertThat(order.isAutoRenewing(), is(false)); - assertThat(order.getAutoRenewalStartDate(), is(nullValue())); - assertThat(order.getAutoRenewalEndDate(), is(nullValue())); - assertThat(order.getAutoRenewalLifetime(), is(nullValue())); - assertThat(order.getAutoRenewalLifetimeAdjust(), is(nullValue())); - assertThat(order.isAutoRenewalGetEnabled(), is(false)); + softly.assertThat(order.isAutoRenewing()).isFalse(); + softly.assertThat(order.getAutoRenewalStartDate()).isNull(); + softly.assertThat(order.getAutoRenewalEndDate()).isNull(); + softly.assertThat(order.getAutoRenewalLifetime()).isNull(); + softly.assertThat(order.getAutoRenewalLifetimeAdjust()).isNull(); + softly.assertThat(order.isAutoRenewalGetEnabled()).isFalse(); - assertThat(order.getError(), is(notNullValue())); - assertThat(order.getError().getType(), is(URI.create("urn:ietf:params:acme:error:connection"))); - assertThat(order.getError().getDetail(), is("connection refused")); + softly.assertThat(order.getError()).isNotNull(); + softly.assertThat(order.getError().getType()) + .isEqualTo(URI.create("urn:ietf:params:acme:error:connection")); + softly.assertThat(order.getError().getDetail()) + .isEqualTo("connection refused"); - List auths = order.getAuthorizations(); - assertThat(auths.size(), is(2)); - assertThat(auths.stream().map(Authorization::getLocation)::iterator, - containsInAnyOrder( - url("https://example.com/acme/authz/1234"), - url("https://example.com/acme/authz/2345"))); + List auths = order.getAuthorizations(); + softly.assertThat(auths).hasSize(2); + softly.assertThat(auths.stream()) + .map(Authorization::getLocation) + .containsExactlyInAnyOrder( + url("https://example.com/acme/authz/1234"), + url("https://example.com/acme/authz/2345")); + } provider.close(); } @@ -113,7 +118,7 @@ public class OrderTest { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { requestWasSent.set(true); - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -124,7 +129,7 @@ public class OrderTest { @Override public void handleRetryAfter(String message) { - assertThat(message, not(nullValue())); + assertThat(message).isNotNull(); } }; @@ -132,17 +137,21 @@ public class OrderTest { Order order = new Order(login, locationUrl); - // Lazy loading - assertThat(requestWasSent.get(), is(false)); - assertThat(order.getCertificate().getLocation(), is(url("https://example.com/acme/cert/1234"))); - assertThat(requestWasSent.get(), is(true)); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + // Lazy loading + softly.assertThat(requestWasSent).isFalse(); + softly.assertThat(order.getCertificate().getLocation()) + .isEqualTo(url("https://example.com/acme/cert/1234")); + softly.assertThat(requestWasSent).isTrue(); - // Subsequent queries do not trigger another load - requestWasSent.set(false); - assertThat(order.getCertificate().getLocation(), is(url("https://example.com/acme/cert/1234"))); - assertThat(order.getStatus(), is(Status.PENDING)); - assertThat(order.getExpires(), is(parseTimestamp("2015-03-01T14:09:00Z"))); - assertThat(requestWasSent.get(), is(false)); + // Subsequent queries do not trigger another load + requestWasSent.set(false); + softly.assertThat(order.getCertificate().getLocation()) + .isEqualTo(url("https://example.com/acme/cert/1234")); + softly.assertThat(order.getStatus()).isEqualTo(Status.PENDING); + softly.assertThat(order.getExpires()).isEqualTo("2015-03-01T14:09:00Z"); + softly.assertThat(requestWasSent).isFalse(); + } provider.close(); } @@ -159,15 +168,15 @@ public class OrderTest { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { - assertThat(url, is(finalizeUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("finalizeRequest").toString())); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(finalizeUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("finalizeRequest").toString()); + assertThat(login).isNotNull(); isFinalized = true; return HttpURLConnection.HTTP_OK; } @@ -179,7 +188,7 @@ public class OrderTest { @Override public void handleRetryAfter(String message) { - assertThat(message, not(nullValue())); + assertThat(message).isNotNull(); } }; @@ -188,25 +197,29 @@ public class OrderTest { Order order = new Order(login, locationUrl); order.execute(csr); - assertThat(order.getStatus(), is(Status.VALID)); - assertThat(order.getExpires(), is(parseTimestamp("2015-03-01T14:09:00Z"))); - assertThat(order.getLocation(), is(locationUrl)); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(order.getStatus()).isEqualTo(Status.VALID); + softly.assertThat(order.getExpires()).isEqualTo("2015-03-01T14:09:00Z"); + softly.assertThat(order.getLocation()).isEqualTo(locationUrl); - assertThat(order.getIdentifiers(), containsInAnyOrder( - Identifier.dns("example.com"), - Identifier.dns("www.example.com"))); - assertThat(order.getNotBefore(), is(parseTimestamp("2016-01-01T00:00:00Z"))); - assertThat(order.getNotAfter(), is(parseTimestamp("2016-01-08T00:00:00Z"))); - assertThat(order.getCertificate().getLocation(), is(url("https://example.com/acme/cert/1234"))); - assertThat(order.getAutoRenewalCertificate(), is(nullValue())); - assertThat(order.getFinalizeLocation(), is(finalizeUrl)); + softly.assertThat(order.getIdentifiers()).containsExactlyInAnyOrder( + Identifier.dns("example.com"), + Identifier.dns("www.example.com")); + softly.assertThat(order.getNotBefore()).isEqualTo("2016-01-01T00:00:00Z"); + softly.assertThat(order.getNotAfter()).isEqualTo("2016-01-08T00:00:00Z"); + softly.assertThat(order.getCertificate().getLocation()) + .isEqualTo(url("https://example.com/acme/cert/1234")); + softly.assertThat(order.getAutoRenewalCertificate()).isNull(); + softly.assertThat(order.getFinalizeLocation()).isEqualTo(finalizeUrl); - List auths = order.getAuthorizations(); - assertThat(auths.size(), is(2)); - assertThat(auths.stream().map(Authorization::getLocation)::iterator, - containsInAnyOrder( - url("https://example.com/acme/authz/1234"), - url("https://example.com/acme/authz/2345"))); + List auths = order.getAuthorizations(); + softly.assertThat(auths).hasSize(2); + softly.assertThat(auths.stream()) + .map(Authorization::getLocation) + .containsExactlyInAnyOrder( + url("https://example.com/acme/authz/1234"), + url("https://example.com/acme/authz/2345")); + } provider.close(); } @@ -219,7 +232,7 @@ public class OrderTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -230,7 +243,7 @@ public class OrderTest { @Override public void handleRetryAfter(String message) { - assertThat(message, not(nullValue())); + assertThat(message).isNotNull(); } }; @@ -241,14 +254,16 @@ public class OrderTest { Order order = new Order(login, locationUrl); order.update(); - assertThat(order.isAutoRenewing(), is(true)); - assertThat(order.getAutoRenewalStartDate(), is(parseTimestamp("2016-01-01T00:00:00Z"))); - assertThat(order.getAutoRenewalEndDate(), is(parseTimestamp("2017-01-01T00:00:00Z"))); - assertThat(order.getAutoRenewalLifetime(), is(Duration.ofHours(168))); - assertThat(order.getAutoRenewalLifetimeAdjust(), is(Duration.ofDays(6))); - assertThat(order.getNotBefore(), is(nullValue())); - assertThat(order.getNotAfter(), is(nullValue())); - assertThat(order.isAutoRenewalGetEnabled(), is(true)); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(order.isAutoRenewing()).isTrue(); + softly.assertThat(order.getAutoRenewalStartDate()).isEqualTo("2016-01-01T00:00:00Z"); + softly.assertThat(order.getAutoRenewalEndDate()).isEqualTo("2017-01-01T00:00:00Z"); + softly.assertThat(order.getAutoRenewalLifetime()).isEqualTo(Duration.ofHours(168)); + softly.assertThat(order.getAutoRenewalLifetimeAdjust()).isEqualTo(Duration.ofDays(6)); + softly.assertThat(order.getNotBefore()).isNull(); + softly.assertThat(order.getNotAfter()).isNull(); + softly.assertThat(order.isAutoRenewalGetEnabled()).isTrue(); + } provider.close(); } @@ -261,7 +276,7 @@ public class OrderTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -272,23 +287,26 @@ public class OrderTest { @Override public void handleRetryAfter(String message) { - assertThat(message, not(nullValue())); + assertThat(message).isNotNull(); } }; Login login = provider.createLogin(); Order order = login.bindOrder(locationUrl); - assertThat(order.getCertificate(), is(nullValue())); - assertThat(order.getAutoRenewalCertificate().getLocation(), is(url("https://example.com/acme/cert/1234"))); - assertThat(order.isAutoRenewing(), is(true)); - assertThat(order.getAutoRenewalStartDate(), is(parseTimestamp("2018-01-01T00:00:00Z"))); - assertThat(order.getAutoRenewalEndDate(), is(parseTimestamp("2019-01-01T00:00:00Z"))); - assertThat(order.getAutoRenewalLifetime(), is(Duration.ofHours(168))); - assertThat(order.getAutoRenewalLifetimeAdjust(), is(Duration.ofDays(6))); - assertThat(order.getNotBefore(), is(nullValue())); - assertThat(order.getNotAfter(), is(nullValue())); - assertThat(order.isAutoRenewalGetEnabled(), is(true)); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(order.getCertificate()).isNull(); + softly.assertThat(order.getAutoRenewalCertificate().getLocation()) + .isEqualTo(url("https://example.com/acme/cert/1234")); + softly.assertThat(order.isAutoRenewing()).isTrue(); + softly.assertThat(order.getAutoRenewalStartDate()).isEqualTo("2018-01-01T00:00:00Z"); + softly.assertThat(order.getAutoRenewalEndDate()).isEqualTo("2019-01-01T00:00:00Z"); + softly.assertThat(order.getAutoRenewalLifetime()).isEqualTo(Duration.ofHours(168)); + softly.assertThat(order.getAutoRenewalLifetimeAdjust()).isEqualTo(Duration.ofDays(6)); + softly.assertThat(order.getNotBefore()).isNull(); + softly.assertThat(order.getNotAfter()).isNull(); + softly.assertThat(order.isAutoRenewalGetEnabled()).isTrue(); + } provider.close(); } @@ -302,9 +320,9 @@ public class OrderTest { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { JSON json = claims.toJSON(); - assertThat(json.get("status").asString(), is("canceled")); - assertThat(url, is(locationUrl)); - assertThat(login, is(notNullValue())); + assertThat(json.get("status").asString()).isEqualTo("canceled"); + assertThat(url).isEqualTo(locationUrl); + assertThat(login).isNotNull(); return HttpURLConnection.HTTP_OK; } @@ -321,7 +339,7 @@ public class OrderTest { Order order = new Order(login, locationUrl); order.cancelAutoRenewal(); - assertThat(order.getStatus(), is(Status.CANCELED)); + assertThat(order.getStatus()).isEqualTo(Status.CANCELED); provider.close(); } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/ProblemTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/ProblemTest.java index 9df383bd..956d0a65 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/ProblemTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/ProblemTest.java @@ -13,16 +13,15 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.shredzone.acme4j.toolbox.TestUtils.url; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.net.URI; import java.net.URL; import java.util.List; +import org.assertj.core.api.AutoCloseableSoftAssertions; import org.junit.jupiter.api.Test; import org.shredzone.acme4j.toolbox.JSON; import org.shredzone.acme4j.toolbox.JSONBuilder; @@ -40,34 +39,36 @@ public class ProblemTest { Problem problem = new Problem(original, baseUrl); - assertThat(problem.getType(), is(URI.create("urn:ietf:params:acme:error:malformed"))); - assertThat(problem.getTitle(), is("Some of the identifiers requested were rejected")); - assertThat(problem.getDetail(), is("Identifier \"abc12_\" is malformed")); - assertThat(problem.getInstance(), is(URI.create("https://example.com/documents/error.html"))); - assertThat(problem.getIdentifier(), is(nullValue())); - assertThat(problem.asJSON().toString(), is(sameJSONAs(original.toString()))); - assertThat(problem.toString(), is( - "Identifier \"abc12_\" is malformed (" - + "Invalid underscore in DNS name \"_example.com\" ‒ " - + "This CA will not issue for \"example.net\")")); + assertThatJson(problem.asJSON().toString()).isEqualTo(original.toString()); - List subs = problem.getSubProblems(); - assertThat(subs, not(nullValue())); - assertThat(subs, hasSize(2)); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(problem.getType()).isEqualTo(URI.create("urn:ietf:params:acme:error:malformed")); + softly.assertThat(problem.getTitle()).isEqualTo("Some of the identifiers requested were rejected"); + softly.assertThat(problem.getDetail()).isEqualTo("Identifier \"abc12_\" is malformed"); + softly.assertThat(problem.getInstance()).isEqualTo(URI.create("https://example.com/documents/error.html")); + softly.assertThat(problem.getIdentifier()).isNull(); + softly.assertThat(problem.toString()).isEqualTo( + "Identifier \"abc12_\" is malformed (" + + "Invalid underscore in DNS name \"_example.com\" ‒ " + + "This CA will not issue for \"example.net\")"); - Problem p1 = subs.get(0); - assertThat(p1.getType(), is(URI.create("urn:ietf:params:acme:error:malformed"))); - assertThat(p1.getTitle(), is(nullValue())); - assertThat(p1.getDetail(), is("Invalid underscore in DNS name \"_example.com\"")); - assertThat(p1.getIdentifier().getDomain(), is("_example.com")); - assertThat(p1.toString(), is("Invalid underscore in DNS name \"_example.com\"")); + List subs = problem.getSubProblems(); + softly.assertThat(subs).isNotNull().hasSize(2); - Problem p2 = subs.get(1); - assertThat(p2.getType(), is(URI.create("urn:ietf:params:acme:error:rejectedIdentifier"))); - assertThat(p2.getTitle(), is(nullValue())); - assertThat(p2.getDetail(), is("This CA will not issue for \"example.net\"")); - assertThat(p2.getIdentifier().getDomain(), is("example.net")); - assertThat(p2.toString(), is("This CA will not issue for \"example.net\"")); + Problem p1 = subs.get(0); + softly.assertThat(p1.getType()).isEqualTo(URI.create("urn:ietf:params:acme:error:malformed")); + softly.assertThat(p1.getTitle()).isNull(); + softly.assertThat(p1.getDetail()).isEqualTo("Invalid underscore in DNS name \"_example.com\""); + softly.assertThat(p1.getIdentifier().getDomain()).isEqualTo("_example.com"); + softly.assertThat(p1.toString()).isEqualTo("Invalid underscore in DNS name \"_example.com\""); + + Problem p2 = subs.get(1); + softly.assertThat(p2.getType()).isEqualTo(URI.create("urn:ietf:params:acme:error:rejectedIdentifier")); + softly.assertThat(p2.getTitle()).isNull(); + softly.assertThat(p2.getDetail()).isEqualTo("This CA will not issue for \"example.net\""); + softly.assertThat(p2.getIdentifier().getDomain()).isEqualTo("example.net"); + softly.assertThat(p2.toString()).isEqualTo("This CA will not issue for \"example.net\""); + } } /** @@ -82,15 +83,15 @@ public class ProblemTest { jb.put("type", typeUri); Problem p1 = new Problem(jb.toJSON(), baseUrl); - assertThat(p1.toString(), is(typeUri.toString())); + assertThat(p1.toString()).isEqualTo(typeUri.toString()); jb.put("title", "Some of the identifiers requested were rejected"); Problem p2 = new Problem(jb.toJSON(), baseUrl); - assertThat(p2.toString(), is("Some of the identifiers requested were rejected")); + assertThat(p2.toString()).isEqualTo("Some of the identifiers requested were rejected"); jb.put("detail", "Identifier \"abc12_\" is malformed"); Problem p3 = new Problem(jb.toJSON(), baseUrl); - assertThat(p3.toString(), is("Identifier \"abc12_\" is malformed")); + assertThat(p3.toString()).isEqualTo("Identifier \"abc12_\" is malformed"); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/SessionTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/SessionTest.java index 76d183d0..efdf63af 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/SessionTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/SessionTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*; import static org.shredzone.acme4j.toolbox.TestUtils.*; @@ -26,6 +25,7 @@ import java.security.KeyPair; import java.time.Duration; import java.time.ZonedDateTime; +import org.assertj.core.api.AutoCloseableSoftAssertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.shredzone.acme4j.connector.Resource; @@ -49,16 +49,16 @@ public class SessionTest { assertThrows(NullPointerException.class, () -> new Session((URI) null)); Session session = new Session(serverUri); - assertThat(session, not(nullValue())); - assertThat(session.getServerUri(), is(serverUri)); + assertThat(session).isNotNull(); + assertThat(session.getServerUri()).isEqualTo(serverUri); Session session2 = new Session(TestUtils.ACME_SERVER_URI); - assertThat(session2, not(nullValue())); - assertThat(session2.getServerUri(), is(serverUri)); + assertThat(session2).isNotNull(); + assertThat(session2.getServerUri()).isEqualTo(serverUri); Session session3 = new Session(serverUri, new GenericAcmeProvider()); - assertThat(session3, not(nullValue())); - assertThat(session3.getServerUri(), is(serverUri)); + assertThat(session3).isNotNull(); + assertThat(session3.getServerUri()).isEqualTo(serverUri); assertThrows(IllegalArgumentException.class, () -> new Session("#*aBaDuRi*#"), @@ -78,24 +78,24 @@ public class SessionTest { Session session = new Session(serverUri); - assertThat(session.getNonce(), is(nullValue())); + assertThat(session.getNonce()).isNull(); session.setNonce(DUMMY_NONCE); - assertThat(session.getNonce(), is(equalTo(DUMMY_NONCE))); + assertThat(session.getNonce()).isEqualTo(DUMMY_NONCE); - assertThat(session.getServerUri(), is(serverUri)); - assertThat(session.networkSettings(), is(notNullValue())); + assertThat(session.getServerUri()).isEqualTo(serverUri); + assertThat(session.networkSettings()).isNotNull(); - assertThat(session.getDirectoryExpires(), is(nullValue())); + assertThat(session.getDirectoryExpires()).isNull(); session.setDirectoryExpires(now); - assertThat(session.getDirectoryExpires(), is(equalTo(now))); + assertThat(session.getDirectoryExpires()).isEqualTo(now); session.setDirectoryExpires(null); - assertThat(session.getDirectoryExpires(), is(nullValue())); + assertThat(session.getDirectoryExpires()).isNull(); - assertThat(session.getDirectoryLastModified(), is(nullValue())); + assertThat(session.getDirectoryLastModified()).isNull(); session.setDirectoryLastModified(now); - assertThat(session.getDirectoryLastModified(), is(equalTo(now))); + assertThat(session.getDirectoryLastModified()).isEqualTo(now); session.setDirectoryLastModified(null); - assertThat(session.getDirectoryLastModified(), is(nullValue())); + assertThat(session.getDirectoryLastModified()).isNull(); } /** @@ -110,10 +110,10 @@ public class SessionTest { Session session = new Session(serverUri); Login login = session.login(accountLocation, accountKeyPair); - assertThat(login, is(notNullValue())); - assertThat(login.getSession(), is(session)); - assertThat(login.getAccountLocation(), is(accountLocation)); - assertThat(login.getKeyPair(), is(accountKeyPair)); + assertThat(login).isNotNull(); + assertThat(login.getSession()).isEqualTo(session); + assertThat(login.getAccountLocation()).isEqualTo(accountLocation); + assertThat(login.getKeyPair()).isEqualTo(accountKeyPair); } /** @@ -137,32 +137,35 @@ public class SessionTest { }; // No directory has been fetched yet - assertThat(session.hasDirectory(), is(false)); + assertThat(session.hasDirectory()).isFalse(); - assertThat(session.resourceUrl(Resource.NEW_ACCOUNT), - is(new URL("https://example.com/acme/new-account"))); + assertThat(session.resourceUrl(Resource.NEW_ACCOUNT)) + .isEqualTo(new URL("https://example.com/acme/new-account")); // There is a local copy of the directory now - assertThat(session.hasDirectory(), is(true)); + assertThat(session.hasDirectory()).isTrue(); - assertThat(session.resourceUrl(Resource.NEW_AUTHZ), - is(new URL("https://example.com/acme/new-authz"))); - assertThat(session.resourceUrl(Resource.NEW_ORDER), - is(new URL("https://example.com/acme/new-order"))); + assertThat(session.resourceUrl(Resource.NEW_AUTHZ)) + .isEqualTo(new URL("https://example.com/acme/new-authz")); + assertThat(session.resourceUrl(Resource.NEW_ORDER)) + .isEqualTo(new URL("https://example.com/acme/new-order")); assertThrows(AcmeException.class, () -> session.resourceUrl(Resource.REVOKE_CERT)); Metadata meta = session.getMetadata(); - assertThat(meta, not(nullValue())); - assertThat(meta.getTermsOfService(), is(URI.create("https://example.com/acme/terms"))); - assertThat(meta.getWebsite(), is(url("https://www.example.com/"))); - assertThat(meta.getCaaIdentities(), containsInAnyOrder("example.com")); - assertThat(meta.isAutoRenewalEnabled(), is(true)); - assertThat(meta.getAutoRenewalMaxDuration(), is(Duration.ofDays(365))); - assertThat(meta.getAutoRenewalMinLifetime(), is(Duration.ofHours(24))); - assertThat(meta.isAutoRenewalGetAllowed(), is(true)); - assertThat(meta.isExternalAccountRequired(), is(true)); - assertThat(meta.getJSON(), is(notNullValue())); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(meta).isNotNull(); + softly.assertThat(meta.getTermsOfService()) + .isEqualTo(URI.create("https://example.com/acme/terms")); + softly.assertThat(meta.getWebsite()).isEqualTo(url("https://www.example.com/")); + softly.assertThat(meta.getCaaIdentities()).containsExactlyInAnyOrder("example.com"); + softly.assertThat(meta.isAutoRenewalEnabled()).isTrue(); + softly.assertThat(meta.getAutoRenewalMaxDuration()).isEqualTo(Duration.ofDays(365)); + softly.assertThat(meta.getAutoRenewalMinLifetime()).isEqualTo(Duration.ofHours(24)); + softly.assertThat(meta.isAutoRenewalGetAllowed()).isTrue(); + softly.assertThat(meta.isExternalAccountRequired()).isTrue(); + softly.assertThat(meta.getJSON()).isNotNull(); + } // Make sure directory is read verify(mockProvider, atLeastOnce()).directory( @@ -190,22 +193,24 @@ public class SessionTest { } }; - assertThat(session.resourceUrl(Resource.NEW_ACCOUNT), - is(new URL("https://example.com/acme/new-account"))); - assertThat(session.resourceUrl(Resource.NEW_AUTHZ), - is(new URL("https://example.com/acme/new-authz"))); - assertThat(session.resourceUrl(Resource.NEW_ORDER), - is(new URL("https://example.com/acme/new-order"))); + assertThat(session.resourceUrl(Resource.NEW_ACCOUNT)) + .isEqualTo(new URL("https://example.com/acme/new-account")); + assertThat(session.resourceUrl(Resource.NEW_AUTHZ)) + .isEqualTo(new URL("https://example.com/acme/new-authz")); + assertThat(session.resourceUrl(Resource.NEW_ORDER)) + .isEqualTo(new URL("https://example.com/acme/new-order")); Metadata meta = session.getMetadata(); - assertThat(meta, not(nullValue())); - assertThat(meta.getTermsOfService(), is(nullValue())); - assertThat(meta.getWebsite(), is(nullValue())); - assertThat(meta.getCaaIdentities(), is(empty())); - assertThat(meta.isAutoRenewalEnabled(), is(false)); - assertThat(meta.getAutoRenewalMaxDuration(), is(nullValue())); - assertThat(meta.getAutoRenewalMinLifetime(), is(nullValue())); - assertThat(meta.isAutoRenewalGetAllowed(), is(false)); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(meta).isNotNull(); + softly.assertThat(meta.getTermsOfService()).isNull(); + softly.assertThat(meta.getWebsite()).isNull(); + softly.assertThat(meta.getCaaIdentities()).isEmpty(); + softly.assertThat(meta.isAutoRenewalEnabled()).isFalse(); + softly.assertThat(meta.getAutoRenewalMaxDuration()).isNull(); + softly.assertThat(meta.getAutoRenewalMinLifetime()).isNull(); + softly.assertThat(meta.isAutoRenewalGetAllowed()).isFalse(); + } } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/StatusTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/StatusTest.java index 8d6754dc..17d084b3 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/StatusTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/StatusTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; @@ -30,11 +29,11 @@ public class StatusTest { public void testParse() { for (Status s : Status.values()) { Status parsed = Status.parse(s.name().toLowerCase()); - assertThat(parsed, is(s)); + assertThat(parsed).isEqualTo(s); } // unknown status returns UNKNOWN - assertThat(Status.parse("foo"), is(Status.UNKNOWN)); + assertThat(Status.parse("foo")).isEqualTo(Status.UNKNOWN); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/ChallengeTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/ChallengeTest.java index 1e8a8628..5bed7216 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/ChallengeTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/ChallengeTest.java @@ -13,21 +13,21 @@ */ package org.shredzone.acme4j.challenge; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.shredzone.acme4j.toolbox.AcmeUtils.parseTimestamp; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; import static org.shredzone.acme4j.toolbox.TestUtils.url; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.time.Duration; import java.time.Instant; +import java.time.temporal.ChronoUnit; +import org.assertj.core.api.AutoCloseableSoftAssertions; import org.junit.jupiter.api.Test; import org.shredzone.acme4j.Login; import org.shredzone.acme4j.Problem; @@ -54,18 +54,20 @@ public class ChallengeTest { Challenge challenge = new Challenge(TestUtils.login(), getJSON("genericChallenge")); // Test unmarshalled values - assertThat(challenge.getType(), is("generic-01")); - assertThat(challenge.getStatus(), is(Status.INVALID)); - assertThat(challenge.getLocation(), is(url("http://example.com/challenge/123"))); - assertThat(challenge.getValidated(), is(parseTimestamp("2015-12-12T17:19:36.336785823Z"))); - assertThat(challenge.getJSON().get("type").asString(), is("generic-01")); - assertThat(challenge.getJSON().get("url").asURL(), is(url("http://example.com/challenge/123"))); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(challenge.getType()).isEqualTo("generic-01"); + softly.assertThat(challenge.getStatus()).isEqualTo(Status.INVALID); + softly.assertThat(challenge.getLocation()).isEqualTo(url("http://example.com/challenge/123")); + softly.assertThat(challenge.getValidated()).isCloseTo("2015-12-12T17:19:36.336Z", within(1, ChronoUnit.MILLIS)); + softly.assertThat(challenge.getJSON().get("type").asString()).isEqualTo("generic-01"); + softly.assertThat(challenge.getJSON().get("url").asURL()).isEqualTo(url("http://example.com/challenge/123")); - Problem error = challenge.getError(); - assertThat(error, is(notNullValue())); - assertThat(error.getType(), is(URI.create("urn:ietf:params:acme:error:incorrectResponse"))); - assertThat(error.getDetail(), is("bad token")); - assertThat(error.getInstance(), is(URI.create("http://example.com/documents/faq.html"))); + Problem error = challenge.getError(); + softly.assertThat(error).isNotNull(); + softly.assertThat(error.getType()).isEqualTo(URI.create("urn:ietf:params:acme:error:incorrectResponse")); + softly.assertThat(error.getDetail()).isEqualTo("bad token"); + softly.assertThat(error.getInstance()).isEqualTo(URI.create("http://example.com/documents/faq.html")); + } } /** @@ -78,7 +80,7 @@ public class ChallengeTest { JSONBuilder response = new JSONBuilder(); challenge.prepareResponse(response); - assertThat(response.toString(), sameJSONAs("{}")); + assertThatJson(response.toString()).isEqualTo("{}"); } /** @@ -99,9 +101,9 @@ public class ChallengeTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedRequest(URL url, JSONBuilder claims, Login login) { - assertThat(url, is(locationUrl)); - assertThat(claims.toString(), sameJSONAs(getJSON("triggerHttpChallengeRequest").toString())); - assertThat(login, is(notNullValue())); + assertThat(url).isEqualTo(locationUrl); + assertThatJson(claims.toString()).isEqualTo(getJSON("triggerHttpChallengeRequest").toString()); + assertThat(login).isNotNull(); return HttpURLConnection.HTTP_OK; } @@ -117,8 +119,8 @@ public class ChallengeTest { challenge.trigger(); - assertThat(challenge.getStatus(), is(Status.PENDING)); - assertThat(challenge.getLocation(), is(locationUrl)); + assertThat(challenge.getStatus()).isEqualTo(Status.PENDING); + assertThat(challenge.getLocation()).isEqualTo(locationUrl); provider.close(); } @@ -131,7 +133,7 @@ public class ChallengeTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -152,8 +154,8 @@ public class ChallengeTest { challenge.update(); - assertThat(challenge.getStatus(), is(Status.VALID)); - assertThat(challenge.getLocation(), is(locationUrl)); + assertThat(challenge.getStatus()).isEqualTo(Status.VALID); + assertThat(challenge.getLocation()).isEqualTo(locationUrl); provider.close(); } @@ -168,7 +170,7 @@ public class ChallengeTest { TestableConnectionProvider provider = new TestableConnectionProvider() { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { - assertThat(url, is(locationUrl)); + assertThat(url).isEqualTo(locationUrl); return HttpURLConnection.HTTP_OK; } @@ -189,8 +191,8 @@ public class ChallengeTest { Challenge challenge = new Http01Challenge(login, getJSON("triggerHttpChallengeResponse")); assertThrows(AcmeRetryAfterException.class, challenge::update); - assertThat(challenge.getStatus(), is(Status.VALID)); - assertThat(challenge.getLocation(), is(locationUrl)); + assertThat(challenge.getStatus()).isEqualTo(Status.VALID); + assertThat(challenge.getLocation()).isEqualTo(locationUrl); provider.close(); } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/DnsChallengeTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/DnsChallengeTest.java index f02552e5..48ede64e 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/DnsChallengeTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/DnsChallengeTest.java @@ -13,10 +13,9 @@ */ package org.shredzone.acme4j.challenge; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import org.junit.jupiter.api.Test; import org.shredzone.acme4j.Login; @@ -38,15 +37,15 @@ public class DnsChallengeTest { public void testDnsChallenge() { Dns01Challenge challenge = new Dns01Challenge(login, getJSON("dnsChallenge")); - assertThat(challenge.getType(), is(Dns01Challenge.TYPE)); - assertThat(challenge.getStatus(), is(Status.PENDING)); - assertThat(challenge.getDigest(), is("rzMmotrIgsithyBYc0vgiLUEEKYx0WetQRgEF2JIozA")); - assertThat(challenge.getAuthorization(), is("pNvmJivs0WCko2suV7fhe-59oFqyYx_yB7tx6kIMAyE.HnWjTDnyqlCrm6tZ-6wX-TrEXgRdeNu9G71gqxSO6o0")); + assertThat(challenge.getType()).isEqualTo(Dns01Challenge.TYPE); + assertThat(challenge.getStatus()).isEqualTo(Status.PENDING); + assertThat(challenge.getDigest()).isEqualTo("rzMmotrIgsithyBYc0vgiLUEEKYx0WetQRgEF2JIozA"); + assertThat(challenge.getAuthorization()).isEqualTo("pNvmJivs0WCko2suV7fhe-59oFqyYx_yB7tx6kIMAyE.HnWjTDnyqlCrm6tZ-6wX-TrEXgRdeNu9G71gqxSO6o0"); JSONBuilder response = new JSONBuilder(); challenge.prepareResponse(response); - assertThat(response.toString(), sameJSONAs("{}").allowingExtraUnexpectedFields()); + assertThatJson(response.toString()).isEqualTo("{}"); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/HttpChallengeTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/HttpChallengeTest.java index 1d82170f..6f1dc909 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/HttpChallengeTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/HttpChallengeTest.java @@ -13,11 +13,10 @@ */ package org.shredzone.acme4j.challenge; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import org.junit.jupiter.api.Test; import org.shredzone.acme4j.Login; @@ -44,15 +43,15 @@ public class HttpChallengeTest { public void testHttpChallenge() { Http01Challenge challenge = new Http01Challenge(login, getJSON("httpChallenge")); - assertThat(challenge.getType(), is(Http01Challenge.TYPE)); - assertThat(challenge.getStatus(), is(Status.PENDING)); - assertThat(challenge.getToken(), is(TOKEN)); - assertThat(challenge.getAuthorization(), is(KEY_AUTHORIZATION)); + assertThat(challenge.getType()).isEqualTo(Http01Challenge.TYPE); + assertThat(challenge.getStatus()).isEqualTo(Status.PENDING); + assertThat(challenge.getToken()).isEqualTo(TOKEN); + assertThat(challenge.getAuthorization()).isEqualTo(KEY_AUTHORIZATION); JSONBuilder response = new JSONBuilder(); challenge.prepareResponse(response); - assertThat(response.toString(), sameJSONAs("{}").allowingExtraUnexpectedFields()); + assertThatJson(response.toString()).isEqualTo("{}"); } /** diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/TlsAlpn01ChallengeTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/TlsAlpn01ChallengeTest.java index 845aa273..820676d9 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/TlsAlpn01ChallengeTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/challenge/TlsAlpn01ChallengeTest.java @@ -13,10 +13,9 @@ */ package org.shredzone.acme4j.challenge; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import org.junit.jupiter.api.Test; import org.shredzone.acme4j.Login; @@ -43,16 +42,16 @@ public class TlsAlpn01ChallengeTest { public void testTlsAlpn01Challenge() { TlsAlpn01Challenge challenge = new TlsAlpn01Challenge(login, getJSON("tlsAlpnChallenge")); - assertThat(challenge.getType(), is(TlsAlpn01Challenge.TYPE)); - assertThat(challenge.getStatus(), is(Status.PENDING)); - assertThat(challenge.getToken(), is(TOKEN)); - assertThat(challenge.getAuthorization(), is(KEY_AUTHORIZATION)); - assertThat(challenge.getAcmeValidation(), is(AcmeUtils.sha256hash(KEY_AUTHORIZATION))); + assertThat(challenge.getType()).isEqualTo(TlsAlpn01Challenge.TYPE); + assertThat(challenge.getStatus()).isEqualTo(Status.PENDING); + assertThat(challenge.getToken()).isEqualTo(TOKEN); + assertThat(challenge.getAuthorization()).isEqualTo(KEY_AUTHORIZATION); + assertThat(challenge.getAcmeValidation()).isEqualTo(AcmeUtils.sha256hash(KEY_AUTHORIZATION)); JSONBuilder response = new JSONBuilder(); challenge.prepareResponse(response); - assertThat(response.toString(), sameJSONAs("{}").allowingExtraUnexpectedFields()); + assertThatJson(response.toString()).isEqualTo("{}"); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/DefaultConnectionTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/DefaultConnectionTest.java index 7c435651..c7f5e19b 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/DefaultConnectionTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/DefaultConnectionTest.java @@ -16,14 +16,11 @@ package org.shredzone.acme4j.connector; import static java.nio.charset.StandardCharsets.UTF_8; import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME; import static java.util.Collections.singletonList; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.fail; -import static org.mockito.Mockito.any; import static org.mockito.Mockito.*; import static org.shredzone.acme4j.toolbox.TestUtils.url; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -114,10 +111,10 @@ public class DefaultConnectionTest { public void testNoNonceFromHeader() { when(mockUrlConnection.getHeaderField("Replay-Nonce")).thenReturn(null); - assertThat(session.getNonce(), is(nullValue())); + assertThat(session.getNonce()).isNull(); try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getNonce(), is(nullValue())); + assertThat(conn.getNonce()).isNull(); } verify(mockUrlConnection).getHeaderField("Replay-Nonce"); @@ -135,7 +132,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getNonce(), is(TestUtils.DUMMY_NONCE)); + assertThat(conn.getNonce()).isEqualTo(TestUtils.DUMMY_NONCE); } verify(mockUrlConnection).getHeaderField("Replay-Nonce"); @@ -158,7 +155,7 @@ public class DefaultConnectionTest { conn.getNonce(); } }); - assertThat(ex.getMessage(), org.hamcrest.Matchers.startsWith("Invalid replay nonce")); + assertThat(ex.getMessage()).startsWith("Invalid replay nonce"); verify(mockUrlConnection).getHeaderField("Replay-Nonce"); verifyNoMoreInteractions(mockUrlConnection); @@ -175,7 +172,7 @@ public class DefaultConnectionTest { when(mockUrlConnection.getResponseCode()) .thenReturn(HttpURLConnection.HTTP_NO_CONTENT); - assertThat(session.getNonce(), is(nullValue())); + assertThat(session.getNonce()).isNull(); assertThrows(AcmeProtocolException.class, () -> { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { @@ -183,7 +180,7 @@ public class DefaultConnectionTest { } }); - assertThat(session.getNonce(), is(nullValue())); + assertThat(session.getNonce()).isNull(); when(mockUrlConnection.getHeaderField("Replay-Nonce")) .thenReturn(TestUtils.DUMMY_NONCE); @@ -192,7 +189,7 @@ public class DefaultConnectionTest { conn.resetNonce(session); } - assertThat(session.getNonce(), is(TestUtils.DUMMY_NONCE)); + assertThat(session.getNonce()).isEqualTo(TestUtils.DUMMY_NONCE); verify(mockUrlConnection, atLeastOnce()).setRequestMethod("HEAD"); verify(mockUrlConnection, atLeastOnce()).setRequestProperty("Accept-Language", "ja-JP"); @@ -214,7 +211,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; URL location = conn.getLocation(); - assertThat(location, is(new URL("https://example.com/otherlocation"))); + assertThat(location).isEqualTo(new URL("https://example.com/otherlocation")); } verify(mockUrlConnection).getHeaderField("Location"); @@ -233,7 +230,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; URL location = conn.getLocation(); - assertThat(location, is(new URL("https://example.org/otherlocation"))); + assertThat(location).isEqualTo(new URL("https://example.org/otherlocation")); } verify(mockUrlConnection).getHeaderField("Location"); @@ -260,10 +257,10 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getLinks("next"), containsInAnyOrder(new URL("https://example.com/acme/new-authz"))); - assertThat(conn.getLinks("recover"), containsInAnyOrder(new URL("https://example.org/recover-acct"))); - assertThat(conn.getLinks("terms-of-service"), containsInAnyOrder(new URL("https://example.com/acme/terms"))); - assertThat(conn.getLinks("secret-stuff"), is(empty())); + assertThat(conn.getLinks("next")).containsExactly(new URL("https://example.com/acme/new-authz")); + assertThat(conn.getLinks("recover")).containsExactly(new URL("https://example.org/recover-acct")); + assertThat(conn.getLinks("terms-of-service")).containsExactly(new URL("https://example.com/acme/terms")); + assertThat(conn.getLinks("secret-stuff")).isEmpty(); } } @@ -286,11 +283,11 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getLinks("terms-of-service"), containsInAnyOrder( + assertThat(conn.getLinks("terms-of-service")).containsExactlyInAnyOrder( url("https://example.com/acme/terms1"), url("https://example.com/acme/terms2"), url("https://example.com/acme/terms3") - )); + ); } } @@ -304,7 +301,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getLinks("something"), is(empty())); + assertThat(conn.getLinks("something")).isEmpty(); } } @@ -316,7 +313,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; URL location = conn.getLocation(); - assertThat(location, is(nullValue())); + assertThat(location).isNull(); } verify(mockUrlConnection).getHeaderField("Location"); @@ -341,8 +338,8 @@ public class DefaultConnectionTest { conn.handleRetryAfter(retryMsg); } }); - assertThat(ex.getRetryAfter(), is(retryDate)); - assertThat(ex.getMessage(), is(retryMsg)); + assertThat(ex.getRetryAfter()).isEqualTo(retryDate); + assertThat(ex.getMessage()).isEqualTo(retryMsg); verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); } @@ -371,8 +368,8 @@ public class DefaultConnectionTest { conn.handleRetryAfter(retryMsg); } }); - assertThat(ex.getRetryAfter(), is(Instant.ofEpochMilli(now).plusSeconds(delta))); - assertThat(ex.getMessage(), is(retryMsg)); + assertThat(ex.getRetryAfter()).isEqualTo(Instant.ofEpochMilli(now).plusSeconds(delta)); + assertThat(ex.getMessage()).isEqualTo(retryMsg); verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); } @@ -420,7 +417,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { int rc = conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); - assertThat(rc, is(HttpURLConnection.HTTP_OK)); + assertThat(rc).isEqualTo(HttpURLConnection.HTTP_OK); } verify(mockUrlConnection).getResponseCode(); @@ -447,10 +444,10 @@ public class DefaultConnectionTest { conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); } }); - assertThat(ex, instanceOf(AcmeUnauthorizedException.class)); - assertThat(((AcmeUnauthorizedException) ex).getType(), - is(URI.create("urn:ietf:params:acme:error:unauthorized"))); - assertThat(ex.getMessage(), is("Invalid response: 404")); + assertThat(ex).isInstanceOf(AcmeUnauthorizedException.class); + assertThat(((AcmeUnauthorizedException) ex).getType()) + .isEqualTo(URI.create("urn:ietf:params:acme:error:unauthorized")); + assertThat(ex.getMessage()).isEqualTo("Invalid response: 404"); verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); verify(mockUrlConnection, atLeastOnce()).getResponseCode(); @@ -484,12 +481,12 @@ public class DefaultConnectionTest { conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); } }); - assertThat(ex, instanceOf(AcmeUserActionRequiredException.class)); - assertThat(((AcmeUserActionRequiredException) ex).getType(), - is(URI.create("urn:ietf:params:acme:error:userActionRequired"))); - assertThat(ex.getMessage(), is("Accept the TOS")); - assertThat(((AcmeUserActionRequiredException) ex).getTermsOfServiceUri(), - is(URI.create("https://example.com/tos.pdf"))); + assertThat(ex).isInstanceOf(AcmeUserActionRequiredException.class); + assertThat(((AcmeUserActionRequiredException) ex).getType()) + .isEqualTo(URI.create("urn:ietf:params:acme:error:userActionRequired")); + assertThat(ex.getMessage()).isEqualTo("Accept the TOS"); + assertThat(((AcmeUserActionRequiredException) ex).getTermsOfServiceUri()) + .isEqualTo(URI.create("https://example.com/tos.pdf")); verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); verify(mockUrlConnection, atLeastOnce()).getHeaderFields(); @@ -528,14 +525,14 @@ public class DefaultConnectionTest { conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); } }); - assertThat(ex, instanceOf(AcmeRateLimitedException.class)); + assertThat(ex).isInstanceOf(AcmeRateLimitedException.class); AcmeRateLimitedException arlex = (AcmeRateLimitedException) ex; - assertThat(arlex.getType(), is(URI.create("urn:ietf:params:acme:error:rateLimited"))); - assertThat(ex.getMessage(), is("Too many invocations")); - assertThat(arlex.getRetryAfter(), is(retryAfter)); - assertThat(arlex.getDocuments(), is(notNullValue())); - assertThat(arlex.getDocuments().size(), is(1)); - assertThat(arlex.getDocuments().iterator().next(), is(url("https://example.com/rates.pdf"))); + assertThat(arlex.getType()).isEqualTo(URI.create("urn:ietf:params:acme:error:rateLimited")); + assertThat(ex.getMessage()).isEqualTo("Too many invocations"); + assertThat(arlex.getRetryAfter()).isEqualTo(retryAfter); + assertThat(arlex.getDocuments()).isNotNull(); + assertThat(arlex.getDocuments()).hasSize(1); + assertThat(arlex.getDocuments().iterator().next()).isEqualTo(url("https://example.com/rates.pdf")); verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); @@ -576,10 +573,10 @@ public class DefaultConnectionTest { conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); } }); - assertThat(ex, instanceOf(AcmeServerException.class)); - assertThat(((AcmeServerException) ex).getType(), - is(URI.create("urn:zombie:error:apocalypse"))); - assertThat(ex.getMessage(), is("Zombie apocalypse in progress")); + assertThat(ex).isInstanceOf(AcmeServerException.class); + assertThat(((AcmeServerException) ex).getType()) + .isEqualTo(URI.create("urn:zombie:error:apocalypse")); + assertThat(ex.getMessage()).isEqualTo("Zombie apocalypse in progress"); verify(mockUrlConnection).getHeaderField("Content-Type"); verify(mockUrlConnection, atLeastOnce()).getResponseCode(); @@ -612,7 +609,7 @@ public class DefaultConnectionTest { conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); } }); - assertThat(ex.getMessage(), not(emptyOrNullString())); + assertThat(ex.getMessage()).isNotEmpty(); verify(mockUrlConnection).getHeaderField("Content-Type"); verify(mockUrlConnection, atLeastOnce()).getResponseCode(); @@ -640,7 +637,7 @@ public class DefaultConnectionTest { conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); } }); - assertThat(ex.getMessage(), is("HTTP 500: Infernal Server Error")); + assertThat(ex.getMessage()).isEqualTo("HTTP 500: Infernal Server Error"); verify(mockUrlConnection).getHeaderField("Content-Type"); verify(mockUrlConnection, atLeastOnce()).getResponseCode(); @@ -690,7 +687,7 @@ public class DefaultConnectionTest { } }) { int rc = conn.sendRequest(requestUrl, session, ifModifiedSince); - assertThat(rc, is(HttpURLConnection.HTTP_NOT_MODIFIED)); + assertThat(rc).isEqualTo(HttpURLConnection.HTTP_NOT_MODIFIED); } verify(mockUrlConnection).setRequestMethod("GET"); @@ -720,15 +717,15 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { @Override public void resetNonce(Session session) { - assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); - assertThat(session.getNonce(), nullValue()); + assertThat(session).isSameAs(DefaultConnectionTest.this.session); + assertThat(session.getNonce()).isNull(); session.setNonce(nonce1); } @Override public String getNonce() { - assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); - assertThat(session.getNonce(), is(nonce1)); + assertThat(session).isSameAs(DefaultConnectionTest.this.session); + assertThat(session.getNonce()).isEqualTo(nonce1); return nonce2; } }) { @@ -763,14 +760,14 @@ public class DefaultConnectionTest { expectedHeader.append("\"kid\":\"").append(accountUrl).append('"'); expectedHeader.append('}'); - assertThat(new String(URL_DECODER.decode(encodedHeader), UTF_8), sameJSONAs(expectedHeader.toString())); - assertThat(new String(URL_DECODER.decode(encodedPayload), UTF_8), sameJSONAs("{\"foo\":123,\"bar\":\"a-string\"}")); - assertThat(encodedSignature, not(emptyOrNullString())); + assertThatJson(new String(URL_DECODER.decode(encodedHeader), UTF_8)).isEqualTo(expectedHeader.toString()); + assertThatJson(new String(URL_DECODER.decode(encodedPayload), UTF_8)).isEqualTo("{\"foo\":123,\"bar\":\"a-string\"}"); + assertThat(encodedSignature).isNotEmpty(); JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); jws.setKey(login.getKeyPair().getPublic()); - assertThat(jws.verifySignature(), is(true)); + assertThat(jws.verifySignature()).isTrue(); } /** @@ -788,15 +785,15 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { @Override public void resetNonce(Session session) { - assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); - assertThat(session.getNonce(), nullValue()); + assertThat(session).isSameAs(DefaultConnectionTest.this.session); + assertThat(session.getNonce()).isNull(); session.setNonce(nonce1); } @Override public String getNonce() { - assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); - assertThat(session.getNonce(), is(nonce1)); + assertThat(session).isSameAs(DefaultConnectionTest.this.session); + assertThat(session.getNonce()).isEqualTo(nonce1); return nonce2; } }) { @@ -829,14 +826,14 @@ public class DefaultConnectionTest { expectedHeader.append("\"kid\":\"").append(accountUrl).append('"'); expectedHeader.append('}'); - assertThat(new String(URL_DECODER.decode(encodedHeader), UTF_8), sameJSONAs(expectedHeader.toString())); - assertThat(new String(URL_DECODER.decode(encodedPayload), UTF_8), is("")); - assertThat(encodedSignature, not(emptyOrNullString())); + assertThatJson(new String(URL_DECODER.decode(encodedHeader), UTF_8)).isEqualTo(expectedHeader.toString()); + assertThat(new String(URL_DECODER.decode(encodedPayload), UTF_8)).isEqualTo(""); + assertThat(encodedSignature).isNotEmpty(); JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); jws.setKey(login.getKeyPair().getPublic()); - assertThat(jws.verifySignature(), is(true)); + assertThat(jws.verifySignature()).isTrue(); } /** @@ -854,15 +851,15 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { @Override public void resetNonce(Session session) { - assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); - assertThat(session.getNonce(), nullValue()); + assertThat(session).isSameAs(DefaultConnectionTest.this.session); + assertThat(session.getNonce()).isNull(); session.setNonce(nonce1); } @Override public String getNonce() { - assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); - assertThat(session.getNonce(), is(nonce1)); + assertThat(session).isSameAs(DefaultConnectionTest.this.session); + assertThat(session.getNonce()).isEqualTo(nonce1); return nonce2; } }) { @@ -898,15 +895,15 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { @Override public void resetNonce(Session session) { - assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); - assertThat(session.getNonce(), nullValue()); + assertThat(session).isSameAs(DefaultConnectionTest.this.session); + assertThat(session.getNonce()).isNull(); session.setNonce(nonce1); } @Override public String getNonce() { - assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); - assertThat(session.getNonce(), is(nonce1)); + assertThat(session).isSameAs(DefaultConnectionTest.this.session); + assertThat(session.getNonce()).isEqualTo(nonce1); return nonce2; } }) { @@ -944,14 +941,16 @@ public class DefaultConnectionTest { expectedHeader.append("\"n\":\"").append(TestUtils.N).append("\""); expectedHeader.append("}}"); - assertThat(new String(URL_DECODER.decode(encodedHeader), UTF_8), sameJSONAs(expectedHeader.toString())); - assertThat(new String(URL_DECODER.decode(encodedPayload), UTF_8), sameJSONAs("{\"foo\":123,\"bar\":\"a-string\"}")); - assertThat(encodedSignature, not(emptyOrNullString())); + assertThatJson(new String(URL_DECODER.decode(encodedHeader), UTF_8)) + .isEqualTo(expectedHeader.toString()); + assertThatJson(new String(URL_DECODER.decode(encodedPayload), UTF_8)) + .isEqualTo("{\"foo\":123,\"bar\":\"a-string\"}"); + assertThat(encodedSignature).isNotEmpty(); JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); jws.setKey(login.getKeyPair().getPublic()); - assertThat(jws.verifySignature(), is(true)); + assertThat(jws.verifySignature()).isTrue(); } /** @@ -987,10 +986,10 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; JSON result = conn.readJsonResponse(); - assertThat(result, is(notNullValue())); - assertThat(result.keySet(), hasSize(2)); - assertThat(result.get("foo").asInt(), is(123)); - assertThat(result.get("bar").asString(), is("a-string")); + assertThat(result).isNotNull(); + assertThat(result.keySet()).hasSize(2); + assertThat(result.get("foo").asInt()).isEqualTo(123); + assertThat(result.get("bar").asString()).isEqualTo("a-string"); } verify(mockUrlConnection).getHeaderField("Content-Type"); @@ -1015,12 +1014,12 @@ public class DefaultConnectionTest { } List original = TestUtils.createCertificate(); - assertThat(original.size(), is(2)); + assertThat(original).hasSize(2); - assertThat(downloaded, not(nullValue())); - assertThat(downloaded.size(), is(original.size())); + assertThat(downloaded).isNotNull(); + assertThat(downloaded).hasSize(original.size()); for (int ix = 0; ix < downloaded.size(); ix++) { - assertThat(downloaded.get(ix).getEncoded(), is(original.get(ix).getEncoded())); + assertThat(downloaded.get(ix).getEncoded()).isEqualTo(original.get(ix).getEncoded()); } verify(mockUrlConnection).getHeaderField("Content-Type"); @@ -1066,7 +1065,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getLastModified().isPresent(), is(false)); + assertThat(conn.getLastModified().isPresent()).isFalse(); } verify(mockUrlConnection).getHeaderField("Last-Modified"); @@ -1080,9 +1079,9 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; Optional lm = conn.getLastModified(); - assertThat(lm.isPresent(), is(true)); - assertThat(lm.get().format(DateTimeFormatter.ISO_DATE_TIME), - is("2020-05-07T19:42:46Z")); + assertThat(lm.isPresent()).isTrue(); + assertThat(lm.get().format(DateTimeFormatter.ISO_DATE_TIME)) + .isEqualTo("2020-05-07T19:42:46Z"); } verify(mockUrlConnection).getHeaderField("Last-Modified"); @@ -1095,7 +1094,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getLastModified().isPresent(), is(false)); + assertThat(conn.getLastModified().isPresent()).isFalse(); } verify(mockUrlConnection).getHeaderField("Last-Modified"); @@ -1112,7 +1111,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getExpiration().isPresent(), is(false)); + assertThat(conn.getExpiration().isPresent()).isFalse(); } verify(mockUrlConnection).getHeaderField("Cache-Control"); @@ -1127,7 +1126,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getExpiration().isPresent(), is(false)); + assertThat(conn.getExpiration().isPresent()).isFalse(); } verify(mockUrlConnection).getHeaderField("Cache-Control"); @@ -1141,7 +1140,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getExpiration().isPresent(), is(false)); + assertThat(conn.getExpiration().isPresent()).isFalse(); } verify(mockUrlConnection).getHeaderField("Cache-Control"); @@ -1155,7 +1154,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getExpiration().isPresent(), is(false)); + assertThat(conn.getExpiration().isPresent()).isFalse(); } verify(mockUrlConnection).getHeaderField("Cache-Control"); @@ -1170,9 +1169,9 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; Optional exp = conn.getExpiration(); - assertThat(exp.isPresent(), is(true)); - assertThat(exp.get().isAfter(ZonedDateTime.now().plusHours(1).minusMinutes(1)), is(true)); - assertThat(exp.get().isBefore(ZonedDateTime.now().plusHours(1).plusMinutes(1)), is(true)); + assertThat(exp.isPresent()).isTrue(); + assertThat(exp.get().isAfter(ZonedDateTime.now().plusHours(1).minusMinutes(1))).isTrue(); + assertThat(exp.get().isBefore(ZonedDateTime.now().plusHours(1).plusMinutes(1))).isTrue(); } verify(mockUrlConnection).getHeaderField("Cache-Control"); @@ -1187,9 +1186,9 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; Optional exp = conn.getExpiration(); - assertThat(exp.isPresent(), is(true)); - assertThat(exp.get().format(DateTimeFormatter.ISO_DATE_TIME), - is("2020-06-18T08:43:04Z")); + assertThat(exp.isPresent()).isTrue(); + assertThat(exp.get().format(DateTimeFormatter.ISO_DATE_TIME)) + .isEqualTo("2020-06-18T08:43:04Z"); } verify(mockUrlConnection).getHeaderField("Cache-Control"); @@ -1204,7 +1203,7 @@ public class DefaultConnectionTest { try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { conn.conn = mockUrlConnection; - assertThat(conn.getExpiration().isPresent(), is(false)); + assertThat(conn.getExpiration().isPresent()).isFalse(); } verify(mockUrlConnection).getHeaderField("Cache-Control"); diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/HttpConnectorTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/HttpConnectorTest.java index 72ab8582..9da116f3 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/HttpConnectorTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/HttpConnectorTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.connector; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -64,9 +63,9 @@ public class HttpConnectorTest { NetworkSettings settings = new NetworkSettings(); HttpConnector connector = new HttpConnector(); HttpURLConnection conn = connector.openConnection(new URL("http://example.com"), settings); - assertThat(conn, not(nullValue())); + assertThat(conn).isNotNull(); conn.connect(); - assertThat(conn.getResponseCode(), is(HttpURLConnection.HTTP_OK)); + assertThat(conn.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK); } /** @@ -75,8 +74,8 @@ public class HttpConnectorTest { @Test public void testUserAgent() { String userAgent = HttpConnector.defaultUserAgent(); - assertThat(userAgent.contains("acme4j/"), is(true)); - assertThat(userAgent.contains("Java/"), is(true)); + assertThat(userAgent).contains("acme4j/"); + assertThat(userAgent).contains("Java/"); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/NetworkSettingsTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/NetworkSettingsTest.java index 19e738c1..3cc0234a 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/NetworkSettingsTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/NetworkSettingsTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.connector; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.InetSocketAddress; @@ -35,16 +34,16 @@ public class NetworkSettingsTest { public void testGettersAndSetters() { NetworkSettings settings = new NetworkSettings(); - assertThat(settings.getProxy(), is(Proxy.NO_PROXY)); + assertThat(settings.getProxy()).isEqualTo(Proxy.NO_PROXY); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080)); settings.setProxy(proxy); - assertThat(settings.getProxy(), is(proxy)); + assertThat(settings.getProxy()).isEqualTo(proxy); settings.setProxy(null); - assertThat(settings.getProxy(), is(Proxy.NO_PROXY)); + assertThat(settings.getProxy()).isEqualTo(Proxy.NO_PROXY); - assertThat(settings.getTimeout(), is(Duration.ofSeconds(10))); + assertThat(settings.getTimeout()).isEqualTo(Duration.ofSeconds(10)); settings.setTimeout(Duration.ofMillis(5120)); - assertThat(settings.getTimeout(), is(Duration.ofMillis(5120))); + assertThat(settings.getTimeout()).isEqualTo(Duration.ofMillis(5120)); } @Test diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/ResourceIteratorTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/ResourceIteratorTest.java index 0b7bc7e1..d31c3407 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/ResourceIteratorTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/ResourceIteratorTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.connector; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.shredzone.acme4j.toolbox.TestUtils.url; @@ -69,8 +68,8 @@ public class ResourceIteratorTest { assertThrows(NoSuchElementException.class, () -> { Iterator it = createIterator(null); - assertThat(it, not(nullValue())); - assertThat(it.hasNext(), is(false)); + assertThat(it).isNotNull(); + assertThat(it.hasNext()).isFalse(); it.next(); // throws NoSuchElementException }); } @@ -87,7 +86,7 @@ public class ResourceIteratorTest { result.add(it.next().getLocation()); } - assertThat(result, is(equalTo(resourceURLs))); + assertThat(result).isEqualTo(resourceURLs); } /** @@ -98,8 +97,8 @@ public class ResourceIteratorTest { List result = new ArrayList<>(); Iterator it = createIterator(pageURLs.get(0)); - assertThat(it.hasNext(), is(true)); - assertThat(it.hasNext(), is(true)); + assertThat(it.hasNext()).isTrue(); + assertThat(it.hasNext()).isTrue(); // don't try this at home, kids... try { @@ -107,11 +106,11 @@ public class ResourceIteratorTest { result.add(it.next().getLocation()); } } catch (NoSuchElementException ex) { - assertThat(it.hasNext(), is(false)); - assertThat(it.hasNext(), is(false)); + assertThat(it.hasNext()).isFalse(); + assertThat(it.hasNext()).isFalse(); } - assertThat(result, is(equalTo(resourceURLs))); + assertThat(result).isEqualTo(resourceURLs); } /** @@ -140,7 +139,7 @@ public class ResourceIteratorTest { @Override public int sendSignedPostAsGetRequest(URL url, Login login) { ix = pageURLs.indexOf(url); - assertThat(ix, is(greaterThanOrEqualTo(0))); + assertThat(ix).isGreaterThanOrEqualTo(0); return HttpURLConnection.HTTP_OK; } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/ResourceTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/ResourceTest.java index 6d49990f..8582b5a1 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/ResourceTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/ResourceTest.java @@ -13,9 +13,9 @@ */ package org.shredzone.acme4j.connector; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; +import org.assertj.core.api.SoftAssertions; import org.junit.jupiter.api.Test; /** @@ -28,15 +28,17 @@ public class ResourceTest { */ @Test public void testPath() { - assertThat(Resource.NEW_NONCE.path(), is("newNonce")); - assertThat(Resource.NEW_ACCOUNT.path(), is("newAccount")); - assertThat(Resource.NEW_ORDER.path(), is("newOrder")); - assertThat(Resource.NEW_AUTHZ.path(), is("newAuthz")); - assertThat(Resource.REVOKE_CERT.path(), is("revokeCert")); - assertThat(Resource.KEY_CHANGE.path(), is("keyChange")); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(Resource.NEW_NONCE.path()).isEqualTo("newNonce"); + softly.assertThat(Resource.NEW_ACCOUNT.path()).isEqualTo("newAccount"); + softly.assertThat(Resource.NEW_ORDER.path()).isEqualTo("newOrder"); + softly.assertThat(Resource.NEW_AUTHZ.path()).isEqualTo("newAuthz"); + softly.assertThat(Resource.REVOKE_CERT.path()).isEqualTo("revokeCert"); + softly.assertThat(Resource.KEY_CHANGE.path()).isEqualTo("keyChange"); + }); // fails if there are untested future Resource values - assertThat(Resource.values().length, is(6)); + assertThat(Resource.values()).hasSize(6); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/SessionProviderTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/SessionProviderTest.java index 3e216033..9cd5ed7d 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/SessionProviderTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/SessionProviderTest.java @@ -13,9 +13,8 @@ */ package org.shredzone.acme4j.connector; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.net.URI; import java.net.URL; @@ -41,9 +40,9 @@ public class SessionProviderTest { */ @Test public void testNone() throws Exception { - assertThrows(IllegalArgumentException.class, () -> - new Session(new URI("acme://example.org")).provider() - ); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new Session(new URI("acme://example.org")).provider()) + .withMessage("No ACME provider found for acme://example.org"); } /** @@ -55,11 +54,11 @@ public class SessionProviderTest { Session session = new Session(new URI("acme://example.com")); AcmeProvider provider = session.provider(); - assertThat(provider, is(instanceOf(Provider1.class))); + assertThat(provider).isInstanceOf(Provider1.class); AcmeProvider provider2 = session.provider(); - assertThat(provider2, is(instanceOf(Provider1.class))); - assertThat(provider2, is(sameInstance(provider))); + assertThat(provider2).isInstanceOf(Provider1.class); + assertThat(provider2).isSameAs(provider); } /** @@ -68,9 +67,10 @@ public class SessionProviderTest { */ @Test public void testDuplicate() throws Exception { - assertThrows(IllegalArgumentException.class, () -> - new Session(new URI("acme://example.net")).provider() - ); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new Session(new URI("acme://example.net")).provider()) + .withMessage("Both ACME providers Provider1 and Provider2 accept" + + " acme://example.net. Please check your classpath."); } public static class Provider1 implements AcmeProvider { diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/TrimmingInputStreamTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/TrimmingInputStreamTest.java index e21cc0e6..b6e49296 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/connector/TrimmingInputStreamTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/connector/TrimmingInputStreamTest.java @@ -13,9 +13,7 @@ */ package org.shredzone.acme4j.connector; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -40,50 +38,50 @@ public class TrimmingInputStreamTest { @Test public void testEmpty() throws IOException { String out = trimByStream(""); - assertThat(out, is("")); + assertThat(out).isEqualTo(""); } @Test public void testLineBreakOnly() throws IOException { String out1 = trimByStream("\n"); - assertThat(out1, is("")); + assertThat(out1).isEqualTo(""); String out2 = trimByStream("\r"); - assertThat(out2, is("")); + assertThat(out2).isEqualTo(""); String out3 = trimByStream("\r\n"); - assertThat(out2, is("")); + assertThat(out2).isEqualTo(""); } @Test public void testTrim() throws IOException { String out = trimByStream(FULL_TEXT); - assertThat(out, is(TRIMMED_TEXT)); + assertThat(out).isEqualTo(TRIMMED_TEXT); } @Test public void testTrimEndOnly() throws IOException { String out = trimByStream(FULL_TEXT + "\r\n\r\n"); - assertThat(out, is(TRIMMED_TEXT + "\n")); + assertThat(out).isEqualTo(TRIMMED_TEXT + "\n"); } @Test public void testTrimStartOnly() throws IOException { String out = trimByStream("\n\n" + FULL_TEXT); - assertThat(out, is(TRIMMED_TEXT)); + assertThat(out).isEqualTo(TRIMMED_TEXT); } @Test public void testTrimFull() throws IOException { String out = trimByStream("\n\n" + FULL_TEXT + "\r\n\r\n"); - assertThat(out, is(TRIMMED_TEXT + "\n")); + assertThat(out).isEqualTo(TRIMMED_TEXT + "\n"); } @Test public void testAvailable() throws IOException { try (TrimmingInputStream in = new TrimmingInputStream( new ByteArrayInputStream("Test".getBytes(StandardCharsets.US_ASCII)))) { - assertThat(in.available(), not(0)); + assertThat(in.available()).isNotEqualTo(0); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeExceptionTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeExceptionTest.java index b25f4d68..e6375e46 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeExceptionTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeExceptionTest.java @@ -13,9 +13,7 @@ */ package org.shredzone.acme4j.exception; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; @@ -29,16 +27,16 @@ public class AcmeExceptionTest { @Test public void testAcmeException() { AcmeException ex = new AcmeException(); - assertThat(ex.getMessage(), nullValue()); - assertThat(ex.getCause(), nullValue()); + assertThat(ex.getMessage()).isNull(); + assertThat(ex.getCause()).isNull(); } @Test public void testMessageAcmeException() { String message = "Failure"; AcmeException ex = new AcmeException(message); - assertThat(ex.getMessage(), is(message)); - assertThat(ex.getCause(), nullValue()); + assertThat(ex.getMessage()).isEqualTo(message); + assertThat(ex.getCause()).isNull(); } @Test @@ -47,8 +45,8 @@ public class AcmeExceptionTest { IOException cause = new IOException("No network"); AcmeException ex = new AcmeException(message, cause); - assertThat(ex.getMessage(), is(message)); - assertThat(ex.getCause(), is(cause)); + assertThat(ex.getMessage()).isEqualTo(message); + assertThat(ex.getCause()).isEqualTo(cause); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeLazyLoadingExceptionTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeLazyLoadingExceptionTest.java index 3862de22..3c0428bc 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeLazyLoadingExceptionTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeLazyLoadingExceptionTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.exception; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.net.URL; @@ -39,12 +38,12 @@ public class AcmeLazyLoadingExceptionTest { AcmeException cause = new AcmeException("Something went wrong"); AcmeLazyLoadingException ex = new AcmeLazyLoadingException(resource, cause); - assertThat(ex, is(instanceOf(RuntimeException.class))); - assertThat(ex.getMessage(), containsString(resourceUrl.toString())); - assertThat(ex.getMessage(), containsString(TestResource.class.getSimpleName())); - assertThat(ex.getCause(), is(cause)); - assertThat(ex.getType(), is(equalTo(TestResource.class))); - assertThat(ex.getLocation(), is(resourceUrl)); + assertThat(ex).isInstanceOf(RuntimeException.class); + assertThat(ex.getMessage()).contains(resourceUrl.toString()); + assertThat(ex.getMessage()).contains(TestResource.class.getSimpleName()); + assertThat(ex.getCause()).isEqualTo(cause); + assertThat(ex.getType()).isEqualTo(TestResource.class); + assertThat(ex.getLocation()).isEqualTo(resourceUrl); } private static class TestResource extends AcmeResource { diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeNetworkExceptionTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeNetworkExceptionTest.java index 8981747a..de087379 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeNetworkExceptionTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeNetworkExceptionTest.java @@ -13,9 +13,7 @@ */ package org.shredzone.acme4j.exception; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; @@ -32,8 +30,8 @@ public class AcmeNetworkExceptionTest { AcmeNetworkException ex = new AcmeNetworkException(cause); - assertThat(ex.getMessage(), notNullValue()); - assertThat(ex.getCause(), is(cause)); + assertThat(ex.getMessage()).isNotNull(); + assertThat(ex.getCause()).isEqualTo(cause); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeProtocolExceptionTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeProtocolExceptionTest.java index d812bdf8..c184cb78 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeProtocolExceptionTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeProtocolExceptionTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.exception; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; @@ -27,9 +26,9 @@ public class AcmeProtocolExceptionTest { public void testAcmeProtocolException() { String msg = "Bad content"; AcmeProtocolException ex = new AcmeProtocolException(msg); - assertThat(ex, is(instanceOf(RuntimeException.class))); - assertThat(ex.getMessage(), is(msg)); - assertThat(ex.getCause(), nullValue()); + assertThat(ex).isInstanceOf(RuntimeException.class); + assertThat(ex.getMessage()).isEqualTo(msg); + assertThat(ex.getCause()).isNull(); } @Test @@ -37,8 +36,8 @@ public class AcmeProtocolExceptionTest { String message = "Bad content"; NumberFormatException cause = new NumberFormatException("Not a number: abc"); AcmeProtocolException ex = new AcmeProtocolException(message, cause); - assertThat(ex.getMessage(), is(message)); - assertThat(ex.getCause(), is(cause)); + assertThat(ex.getMessage()).isEqualTo(message); + assertThat(ex.getCause()).isEqualTo(cause); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeRateLimitedExceptionTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeRateLimitedExceptionTest.java index c6ac7438..138e802a 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeRateLimitedExceptionTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeRateLimitedExceptionTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.exception; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.shredzone.acme4j.toolbox.TestUtils.createProblem; import static org.shredzone.acme4j.toolbox.TestUtils.url; @@ -50,10 +49,10 @@ public class AcmeRateLimitedExceptionTest { AcmeRateLimitedException ex = new AcmeRateLimitedException(problem, retryAfter, documents); - assertThat(ex.getType(), is(type)); - assertThat(ex.getMessage(), is(detail)); - assertThat(ex.getRetryAfter(), is(retryAfter)); - assertThat(ex.getDocuments(), containsInAnyOrder(documents.toArray())); + assertThat(ex.getType()).isEqualTo(type); + assertThat(ex.getMessage()).isEqualTo(detail); + assertThat(ex.getRetryAfter()).isEqualTo(retryAfter); + assertThat(ex.getDocuments()).containsAll(documents); } /** @@ -69,10 +68,10 @@ public class AcmeRateLimitedExceptionTest { AcmeRateLimitedException ex = new AcmeRateLimitedException(problem, null, null); - assertThat(ex.getType(), is(type)); - assertThat(ex.getMessage(), is(detail)); - assertThat(ex.getRetryAfter(), nullValue()); - assertThat(ex.getDocuments(), nullValue()); + assertThat(ex.getType()).isEqualTo(type); + assertThat(ex.getMessage()).isEqualTo(detail); + assertThat(ex.getRetryAfter()).isNull(); + assertThat(ex.getDocuments()).isNull(); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeRetryAfterExceptionTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeRetryAfterExceptionTest.java index 52bf702e..9dabc3ed 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeRetryAfterExceptionTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeRetryAfterExceptionTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.exception; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Duration; @@ -37,8 +36,8 @@ public class AcmeRetryAfterExceptionTest { AcmeRetryAfterException ex = new AcmeRetryAfterException(detail, retryAfter); - assertThat(ex.getMessage(), is(detail)); - assertThat(ex.getRetryAfter(), is(retryAfter)); + assertThat(ex.getMessage()).isEqualTo(detail); + assertThat(ex.getRetryAfter()).isEqualTo(retryAfter); } /** diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeUserActionRequiredExceptionTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeUserActionRequiredExceptionTest.java index fd737a0e..300f527c 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeUserActionRequiredExceptionTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/exception/AcmeUserActionRequiredExceptionTest.java @@ -13,9 +13,7 @@ */ package org.shredzone.acme4j.exception; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; +import static org.assertj.core.api.Assertions.assertThat; import static org.shredzone.acme4j.toolbox.TestUtils.createProblem; import java.net.MalformedURLException; @@ -45,10 +43,10 @@ public class AcmeUserActionRequiredExceptionTest { AcmeUserActionRequiredException ex = new AcmeUserActionRequiredException(problem, tosUri); - assertThat(ex.getType(), is(type)); - assertThat(ex.getMessage(), is(detail)); - assertThat(ex.getTermsOfServiceUri(), is(tosUri)); - assertThat(ex.getInstance(), is(instanceUrl)); + assertThat(ex.getType()).isEqualTo(type); + assertThat(ex.getMessage()).isEqualTo(detail); + assertThat(ex.getTermsOfServiceUri()).isEqualTo(tosUri); + assertThat(ex.getInstance()).isEqualTo(instanceUrl); } /** @@ -65,10 +63,10 @@ public class AcmeUserActionRequiredExceptionTest { AcmeUserActionRequiredException ex = new AcmeUserActionRequiredException(problem, null); - assertThat(ex.getType(), is(type)); - assertThat(ex.getMessage(), is(detail)); - assertThat(ex.getTermsOfServiceUri(), nullValue()); - assertThat(ex.getInstance(), is(instanceUrl)); + assertThat(ex.getType()).isEqualTo(type); + assertThat(ex.getMessage()).isEqualTo(detail); + assertThat(ex.getTermsOfServiceUri()).isNull(); + assertThat(ex.getInstance()).isEqualTo(instanceUrl); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/provider/AbstractAcmeProviderTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/provider/AbstractAcmeProviderTest.java index a3da9b8d..21816dda 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/provider/AbstractAcmeProviderTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/provider/AbstractAcmeProviderTest.java @@ -13,13 +13,11 @@ */ package org.shredzone.acme4j.provider; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.any; import static org.mockito.Mockito.*; import static org.shredzone.acme4j.toolbox.TestUtils.getJSON; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.io.IOException; import java.net.HttpURLConnection; @@ -71,9 +69,9 @@ public class AbstractAcmeProviderTest { }; Connection connection = provider.connect(SERVER_URI); - assertThat(connection, not(nullValue())); - assertThat(connection, instanceOf(DefaultConnection.class)); - assertThat(invoked.get(), is(true)); + assertThat(connection).isNotNull(); + assertThat(connection).isInstanceOf(DefaultConnection.class); + assertThat(invoked).isTrue(); } /** @@ -89,7 +87,7 @@ public class AbstractAcmeProviderTest { AbstractAcmeProvider provider = new TestAbstractAcmeProvider(connection); JSON map = provider.directory(session, SERVER_URI); - assertThat(map.toString(), sameJSONAs(TestUtils.getJSON("directory").toString())); + assertThatJson(map.toString()).isEqualTo(TestUtils.getJSON("directory").toString()); verify(connection).sendRequest(RESOLVED_URL, session, null); verify(connection).getNonce(); @@ -120,7 +118,7 @@ public class AbstractAcmeProviderTest { AbstractAcmeProvider provider = new TestAbstractAcmeProvider(connection); JSON map = provider.directory(session, SERVER_URI); - assertThat(map.toString(), sameJSONAs(TestUtils.getJSON("directory").toString())); + assertThatJson(map.toString()).isEqualTo(TestUtils.getJSON("directory").toString()); verify(session).setDirectoryLastModified(eq(lastModified)); verify(session).setDirectoryExpires(eq(expiryDate)); @@ -152,7 +150,7 @@ public class AbstractAcmeProviderTest { AbstractAcmeProvider provider = new TestAbstractAcmeProvider(); JSON map = provider.directory(session, SERVER_URI); - assertThat(map, is(nullValue())); + assertThat(map).isNull(); verify(session).getDirectoryExpires(); verifyNoMoreInteractions(session); @@ -179,7 +177,7 @@ public class AbstractAcmeProviderTest { AbstractAcmeProvider provider = new TestAbstractAcmeProvider(connection); JSON map = provider.directory(session, SERVER_URI); - assertThat(map.toString(), sameJSONAs(TestUtils.getJSON("directory").toString())); + assertThatJson(map.toString()).isEqualTo(TestUtils.getJSON("directory").toString()); verify(session).setDirectoryExpires(eq(expiryDate)); verify(session).setDirectoryLastModified(eq(null)); @@ -214,7 +212,7 @@ public class AbstractAcmeProviderTest { AbstractAcmeProvider provider = new TestAbstractAcmeProvider(connection); JSON map = provider.directory(session, SERVER_URI); - assertThat(map, is(nullValue())); + assertThat(map).isNull(); verify(session).getDirectoryExpires(); verify(session).getDirectoryLastModified(); @@ -254,27 +252,27 @@ public class AbstractAcmeProviderTest { AbstractAcmeProvider provider = new TestAbstractAcmeProvider(); Challenge c1 = provider.createChallenge(login, getJSON("httpChallenge")); - assertThat(c1, not(nullValue())); - assertThat(c1, instanceOf(Http01Challenge.class)); + assertThat(c1).isNotNull(); + assertThat(c1).isInstanceOf(Http01Challenge.class); Challenge c2 = provider.createChallenge(login, getJSON("httpChallenge")); - assertThat(c2, not(sameInstance(c1))); + assertThat(c2).isNotSameAs(c1); Challenge c3 = provider.createChallenge(login, getJSON("dnsChallenge")); - assertThat(c3, not(nullValue())); - assertThat(c3, instanceOf(Dns01Challenge.class)); + assertThat(c3).isNotNull(); + assertThat(c3).isInstanceOf(Dns01Challenge.class); Challenge c4 = provider.createChallenge(login, getJSON("tlsAlpnChallenge")); - assertThat(c4, not(nullValue())); - assertThat(c4, instanceOf(TlsAlpn01Challenge.class)); + assertThat(c4).isNotNull(); + assertThat(c4).isInstanceOf(TlsAlpn01Challenge.class); JSON json6 = new JSONBuilder() .put("type", "foobar-01") .put("url", "https://example.com/some/challenge") .toJSON(); Challenge c6 = provider.createChallenge(login, json6); - assertThat(c6, not(nullValue())); - assertThat(c6, instanceOf(Challenge.class)); + assertThat(c6).isNotNull(); + assertThat(c6).isInstanceOf(Challenge.class); JSON json7 = new JSONBuilder() .put("type", "foobar-01") @@ -282,8 +280,8 @@ public class AbstractAcmeProviderTest { .put("url", "https://example.com/some/challenge") .toJSON(); Challenge c7 = provider.createChallenge(login, json7); - assertThat(c7, not(nullValue())); - assertThat(c7, instanceOf(TokenChallenge.class)); + assertThat(c7).isNotNull(); + assertThat(c7).isInstanceOf(TokenChallenge.class); assertThrows(AcmeProtocolException.class, () -> { JSON json8 = new JSONBuilder() @@ -310,19 +308,19 @@ public class AbstractAcmeProviderTest { @Override public boolean accepts(URI serverUri) { - assertThat(serverUri, is(SERVER_URI)); + assertThat(serverUri).isEqualTo(SERVER_URI); return true; } @Override public URL resolve(URI serverUri) { - assertThat(serverUri, is(SERVER_URI)); + assertThat(serverUri).isEqualTo(SERVER_URI); return RESOLVED_URL; } @Override public Connection connect(URI serverUri) { - assertThat(serverUri, is(SERVER_URI)); + assertThat(serverUri).isEqualTo(SERVER_URI); return connection != null ? connection : super.connect(serverUri); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/provider/GenericAcmeProviderTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/provider/GenericAcmeProviderTest.java index e42825c8..a3b6e5d3 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/provider/GenericAcmeProviderTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/provider/GenericAcmeProviderTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.provider; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.net.URISyntaxException; @@ -36,9 +35,9 @@ public class GenericAcmeProviderTest { public void testAccepts() throws URISyntaxException { GenericAcmeProvider provider = new GenericAcmeProvider(); - assertThat(provider.accepts(new URI("http://example.com/acme")), is(true)); - assertThat(provider.accepts(new URI("https://example.com/acme")), is(true)); - assertThat(provider.accepts(new URI("acme://example.com")), is(false)); + assertThat(provider.accepts(new URI("http://example.com/acme"))).isTrue(); + assertThat(provider.accepts(new URI("https://example.com/acme"))).isTrue(); + assertThat(provider.accepts(new URI("acme://example.com"))).isFalse(); } /** @@ -51,10 +50,10 @@ public class GenericAcmeProviderTest { GenericAcmeProvider provider = new GenericAcmeProvider(); URL resolvedUrl = provider.resolve(serverUri); - assertThat(resolvedUrl.toString(), is(equalTo(serverUri.toString()))); + assertThat(resolvedUrl.toString()).isEqualTo(serverUri.toString()); Connection connection = provider.connect(serverUri); - assertThat(connection, is(instanceOf(DefaultConnection.class))); + assertThat(connection).isInstanceOf(DefaultConnection.class); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/provider/letsencrypt/LetsEncryptAcmeProviderTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/provider/letsencrypt/LetsEncryptAcmeProviderTest.java index c92d6ed6..e81f8629 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/provider/letsencrypt/LetsEncryptAcmeProviderTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/provider/letsencrypt/LetsEncryptAcmeProviderTest.java @@ -13,14 +13,14 @@ */ package org.shredzone.acme4j.provider.letsencrypt; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.shredzone.acme4j.toolbox.TestUtils.url; import java.net.URI; import java.net.URISyntaxException; +import org.assertj.core.api.AutoCloseableSoftAssertions; import org.junit.jupiter.api.Test; /** @@ -38,13 +38,15 @@ public class LetsEncryptAcmeProviderTest { public void testAccepts() throws URISyntaxException { LetsEncryptAcmeProvider provider = new LetsEncryptAcmeProvider(); - assertThat(provider.accepts(new URI("acme://letsencrypt.org")), is(true)); - assertThat(provider.accepts(new URI("acme://letsencrypt.org/")), is(true)); - assertThat(provider.accepts(new URI("acme://letsencrypt.org/staging")), is(true)); - assertThat(provider.accepts(new URI("acme://letsencrypt.org/v02")), is(true)); - assertThat(provider.accepts(new URI("acme://example.com")), is(false)); - assertThat(provider.accepts(new URI("http://example.com/acme")), is(false)); - assertThat(provider.accepts(new URI("https://example.com/acme")), is(false)); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(provider.accepts(new URI("acme://letsencrypt.org"))).isTrue(); + softly.assertThat(provider.accepts(new URI("acme://letsencrypt.org/"))).isTrue(); + softly.assertThat(provider.accepts(new URI("acme://letsencrypt.org/staging"))).isTrue(); + softly.assertThat(provider.accepts(new URI("acme://letsencrypt.org/v02"))).isTrue(); + softly.assertThat(provider.accepts(new URI("acme://example.com"))).isFalse(); + softly.assertThat(provider.accepts(new URI("http://example.com/acme"))).isFalse(); + softly.assertThat(provider.accepts(new URI("https://example.com/acme"))).isFalse(); + } } /** @@ -54,10 +56,10 @@ public class LetsEncryptAcmeProviderTest { public void testResolve() throws URISyntaxException { LetsEncryptAcmeProvider provider = new LetsEncryptAcmeProvider(); - assertThat(provider.resolve(new URI("acme://letsencrypt.org")), is(url(V02_DIRECTORY_URL))); - assertThat(provider.resolve(new URI("acme://letsencrypt.org/")), is(url(V02_DIRECTORY_URL))); - assertThat(provider.resolve(new URI("acme://letsencrypt.org/v02")), is(url(V02_DIRECTORY_URL))); - assertThat(provider.resolve(new URI("acme://letsencrypt.org/staging")), is(url(STAGING_DIRECTORY_URL))); + assertThat(provider.resolve(new URI("acme://letsencrypt.org"))).isEqualTo(url(V02_DIRECTORY_URL)); + assertThat(provider.resolve(new URI("acme://letsencrypt.org/"))).isEqualTo(url(V02_DIRECTORY_URL)); + assertThat(provider.resolve(new URI("acme://letsencrypt.org/v02"))).isEqualTo(url(V02_DIRECTORY_URL)); + assertThat(provider.resolve(new URI("acme://letsencrypt.org/staging"))).isEqualTo(url(STAGING_DIRECTORY_URL)); assertThrows(IllegalArgumentException.class, () -> { provider.resolve(new URI("acme://letsencrypt.org/v99")); diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/provider/pebble/PebbleAcmeProviderTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/provider/pebble/PebbleAcmeProviderTest.java index 49b5236c..251f191d 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/provider/pebble/PebbleAcmeProviderTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/provider/pebble/PebbleAcmeProviderTest.java @@ -13,14 +13,14 @@ */ package org.shredzone.acme4j.provider.pebble; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.shredzone.acme4j.toolbox.TestUtils.url; import java.net.URI; import java.net.URISyntaxException; +import org.assertj.core.api.AutoCloseableSoftAssertions; import org.junit.jupiter.api.Test; /** @@ -35,13 +35,15 @@ public class PebbleAcmeProviderTest { public void testAccepts() throws URISyntaxException { PebbleAcmeProvider provider = new PebbleAcmeProvider(); - assertThat(provider.accepts(new URI("acme://pebble")), is(true)); - assertThat(provider.accepts(new URI("acme://pebble/")), is(true)); - assertThat(provider.accepts(new URI("acme://pebble/some-host.example.com")), is(true)); - assertThat(provider.accepts(new URI("acme://pebble/some-host.example.com:12345")), is(true)); - assertThat(provider.accepts(new URI("acme://example.com")), is(false)); - assertThat(provider.accepts(new URI("http://example.com/acme")), is(false)); - assertThat(provider.accepts(new URI("https://example.com/acme")), is(false)); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(provider.accepts(new URI("acme://pebble"))).isTrue(); + softly.assertThat(provider.accepts(new URI("acme://pebble/"))).isTrue(); + softly.assertThat(provider.accepts(new URI("acme://pebble/some-host.example.com"))).isTrue(); + softly.assertThat(provider.accepts(new URI("acme://pebble/some-host.example.com:12345"))).isTrue(); + softly.assertThat(provider.accepts(new URI("acme://example.com"))).isFalse(); + softly.assertThat(provider.accepts(new URI("http://example.com/acme"))).isFalse(); + softly.assertThat(provider.accepts(new URI("https://example.com/acme"))).isFalse(); + } } /** @@ -51,16 +53,16 @@ public class PebbleAcmeProviderTest { public void testResolve() throws URISyntaxException { PebbleAcmeProvider provider = new PebbleAcmeProvider(); - assertThat(provider.resolve(new URI("acme://pebble")), - is(url("https://localhost:14000/dir"))); - assertThat(provider.resolve(new URI("acme://pebble/")), - is(url("https://localhost:14000/dir"))); - assertThat(provider.resolve(new URI("acme://pebble/pebble.example.com")), - is(url("https://pebble.example.com:14000/dir"))); - assertThat(provider.resolve(new URI("acme://pebble/pebble.example.com:12345")), - is(url("https://pebble.example.com:12345/dir"))); - assertThat(provider.resolve(new URI("acme://pebble/pebble.example.com:12345/")), - is(url("https://pebble.example.com:12345/dir"))); + assertThat(provider.resolve(new URI("acme://pebble"))) + .isEqualTo(url("https://localhost:14000/dir")); + assertThat(provider.resolve(new URI("acme://pebble/"))) + .isEqualTo(url("https://localhost:14000/dir")); + assertThat(provider.resolve(new URI("acme://pebble/pebble.example.com"))) + .isEqualTo(url("https://pebble.example.com:14000/dir")); + assertThat(provider.resolve(new URI("acme://pebble/pebble.example.com:12345"))) + .isEqualTo(url("https://pebble.example.com:12345/dir")); + assertThat(provider.resolve(new URI("acme://pebble/pebble.example.com:12345/"))) + .isEqualTo(url("https://pebble.example.com:12345/dir")); assertThrows(IllegalArgumentException.class, () -> { provider.resolve(new URI("acme://pebble/bad.example.com:port")); diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/AcmeUtilsTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/AcmeUtilsTest.java index d1721a7d..bda3281c 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/AcmeUtilsTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/AcmeUtilsTest.java @@ -13,9 +13,8 @@ */ package org.shredzone.acme4j.toolbox; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.shredzone.acme4j.toolbox.AcmeUtils.*; @@ -30,17 +29,18 @@ import java.net.URI; import java.security.Security; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; import java.util.List; +import java.util.stream.Stream; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import org.shredzone.acme4j.exception.AcmeProtocolException; /** @@ -59,7 +59,7 @@ public class AcmeUtilsTest { @Test public void testPrivateConstructor() throws Exception { Constructor constructor = AcmeUtils.class.getDeclaredConstructor(); - assertThat(Modifier.isPrivate(constructor.getModifiers()), is(true)); + assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); constructor.setAccessible(true); constructor.newInstance(); } @@ -70,7 +70,7 @@ public class AcmeUtilsTest { @Test public void testSha256HashHexEncode() { String hexEncode = hexEncode(sha256hash("foobar")); - assertThat(hexEncode, is("c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2")); + assertThat(hexEncode).isEqualTo("c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2"); } /** @@ -79,7 +79,7 @@ public class AcmeUtilsTest { @Test public void testBase64UrlEncode() { String base64UrlEncode = base64UrlEncode(sha256hash("foobar")); - assertThat(base64UrlEncode, is("w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI")); + assertThat(base64UrlEncode).isEqualTo("w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI"); } /** @@ -88,23 +88,36 @@ public class AcmeUtilsTest { @Test public void testBase64UrlDecode() { byte[] base64UrlDecode = base64UrlDecode("w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI"); - assertThat(base64UrlDecode, is(sha256hash("foobar"))); + assertThat(base64UrlDecode).isEqualTo(sha256hash("foobar")); } /** - * Test base64 URL validation. + * Test base64 URL validation for valid values */ - @Test - public void testBase64UrlValidate() { - assertThat(isValidBase64Url(null), is(false)); - assertThat(isValidBase64Url(""), is(true)); - assertThat(isValidBase64Url(" "), is(false)); - assertThat(isValidBase64Url("Zg"), is(true)); - assertThat(isValidBase64Url("Zg="), is(false)); - assertThat(isValidBase64Url("Zg=="), is(false)); - assertThat(isValidBase64Url("Zm9v"), is(true)); - assertThat(isValidBase64Url(" Zm9v "), is(false)); - assertThat(isValidBase64Url(".illegal#Text"), is(false)); + @ParameterizedTest + @ValueSource(strings = { + "", + "Zg", + "Zm9v", + }) + public void testBase64UrlValid(String url) { + assertThat(isValidBase64Url(url)).isTrue(); + } + + /** + * Test base64 URL validation for invalid values + */ + @ParameterizedTest + @ValueSource(strings = { + " ", + "Zg=", + "Zg==", + " Zm9v ", + ".illegal#Text", + }) + @NullSource + public void testBase64UrlInvalid(String url) { + assertThat(isValidBase64Url(url)).isFalse(); } /** @@ -113,57 +126,64 @@ public class AcmeUtilsTest { @Test public void testToAce() { // Test ASCII domains in different notations - assertThat(toAce("example.com"), is("example.com")); - assertThat(toAce(" example.com "), is("example.com")); - assertThat(toAce("ExAmPlE.CoM"), is("example.com")); - assertThat(toAce("foo.example.com"), is("foo.example.com")); - assertThat(toAce("bar.foo.example.com"), is("bar.foo.example.com")); + assertThat(toAce("example.com")).isEqualTo("example.com"); + assertThat(toAce(" example.com ")).isEqualTo("example.com"); + assertThat(toAce("ExAmPlE.CoM")).isEqualTo("example.com"); + assertThat(toAce("foo.example.com")).isEqualTo("foo.example.com"); + assertThat(toAce("bar.foo.example.com")).isEqualTo("bar.foo.example.com"); // Test IDN domains - assertThat(toAce("ExÄmþle.¢öM"), is("xn--exmle-hra7p.xn--m-7ba6w")); + assertThat(toAce("ExÄmþle.¢öM")).isEqualTo("xn--exmle-hra7p.xn--m-7ba6w"); // Test alternate separators - assertThat(toAce("example\u3002com"), is("example.com")); - assertThat(toAce("example\uff0ecom"), is("example.com")); - assertThat(toAce("example\uff61com"), is("example.com")); + assertThat(toAce("example\u3002com")).isEqualTo("example.com"); + assertThat(toAce("example\uff0ecom")).isEqualTo("example.com"); + assertThat(toAce("example\uff61com")).isEqualTo("example.com"); // Test ACE encoded domains, they must not change - assertThat(toAce("xn--exmle-hra7p.xn--m-7ba6w"), - is("xn--exmle-hra7p.xn--m-7ba6w")); + assertThat(toAce("xn--exmle-hra7p.xn--m-7ba6w")) + .isEqualTo("xn--exmle-hra7p.xn--m-7ba6w"); } /** * Test valid strings. */ - @Test - public void testParser() { - assertThat(parseTimestamp("2015-12-27T22:58:35.006769519Z"), isDate(2015, 12, 27, 22, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35.00676951Z"), isDate(2015, 12, 27, 22, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35.0067695Z"), isDate(2015, 12, 27, 22, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35.006769Z"), isDate(2015, 12, 27, 22, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35.00676Z"), isDate(2015, 12, 27, 22, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35.0067Z"), isDate(2015, 12, 27, 22, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35.006Z"), isDate(2015, 12, 27, 22, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35.01Z"), isDate(2015, 12, 27, 22, 58, 35, 10)); - assertThat(parseTimestamp("2015-12-27T22:58:35.2Z"), isDate(2015, 12, 27, 22, 58, 35, 200)); - assertThat(parseTimestamp("2015-12-27T22:58:35Z"), isDate(2015, 12, 27, 22, 58, 35)); - assertThat(parseTimestamp("2015-12-27t22:58:35z"), isDate(2015, 12, 27, 22, 58, 35)); + @ParameterizedTest + @MethodSource("provideTimestamps") + public void testParser(String input, String expected) { + Arguments.of(input, expected, within(1, ChronoUnit.MILLIS)); + } - assertThat(parseTimestamp("2015-12-27T22:58:35.006769519+02:00"), isDate(2015, 12, 27, 20, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35.006+02:00"), isDate(2015, 12, 27, 20, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35+02:00"), isDate(2015, 12, 27, 20, 58, 35)); + private static Stream provideTimestamps() { + return Stream.of( + Arguments.of("2015-12-27T22:58:35.006769519Z", "2015-12-27T22:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35.00676951Z", "2015-12-27T22:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35.0067695Z", "2015-12-27T22:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35.006769Z", "2015-12-27T22:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35.00676Z", "2015-12-27T22:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35.0067Z", "2015-12-27T22:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35.006Z", "2015-12-27T22:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35.01Z", "2015-12-27T22:58:35.010Z"), + Arguments.of("2015-12-27T22:58:35.2Z", "2015-12-27T22:58:35.200Z"), + Arguments.of("2015-12-27T22:58:35Z", "2015-12-27T22:58:35.000Z"), + Arguments.of("2015-12-27t22:58:35z", "2015-12-27T22:58:35.000Z"), - assertThat(parseTimestamp("2015-12-27T21:58:35.006769519-02:00"), isDate(2015, 12, 27, 23, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T21:58:35.006-02:00"), isDate(2015, 12, 27, 23, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T21:58:35-02:00"), isDate(2015, 12, 27, 23, 58, 35)); + Arguments.of("2015-12-27T22:58:35.006769519+02:00", "2015-12-27T20:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35.006+02:00", "2015-12-27T20:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35+02:00", "2015-12-27T20:58:35.000Z"), - assertThat(parseTimestamp("2015-12-27T22:58:35.006769519+0200"), isDate(2015, 12, 27, 20, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35.006+0200"), isDate(2015, 12, 27, 20, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T22:58:35+0200"), isDate(2015, 12, 27, 20, 58, 35)); + Arguments.of("2015-12-27T21:58:35.006769519-02:00", "2015-12-27T23:58:35.006Z"), + Arguments.of("2015-12-27T21:58:35.006-02:00", "2015-12-27T23:58:35.006Z"), + Arguments.of("2015-12-27T21:58:35-02:00", "2015-12-27T23:58:35.000Z"), - assertThat(parseTimestamp("2015-12-27T21:58:35.006769519-0200"), isDate(2015, 12, 27, 23, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T21:58:35.006-0200"), isDate(2015, 12, 27, 23, 58, 35, 6)); - assertThat(parseTimestamp("2015-12-27T21:58:35-0200"), isDate(2015, 12, 27, 23, 58, 35)); + Arguments.of("2015-12-27T22:58:35.006769519+0200", "2015-12-27T20:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35.006+0200", "2015-12-27T20:58:35.006Z"), + Arguments.of("2015-12-27T22:58:35+0200", "2015-12-27T20:58:35.000Z"), + + Arguments.of("2015-12-27T21:58:35.006769519-0200", "2015-12-27T23:58:35.006Z"), + Arguments.of("2015-12-27T21:58:35.006-0200", "2015-12-27T23:58:35.006Z"), + Arguments.of("2015-12-27T21:58:35-0200", "2015-12-27T23:58:35.000Z") + ); } /** @@ -190,9 +210,9 @@ public class AcmeUtilsTest { */ @Test public void testStripErrorPrefix() { - assertThat(stripErrorPrefix("urn:ietf:params:acme:error:unauthorized"), is("unauthorized")); - assertThat(stripErrorPrefix("urn:somethingelse:error:message"), is(nullValue())); - assertThat(stripErrorPrefix(null), is(nullValue())); + assertThat(stripErrorPrefix("urn:ietf:params:acme:error:unauthorized")).isEqualTo("unauthorized"); + assertThat(stripErrorPrefix("urn:somethingelse:error:message")).isNull(); + assertThat(stripErrorPrefix(null)).isNull(); } /** @@ -219,29 +239,33 @@ public class AcmeUtilsTest { } } - assertThat(pemFile.toByteArray(), is(originalFile.toByteArray())); + assertThat(pemFile.toByteArray()).isEqualTo(originalFile.toByteArray()); } /** - * Test {@link AcmeUtils#getContentType(String)}. + * Test {@link AcmeUtils#getContentType(String)} for JSON types. + */ + @ParameterizedTest + @ValueSource(strings = { + "application/json", + "application/json; charset=utf-8", + "application/json; charset=utf-8 (Plain text)", + "application/json; charset=\"utf-8\"", + "application/json; charset=\"UTF-8\"; foo=4", + " application/json ;foo=4", + }) + public void testGetContentTypeForJson(String contentType) { + assertThat(AcmeUtils.getContentType(contentType)).isEqualTo("application/json"); + } + + /** + * Test {@link AcmeUtils#getContentType(String)} with other types. */ @Test public void testGetContentType() { - assertThat(AcmeUtils.getContentType(null), is(nullValue())); - assertThat(AcmeUtils.getContentType("application/json"), - is("application/json")); - assertThat(AcmeUtils.getContentType("Application/Problem+JSON"), - is("application/problem+json")); - assertThat(AcmeUtils.getContentType("application/json; charset=utf-8"), - is("application/json")); - assertThat(AcmeUtils.getContentType("application/json; charset=utf-8 (Plain text)"), - is("application/json")); - assertThat(AcmeUtils.getContentType("application/json; charset=\"utf-8\""), - is("application/json")); - assertThat(AcmeUtils.getContentType("application/json; charset=\"UTF-8\"; foo=4"), - is("application/json")); - assertThat(AcmeUtils.getContentType(" application/json ;foo=4"), - is("application/json")); + assertThat(AcmeUtils.getContentType(null)).isNull(); + assertThat(AcmeUtils.getContentType("Application/Problem+JSON")) + .isEqualTo("application/problem+json"); assertThrows(AcmeProtocolException.class, () -> AcmeUtils.getContentType("application/json; charset=\"iso-8859-1\"")); } @@ -265,59 +289,4 @@ public class AcmeUtilsTest { "only hfields are accepted"); } - /** - * Matches the given time. - */ - private InstantMatcher isDate(int year, int month, int dom, int hour, int minute, int second) { - return isDate(year, month, dom, hour, minute, second, 0); - } - - /** - * Matches the given time and milliseconds. - */ - private InstantMatcher isDate(int year, int month, int dom, int hour, int minute, int second, int ms) { - Instant cmp = ZonedDateTime.of( - year, month, dom, hour, minute, second, ms * 1_000_000, - ZoneId.of("UTC")).toInstant(); - return new InstantMatcher(cmp); - } - - /** - * Date matcher that gives a readable output on mismatch. - */ - private static class InstantMatcher extends BaseMatcher { - private final Instant cmp; - private final DateTimeFormatter dtf = DateTimeFormatter.ISO_INSTANT; - - public InstantMatcher(Instant cmp) { - this.cmp = cmp; - } - - @Override - public boolean matches(Object item) { - if (!(item instanceof Instant)) { - return false; - } - - Instant date = (Instant) item; - return date.equals(cmp); - } - - @Override - public void describeTo(Description description) { - description.appendValue(dtf.format(cmp)); - } - - @Override - public void describeMismatch(Object item, Description description) { - if (!(item instanceof Instant)) { - description.appendText("is not an Instant"); - return; - } - - Instant date = (Instant) item; - description.appendText("was ").appendValue(dtf.format(date)); - } - } - } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JSONBuilderTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JSONBuilderTest.java index 365bc763..8093c914 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JSONBuilderTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JSONBuilderTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.toolbox; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.security.KeyPair; @@ -41,7 +40,7 @@ public class JSONBuilderTest { @Test public void testEmpty() { JSONBuilder cb = new JSONBuilder(); - assertThat(cb.toString(), is("{}")); + assertThat(cb.toString()).isEqualTo("{}"); } /** @@ -54,27 +53,25 @@ public class JSONBuilderTest { JSONBuilder cb = new JSONBuilder(); res = cb.put("fooStr", "String"); - assertThat(res, is(sameInstance(cb))); + assertThat(res).isSameAs(cb); res = cb.put("fooInt", 123); - assertThat(res, is(sameInstance(cb))); + assertThat(res).isSameAs(cb); res = cb.put("fooInt", 456); - assertThat(res, is(sameInstance(cb))); + assertThat(res).isSameAs(cb); - assertThat(cb.toString(), is("{\"fooStr\":\"String\",\"fooInt\":456}")); + assertThat(cb.toString()).isEqualTo("{\"fooStr\":\"String\",\"fooInt\":456}"); Map map = cb.toMap(); - assertThat(map.keySet(), hasSize(2)); - assertThat(map, allOf( - hasEntry("fooInt", 456), - hasEntry("fooStr", (Object) "String") - )); + assertThat(map.keySet()).hasSize(2); + assertThat(map).extracting("fooInt").isEqualTo(456); + assertThat(map).extracting("fooStr").isEqualTo("String"); JSON json = cb.toJSON(); - assertThat(json.keySet(), hasSize(2)); - assertThat(json.get("fooInt").asInt(), is(456)); - assertThat(json.get("fooStr").asString(), is("String")); + assertThat(json.keySet()).hasSize(2); + assertThat(json.get("fooInt").asInt()).isEqualTo(456); + assertThat(json.get("fooStr").asString()).isEqualTo("String"); } /** @@ -90,7 +87,7 @@ public class JSONBuilderTest { cb.put("fooDuration", duration); cb.put("fooNull", (Object) null); - assertThat(cb.toString(), is("{\"fooDate\":\"2016-06-01T03:13:46Z\",\"fooDuration\":300,\"fooNull\":null}")); + assertThat(cb.toString()).isEqualTo("{\"fooDate\":\"2016-06-01T03:13:46Z\",\"fooDuration\":300,\"fooNull\":null}"); } /** @@ -104,8 +101,8 @@ public class JSONBuilderTest { JSONBuilder cb = new JSONBuilder(); res = cb.putBase64("foo", data); - assertThat(res, is(sameInstance(cb))); - assertThat(cb.toString(), is("{\"foo\":\"YWJjMTIz\"}")); + assertThat(res).isSameAs(cb); + assertThat(cb.toString()).isEqualTo("{\"foo\":\"YWJjMTIz\"}"); } /** @@ -119,16 +116,16 @@ public class JSONBuilderTest { JSONBuilder cb = new JSONBuilder(); res = cb.putKey("foo", keyPair.getPublic()); - assertThat(res, is(sameInstance(cb))); + assertThat(res).isSameAs(cb); Map json = JsonUtil.parseJson(cb.toString()); - assertThat(json, hasKey("foo")); + assertThat(json).containsKey("foo"); Map jwk = (Map) json.get("foo"); - assertThat(jwk.keySet(), hasSize(3)); - assertThat(jwk, hasEntry("n", TestUtils.N)); - assertThat(jwk, hasEntry("e", TestUtils.E)); - assertThat(jwk, hasEntry("kty", TestUtils.KTY)); + assertThat(jwk.keySet()).hasSize(3); + assertThat(jwk).extracting("n").isEqualTo(TestUtils.N); + assertThat(jwk).extracting("e").isEqualTo(TestUtils.E); + assertThat(jwk).extracting("kty").isEqualTo(TestUtils.KTY); } /** @@ -138,14 +135,14 @@ public class JSONBuilderTest { public void testObject() { JSONBuilder cb = new JSONBuilder(); JSONBuilder sub = cb.object("sub"); - assertThat(sub, not(sameInstance(cb))); + assertThat(sub).isNotSameAs(cb); - assertThat(cb.toString(), is("{\"sub\":{}}")); + assertThat(cb.toString()).isEqualTo("{\"sub\":{}}"); cb.put("foo", 123); sub.put("foo", 456); - assertThat(cb.toString(), is("{\"sub\":{\"foo\":456},\"foo\":123}")); + assertThat(cb.toString()).isEqualTo("{\"sub\":{\"foo\":456},\"foo\":123}"); } /** @@ -157,18 +154,18 @@ public class JSONBuilderTest { JSONBuilder cb1 = new JSONBuilder(); res = cb1.array("ar", Collections.emptyList()); - assertThat(res, is(sameInstance(cb1))); - assertThat(cb1.toString(), is("{\"ar\":[]}")); + assertThat(res).isSameAs(cb1); + assertThat(cb1.toString()).isEqualTo("{\"ar\":[]}"); JSONBuilder cb2 = new JSONBuilder(); res = cb2.array("ar", Collections.singletonList(123)); - assertThat(res, is(sameInstance(cb2))); - assertThat(cb2.toString(), is("{\"ar\":[123]}")); + assertThat(res).isSameAs(cb2); + assertThat(cb2.toString()).isEqualTo("{\"ar\":[123]}"); JSONBuilder cb3 = new JSONBuilder(); res = cb3.array("ar", Arrays.asList(123, "foo", 456)); - assertThat(res, is(sameInstance(cb3))); - assertThat(cb3.toString(), is("{\"ar\":[123,\"foo\",456]}")); + assertThat(res).isSameAs(cb3); + assertThat(cb3.toString()).isEqualTo("{\"ar\":[123,\"foo\",456]}"); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JSONTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JSONTest.java index 03ecc9dc..275d8586 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JSONTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JSONTest.java @@ -14,11 +14,10 @@ package org.shredzone.acme4j.toolbox; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.shredzone.acme4j.toolbox.TestUtils.url; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -28,7 +27,6 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.URI; import java.net.URL; -import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; @@ -58,8 +56,8 @@ public class JSONTest { @Test public void testEmpty() { JSON empty = JSON.empty(); - assertThat(empty.toString(), is("{}")); - assertThat(empty.toMap().keySet(), is(empty())); + assertThat(empty.toString()).isEqualTo("{}"); + assertThat(empty.toMap().keySet()).isEmpty(); } /** @@ -70,21 +68,21 @@ public class JSONTest { String json = "{\"foo\":\"a-text\",\n\"bar\":123}"; JSON fromString = JSON.parse(json); - assertThat(fromString.toString(), is(sameJSONAs(json))); + assertThatJson(fromString.toString()).isEqualTo(json); Map map = fromString.toMap(); - assertThat(map.size(), is(2)); - assertThat(map.keySet(), containsInAnyOrder("foo", "bar")); - assertThat(map.get("foo"), is("a-text")); - assertThat(map.get("bar"), is(123L)); + assertThat(map).hasSize(2); + assertThat(map.keySet()).containsExactlyInAnyOrder("foo", "bar"); + assertThat(map.get("foo")).isEqualTo("a-text"); + assertThat(map.get("bar")).isEqualTo(123L); try (InputStream in = new ByteArrayInputStream(json.getBytes(UTF_8))) { JSON fromStream = JSON.parse(in); - assertThat(fromStream.toString(), is(sameJSONAs(json))); + assertThatJson(fromStream.toString()).isEqualTo(json); Map map2 = fromStream.toMap(); - assertThat(map2.size(), is(2)); - assertThat(map2.keySet(), containsInAnyOrder("foo", "bar")); - assertThat(map2.get("foo"), is("a-text")); - assertThat(map2.get("bar"), is(123L)); + assertThat(map2).hasSize(2); + assertThat(map2.keySet()).containsExactlyInAnyOrder("foo", "bar"); + assertThat(map2.get("foo")).isEqualTo("a-text"); + assertThat(map2.get("bar")).isEqualTo(123L); } } @@ -105,13 +103,13 @@ public class JSONTest { public void testObject() { JSON json = TestUtils.getJSON("datatypes"); - assertThat(json.keySet(), containsInAnyOrder( + assertThat(json.keySet()).containsExactlyInAnyOrder( "text", "number", "boolean", "uri", "url", "date", "array", - "collect", "status", "binary", "duration", "problem", "encoded")); - assertThat(json.contains("text"), is(true)); - assertThat(json.contains("music"), is(false)); - assertThat(json.get("text"), is(notNullValue())); - assertThat(json.get("music"), is(notNullValue())); + "collect", "status", "binary", "duration", "problem", "encoded"); + assertThat(json.contains("text")).isTrue(); + assertThat(json.contains("music")).isFalse(); + assertThat(json.get("text")).isNotNull(); + assertThat(json.get("music")).isNotNull(); } /** @@ -122,12 +120,8 @@ public class JSONTest { JSON json = TestUtils.getJSON("datatypes"); JSON.Array array = json.get("array").asArray(); - assertThat(array.size(), is(4)); - assertThat(array.isEmpty(), is(false)); - assertThat(array.get(0), is(notNullValue())); - assertThat(array.get(1), is(notNullValue())); - assertThat(array.get(2), is(notNullValue())); - assertThat(array.get(3), is(notNullValue())); + assertThat(array.isEmpty()).isFalse(); + assertThat(array).hasSize(4).doesNotContainNull(); } /** @@ -138,9 +132,9 @@ public class JSONTest { JSON json = TestUtils.getJSON("datatypes"); JSON.Array array = json.get("missingArray").asArray(); - assertThat(array.size(), is(0)); - assertThat(array.isEmpty(), is(true)); - assertThat(array.stream().count(), is(0L)); + assertThat(array.isEmpty()).isTrue(); + assertThat(array).hasSize(0); + assertThat(array.stream().count()).isEqualTo(0L); } /** @@ -152,22 +146,22 @@ public class JSONTest { JSON.Array array = json.get("array").asArray(); Iterator it = array.iterator(); - assertThat(it, is(notNullValue())); + assertThat(it).isNotNull(); - assertThat(it.hasNext(), is(true)); - assertThat(it.next().asString(), is("foo")); + assertThat(it.hasNext()).isTrue(); + assertThat(it.next().asString()).isEqualTo("foo"); - assertThat(it.hasNext(), is(true)); - assertThat(it.next().asInt(), is(987)); + assertThat(it.hasNext()).isTrue(); + assertThat(it.next().asInt()).isEqualTo(987); - assertThat(it.hasNext(), is(true)); - assertThat(it.next().asArray().size(), is(3)); + assertThat(it.hasNext()).isTrue(); + assertThat(it.next().asArray()).hasSize(3); - assertThat(it.hasNext(), is(true)); + assertThat(it.hasNext()).isTrue(); assertThrows(UnsupportedOperationException.class, it::remove); - assertThat(it.next().asObject(), is(notNullValue())); + assertThat(it.next().asObject()).isNotNull(); - assertThat(it.hasNext(), is(false)); + assertThat(it.hasNext()).isFalse(); assertThrows(NoSuchElementException.class, it::next); } @@ -187,7 +181,7 @@ public class JSONTest { iteratorValues.add(it.next()); } - assertThat(streamValues, contains(iteratorValues.toArray())); + assertThat(streamValues).containsAll(iteratorValues); } /** @@ -199,40 +193,40 @@ public class JSONTest { JSON json = TestUtils.getJSON("datatypes"); - assertThat(json.get("text").asString(), is("lorem ipsum")); - assertThat(json.get("number").asInt(), is(123)); - assertThat(json.get("boolean").asBoolean(), is(true)); - assertThat(json.get("uri").asURI(), is(URI.create("mailto:foo@example.com"))); - assertThat(json.get("url").asURL(), is(url("http://example.com"))); - assertThat(json.get("date").asInstant(), is(date)); - assertThat(json.get("status").asStatus(), is(Status.VALID)); - assertThat(json.get("binary").asBinary(), is("Chainsaw".getBytes())); - assertThat(json.get("duration").asDuration(), is(Duration.ofSeconds(86400))); + assertThat(json.get("text").asString()).isEqualTo("lorem ipsum"); + assertThat(json.get("number").asInt()).isEqualTo(123); + assertThat(json.get("boolean").asBoolean()).isTrue(); + assertThat(json.get("uri").asURI()).isEqualTo(URI.create("mailto:foo@example.com")); + assertThat(json.get("url").asURL()).isEqualTo(url("http://example.com")); + assertThat(json.get("date").asInstant()).isEqualTo(date); + assertThat(json.get("status").asStatus()).isEqualTo(Status.VALID); + assertThat(json.get("binary").asBinary()).isEqualTo("Chainsaw".getBytes()); + assertThat(json.get("duration").asDuration()).hasSeconds(86400L); - assertThat(json.get("text").isPresent(), is(true)); - assertThat(json.get("text").optional().isPresent(), is(true)); - assertThat(json.get("text").map(Value::asString).isPresent(), is(true)); + assertThat(json.get("text").isPresent()).isTrue(); + assertThat(json.get("text").optional().isPresent()).isTrue(); + assertThat(json.get("text").map(Value::asString).isPresent()).isTrue(); JSON.Array array = json.get("array").asArray(); - assertThat(array.get(0).asString(), is("foo")); - assertThat(array.get(1).asInt(), is(987)); + assertThat(array.get(0).asString()).isEqualTo("foo"); + assertThat(array.get(1).asInt()).isEqualTo(987); JSON.Array array2 = array.get(2).asArray(); - assertThat(array2.get(0).asInt(), is(1)); - assertThat(array2.get(1).asInt(), is(2)); - assertThat(array2.get(2).asInt(), is(3)); + assertThat(array2.get(0).asInt()).isEqualTo(1); + assertThat(array2.get(1).asInt()).isEqualTo(2); + assertThat(array2.get(2).asInt()).isEqualTo(3); JSON sub = array.get(3).asObject(); - assertThat(sub.get("test").asString(), is("ok")); + assertThat(sub.get("test").asString()).isEqualTo("ok"); JSON encodedSub = json.get("encoded").asEncodedObject(); - assertThat(encodedSub.toString(), is(sameJSONAs("{\"key\":\"value\"}"))); + assertThatJson(encodedSub.toString()).isEqualTo("{\"key\":\"value\"}"); Problem problem = json.get("problem").asProblem(BASE_URL); - assertThat(problem, is(notNullValue())); - assertThat(problem.getType(), is(URI.create("urn:ietf:params:acme:error:rateLimited"))); - assertThat(problem.getDetail(), is("too many requests")); - assertThat(problem.getInstance(), is(URI.create("https://example.com/documents/errors.html"))); + assertThat(problem).isNotNull(); + assertThat(problem.getType()).isEqualTo(URI.create("urn:ietf:params:acme:error:rateLimited")); + assertThat(problem.getDetail()).isEqualTo("too many requests"); + assertThat(problem.getInstance()).isEqualTo(URI.create("https://example.com/documents/errors.html")); } /** @@ -242,10 +236,10 @@ public class JSONTest { public void testNullGetter() { JSON json = TestUtils.getJSON("datatypes"); - assertThat(json.get("none"), is(notNullValue())); - assertThat(json.get("none").isPresent(), is(false)); - assertThat(json.get("none").optional().isPresent(), is(false)); - assertThat(json.get("none").map(Value::asString).isPresent(), is(false)); + assertThat(json.get("none")).isNotNull(); + assertThat(json.get("none").isPresent()).isFalse(); + assertThat(json.get("none").optional().isPresent()).isFalse(); + assertThat(json.get("none").map(Value::asString).isPresent()).isFalse(); assertThrows(AcmeProtocolException.class, () -> json.get("none").asString(), @@ -345,9 +339,9 @@ public class JSONTest { } } - assertThat(testJson, not(sameInstance(originalJson))); - assertThat(testJson.toString(), not(emptyOrNullString())); - assertThat(testJson.toString(), is(sameJSONAs(originalJson.toString()))); + assertThat(testJson).isNotSameAs(originalJson); + assertThat(testJson.toString()).isNotEmpty(); + assertThatJson(testJson.toString()).isEqualTo(originalJson.toString()); } } diff --git a/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JoseUtilsTest.java b/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JoseUtilsTest.java index 74ac5289..b048e561 100644 --- a/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JoseUtilsTest.java +++ b/acme4j-client/src/test/java/org/shredzone/acme4j/toolbox/JoseUtilsTest.java @@ -14,11 +14,10 @@ package org.shredzone.acme4j.toolbox; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.fail; import static org.shredzone.acme4j.toolbox.TestUtils.url; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; import java.net.URL; import java.security.KeyPair; @@ -71,14 +70,16 @@ public class JoseUtilsTest { expectedHeader.append("\"kid\":\"").append(TestUtils.ACCOUNT_URL).append('"'); expectedHeader.append('}'); - assertThat(new String(URL_DECODER.decode(encodedHeader), UTF_8), sameJSONAs(expectedHeader.toString())); - assertThat(new String(URL_DECODER.decode(encodedPayload), UTF_8), sameJSONAs("{\"foo\":123,\"bar\":\"a-string\"}")); - assertThat(encodedSignature, not(emptyOrNullString())); + assertThatJson(new String(URL_DECODER.decode(encodedHeader), UTF_8)) + .isEqualTo(expectedHeader.toString()); + assertThatJson(new String(URL_DECODER.decode(encodedPayload), UTF_8)) + .isEqualTo("{\"foo\":123,\"bar\":\"a-string\"}"); + assertThat(encodedSignature).isNotEmpty(); JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); jws.setKey(accountKey.getPublic()); - assertThat(jws.verifySignature(), is(true)); + assertThat(jws.verifySignature()).isTrue(); } /** @@ -106,14 +107,15 @@ public class JoseUtilsTest { expectedHeader.append("\"kid\":\"").append(TestUtils.ACCOUNT_URL).append('"'); expectedHeader.append('}'); - assertThat(new String(URL_DECODER.decode(encodedHeader), UTF_8), sameJSONAs(expectedHeader.toString())); - assertThat(new String(URL_DECODER.decode(encodedPayload), UTF_8), is("")); - assertThat(encodedSignature, not(emptyOrNullString())); + assertThatJson(new String(URL_DECODER.decode(encodedHeader), UTF_8)) + .isEqualTo(expectedHeader.toString()); + assertThat(new String(URL_DECODER.decode(encodedPayload), UTF_8)).isEmpty(); + assertThat(encodedSignature).isNotEmpty(); JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); jws.setKey(accountKey.getPublic()); - assertThat(jws.verifySignature(), is(true)); + assertThat(jws.verifySignature()).isTrue(); } /** @@ -145,14 +147,16 @@ public class JoseUtilsTest { expectedHeader.append("\"n\": \"").append(TestUtils.N).append("\"}"); expectedHeader.append("}"); - assertThat(new String(URL_DECODER.decode(encodedHeader), UTF_8), sameJSONAs(expectedHeader.toString())); - assertThat(new String(URL_DECODER.decode(encodedPayload), UTF_8), sameJSONAs("{\"foo\":123,\"bar\":\"a-string\"}")); - assertThat(encodedSignature, not(emptyOrNullString())); + assertThatJson(new String(URL_DECODER.decode(encodedHeader), UTF_8)) + .isEqualTo(expectedHeader.toString()); + assertThatJson(new String(URL_DECODER.decode(encodedPayload), UTF_8)) + .isEqualTo("{\"foo\":123,\"bar\":\"a-string\"}"); + assertThat(encodedSignature).isNotEmpty(); JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); jws.setKey(accountKey.getPublic()); - assertThat(jws.verifySignature(), is(true)); + assertThat(jws.verifySignature()).isTrue(); } /** @@ -182,10 +186,10 @@ public class JoseUtilsTest { @Test public void testPublicKeyToJWK() throws Exception { Map json = JoseUtils.publicKeyToJWK(TestUtils.createKeyPair().getPublic()); - assertThat(json.size(), is(3)); - assertThat(json.get("kty"), is(TestUtils.KTY)); - assertThat(json.get("n"), is(TestUtils.N)); - assertThat(json.get("e"), is(TestUtils.E)); + assertThat(json).hasSize(3); + assertThat(json.get("kty")).isEqualTo(TestUtils.KTY); + assertThat(json.get("n")).isEqualTo(TestUtils.N); + assertThat(json.get("e")).isEqualTo(TestUtils.E); } /** @@ -198,7 +202,7 @@ public class JoseUtilsTest { json.put("n", TestUtils.N); json.put("e", TestUtils.E); PublicKey key = JoseUtils.jwkToPublicKey(json); - assertThat(key.getEncoded(), is(TestUtils.createKeyPair().getPublic().getEncoded())); + assertThat(key.getEncoded()).isEqualTo(TestUtils.createKeyPair().getPublic().getEncoded()); } /** @@ -208,7 +212,7 @@ public class JoseUtilsTest { public void testThumbprint() throws Exception { byte[] thumb = JoseUtils.thumbprint(TestUtils.createKeyPair().getPublic()); String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(thumb); - assertThat(encoded, is(TestUtils.THUMBPRINT)); + assertThat(encoded).isEqualTo(TestUtils.THUMBPRINT); } /** @@ -220,8 +224,7 @@ public class JoseUtilsTest { final PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(rsaKeyPair.getPublic()); String type = JoseUtils.keyAlgorithm(jwk); - - assertThat(type, is("RS256")); + assertThat(type).isEqualTo("RS256"); } /** @@ -233,8 +236,7 @@ public class JoseUtilsTest { final PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(ecKeyPair.getPublic()); String type = JoseUtils.keyAlgorithm(jwk); - - assertThat(type, is("ES256")); + assertThat(type).isEqualTo("ES256"); } /** @@ -246,8 +248,7 @@ public class JoseUtilsTest { final PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(ecKeyPair.getPublic()); String type = JoseUtils.keyAlgorithm(jwk); - - assertThat(type, is("ES384")); + assertThat(type).isEqualTo("ES384"); } /** @@ -259,8 +260,7 @@ public class JoseUtilsTest { final PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(ecKeyPair.getPublic()); String type = JoseUtils.keyAlgorithm(jwk); - - assertThat(type, is("ES512")); + assertThat(type).isEqualTo("ES512"); } /** @@ -268,9 +268,9 @@ public class JoseUtilsTest { */ @Test public void testMacKey() throws Exception { - assertThat(JoseUtils.macKeyAlgorithm(TestUtils.createSecretKey("SHA-256")), is("HS256")); - assertThat(JoseUtils.macKeyAlgorithm(TestUtils.createSecretKey("SHA-384")), is("HS384")); - assertThat(JoseUtils.macKeyAlgorithm(TestUtils.createSecretKey("SHA-512")), is("HS512")); + assertThat(JoseUtils.macKeyAlgorithm(TestUtils.createSecretKey("SHA-256"))).isEqualTo("HS256"); + assertThat(JoseUtils.macKeyAlgorithm(TestUtils.createSecretKey("SHA-384"))).isEqualTo("HS384"); + assertThat(JoseUtils.macKeyAlgorithm(TestUtils.createSecretKey("SHA-512"))).isEqualTo("HS512"); } /** @@ -292,11 +292,11 @@ public class JoseUtilsTest { JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(serialized); jws.setKey(macKey); - assertThat(jws.verifySignature(), is(true)); + assertThat(jws.verifySignature()).isTrue(); - assertThat(jws.getHeader("url"), is(resourceUrl.toString())); - assertThat(jws.getHeader("kid"), is(keyIdentifier)); - assertThat(jws.getHeader("alg"), is("HS256")); + assertThat(jws.getHeader("url")).isEqualTo(resourceUrl.toString()); + assertThat(jws.getHeader("kid")).isEqualTo(keyIdentifier); + assertThat(jws.getHeader("alg")).isEqualTo("HS256"); String decodedPayload = jws.getPayload(); StringBuilder expectedPayload = new StringBuilder(); @@ -305,7 +305,7 @@ public class JoseUtilsTest { expectedPayload.append("\"e\":\"").append(TestUtils.E).append("\","); expectedPayload.append("\"n\":\"").append(TestUtils.N).append("\""); expectedPayload.append("}"); - assertThat(decodedPayload, sameJSONAs(expectedPayload.toString())); + assertThatJson(decodedPayload).isEqualTo(expectedPayload.toString()); } catch (JoseException ex) { fail(ex); } diff --git a/acme4j-it/src/test/java/org/shredzone/acme4j/it/boulder/OrderHttpIT.java b/acme4j-it/src/test/java/org/shredzone/acme4j/it/boulder/OrderHttpIT.java index 633bb7ea..c16abbff 100644 --- a/acme4j-it/src/test/java/org/shredzone/acme4j/it/boulder/OrderHttpIT.java +++ b/acme4j-it/src/test/java/org/shredzone/acme4j/it/boulder/OrderHttpIT.java @@ -14,9 +14,8 @@ package org.shredzone.acme4j.it.boulder; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; import java.net.URI; import java.security.KeyPair; @@ -67,7 +66,7 @@ public class OrderHttpIT { for (Authorization auth : order.getAuthorizations()) { Http01Challenge challenge = auth.findChallenge(Http01Challenge.TYPE); - assertThat(challenge, is(notNullValue())); + assertThat(challenge).isNotNull(); client.httpAddToken(challenge.getToken(), challenge.getAuthorization()); @@ -77,9 +76,9 @@ public class OrderHttpIT { .pollInterval(1, SECONDS) .timeout(30, SECONDS) .conditionEvaluationListener(cond -> updateAuth(auth)) - .until(auth::getStatus, not(oneOf(Status.PENDING, Status.PROCESSING))); + .untilAsserted(() -> assertThat(auth.getStatus()).isNotIn(Status.PENDING, Status.PROCESSING)); - assertThat(auth.getStatus(), is(Status.VALID)); + assertThat(auth.getStatus()).isEqualTo(Status.VALID); client.httpRemoveToken(challenge.getToken()); } @@ -95,14 +94,14 @@ public class OrderHttpIT { .pollInterval(1, SECONDS) .timeout(30, SECONDS) .conditionEvaluationListener(cond -> updateOrder(order)) - .until(order::getStatus, not(oneOf(Status.PENDING, Status.PROCESSING))); + .untilAsserted(() -> assertThat(order.getStatus()).isNotIn(Status.PENDING, Status.PROCESSING)); Certificate certificate = order.getCertificate(); X509Certificate cert = certificate.getCertificate(); - assertThat(cert, not(nullValue())); - assertThat(cert.getNotAfter(), not(nullValue())); - assertThat(cert.getNotBefore(), not(nullValue())); - assertThat(cert.getSubjectX500Principal().getName(), containsString("CN=" + TEST_DOMAIN)); + assertThat(cert).isNotNull(); + assertThat(cert.getNotAfter()).isNotNull(); + assertThat(cert.getNotBefore()).isNotNull(); + assertThat(cert.getSubjectX500Principal().getName()).contains("CN=" + TEST_DOMAIN); } /** diff --git a/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/AccountIT.java b/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/AccountIT.java index b9abaa82..11efb8d5 100644 --- a/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/AccountIT.java +++ b/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/AccountIT.java @@ -13,9 +13,7 @@ */ package org.shredzone.acme4j.it.pebble; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.URI; @@ -57,18 +55,18 @@ public class AccountIT extends PebbleITBase { // Check registered data Account acct = login.getAccount(); - assertThat(acct.getLocation(), is(location)); - assertThat(acct.getContacts(), contains(URI.create("mailto:acme@example.com"))); - assertThat(acct.getStatus(), is(Status.VALID)); + assertThat(acct.getLocation()).isEqualTo(location); + assertThat(acct.getContacts()).contains(URI.create("mailto:acme@example.com")); + assertThat(acct.getStatus()).isEqualTo(Status.VALID); // Bind another Account object Session session2 = new Session(pebbleURI()); Login login2 = new Login(location, keyPair, session2); - assertThat(login2.getAccountLocation(), is(location)); + assertThat(login2.getAccountLocation()).isEqualTo(location); Account acct2 = login2.getAccount(); - assertThat(acct2.getLocation(), is(location)); - assertThat(acct2.getContacts(), contains(URI.create("mailto:acme@example.com"))); - assertThat(acct2.getStatus(), is(Status.VALID)); + assertThat(acct2.getLocation()).isEqualTo(location); + assertThat(acct2.getContacts()).contains(URI.create("mailto:acme@example.com")); + assertThat(acct2.getStatus()).isEqualTo(Status.VALID); } /** @@ -100,7 +98,7 @@ public class AccountIT extends PebbleITBase { URL location2 = login2.getAccountLocation(); assertIsPebbleUrl(location2); - assertThat(location1, is(location2)); + assertThat(location1).isEqualTo(location2); } /** @@ -128,7 +126,7 @@ public class AccountIT extends PebbleITBase { URL location2 = login2.getAccountLocation(); assertIsPebbleUrl(location2); - assertThat(location1, is(location2)); + assertThat(location1).isEqualTo(location2); } /** @@ -142,7 +140,7 @@ public class AccountIT extends PebbleITBase { Session session = new Session(pebbleURI()); new AccountBuilder().onlyExisting().useKeyPair(keyPair).create(session); }); - assertThat(ex.getType(), is(URI.create("urn:ietf:params:acme:error:accountDoesNotExist"))); + assertThat(ex.getType()).isEqualTo(URI.create("urn:ietf:params:acme:error:accountDoesNotExist")); } /** @@ -163,15 +161,15 @@ public class AccountIT extends PebbleITBase { acct.modify().addContact("mailto:acme2@example.com").commit(); - assertThat(acct.getContacts(), contains( + assertThat(acct.getContacts()).contains( URI.create("mailto:acme@example.com"), - URI.create("mailto:acme2@example.com"))); + URI.create("mailto:acme2@example.com")); // Still the same after updating acct.update(); - assertThat(acct.getContacts(), contains( + assertThat(acct.getContacts()).contains( URI.create("mailto:acme@example.com"), - URI.create("mailto:acme2@example.com"))); + URI.create("mailto:acme2@example.com")); } /** @@ -199,7 +197,7 @@ public class AccountIT extends PebbleITBase { Session sessionNewKey = new Session(pebbleURI()); Account newAccount = sessionNewKey.login(location, newKeyPair).getAccount(); - assertThat(newAccount.getStatus(), is(Status.VALID)); + assertThat(newAccount.getStatus()).isEqualTo(Status.VALID); } /** @@ -219,7 +217,7 @@ public class AccountIT extends PebbleITBase { acct.deactivate(); // Make sure it is deactivated now... - assertThat(acct.getStatus(), is(Status.DEACTIVATED)); + assertThat(acct.getStatus()).isEqualTo(Status.DEACTIVATED); // Make sure account cannot be accessed any more... AcmeUnauthorizedException ex = assertThrows(AcmeUnauthorizedException.class, @@ -228,7 +226,7 @@ public class AccountIT extends PebbleITBase { Account acct2 = session2.login(location, keyPair).getAccount(); acct2.update(); }, "Account can still be accessed"); - assertThat(ex.getMessage(), is("Account has been deactivated")); + assertThat(ex.getMessage()).isEqualTo("Account has been deactivated"); } } diff --git a/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/OrderIT.java b/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/OrderIT.java index 2d057849..0777cde2 100644 --- a/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/OrderIT.java +++ b/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/OrderIT.java @@ -14,9 +14,8 @@ package org.shredzone.acme4j.it.pebble; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.URI; @@ -61,7 +60,7 @@ public class OrderIT extends PebbleITBase { BammBammClient client = getBammBammClient(); Http01Challenge challenge = auth.findChallenge(Http01Challenge.TYPE); - assertThat(challenge, is(notNullValue())); + assertThat(challenge).isNotNull(); client.httpAddToken(challenge.getToken(), challenge.getAuthorization()); @@ -80,7 +79,7 @@ public class OrderIT extends PebbleITBase { BammBammClient client = getBammBammClient(); Dns01Challenge challenge = auth.findChallenge(Dns01Challenge.TYPE); - assertThat(challenge, is(notNullValue())); + assertThat(challenge).isNotNull(); String challengeDomainName = "_acme-challenge." + auth.getIdentifier().getDomain(); @@ -101,7 +100,7 @@ public class OrderIT extends PebbleITBase { BammBammClient client = getBammBammClient(); TlsAlpn01Challenge challenge = auth.findChallenge(TlsAlpn01Challenge.TYPE); - assertThat(challenge, is(notNullValue())); + assertThat(challenge).isNotNull(); client.tlsAlpnAddCertificate( auth.getIdentifier().getDomain(), @@ -122,7 +121,7 @@ public class OrderIT extends PebbleITBase { BammBammClient client = getBammBammClient(); Http01Challenge challenge = auth.findChallenge(Http01Challenge.TYPE); - assertThat(challenge, is(notNullValue())); + assertThat(challenge).isNotNull(); client.httpAddToken(challenge.getToken(), challenge.getAuthorization()); @@ -163,13 +162,13 @@ public class OrderIT extends PebbleITBase { .notBefore(notBefore) .notAfter(notAfter) .create(); - assertThat(order.getNotBefore(), is(notBefore)); - assertThat(order.getNotAfter(), is(notAfter)); - assertThat(order.getStatus(), is(Status.PENDING)); + assertThat(order.getNotBefore()).isEqualTo(notBefore); + assertThat(order.getNotAfter()).isEqualTo(notAfter); + assertThat(order.getStatus()).isEqualTo(Status.PENDING); for (Authorization auth : order.getAuthorizations()) { - assertThat(auth.getIdentifier().getDomain(), is(domain)); - assertThat(auth.getStatus(), is(Status.PENDING)); + assertThat(auth.getIdentifier().getDomain()).isEqualTo(domain); + assertThat(auth.getStatus()).isEqualTo(Status.PENDING); if (auth.getStatus() == Status.VALID) { continue; @@ -182,9 +181,9 @@ public class OrderIT extends PebbleITBase { .pollInterval(1, SECONDS) .timeout(30, SECONDS) .conditionEvaluationListener(cond -> updateAuth(auth)) - .until(auth::getStatus, not(oneOf(Status.PENDING, Status.PROCESSING))); + .untilAsserted(() -> assertThat(auth.getStatus()).isNotIn(Status.PENDING, Status.PROCESSING)); - assertThat(auth.getStatus(), is(Status.VALID)); + assertThat(auth.getStatus()).isEqualTo(Status.VALID); } CSRBuilder csr = new CSRBuilder(); @@ -198,21 +197,22 @@ public class OrderIT extends PebbleITBase { .pollInterval(1, SECONDS) .timeout(30, SECONDS) .conditionEvaluationListener(cond -> updateOrder(order)) - .until(order::getStatus, not(oneOf(Status.PENDING, Status.PROCESSING, Status.READY))); + .untilAsserted(() -> assertThat(order.getStatus()) + .isNotIn(Status.PENDING, Status.PROCESSING, Status.READY)); - assertThat(order.getStatus(), is(Status.VALID)); + assertThat(order.getStatus()).isEqualTo(Status.VALID); Certificate certificate = order.getCertificate(); X509Certificate cert = certificate.getCertificate(); - assertThat(cert, not(nullValue())); - assertThat(cert.getNotBefore().toInstant(), is(notBefore)); - assertThat(cert.getNotAfter().toInstant(), is(notAfter)); - assertThat(cert.getSubjectX500Principal().getName(), containsString("CN=" + domain)); + assertThat(cert).isNotNull(); + assertThat(cert.getNotBefore().toInstant()).isEqualTo(notBefore); + assertThat(cert.getNotAfter().toInstant()).isEqualTo(notAfter); + assertThat(cert.getSubjectX500Principal().getName()).contains("CN=" + domain); for (Authorization auth : order.getAuthorizations()) { - assertThat(auth.getStatus(), is(Status.VALID)); + assertThat(auth.getStatus()).isEqualTo(Status.VALID); auth.deactivate(); - assertThat(auth.getStatus(), is(Status.DEACTIVATED)); + assertThat(auth.getStatus()).isEqualTo(Status.DEACTIVATED); } revoker.revoke(session, certificate, keyPair, domainKeyPair); @@ -223,13 +223,13 @@ public class OrderIT extends PebbleITBase { Certificate cert2 = login2.bindCertificate(certificate.getLocation()); cert2.download(); }, "Could download revoked cert"); - assertThat(ex.getMessage(), is("HTTP 404: Not Found")); + assertThat(ex.getMessage()).isEqualTo("HTTP 404: Not Found"); // Try to revoke again AcmeServerException ex2 = assertThrows(AcmeServerException.class, () -> certificate.revoke(), "Could revoke again"); - assertThat(ex2.getProblem().getType(), is(URI.create("urn:ietf:params:acme:error:alreadyRevoked"))); + assertThat(ex2.getProblem().getType()).isEqualTo(URI.create("urn:ietf:params:acme:error:alreadyRevoked")); } /** diff --git a/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/OrderWildcardIT.java b/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/OrderWildcardIT.java index abd6c8d8..bf39ccf1 100644 --- a/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/OrderWildcardIT.java +++ b/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/OrderWildcardIT.java @@ -15,9 +15,8 @@ package org.shredzone.acme4j.it.pebble; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; import java.security.KeyPair; import java.security.cert.X509Certificate; @@ -73,20 +72,20 @@ public class OrderWildcardIT extends PebbleITBase { .notBefore(notBefore) .notAfter(notAfter) .create(); - assertThat(order.getNotBefore(), is(notBefore)); - assertThat(order.getNotAfter(), is(notAfter)); - assertThat(order.getStatus(), is(Status.PENDING)); + assertThat(order.getNotBefore()).isEqualTo(notBefore); + assertThat(order.getNotAfter()).isEqualTo(notAfter); + assertThat(order.getStatus()).isEqualTo(Status.PENDING); for (Authorization auth : order.getAuthorizations()) { - assertThat(auth.getIdentifier().getDomain(), is(TEST_DOMAIN)); - assertThat(auth.getStatus(), is(Status.PENDING)); + assertThat(auth.getIdentifier().getDomain()).isEqualTo(TEST_DOMAIN); + assertThat(auth.getStatus()).isEqualTo(Status.PENDING); if (auth.getStatus() == Status.VALID) { continue; } Dns01Challenge challenge = auth.findChallenge(Dns01Challenge.TYPE); - assertThat(challenge, is(notNullValue())); + assertThat(challenge).isNotNull(); String challengeDomainName = "_acme-challenge." + TEST_DOMAIN; @@ -99,9 +98,10 @@ public class OrderWildcardIT extends PebbleITBase { .pollInterval(1, SECONDS) .timeout(30, SECONDS) .conditionEvaluationListener(cond -> updateAuth(auth)) - .until(auth::getStatus, not(oneOf(Status.PENDING, Status.PROCESSING))); + .untilAsserted(() -> assertThat( + auth.getStatus()).isNotIn(Status.PENDING, Status.PROCESSING)); - assertThat(auth.getStatus(), is(Status.VALID)); + assertThat(auth.getStatus()).isEqualTo(Status.VALID); } CSRBuilder csr = new CSRBuilder(); @@ -116,21 +116,22 @@ public class OrderWildcardIT extends PebbleITBase { .pollInterval(1, SECONDS) .timeout(30, SECONDS) .conditionEvaluationListener(cond -> updateOrder(order)) - .until(order::getStatus, not(oneOf(Status.PENDING, Status.PROCESSING))); + .untilAsserted(() -> assertThat( + order.getStatus()).isNotIn(Status.PENDING, Status.PROCESSING)); Certificate certificate = order.getCertificate(); X509Certificate cert = certificate.getCertificate(); - assertThat(cert, not(nullValue())); - assertThat(cert.getNotAfter(), not(notBefore)); - assertThat(cert.getNotBefore(), not(notAfter)); - assertThat(cert.getSubjectX500Principal().getName(), containsString("CN=" + TEST_DOMAIN)); + assertThat(cert).isNotNull(); + assertThat(cert.getNotAfter()).isNotEqualTo(notBefore); + assertThat(cert.getNotBefore()).isNotEqualTo(notAfter); + assertThat(cert.getSubjectX500Principal().getName()).contains("CN=" + TEST_DOMAIN); List san = cert.getSubjectAlternativeNames().stream() .filter(it -> ((Number) it.get(0)).intValue() == GeneralName.dNSName) .map(it -> (String) it.get(1)) .collect(toList()); - assertThat(san, contains(TEST_DOMAIN, TEST_WILDCARD_DOMAIN)); + assertThat(san).contains(TEST_DOMAIN, TEST_WILDCARD_DOMAIN); } } diff --git a/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/PebbleITBase.java b/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/PebbleITBase.java index 0da8a17b..c13625bb 100644 --- a/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/PebbleITBase.java +++ b/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/PebbleITBase.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.it.pebble; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.net.URL; @@ -97,11 +96,11 @@ public abstract class PebbleITBase { * {@link URL} to assert */ protected void assertIsPebbleUrl(URL url) { - assertThat(url, not(nullValue())); - assertThat(url.getProtocol(), is("https")); - assertThat(url.getHost(), is(pebbleHost)); - assertThat(url.getPort(), is(pebblePort)); - assertThat(url.getPath(), not(emptyOrNullString())); + assertThat(url).isNotNull(); + assertThat(url.getProtocol()).isEqualTo("https"); + assertThat(url.getHost()).isEqualTo(pebbleHost); + assertThat(url.getPort()).isEqualTo(pebblePort); + assertThat(url.getPath()).isNotEmpty(); } /** diff --git a/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/SessionIT.java b/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/SessionIT.java index e67c8304..ee7d152c 100644 --- a/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/SessionIT.java +++ b/acme4j-it/src/test/java/org/shredzone/acme4j/it/pebble/SessionIT.java @@ -13,9 +13,8 @@ */ package org.shredzone.acme4j.it.pebble; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; +import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; @@ -44,15 +43,15 @@ public class SessionIT extends PebbleITBase { Session session = new Session(pebbleURI()); Metadata meta = session.getMetadata(); - assertThat(meta, not(nullValue())); + assertThat(meta).isNotNull(); - assertThat(meta.getTermsOfService(), is(URI.create("data:text/plain,Do%20what%20thou%20wilt"))); - assertThat(meta.getWebsite(), is(nullValue())); - assertThat(meta.getCaaIdentities(), is(empty())); - assertThat(meta.getJSON().toString(), sameJSONAs("{" + assertThat(meta.getTermsOfService()).isEqualTo(URI.create("data:text/plain,Do%20what%20thou%20wilt")); + assertThat(meta.getWebsite()).isNull(); + assertThat(meta.getCaaIdentities()).isEmpty(); + assertThatJson(meta.getJSON().toString()).isEqualTo("{" + "'termsOfService': 'data:text/plain,Do%20what%20thou%20wilt'," + "'externalAccountRequired': false" - + "}")); + + "}"); } } diff --git a/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/EmailIdentifierTest.java b/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/EmailIdentifierTest.java index 0257e1b2..cd10daed 100644 --- a/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/EmailIdentifierTest.java +++ b/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/EmailIdentifierTest.java @@ -13,12 +13,16 @@ */ package org.shredzone.acme4j.smime; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.stream.Stream; import jakarta.mail.internet.AddressException; import jakarta.mail.internet.InternetAddress; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests of {@link EmailIdentifier}. @@ -27,25 +31,27 @@ public class EmailIdentifierTest { @Test public void testConstants() { - assertThat(EmailIdentifier.TYPE_EMAIL, is("email")); + assertThat(EmailIdentifier.TYPE_EMAIL).isEqualTo("email"); } - @Test - public void testEmail() throws AddressException { - EmailIdentifier id1 = EmailIdentifier.email("email@example.com"); - assertThat(id1.getType(), is(EmailIdentifier.TYPE_EMAIL)); - assertThat(id1.getValue(), is("email@example.com")); - assertThat(id1.getEmailAddress().getAddress(), is("email@example.com")); + @ParameterizedTest + @MethodSource("provideTestEmails") + public void testEmail(Object input, String expected) { + EmailIdentifier id = input instanceof InternetAddress + ? EmailIdentifier.email((InternetAddress) input) + : EmailIdentifier.email(input.toString()); - EmailIdentifier id2 = EmailIdentifier.email(new InternetAddress("email@example.com")); - assertThat(id2.getType(), is(EmailIdentifier.TYPE_EMAIL)); - assertThat(id2.getValue(), is("email@example.com")); - assertThat(id2.getEmailAddress().getAddress(), is("email@example.com")); + assertThat(id.getType()).isEqualTo(EmailIdentifier.TYPE_EMAIL); + assertThat(id.getValue()).isEqualTo(expected); + assertThat(id.getEmailAddress().getAddress()).isEqualTo(expected); + } - EmailIdentifier id3 = EmailIdentifier.email(new InternetAddress("Example Corp ")); - assertThat(id3.getType(), is(EmailIdentifier.TYPE_EMAIL)); - assertThat(id3.getValue(), is("info@example.com")); - assertThat(id3.getEmailAddress().getAddress(), is("info@example.com")); + public static Stream provideTestEmails() throws AddressException { + return Stream.of( + Arguments.of("email@example.com", "email@example.com"), + Arguments.of(new InternetAddress("email@example.com"), "email@example.com"), + Arguments.of(new InternetAddress("Example Corp "), "info@example.com") + ); } } \ No newline at end of file diff --git a/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/challenge/EmailReply00ChallengeTest.java b/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/challenge/EmailReply00ChallengeTest.java index 5e93d656..d7046601 100644 --- a/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/challenge/EmailReply00ChallengeTest.java +++ b/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/challenge/EmailReply00ChallengeTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.smime.challenge; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.URI; @@ -40,8 +39,8 @@ public class EmailReply00ChallengeTest extends SMIMETests { AcmeProvider provider = new TestAcmeProvider(); Challenge challenge = provider.createChallenge(mockLogin(), getJSON("emailReplyChallenge")); - assertThat(challenge, not(nullValue())); - assertThat(challenge, instanceOf(EmailReply00Challenge.class)); + assertThat(challenge).isNotNull(); + assertThat(challenge).isInstanceOf(EmailReply00Challenge.class); } /** @@ -51,14 +50,14 @@ public class EmailReply00ChallengeTest extends SMIMETests { public void testEmailReplyChallenge() { EmailReply00Challenge challenge = new EmailReply00Challenge(mockLogin(), getJSON("emailReplyChallenge")); - assertThat(challenge.getType(), is(EmailReply00Challenge.TYPE)); - assertThat(challenge.getStatus(), is(Status.PENDING)); - assertThat(challenge.getToken(TOKEN_PART1), is(TOKEN_PART1 + TOKEN_PART2)); - assertThat(challenge.getTokenPart2(), is(TOKEN_PART2)); - assertThat(challenge.getAuthorization(TOKEN_PART1), is(KEY_AUTHORIZATION)); + assertThat(challenge.getType()).isEqualTo(EmailReply00Challenge.TYPE); + assertThat(challenge.getStatus()).isEqualTo(Status.PENDING); + assertThat(challenge.getToken(TOKEN_PART1)).isEqualTo(TOKEN_PART1 + TOKEN_PART2); + assertThat(challenge.getTokenPart2()).isEqualTo(TOKEN_PART2); + assertThat(challenge.getAuthorization(TOKEN_PART1)).isEqualTo(KEY_AUTHORIZATION); - assertThat(challenge.getFrom(), is("acme-generator@example.org")); - assertThat(challenge.getExpectedSender().getAddress(), is("acme-generator@example.org")); + assertThat(challenge.getFrom()).isEqualTo("acme-generator@example.org"); + assertThat(challenge.getExpectedSender().getAddress()).isEqualTo("acme-generator@example.org"); } /** diff --git a/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/csr/SMIMECSRBuilderTest.java b/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/csr/SMIMECSRBuilderTest.java index 767a09ad..d02f6d4b 100644 --- a/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/csr/SMIMECSRBuilderTest.java +++ b/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/csr/SMIMECSRBuilderTest.java @@ -14,8 +14,7 @@ package org.shredzone.acme4j.smime.csr; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.ByteArrayOutputStream; @@ -28,12 +27,12 @@ import java.util.Arrays; import jakarta.mail.internet.AddressException; import jakarta.mail.internet.InternetAddress; +import org.assertj.core.api.AutoCloseableSoftAssertions; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.pkcs.Attribute; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.asn1.x509.Extension; @@ -44,9 +43,6 @@ import org.bouncycastle.asn1.x509.KeyUsage; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.shredzone.acme4j.util.KeyPairUtils; @@ -88,18 +84,18 @@ public class SMIMECSRBuilderTest { builder.setOrganizationalUnit("Testunit"); builder.setState("ABC"); - assertThat(builder.toString(), is("CN=mail@example.com,C=XX,L=Testville," + assertThat(builder.toString()).isEqualTo("CN=mail@example.com,C=XX,L=Testville," + "O=Testing Co,OU=Testunit,ST=ABC," + "EMAIL=mail@example.com,EMAIL=info@example.com," + "EMAIL=sales@example.com,EMAIL=shop@example.com," + "EMAIL=support@example.com,EMAIL=help@example.com," - + "TYPE=SIGNING_AND_ENCRYPTION")); + + "TYPE=SIGNING_AND_ENCRYPTION"); builder.sign(testKey); PKCS10CertificationRequest csr = builder.getCSR(); - assertThat(csr, is(Matchers.notNullValue())); - assertThat(csr.getEncoded(), is(Matchers.equalTo(builder.getEncoded()))); + assertThat(csr).isNotNull(); + assertThat(csr.getEncoded()).isEqualTo(builder.getEncoded()); smimeCsrTest(csr); keyUsageTest(csr, KeyUsage.digitalSignature | KeyUsage.keyEncipherment); @@ -116,7 +112,7 @@ public class SMIMECSRBuilderTest { builder.setKeyUsageType(KeyUsageType.ENCRYPTION_ONLY); builder.sign(testKey); PKCS10CertificationRequest csr = builder.getCSR(); - assertThat(csr, is(Matchers.notNullValue())); + assertThat(csr).isNotNull(); keyUsageTest(csr, KeyUsage.keyEncipherment); } @@ -130,7 +126,7 @@ public class SMIMECSRBuilderTest { builder.setKeyUsageType(KeyUsageType.SIGNING_ONLY); builder.sign(testKey); PKCS10CertificationRequest csr = builder.getCSR(); - assertThat(csr, is(Matchers.notNullValue())); + assertThat(csr).isNotNull(); keyUsageTest(csr, KeyUsage.digitalSignature); } @@ -144,7 +140,7 @@ public class SMIMECSRBuilderTest { builder.setKeyUsageType(KeyUsageType.SIGNING_AND_ENCRYPTION); builder.sign(testKey); PKCS10CertificationRequest csr = builder.getCSR(); - assertThat(csr, is(Matchers.notNullValue())); + assertThat(csr).isNotNull(); keyUsageTest(csr, KeyUsage.digitalSignature | KeyUsage.keyEncipherment); } @@ -157,25 +153,41 @@ public class SMIMECSRBuilderTest { */ private void smimeCsrTest(PKCS10CertificationRequest csr) { X500Name name = csr.getSubject(); - assertThat(name.getRDNs(BCStyle.CN), Matchers.arrayContaining(new RDNMatcher("mail@example.com"))); - assertThat(name.getRDNs(BCStyle.C), Matchers.arrayContaining(new RDNMatcher("XX"))); - assertThat(name.getRDNs(BCStyle.L), Matchers.arrayContaining(new RDNMatcher("Testville"))); - assertThat(name.getRDNs(BCStyle.O), Matchers.arrayContaining(new RDNMatcher("Testing Co"))); - assertThat(name.getRDNs(BCStyle.OU), Matchers.arrayContaining(new RDNMatcher("Testunit"))); - assertThat(name.getRDNs(BCStyle.ST), Matchers.arrayContaining(new RDNMatcher("ABC"))); + + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(name.getRDNs(BCStyle.CN)).as("CN") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("mail@example.com"); + softly.assertThat(name.getRDNs(BCStyle.C)).as("C") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("XX"); + softly.assertThat(name.getRDNs(BCStyle.L)).as("L") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("Testville"); + softly.assertThat(name.getRDNs(BCStyle.O)).as("O") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("Testing Co"); + softly.assertThat(name.getRDNs(BCStyle.OU)).as("OU") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("Testunit"); + softly.assertThat(name.getRDNs(BCStyle.ST)).as("ST") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("ABC"); + } Attribute[] attr = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); - assertThat(attr.length, is(1)); + assertThat(attr).hasSize(1); + ASN1Encodable[] extensions = attr[0].getAttrValues().toArray(); - assertThat(extensions.length, is(1)); + assertThat(extensions).hasSize(1); + GeneralNames names = GeneralNames.fromExtensions((Extensions) extensions[0], Extension.subjectAlternativeName); - assertThat(names.getNames(), Matchers.arrayContaining( - new GeneralNameMatcher("mail@example.com", GeneralName.rfc822Name), - new GeneralNameMatcher("info@example.com", GeneralName.rfc822Name), - new GeneralNameMatcher("sales@example.com", GeneralName.rfc822Name), - new GeneralNameMatcher("shop@example.com", GeneralName.rfc822Name), - new GeneralNameMatcher("support@example.com", GeneralName.rfc822Name), - new GeneralNameMatcher("help@example.com", GeneralName.rfc822Name))); + assertThat(names.getNames()) + .filteredOn(gn -> gn.getTagNo() == GeneralName.rfc822Name) + .extracting(gn -> DERIA5String.getInstance(gn.getName()).getString()) + .containsExactlyInAnyOrder("mail@example.com", "info@example.com", + "sales@example.com", "shop@example.com", "support@example.com", + "help@example.com"); } /** @@ -189,14 +201,14 @@ public class SMIMECSRBuilderTest { */ private void keyUsageTest(PKCS10CertificationRequest csr, Integer expectedUsageBits) { Attribute[] attr = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); - assertThat(attr.length, is(1)); + assertThat(attr).hasSize(1); ASN1Encodable[] extensions = attr[0].getAttrValues().toArray(); - assertThat(extensions.length, is(1)); + assertThat(extensions).hasSize(1); DERBitString keyUsageBits = (DERBitString) ((Extensions) extensions[0]).getExtensionParsedValue(Extension.keyUsage); if (expectedUsageBits != null) { - assertThat(keyUsageBits.intValue(), is(expectedUsageBits)); + assertThat(keyUsageBits.intValue()).isEqualTo(expectedUsageBits); } else { - assertThat(keyUsageBits, is(Matchers.nullValue())); + assertThat(keyUsageBits).isNull(); } } @@ -213,10 +225,10 @@ public class SMIMECSRBuilderTest { } // Make sure PEM file is properly formatted - assertThat(pem, Matchers.matchesPattern( + assertThat(pem).matches( "-----BEGIN CERTIFICATE REQUEST-----[\\r\\n]+" + "([a-zA-Z0-9/+=]+[\\r\\n]+)+" - + "-----END CERTIFICATE REQUEST-----[\\r\\n]*")); + + "-----END CERTIFICATE REQUEST-----[\\r\\n]*"); // Read CSR from PEM PKCS10CertificationRequest readCsr; @@ -225,8 +237,8 @@ public class SMIMECSRBuilderTest { } // Verify that both keypairs are the same - assertThat(builder.getCSR(), Matchers.not(Matchers.sameInstance(readCsr))); - assertThat(builder.getEncoded(), is(Matchers.equalTo(readCsr.getEncoded()))); + assertThat(builder.getCSR()).isNotSameAs(readCsr); + assertThat(builder.getEncoded()).isEqualTo(readCsr.getEncoded()); // OutputStream is identical? byte[] pemBytes; @@ -234,7 +246,7 @@ public class SMIMECSRBuilderTest { builder.write(baos); pemBytes = baos.toByteArray(); } - assertThat(new String(pemBytes, UTF_8), is(Matchers.equalTo(pem))); + assertThat(new String(pemBytes, UTF_8)).isEqualTo(pem); } /** @@ -264,89 +276,4 @@ public class SMIMECSRBuilderTest { },"write"); } - /** - * Matches {@link RDN} values. - */ - private static class RDNMatcher extends BaseMatcher { - private final String expectedValue; - - public RDNMatcher(String expectedValue) { - this.expectedValue = expectedValue; - } - - @Override - public boolean matches(Object item) { - if (!(item instanceof RDN)) { - return false; - } - return expectedValue.equals(((RDN) item).getFirst().getValue().toString()); - } - - @Override - public void describeTo(Description description) { - description.appendValue(expectedValue); - } - - @Override - public void describeMismatch(Object item, Description description) { - if (!(item instanceof RDN)) { - description.appendText("is a ").appendValue(item.getClass()); - } else { - description.appendText("was ").appendValue(((RDN) item).getFirst().getValue()); - } - } - } - - /** - * Matches {@link GeneralName} DNS tagged values. - */ - private static class GeneralNameMatcher extends BaseMatcher { - private final String expectedValue; - private final int expectedTag; - - public GeneralNameMatcher(String expectedValue, int expectedTag) { - this.expectedTag = expectedTag; - this.expectedValue = expectedValue; - } - - @Override - public boolean matches(Object item) { - if (!(item instanceof GeneralName)) { - return false; - } - - GeneralName gn = (GeneralName) item; - - if (gn.getTagNo() != expectedTag) { - return false; - } - - if (gn.getTagNo() == GeneralName.rfc822Name) { - return expectedValue.equals(DERIA5String.getInstance(gn.getName()).getString()); - } - - return false; - } - - @Override - public void describeTo(Description description) { - description.appendValue(expectedValue); - } - - @Override - public void describeMismatch(Object item, Description description) { - if (!(item instanceof GeneralName)) { - description.appendText("is a ").appendValue(item.getClass()); - return; - } - - GeneralName gn = (GeneralName) item; - if (gn.getTagNo() == GeneralName.rfc822Name) { - description.appendText("was EMAIL ").appendValue(DERIA5String.getInstance(gn.getName()).getString()); - } else { - description.appendText("is not EMAIL, but has tag " + gn.getTagNo()); - } - } - } - } diff --git a/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/email/EmailProcessorTest.java b/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/email/EmailProcessorTest.java index 698fbcfe..5d3f5ff9 100644 --- a/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/email/EmailProcessorTest.java +++ b/acme4j-smime/src/test/java/org/shredzone/acme4j/smime/email/EmailProcessorTest.java @@ -14,8 +14,7 @@ package org.shredzone.acme4j.smime.email; import static jakarta.mail.Message.RecipientType.TO; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; @@ -49,11 +48,11 @@ public class EmailProcessorTest extends SMIMETests { processor.expectedIdentifier(EmailIdentifier.email(expectedTo)); processor.expectedIdentifier(new Identifier("email", expectedTo.getAddress())); - assertThat(processor.getSender(), is(expectedFrom)); - assertThat(processor.getRecipient(), is(expectedTo)); - assertThat(processor.getMessageId(), is(Optional.of(""))); - assertThat(processor.getToken1(), is(TOKEN_PART1)); - assertThat(processor.getReplyTo(), contains(email("acme-validator@example.org"))); + assertThat(processor.getSender()).isEqualTo(expectedFrom); + assertThat(processor.getRecipient()).isEqualTo(expectedTo); + assertThat(processor.getMessageId()).isEqualTo(Optional.of("")); + assertThat(processor.getToken1()).isEqualTo(TOKEN_PART1); + assertThat(processor.getReplyTo()).contains(email("acme-validator@example.org")); } @Test @@ -118,9 +117,9 @@ public class EmailProcessorTest extends SMIMETests { EmailProcessor processor = new EmailProcessor(message); processor.withChallenge(challenge); - assertThat(processor.getToken(), is(TOKEN)); - assertThat(processor.getAuthorization(), is(KEY_AUTHORIZATION)); - assertThat(processor.respond(), is(notNullValue())); + assertThat(processor.getToken()).isEqualTo(TOKEN); + assertThat(processor.getAuthorization()).isEqualTo(KEY_AUTHORIZATION); + assertThat(processor.respond()).isNotNull(); } @Test @@ -176,22 +175,22 @@ public class EmailProcessorTest extends SMIMETests { private void assertResponse(Message response, String expectedBody) throws MessagingException, IOException { - assertThat(response.getContentType(), is("text/plain")); - assertThat(response.getContent().toString(), is(expectedBody)); + assertThat(response.getContentType()).isEqualTo("text/plain"); + assertThat(response.getContent().toString()).isEqualTo(expectedBody); // This is a response, so the expected sender is the recipient of the challenge - assertThat(response.getFrom().length, is(1)); - assertThat(response.getFrom()[0], is(expectedTo)); + assertThat(response.getFrom()).hasSize(1); + assertThat(response.getFrom()[0]).isEqualTo(expectedTo); // There is a Reply-To header, so we expect the mail to go only there - assertThat(response.getRecipients(TO).length, is(1)); - assertThat(response.getRecipients(TO)[0], is(expectedReplyTo)); + assertThat(response.getRecipients(TO)).hasSize(1); + assertThat(response.getRecipients(TO)[0]).isEqualTo(expectedReplyTo); - assertThat(response.getSubject(), is("Re: ACME: " + TOKEN_PART1)); + assertThat(response.getSubject()).isEqualTo("Re: ACME: " + TOKEN_PART1); String[] inReplyToHeader = response.getHeader("In-Reply-To"); - assertThat(inReplyToHeader.length, is(1)); - assertThat(inReplyToHeader[0], is("")); + assertThat(inReplyToHeader).hasSize(1); + assertThat(inReplyToHeader[0]).isEqualTo(""); } } diff --git a/acme4j-utils/src/test/java/org/shredzone/acme4j/util/CSRBuilderTest.java b/acme4j-utils/src/test/java/org/shredzone/acme4j/util/CSRBuilderTest.java index afb5ab50..ce56852a 100644 --- a/acme4j-utils/src/test/java/org/shredzone/acme4j/util/CSRBuilderTest.java +++ b/acme4j-utils/src/test/java/org/shredzone/acme4j/util/CSRBuilderTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.util; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.ByteArrayOutputStream; @@ -28,12 +27,12 @@ import java.security.KeyPair; import java.security.Security; import java.util.Arrays; +import org.assertj.core.api.AutoCloseableSoftAssertions; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.pkcs.Attribute; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.asn1.x509.Extension; @@ -43,8 +42,6 @@ import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.shredzone.acme4j.Identifier; @@ -91,19 +88,19 @@ public class CSRBuilderTest { builder.setOrganizationalUnit("Testunit"); builder.setState("ABC"); - assertThat(builder.toString(), is("CN=abc.de,C=XX,L=Testville,O=Testing Co," + assertThat(builder.toString()).isEqualTo("CN=abc.de,C=XX,L=Testville,O=Testing Co," + "OU=Testunit,ST=ABC," + "DNS=abc.de,DNS=fg.hi,DNS=jklm.no,DNS=pqr.st,DNS=uv.wx,DNS=y.z,DNS=*.wild.card," + "DNS=ide1.nt,DNS=ide2.nt,DNS=ide3.nt," + "IP=192.168.0.1,IP=192.168.0.2,IP=10.0.0.1,IP=10.0.0.2," + "IP=fd00:0:0:0:0:0:0:1,IP=fd00:0:0:0:0:0:0:2," - + "IP=192.168.5.5,IP=192.168.5.6,IP=192.168.5.7")); + + "IP=192.168.5.5,IP=192.168.5.6,IP=192.168.5.7"); builder.sign(testKey); PKCS10CertificationRequest csr = builder.getCSR(); - assertThat(csr, is(notNullValue())); - assertThat(csr.getEncoded(), is(equalTo(builder.getEncoded()))); + assertThat(csr).isNotNull(); + assertThat(csr.getEncoded()).isEqualTo(builder.getEncoded()); csrTest(csr); writerTest(builder); @@ -135,19 +132,19 @@ public class CSRBuilderTest { builder.setOrganizationalUnit("Testunit"); builder.setState("ABC"); - assertThat(builder.toString(), is("CN=abc.de,C=XX,L=Testville,O=Testing Co," + assertThat(builder.toString()).isEqualTo("CN=abc.de,C=XX,L=Testville,O=Testing Co," + "OU=Testunit,ST=ABC," + "DNS=abc.de,DNS=fg.hi,DNS=jklm.no,DNS=pqr.st,DNS=uv.wx,DNS=y.z,DNS=*.wild.card," + "DNS=ide1.nt,DNS=ide2.nt,DNS=ide3.nt," + "IP=192.168.0.1,IP=192.168.0.2,IP=10.0.0.1,IP=10.0.0.2," + "IP=fd00:0:0:0:0:0:0:1,IP=fd00:0:0:0:0:0:0:2," - + "IP=192.168.5.5,IP=192.168.5.6,IP=192.168.5.7")); + + "IP=192.168.5.5,IP=192.168.5.6,IP=192.168.5.7"); builder.sign(testEcKey); PKCS10CertificationRequest csr = builder.getCSR(); - assertThat(csr, is(notNullValue())); - assertThat(csr.getEncoded(), is(equalTo(builder.getEncoded()))); + assertThat(csr).isNotNull(); + assertThat(csr.getEncoded()).isEqualTo(builder.getEncoded()); csrTest(csr); writerTest(builder); @@ -162,38 +159,46 @@ public class CSRBuilderTest { */ private void csrTest(PKCS10CertificationRequest csr) { X500Name name = csr.getSubject(); - assertThat(name.getRDNs(BCStyle.CN), arrayContaining(new RDNMatcher("abc.de"))); - assertThat(name.getRDNs(BCStyle.C), arrayContaining(new RDNMatcher("XX"))); - assertThat(name.getRDNs(BCStyle.L), arrayContaining(new RDNMatcher("Testville"))); - assertThat(name.getRDNs(BCStyle.O), arrayContaining(new RDNMatcher("Testing Co"))); - assertThat(name.getRDNs(BCStyle.OU), arrayContaining(new RDNMatcher("Testunit"))); - assertThat(name.getRDNs(BCStyle.ST), arrayContaining(new RDNMatcher("ABC"))); + try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { + softly.assertThat(name.getRDNs(BCStyle.CN)).as("CN") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("abc.de"); + softly.assertThat(name.getRDNs(BCStyle.C)).as("C") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("XX"); + softly.assertThat(name.getRDNs(BCStyle.L)).as("L") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("Testville"); + softly.assertThat(name.getRDNs(BCStyle.O)).as("O") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("Testing Co"); + softly.assertThat(name.getRDNs(BCStyle.OU)).as("OU") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("Testunit"); + softly.assertThat(name.getRDNs(BCStyle.ST)).as("ST") + .extracting(rdn -> rdn.getFirst().getValue().toString()) + .contains("ABC"); + } Attribute[] attr = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); - assertThat(attr.length, is(1)); + assertThat(attr).hasSize(1); + ASN1Encodable[] extensions = attr[0].getAttrValues().toArray(); - assertThat(extensions.length, is(1)); + assertThat(extensions).hasSize(1); + GeneralNames names = GeneralNames.fromExtensions((Extensions) extensions[0], Extension.subjectAlternativeName); - assertThat(names.getNames(), arrayContaining( - new GeneralNameMatcher("abc.de", GeneralName.dNSName), - new GeneralNameMatcher("fg.hi", GeneralName.dNSName), - new GeneralNameMatcher("jklm.no", GeneralName.dNSName), - new GeneralNameMatcher("pqr.st", GeneralName.dNSName), - new GeneralNameMatcher("uv.wx", GeneralName.dNSName), - new GeneralNameMatcher("y.z", GeneralName.dNSName), - new GeneralNameMatcher("*.wild.card", GeneralName.dNSName), - new GeneralNameMatcher("ide1.nt", GeneralName.dNSName), - new GeneralNameMatcher("ide2.nt", GeneralName.dNSName), - new GeneralNameMatcher("ide3.nt", GeneralName.dNSName), - new GeneralNameMatcher("192.168.0.1", GeneralName.iPAddress), - new GeneralNameMatcher("192.168.0.2", GeneralName.iPAddress), - new GeneralNameMatcher("10.0.0.1", GeneralName.iPAddress), - new GeneralNameMatcher("10.0.0.2", GeneralName.iPAddress), - new GeneralNameMatcher("fd00:0:0:0:0:0:0:1", GeneralName.iPAddress), - new GeneralNameMatcher("fd00:0:0:0:0:0:0:2", GeneralName.iPAddress), - new GeneralNameMatcher("192.168.5.5", GeneralName.iPAddress), - new GeneralNameMatcher("192.168.5.6", GeneralName.iPAddress), - new GeneralNameMatcher("192.168.5.7", GeneralName.iPAddress))); + assertThat(names.getNames()) + .filteredOn(gn -> gn.getTagNo() == GeneralName.dNSName) + .extracting(gn -> DERIA5String.getInstance(gn.getName()).getString()) + .containsExactlyInAnyOrder("abc.de", "fg.hi", "jklm.no", "pqr.st", + "uv.wx", "y.z", "*.wild.card", "ide1.nt", "ide2.nt", "ide3.nt"); + + assertThat(names.getNames()) + .filteredOn(gn -> gn.getTagNo() == GeneralName.iPAddress) + .extracting(gn -> getIP(gn.getName()).getHostAddress()) + .containsExactlyInAnyOrder("192.168.0.1", "192.168.0.2", "10.0.0.1", + "10.0.0.2", "fd00:0:0:0:0:0:0:1", "fd00:0:0:0:0:0:0:2", + "192.168.5.5", "192.168.5.6", "192.168.5.7"); } /** @@ -209,10 +214,10 @@ public class CSRBuilderTest { } // Make sure PEM file is properly formatted - assertThat(pem, matchesPattern( + assertThat(pem).matches( "-----BEGIN CERTIFICATE REQUEST-----[\\r\\n]+" + "([a-zA-Z0-9/+=]+[\\r\\n]+)+" - + "-----END CERTIFICATE REQUEST-----[\\r\\n]*")); + + "-----END CERTIFICATE REQUEST-----[\\r\\n]*"); // Read CSR from PEM PKCS10CertificationRequest readCsr; @@ -221,8 +226,8 @@ public class CSRBuilderTest { } // Verify that both keypairs are the same - assertThat(builder.getCSR(), not(sameInstance(readCsr))); - assertThat(builder.getEncoded(), is(equalTo(readCsr.getEncoded()))); + assertThat(builder.getCSR()).isNotSameAs(readCsr); + assertThat(builder.getEncoded()).isEqualTo(readCsr.getEncoded()); // OutputStream is identical? byte[] pemBytes; @@ -230,7 +235,7 @@ public class CSRBuilderTest { builder.write(baos); pemBytes = baos.toByteArray(); } - assertThat(new String(pemBytes, StandardCharsets.UTF_8), is(equalTo(pem))); + assertThat(new String(pemBytes, StandardCharsets.UTF_8)).isEqualTo(pem); } /** @@ -272,110 +277,19 @@ public class CSRBuilderTest { } /** - * Matches {@link RDN} values. + * Fetches the {@link InetAddress} from the given iPAddress record. + * + * @param name + * Name to convert + * @return {@link InetAddress} + * @throws IllegalArgumentException + * if the IP address could not be read */ - private static class RDNMatcher extends BaseMatcher { - private final String expectedValue; - - public RDNMatcher(String expectedValue) { - this.expectedValue = expectedValue; - } - - @Override - public boolean matches(Object item) { - if (!(item instanceof RDN)) { - return false; - } - return expectedValue.equals(((RDN) item).getFirst().getValue().toString()); - } - - @Override - public void describeTo(Description description) { - description.appendValue(expectedValue); - } - - @Override - public void describeMismatch(Object item, Description description) { - if (!(item instanceof RDN)) { - description.appendText("is a ").appendValue(item.getClass()); - } else { - description.appendText("was ").appendValue(((RDN) item).getFirst().getValue()); - } - } - } - - /** - * Matches {@link GeneralName} DNS tagged values. - */ - private static class GeneralNameMatcher extends BaseMatcher { - private final String expectedValue; - private final int expectedTag; - - public GeneralNameMatcher(String expectedValue, int expectedTag) { - this.expectedTag = expectedTag; - this.expectedValue = expectedValue; - } - - @Override - public boolean matches(Object item) { - if (!(item instanceof GeneralName)) { - return false; - } - - GeneralName gn = (GeneralName) item; - - if (gn.getTagNo() != expectedTag) { - return false; - } - - if (gn.getTagNo() == GeneralName.dNSName) { - return expectedValue.equals(DERIA5String.getInstance(gn.getName()).getString()); - } - - if (gn.getTagNo() == GeneralName.iPAddress) { - return expectedValue.equals(getIP(gn.getName()).getHostAddress()); - } - - return false; - } - - @Override - public void describeTo(Description description) { - description.appendValue(expectedValue); - } - - @Override - public void describeMismatch(Object item, Description description) { - if (!(item instanceof GeneralName)) { - description.appendText("is a ").appendValue(item.getClass()); - return; - } - - GeneralName gn = (GeneralName) item; - if (gn.getTagNo() == GeneralName.dNSName) { - description.appendText("was DNS ").appendValue(DERIA5String.getInstance(gn.getName()).getString()); - } else if (gn.getTagNo() == GeneralName.iPAddress) { - description.appendText("was IP ").appendValue(getIP(gn.getName()).getHostAddress()); - } else { - description.appendText("is neither DNS nor IP, but has tag " + gn.getTagNo()); - } - } - - /** - * Fetches the {@link InetAddress} from the given iPAddress record. - * - * @param name - * Name to convert - * @return {@link InetAddress} - * @throws IllegalArgumentException - * if the IP address could not be read - */ - private InetAddress getIP(ASN1Encodable name) { - try { - return InetAddress.getByAddress(DEROctetString.getInstance(name).getOctets()); - } catch (UnknownHostException ex) { - throw new IllegalArgumentException(ex); - } + private static InetAddress getIP(ASN1Encodable name) { + try { + return InetAddress.getByAddress(DEROctetString.getInstance(name).getOctets()); + } catch (UnknownHostException ex) { + throw new IllegalArgumentException(ex); } } diff --git a/acme4j-utils/src/test/java/org/shredzone/acme4j/util/CertificateUtilsTest.java b/acme4j-utils/src/test/java/org/shredzone/acme4j/util/CertificateUtilsTest.java index a26e5998..f7f57e41 100644 --- a/acme4j-utils/src/test/java/org/shredzone/acme4j/util/CertificateUtilsTest.java +++ b/acme4j-utils/src/test/java/org/shredzone/acme4j/util/CertificateUtilsTest.java @@ -14,8 +14,7 @@ package org.shredzone.acme4j.util; import static java.time.temporal.ChronoUnit.SECONDS; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -72,7 +71,7 @@ public class CertificateUtilsTest { try (ByteArrayInputStream bais = new ByteArrayInputStream(pemFile)) { PKCS10CertificationRequest read = CertificateUtils.readCSR(bais); - assertThat(original.getEncoded(), is(equalTo(read.getEncoded()))); + assertThat(original.getEncoded()).isEqualTo(read.getEncoded()); } } @@ -82,7 +81,7 @@ public class CertificateUtilsTest { @Test public void testPrivateConstructor() throws Exception { Constructor constructor = CertificateUtils.class.getDeclaredConstructor(); - assertThat(Modifier.isPrivate(constructor.getModifiers()), is(true)); + assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); constructor.setAccessible(true); constructor.newInstance(); } @@ -103,18 +102,18 @@ public class CertificateUtilsTest { Instant now = Instant.now(); Instant end = now.plus(Duration.ofDays(8)); - assertThat(cert, not(nullValue())); - assertThat(cert.getNotAfter(), is(greaterThan(Date.from(now)))); - assertThat(cert.getNotAfter(), is(lessThan(Date.from(end)))); - assertThat(cert.getNotBefore(), is(lessThanOrEqualTo(Date.from(now)))); + assertThat(cert).isNotNull(); + assertThat(cert.getNotAfter()).isAfter(Date.from(now)); + assertThat(cert.getNotAfter()).isBefore(Date.from(end)); + assertThat(cert.getNotBefore()).isBeforeOrEqualTo(Date.from(now)); - assertThat(cert.getSubjectX500Principal().getName(), is("CN=acme.invalid")); - assertThat(getSANs(cert), contains(subject)); + assertThat(cert.getSubjectX500Principal().getName()).isEqualTo("CN=acme.invalid"); + assertThat(getSANs(cert)).contains(subject); - assertThat(cert.getCriticalExtensionOIDs(), hasItem(TlsAlpn01Challenge.ACME_VALIDATION_OID)); + assertThat(cert.getCriticalExtensionOIDs()).contains(TlsAlpn01Challenge.ACME_VALIDATION_OID); byte[] encodedExtensionValue = cert.getExtensionValue(TlsAlpn01Challenge.ACME_VALIDATION_OID); - assertThat(encodedExtensionValue, is(notNullValue())); + assertThat(encodedExtensionValue).isNotNull(); try (ASN1InputStream asn = new ASN1InputStream(new ByteArrayInputStream(encodedExtensionValue))) { DEROctetString derOctetString = (DEROctetString) asn.readObject(); @@ -124,7 +123,7 @@ public class CertificateUtilsTest { test[1] = (byte) acmeValidationV1.length; System.arraycopy(acmeValidationV1, 0, test, 2, acmeValidationV1.length); - assertThat(derOctetString.getOctets(), is(test)); + assertThat(derOctetString.getOctets()).isEqualTo(test); } } @@ -141,8 +140,8 @@ public class CertificateUtilsTest { X509Certificate cert = CertificateUtils.createTlsAlpn01Certificate(keypair, Identifier.ip(subject), acmeValidationV1); - assertThat(cert.getSubjectX500Principal().getName(), is("CN=acme.invalid")); - assertThat(getIpSANs(cert), contains(subject)); + assertThat(cert.getSubjectX500Principal().getName()).isEqualTo("CN=acme.invalid"); + assertThat(getIpSANs(cert)).contains(subject); } /** @@ -159,12 +158,12 @@ public class CertificateUtilsTest { X509Certificate cert = CertificateUtils.createTestRootCertificate(subject, notBefore, notAfter, keypair); - assertThat(cert.getIssuerX500Principal().getName(), is(subject)); - assertThat(cert.getSubjectX500Principal().getName(), is(subject)); - assertThat(cert.getNotBefore().toInstant(), is(notBefore)); - assertThat(cert.getNotAfter().toInstant(), is(notAfter)); - assertThat(cert.getSerialNumber(), not(nullValue())); - assertThat(cert.getPublicKey(), is(keypair.getPublic())); + assertThat(cert.getIssuerX500Principal().getName()).isEqualTo(subject); + assertThat(cert.getSubjectX500Principal().getName()).isEqualTo(subject); + assertThat(cert.getNotBefore().toInstant()).isEqualTo(notBefore); + assertThat(cert.getNotAfter().toInstant()).isEqualTo(notAfter); + assertThat(cert.getSerialNumber()).isNotNull(); + assertThat(cert.getPublicKey()).isEqualTo(keypair.getPublic()); cert.verify(cert.getPublicKey()); // self-signed } @@ -191,13 +190,13 @@ public class CertificateUtilsTest { X509Certificate cert = CertificateUtils.createTestIntermediateCertificate(subject, notBefore, notAfter, keypair.getPublic(), rootCert, rootKeypair.getPrivate()); - assertThat(cert.getIssuerX500Principal().getName(), is(rootSubject)); - assertThat(cert.getSubjectX500Principal().getName(), is(subject)); - assertThat(cert.getNotBefore().toInstant(), is(notBefore)); - assertThat(cert.getNotAfter().toInstant(), is(notAfter)); - assertThat(cert.getSerialNumber(), not(nullValue())); - assertThat(cert.getSerialNumber(), not(rootCert.getSerialNumber())); - assertThat(cert.getPublicKey(), is(keypair.getPublic())); + assertThat(cert.getIssuerX500Principal().getName()).isEqualTo(rootSubject); + assertThat(cert.getSubjectX500Principal().getName()).isEqualTo(subject); + assertThat(cert.getNotBefore().toInstant()).isEqualTo(notBefore); + assertThat(cert.getNotAfter().toInstant()).isEqualTo(notAfter); + assertThat(cert.getSerialNumber()).isNotNull(); + assertThat(cert.getSerialNumber()).isNotEqualTo(rootCert.getSerialNumber()); + assertThat(cert.getPublicKey()).isEqualTo(keypair.getPublic()); cert.verify(rootKeypair.getPublic()); // signed by root } @@ -228,15 +227,15 @@ public class CertificateUtilsTest { X509Certificate cert = CertificateUtils.createTestCertificate(csr, notBefore, notAfter, rootCert, rootKeypair.getPrivate()); - assertThat(cert.getIssuerX500Principal().getName(), is(rootSubject)); - assertThat(cert.getSubjectX500Principal().getName(), is("CN=example.org")); - assertThat(getSANs(cert), contains("example.org", "www.example.org")); - assertThat(getIpSANs(cert), contains(InetAddress.getByName("192.168.0.1"))); - assertThat(cert.getNotBefore().toInstant(), is(notBefore)); - assertThat(cert.getNotAfter().toInstant(), is(notAfter)); - assertThat(cert.getSerialNumber(), not(nullValue())); - assertThat(cert.getSerialNumber(), not(rootCert.getSerialNumber())); - assertThat(cert.getPublicKey(), is(keypair.getPublic())); + assertThat(cert.getIssuerX500Principal().getName()).isEqualTo(rootSubject); + assertThat(cert.getSubjectX500Principal().getName()).isEqualTo("CN=example.org"); + assertThat(getSANs(cert)).contains("example.org", "www.example.org"); + assertThat(getIpSANs(cert)).contains(InetAddress.getByName("192.168.0.1")); + assertThat(cert.getNotBefore().toInstant()).isEqualTo(notBefore); + assertThat(cert.getNotAfter().toInstant()).isEqualTo(notAfter); + assertThat(cert.getSerialNumber()).isNotNull(); + assertThat(cert.getSerialNumber()).isNotEqualTo(rootCert.getSerialNumber()); + assertThat(cert.getPublicKey()).isEqualTo(keypair.getPublic()); cert.verify(rootKeypair.getPublic()); // signed by root } diff --git a/acme4j-utils/src/test/java/org/shredzone/acme4j/util/KeyPairUtilsTest.java b/acme4j-utils/src/test/java/org/shredzone/acme4j/util/KeyPairUtilsTest.java index b54be903..9a03bdf8 100644 --- a/acme4j-utils/src/test/java/org/shredzone/acme4j/util/KeyPairUtilsTest.java +++ b/acme4j-utils/src/test/java/org/shredzone/acme4j/util/KeyPairUtilsTest.java @@ -13,8 +13,7 @@ */ package org.shredzone.acme4j.util; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.io.StringReader; @@ -48,11 +47,11 @@ public class KeyPairUtilsTest { @Test public void testCreateStandardKeyPair() { KeyPair pair = KeyPairUtils.createKeyPair(); - assertThat(pair, is(notNullValue())); - assertThat(pair.getPublic(), is(instanceOf(ECPublicKey.class))); + assertThat(pair).isNotNull(); + assertThat(pair.getPublic()).isInstanceOf(ECPublicKey.class); ECPublicKey pk = (ECPublicKey) pair.getPublic(); - assertThat(pk.getAlgorithm(), is("ECDSA")); - assertThat(pk.getParams().getCurve().getField().getFieldSize(), is(384)); + assertThat(pk.getAlgorithm()).isEqualTo("ECDSA"); + assertThat(pk.getParams().getCurve().getField().getFieldSize()).isEqualTo(384); } /** @@ -61,11 +60,11 @@ public class KeyPairUtilsTest { @Test public void testCreateKeyPair() { KeyPair pair = KeyPairUtils.createKeyPair(KEY_SIZE); - assertThat(pair, is(notNullValue())); - assertThat(pair.getPublic(), is(instanceOf(RSAPublicKey.class))); + assertThat(pair).isNotNull(); + assertThat(pair.getPublic()).isInstanceOf(RSAPublicKey.class); RSAPublicKey pub = (RSAPublicKey) pair.getPublic(); - assertThat(pub.getModulus().bitLength(), is(KEY_SIZE)); + assertThat(pub.getModulus().bitLength()).isEqualTo(KEY_SIZE); } /** @@ -84,10 +83,10 @@ public class KeyPairUtilsTest { } // Make sure PEM file is properly formatted - assertThat(pem, matchesPattern( + assertThat(pem).matches( "-----BEGIN RSA PRIVATE KEY-----[\\r\\n]+" + "([a-zA-Z0-9/+=]+[\\r\\n]+)+" - + "-----END RSA PRIVATE KEY-----[\\r\\n]*")); + + "-----END RSA PRIVATE KEY-----[\\r\\n]*"); // Read keypair from PEM KeyPair readPair; @@ -96,9 +95,9 @@ public class KeyPairUtilsTest { } // Verify that both keypairs are the same - assertThat(pair, not(sameInstance(readPair))); - assertThat(pair.getPublic().getEncoded(), is(equalTo(readPair.getPublic().getEncoded()))); - assertThat(pair.getPrivate().getEncoded(), is(equalTo(readPair.getPrivate().getEncoded()))); + assertThat(pair).isNotSameAs(readPair); + assertThat(pair.getPublic().getEncoded()).isEqualTo(readPair.getPublic().getEncoded()); + assertThat(pair.getPrivate().getEncoded()).isEqualTo(readPair.getPrivate().getEncoded()); } /** @@ -107,8 +106,8 @@ public class KeyPairUtilsTest { @Test public void testCreateECCKeyPair() { KeyPair pair = KeyPairUtils.createECKeyPair(EC_CURVE); - assertThat(pair, is(notNullValue())); - assertThat(pair.getPublic(), is(instanceOf(ECPublicKey.class))); + assertThat(pair).isNotNull(); + assertThat(pair.getPublic()).isInstanceOf(ECPublicKey.class); } /** @@ -127,10 +126,10 @@ public class KeyPairUtilsTest { } // Make sure PEM file is properly formatted - assertThat(pem, matchesPattern( + assertThat(pem).matches( "-----BEGIN EC PRIVATE KEY-----[\\r\\n]+" + "([a-zA-Z0-9/+=]+[\\r\\n]+)+" - + "-----END EC PRIVATE KEY-----[\\r\\n]*")); + + "-----END EC PRIVATE KEY-----[\\r\\n]*"); // Read keypair from PEM KeyPair readPair; @@ -139,9 +138,9 @@ public class KeyPairUtilsTest { } // Verify that both keypairs are the same - assertThat(pair, not(sameInstance(readPair))); - assertThat(pair.getPublic().getEncoded(), is(equalTo(readPair.getPublic().getEncoded()))); - assertThat(pair.getPrivate().getEncoded(), is(equalTo(readPair.getPrivate().getEncoded()))); + assertThat(pair).isNotSameAs(readPair); + assertThat(pair.getPublic().getEncoded()).isEqualTo(readPair.getPublic().getEncoded()); + assertThat(pair.getPrivate().getEncoded()).isEqualTo(readPair.getPrivate().getEncoded()); } /** @@ -150,7 +149,7 @@ public class KeyPairUtilsTest { @Test public void testPrivateConstructor() throws Exception { Constructor constructor = KeyPairUtils.class.getDeclaredConstructor(); - assertThat(Modifier.isPrivate(constructor.getModifiers()), is(true)); + assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); constructor.setAccessible(true); constructor.newInstance(); } diff --git a/pom.xml b/pom.xml index 4dc136f7..e32f7048 100644 --- a/pom.xml +++ b/pom.xml @@ -209,16 +209,28 @@ test - org.hamcrest - hamcrest - 2.2 + org.junit.jupiter + junit-jupiter-params + 5.8.2 test - - uk.co.datumedge - hamcrest-json - 0.2 + org.assertj + assertj-core + 3.19.0 + test + + + net.javacrumbs.json-unit + json-unit-assertj + 2.35.0 + test + + + + org.json + json + 20220320 test