From 65bc78d3d74397638b33b9a2fe231e94a42a88c9 Mon Sep 17 00:00:00 2001 From: napoly Date: Sat, 25 Mar 2023 18:11:58 +0100 Subject: [PATCH] moving away from JUnit 4 completely to JUnit 5 Jupiter --- .../test/java/haveno/apitest/JUnitHelper.java | 57 -- .../java/haveno/asset/AbstractAssetTest.java | 4 +- .../haveno/asset/coins/BitcoinCashTest.java | 2 +- .../java/haveno/asset/coins/BitcoinTest.java | 2 +- .../java/haveno/asset/coins/LitecoinTest.java | 2 +- .../java/haveno/asset/coins/MoneroTest.java | 2 +- build.gradle | 34 +- .../haveno/common/app/CapabilitiesTest.java | 8 +- .../java/haveno/common/app/VersionTest.java | 8 +- .../common/config/ConfigFileEditorTests.java | 12 +- .../common/config/ConfigFileOptionTests.java | 2 +- .../common/config/ConfigFileReaderTests.java | 26 +- .../haveno/common/config/ConfigTests.java | 109 ++-- .../haveno/common/util/MathUtilsTest.java | 19 +- .../haveno/common/util/PermutationTest.java | 4 +- .../common/util/PreconditionsTests.java | 28 +- .../haveno/common/util/UtilitiesTest.java | 6 +- .../sign/SignedWitnessServiceTest.java | 10 +- .../core/account/sign/SignedWitnessTest.java | 10 +- .../witness/AccountAgeWitnessServiceTest.java | 24 +- .../core/app/HavenoHelpFormatterTest.java | 4 +- .../arbitration/ArbitratorManagerTest.java | 10 +- .../core/arbitration/ArbitratorTest.java | 4 +- .../haveno/core/arbitration/MediatorTest.java | 4 +- .../core/arbitration/TraderDataItemTest.java | 10 +- .../haveno/core/crypto/EncryptionTest.java | 11 +- .../test/java/haveno/core/crypto/SigTest.java | 12 +- .../java/haveno/core/locale/BankUtilTest.java | 12 +- .../haveno/core/locale/CurrencyUtilTest.java | 22 +- .../haveno/core/message/MarshallerTest.java | 5 +- .../java/haveno/core/monetary/PriceTest.java | 114 ++-- .../seed/DefaultSeedNodeRepositoryTest.java | 16 +- .../core/notifications/MobileModelTest.java | 4 +- .../java/haveno/core/offer/OfferTest.java | 6 +- .../core/offer/OpenOfferManagerTest.java | 12 +- .../availability/ArbitratorSelectionTest.java | 4 +- .../core/payment/PaymentAccountsTest.java | 4 +- .../core/payment/ReceiptPredicatesTest.java | 6 +- .../core/payment/ReceiptValidatorTest.java | 17 +- .../haveno/core/payment/TradeLimitsTest.java | 2 +- .../AltCoinAddressValidatorTest.java | 6 +- .../provider/mempool/TxValidatorTest.java | 10 +- .../price/MarketPriceFeedServiceTest.java | 8 +- .../haveno/core/trade/TradableListTest.java | 4 +- .../haveno/core/user/PreferencesTest.java | 10 +- .../core/user/UserPayloadModelVOTest.java | 6 +- .../haveno/core/util/FormattingUtilsTest.java | 10 +- .../java/haveno/core/util/ProtoUtilTest.java | 19 +- .../haveno/core/util/RegexValidatorTest.java | 10 +- .../haveno/core/util/coin/CoinUtilTest.java | 26 +- .../core/xmr/nodes/BtcNetworkConfigTest.java | 6 +- .../core/xmr/nodes/BtcNodeConverterTest.java | 4 +- .../xmr/nodes/BtcNodesRepositoryTest.java | 8 +- .../nodes/BtcNodesSetupPreferencesTest.java | 6 +- .../core/xmr/wallet/RestrictionsTest.java | 6 +- .../GrpcServiceRateMeteringConfigTest.java | 14 +- .../java/haveno/desktop/GuiceSetupTest.java | 12 +- .../common/fxml/FxmlViewLoaderTests.java | 48 +- .../support/CachingViewLoaderTests.java | 2 +- ...ColoredDecimalPlacesWithZerosTextTest.java | 14 +- .../DisplayedTransactionsTest.java | 4 +- .../ObservableListDecoratorTest.java | 4 +- .../TransactionAwareTradableFactoryTest.java | 4 +- .../TransactionAwareTradeTest.java | 8 +- .../OfferBookChartViewModelTest.java | 8 +- .../market/spread/SpreadViewModelTest.java | 4 +- .../trades/TradesChartsViewModelTest.java | 12 +- .../createoffer/CreateOfferDataModelTest.java | 8 +- .../createoffer/CreateOfferViewModelTest.java | 10 +- .../offerbook/OfferBookViewModelTest.java | 18 +- .../desktop/main/overlays/OverlayTest.java | 8 +- .../downloadupdate/HavenoInstallerTest.java | 4 +- .../downloadupdate/VerifyTaskTest.java | 2 +- .../preferences/PreferencesViewModelTest.java | 6 +- .../haveno/desktop/util/CurrencyListTest.java | 8 +- .../haveno/desktop/util/DisplayUtilsTest.java | 8 +- .../java/haveno/desktop/util/GUIUtilTest.java | 8 +- .../util/ImmutableCoinFormatterTest.java | 8 +- .../desktop/util/MovingAverageUtilsTest.java | 40 +- .../validation/AccountNrValidatorTest.java | 8 +- .../validation/AdvancedCashValidatorTest.java | 10 +- .../validation/BranchIdValidatorTest.java | 10 +- .../validation/CapitualValidatorTest.java | 10 +- .../validation/FiatVolumeValidatorTest.java | 10 +- .../InteracETransferAnswerValidatorTest.java | 10 +- ...InteracETransferQuestionValidatorTest.java | 10 +- .../InteracETransferValidatorTest.java | 10 +- .../util/validation/LengthValidatorTest.java | 10 +- .../NationalAccountIdValidatorTest.java | 12 +- .../validation/PhoneNumberValidatorTest.java | 30 +- .../util/validation/RegexValidatorTest.java | 10 +- .../util/validation/XmrValidatorTest.java | 10 +- gradle/verification-metadata.xml | 25 + .../crypto/EncryptionServiceTests.java | 13 +- .../haveno/network/p2p/PeerServiceTest.java | 14 +- .../p2p/network/LocalhostNetworkNodeTest.java | 6 +- .../p2p/network/TorNetworkNodeTest.java | 6 +- .../network/p2p/peers/PeerManagerTest.java | 20 +- ...2PDataStorageBuildGetDataResponseTest.java | 182 +++--- .../storage/P2PDataStorageClientAPITest.java | 35 +- .../P2PDataStorageGetDataIntegrationTest.java | 12 +- .../P2PDataStorageOnMessageHandlerTest.java | 6 +- ...aStoragePersistableNetworkPayloadTest.java | 119 ++-- .../P2PDataStorageProcessGetDataResponse.java | 14 +- ...PDataStorageProtectedStorageEntryTest.java | 611 ++++++++++-------- .../P2PDataStorageRemoveExpiredTest.java | 86 +-- .../P2PDataStorageRequestDataTest.java | 49 +- .../storage/P2PDataStoreDisconnectTest.java | 18 +- .../haveno/network/p2p/storage/TestState.java | 185 +++--- .../storage/messages/AddDataMessageTest.java | 7 +- .../ProtectedMailboxStorageEntryTest.java | 29 +- .../payload/ProtectedStorageEntryTest.java | 46 +- .../java/haveno/network/utils/UtilsTest.java | 6 +- .../java/haveno/seednode/GuiceSetupTest.java | 2 +- 114 files changed, 1352 insertions(+), 1338 deletions(-) delete mode 100644 apitest/src/test/java/haveno/apitest/JUnitHelper.java diff --git a/apitest/src/test/java/haveno/apitest/JUnitHelper.java b/apitest/src/test/java/haveno/apitest/JUnitHelper.java deleted file mode 100644 index 1936ce30..00000000 --- a/apitest/src/test/java/haveno/apitest/JUnitHelper.java +++ /dev/null @@ -1,57 +0,0 @@ -package haveno.apitest; - -import lombok.extern.slf4j.Slf4j; -import org.junit.runner.Description; -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; - -import static java.lang.String.format; - -@Slf4j -public class JUnitHelper { - - private static boolean allPass; - - public static void runTests(Class... testClasses) { - JUnitCore jUnitCore = new JUnitCore(); - jUnitCore.addListener(new RunListener() { - public void testStarted(Description description) { - log.info("{}", description); - } - - public void testIgnored(Description description) { - log.info("Ignored {}", description); - } - - public void testFailure(Failure failure) { - log.error("Failed {}", failure.getTrace()); - } - }); - Result result = jUnitCore.run(testClasses); - printTestResults(result); - } - - public static boolean allTestsPassed() { - return allPass; - } - - private static void printTestResults(Result result) { - log.info("Total tests: {}, Failed: {}, Ignored: {}", - result.getRunCount(), - result.getFailureCount(), - result.getIgnoreCount()); - - if (result.wasSuccessful()) { - log.info("All {} tests passed", result.getRunCount()); - allPass = true; - } else if (result.getFailureCount() > 0) { - log.error("{} test(s) failed", result.getFailureCount()); - result.getFailures().iterator().forEachRemaining(f -> log.error(format("%s.%s()%n\t%s", - f.getDescription().getTestClass().getName(), - f.getDescription().getMethodName(), - f.getTrace()))); - } - } -} diff --git a/assets/src/test/java/haveno/asset/AbstractAssetTest.java b/assets/src/test/java/haveno/asset/AbstractAssetTest.java index a5cbf562..e6da4c7f 100644 --- a/assets/src/test/java/haveno/asset/AbstractAssetTest.java +++ b/assets/src/test/java/haveno/asset/AbstractAssetTest.java @@ -17,10 +17,10 @@ package haveno.asset; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * Abstract base class for all {@link Asset} unit tests. Subclasses must implement the diff --git a/assets/src/test/java/haveno/asset/coins/BitcoinCashTest.java b/assets/src/test/java/haveno/asset/coins/BitcoinCashTest.java index 90e8f2e2..859b9d60 100644 --- a/assets/src/test/java/haveno/asset/coins/BitcoinCashTest.java +++ b/assets/src/test/java/haveno/asset/coins/BitcoinCashTest.java @@ -18,7 +18,7 @@ package haveno.asset.coins; import haveno.asset.AbstractAssetTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class BitcoinCashTest extends AbstractAssetTest { diff --git a/assets/src/test/java/haveno/asset/coins/BitcoinTest.java b/assets/src/test/java/haveno/asset/coins/BitcoinTest.java index 66264fe3..319559f1 100644 --- a/assets/src/test/java/haveno/asset/coins/BitcoinTest.java +++ b/assets/src/test/java/haveno/asset/coins/BitcoinTest.java @@ -18,7 +18,7 @@ package haveno.asset.coins; import haveno.asset.AbstractAssetTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class BitcoinTest extends AbstractAssetTest { diff --git a/assets/src/test/java/haveno/asset/coins/LitecoinTest.java b/assets/src/test/java/haveno/asset/coins/LitecoinTest.java index 908022bf..1f014429 100644 --- a/assets/src/test/java/haveno/asset/coins/LitecoinTest.java +++ b/assets/src/test/java/haveno/asset/coins/LitecoinTest.java @@ -18,7 +18,7 @@ package haveno.asset.coins; import haveno.asset.AbstractAssetTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class LitecoinTest extends AbstractAssetTest { diff --git a/assets/src/test/java/haveno/asset/coins/MoneroTest.java b/assets/src/test/java/haveno/asset/coins/MoneroTest.java index 9af327fa..4171534d 100644 --- a/assets/src/test/java/haveno/asset/coins/MoneroTest.java +++ b/assets/src/test/java/haveno/asset/coins/MoneroTest.java @@ -18,7 +18,7 @@ package haveno.asset.coins; import haveno.asset.AbstractAssetTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class MoneroTest extends AbstractAssetTest { diff --git a/build.gradle b/build.gradle index 1771e8fa..44cbc47d 100644 --- a/build.gradle +++ b/build.gradle @@ -50,7 +50,7 @@ configure(subprojects) { guiceVersion = '4.2.2' moneroJavaVersion = '0.7.15' httpclient5Version = '5.0' - hamcrestVersion = '1.3' + hamcrestVersion = '2.2' httpclientVersion = '4.5.12' httpcoreVersion = '4.4.13' ioVersion = '2.6' @@ -63,8 +63,7 @@ configure(subprojects) { joptVersion = '5.0.4' jsonsimpleVersion = '1.1.1' jsonrpc4jVersion = '1.6.0.bisq.1' - junitVersion = '4.12' - jupiterVersion = '5.7.0' + jupiterVersion = '5.9.2' kotlinVersion = '1.3.41' langVersion = '3.11' logbackVersion = '1.1.11' @@ -89,10 +88,6 @@ configure(subprojects) { maven { url 'https://mvnrepository.com' } } - dependencies { - testImplementation "junit:junit:$junitVersion" - } - tasks.withType(JavaCompile) { options.encoding = 'UTF-8' } @@ -250,6 +245,9 @@ configure(project(':assets')) { implementation "com.google.guava:guava:$guavaVersion" implementation "org.apache.commons:commons-lang3:$langVersion" implementation "org.slf4j:slf4j-api:$slf4jVersion" + testImplementation "org.hamcrest:hamcrest:$hamcrestVersion" + testImplementation "org.junit.jupiter:junit-jupiter-api:$jupiterVersion" + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion" } } @@ -285,7 +283,9 @@ configure(project(':common')) { implementation "org.bouncycastle:bcpg-jdk15on:$bcVersion" implementation "org.jetbrains:annotations:$jetbrainsAnnotationsVersion" implementation "org.slf4j:slf4j-api:$slf4jVersion" - testImplementation "org.hamcrest:hamcrest-all:$hamcrestVersion" + testImplementation "org.hamcrest:hamcrest:$hamcrestVersion" + testImplementation "org.junit.jupiter:junit-jupiter-api:$jupiterVersion" + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion" runtimeOnly("io.grpc:grpc-netty-shaded:$grpcVersion") { exclude(module: 'guava') exclude(module: 'animal-sniffer-annotations') @@ -332,6 +332,9 @@ configure(project(':p2p')) { } testAnnotationProcessor "org.projectlombok:lombok:$lombokVersion" testCompileOnly "org.projectlombok:lombok:$lombokVersion" + testImplementation "org.junit.jupiter:junit-jupiter-api:$jupiterVersion" + testImplementation "org.junit.jupiter:junit-jupiter-params:$jupiterVersion" + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion" testImplementation "ch.qos.logback:logback-classic:$logbackVersion" testImplementation "ch.qos.logback:logback-core:$logbackVersion" testImplementation "org.apache.commons:commons-lang3:$langVersion" @@ -398,7 +401,9 @@ configure(project(':core')) { testAnnotationProcessor "org.projectlombok:lombok:$lombokVersion" testCompileOnly "org.projectlombok:lombok:$lombokVersion" testImplementation "com.natpryce:make-it-easy:$easyVersion" - testImplementation "org.hamcrest:hamcrest-all:$hamcrestVersion" + testImplementation "org.hamcrest:hamcrest:$hamcrestVersion" + testImplementation "org.junit.jupiter:junit-jupiter-api:$jupiterVersion" + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion" testImplementation "org.mockito:mockito-core:$mockitoVersion" implementation "org.openjfx:javafx-base:$javafxVersion:$os" @@ -556,7 +561,7 @@ configure(project(':cli')) { testImplementation "org.junit.jupiter:junit-jupiter-api:$jupiterVersion" testImplementation "org.junit.jupiter:junit-jupiter-params:$jupiterVersion" testRuntimeOnly "javax.annotation:javax.annotation-api:$javaxAnnotationVersion" - testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:$jupiterVersion") + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion" } test { @@ -624,6 +629,9 @@ configure(project(':desktop')) { testCompileOnly "org.projectlombok:lombok:$lombokVersion" testImplementation "com.natpryce:make-it-easy:$easyVersion" testImplementation "org.mockito:mockito-core:$mockitoVersion" + testImplementation "org.hamcrest:hamcrest:$hamcrestVersion" + testImplementation "org.junit.jupiter:junit-jupiter-api:$jupiterVersion" + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion" implementation("io.github.monero-ecosystem:monero-java:$moneroJavaVersion") { exclude(module: 'jackson-core') @@ -679,7 +687,7 @@ configure(project(':monitor')) { testCompileOnly "org.projectlombok:lombok:$lombokVersion" testImplementation "org.junit.jupiter:junit-jupiter-api:$jupiterVersion" testImplementation "org.junit.jupiter:junit-jupiter-params:$jupiterVersion" - testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:$jupiterVersion") + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion" implementation "org.openjfx:javafx-base:$javafxVersion:$os" implementation "org.openjfx:javafx-graphics:$javafxVersion:$os" @@ -725,6 +733,8 @@ configure(project(':seednode')) { exclude(module: 'guava') } testImplementation "org.mockito:mockito-core:$mockitoVersion" + testImplementation "org.junit.jupiter:junit-jupiter-api:$jupiterVersion" + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion" } } @@ -908,7 +918,7 @@ configure(project(':apitest')) { testImplementation "org.junit.jupiter:junit-jupiter-api:$jupiterVersion" testImplementation "org.junit.jupiter:junit-jupiter-params:$jupiterVersion" testRuntimeOnly "javax.annotation:javax.annotation-api:$javaxAnnotationVersion" - testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:$jupiterVersion") + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion" } } diff --git a/common/src/test/java/haveno/common/app/CapabilitiesTest.java b/common/src/test/java/haveno/common/app/CapabilitiesTest.java index 47c7ecc0..08a629f5 100644 --- a/common/src/test/java/haveno/common/app/CapabilitiesTest.java +++ b/common/src/test/java/haveno/common/app/CapabilitiesTest.java @@ -17,7 +17,7 @@ package haveno.common.app; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; @@ -26,9 +26,9 @@ import java.util.HashSet; import static haveno.common.app.Capability.SEED_NODE; import static haveno.common.app.Capability.TRADE_STATISTICS; import static haveno.common.app.Capability.TRADE_STATISTICS_2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CapabilitiesTest { diff --git a/common/src/test/java/haveno/common/app/VersionTest.java b/common/src/test/java/haveno/common/app/VersionTest.java index a75babf6..b82d7b2a 100644 --- a/common/src/test/java/haveno/common/app/VersionTest.java +++ b/common/src/test/java/haveno/common/app/VersionTest.java @@ -17,11 +17,11 @@ package haveno.common.app; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class VersionTest { diff --git a/common/src/test/java/haveno/common/config/ConfigFileEditorTests.java b/common/src/test/java/haveno/common/config/ConfigFileEditorTests.java index 6f7bb09f..222b7d54 100644 --- a/common/src/test/java/haveno/common/config/ConfigFileEditorTests.java +++ b/common/src/test/java/haveno/common/config/ConfigFileEditorTests.java @@ -1,16 +1,16 @@ package haveno.common.config; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConfigFileEditorTests { @@ -19,7 +19,7 @@ public class ConfigFileEditorTests { private ConfigFileReader reader; private ConfigFileEditor editor; - @Before + @BeforeEach public void setUp() throws IOException { file = File.createTempFile("haveno", "properties"); reader = new ConfigFileReader(file); diff --git a/common/src/test/java/haveno/common/config/ConfigFileOptionTests.java b/common/src/test/java/haveno/common/config/ConfigFileOptionTests.java index 28d8960a..ba66ee49 100644 --- a/common/src/test/java/haveno/common/config/ConfigFileOptionTests.java +++ b/common/src/test/java/haveno/common/config/ConfigFileOptionTests.java @@ -1,6 +1,6 @@ package haveno.common.config; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/common/src/test/java/haveno/common/config/ConfigFileReaderTests.java b/common/src/test/java/haveno/common/config/ConfigFileReaderTests.java index 6e7d610b..ac363095 100644 --- a/common/src/test/java/haveno/common/config/ConfigFileReaderTests.java +++ b/common/src/test/java/haveno/common/config/ConfigFileReaderTests.java @@ -1,18 +1,16 @@ package haveno.common.config; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConfigFileReaderTests { @@ -20,10 +18,7 @@ public class ConfigFileReaderTests { private PrintWriter writer; private ConfigFileReader reader; - @Rule - public ExpectedException exception = ExpectedException.none(); - - @Before + @BeforeEach public void setUp() throws IOException { file = File.createTempFile("haveno", "properties"); reader = new ConfigFileReader(file); @@ -35,11 +30,12 @@ public class ConfigFileReaderTests { writer.close(); assertTrue(file.delete()); - exception.expect(ConfigException.class); - exception.expectMessage(containsString("Config file")); - exception.expectMessage(containsString("does not exist")); + Exception exception = assertThrows(ConfigException.class, () -> reader.getLines()); - reader.getLines(); + String expectedMessage = "does not exist"; + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); } @Test diff --git a/common/src/test/java/haveno/common/config/ConfigTests.java b/common/src/test/java/haveno/common/config/ConfigTests.java index cc573987..7066cc98 100644 --- a/common/src/test/java/haveno/common/config/ConfigTests.java +++ b/common/src/test/java/haveno/common/config/ConfigTests.java @@ -1,8 +1,6 @@ package haveno.common.config; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.File; @@ -21,21 +19,22 @@ import static haveno.common.config.Config.DEFAULT_CONFIG_FILE_NAME; import static haveno.common.config.Config.HELP; import static haveno.common.config.Config.TORRC_FILE; import static haveno.common.config.Config.USER_DATA_DIR; +import static java.io.File.createTempFile; import static java.lang.String.format; -import static org.hamcrest.CoreMatchers.containsString; +import static java.lang.System.getProperty; +import static java.nio.file.Files.createTempDirectory; import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.isEmptyString; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.Matchers.emptyString; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConfigTests { - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); - // Note: "DataDirProperties" in the test method names below represent the group of // configuration options that influence the location of a Haveno node's data directory. // These options include appName, userDataDir, appDataDir and configFile @@ -45,8 +44,8 @@ public class ConfigTests { Config config = new Config(); String defaultAppName = config.defaultAppName; String regex = "Haveno\\d{2,}Temp"; - assertTrue(format("Temp app name '%s' failed to match '%s'", defaultAppName, regex), - defaultAppName.matches(regex)); + assertTrue(defaultAppName.matches(regex), + format("Temp app name '%s' failed to match '%s'", defaultAppName, regex)); } @Test @@ -76,7 +75,7 @@ public class ConfigTests { @Test public void whenAppDataDirOptionIsSet_thenDataDirPropertiesReflectItsValue() throws IOException { - File appDataDir = Files.createTempDirectory("myapp").toFile(); + File appDataDir = createTempDirectory("myapp").toFile(); Config config = configWithOpts(opt(APP_DATA_DIR, appDataDir)); assertThat(config.appName, equalTo(config.defaultAppName)); assertThat(config.userDataDir, equalTo(config.defaultUserDataDir)); @@ -86,7 +85,7 @@ public class ConfigTests { @Test public void whenUserDataDirOptionIsSet_thenDataDirPropertiesReflectItsValue() throws IOException { - File userDataDir = Files.createTempDirectory("myuserdata").toFile(); + File userDataDir = createTempDirectory("myuserdata").toFile(); Config config = configWithOpts(opt(USER_DATA_DIR, userDataDir)); assertThat(config.appName, equalTo(config.defaultAppName)); assertThat(config.userDataDir, equalTo(userDataDir)); @@ -96,7 +95,7 @@ public class ConfigTests { @Test public void whenAppNameAndAppDataDirOptionsAreSet_thenDataDirPropertiesReflectTheirValues() throws IOException { - File appDataDir = Files.createTempDirectory("myapp").toFile(); + File appDataDir = createTempDirectory("myapp").toFile(); Config config = configWithOpts(opt(APP_NAME, "My-Haveno"), opt(APP_DATA_DIR, appDataDir)); assertThat(config.appName, equalTo("My-Haveno")); assertThat(config.userDataDir, equalTo(config.defaultUserDataDir)); @@ -106,7 +105,7 @@ public class ConfigTests { @Test public void whenOptionIsSetAtCommandLineAndInConfigFile_thenCommandLineValueTakesPrecedence() throws IOException { - File configFile = File.createTempFile("haveno", "properties"); + File configFile = createTempFile("haveno", "properties"); try (PrintWriter writer = new PrintWriter(configFile)) { writer.println(new ConfigFileOption(APP_NAME, "Haveno-configFileValue")); } @@ -116,14 +115,17 @@ public class ConfigTests { @Test public void whenUnrecognizedOptionIsSet_thenConfigExceptionIsThrown() { - exceptionRule.expect(ConfigException.class); - exceptionRule.expectMessage("problem parsing option 'bogus': bogus is not a recognized option"); - configWithOpts(opt("bogus")); + Exception exception = assertThrows(ConfigException.class, () -> configWithOpts(opt("bogus"))); + + String expectedMessage = "problem parsing option 'bogus': bogus is not a recognized option"; + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); } @Test public void whenUnrecognizedOptionIsSetInConfigFile_thenNoExceptionIsThrown() throws IOException { - File configFile = File.createTempFile("haveno", "properties"); + File configFile = createTempFile("haveno", "properties"); try (PrintWriter writer = new PrintWriter(configFile)) { writer.println(new ConfigFileOption("bogusOption", "bogusValue")); writer.println(new ConfigFileOption(APP_NAME, "HavenoTest")); @@ -134,40 +136,43 @@ public class ConfigTests { @Test public void whenOptionFileArgumentDoesNotExist_thenConfigExceptionIsThrown() { - String filepath = "/does/not/exist"; - if (System.getProperty("os.name").startsWith("Windows")) { - filepath = "C:\\does\\not\\exist"; - } - exceptionRule.expect(ConfigException.class); - exceptionRule.expectMessage(format("problem parsing option 'torrcFile': File [%s] does not exist", filepath)); - configWithOpts(opt(TORRC_FILE, filepath)); + String filepath = getProperty("os.name").startsWith("Windows") ? "C:\\does\\not\\exist" : "/does/not/exist"; + Exception exception = assertThrows(ConfigException.class, () -> configWithOpts(opt(TORRC_FILE, filepath))); + + String expectedMessage = format("problem parsing option 'torrcFile': File [%s] does not exist", filepath); + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); } @Test public void whenConfigFileOptionIsSetToNonExistentFile_thenConfigExceptionIsThrown() { - String filepath = "/no/such/haveno.properties"; - if (System.getProperty("os.name").startsWith("Windows")) { - filepath = "C:\\no\\such\\haveno.properties"; - } - exceptionRule.expect(ConfigException.class); - exceptionRule.expectMessage(format("The specified config file '%s' does not exist", filepath)); - configWithOpts(opt(CONFIG_FILE, filepath)); + String filepath = getProperty("os.name").startsWith("Windows") ? "C:\\no\\such\\haveno.properties" : "/no/such/haveno.properties"; + Exception exception = assertThrows(ConfigException.class, () -> configWithOpts(opt(CONFIG_FILE, filepath))); + + String expectedMessage = format("The specified config file '%s' does not exist", filepath); + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); } @Test public void whenConfigFileOptionIsSetInConfigFile_thenConfigExceptionIsThrown() throws IOException { - File configFile = File.createTempFile("haveno", "properties"); + File configFile = createTempFile("haveno", "properties"); try (PrintWriter writer = new PrintWriter(configFile)) { writer.println(new ConfigFileOption(CONFIG_FILE, "/tmp/other.haveno.properties")); } - exceptionRule.expect(ConfigException.class); - exceptionRule.expectMessage(format("The '%s' option is disallowed in config files", CONFIG_FILE)); - configWithOpts(opt(CONFIG_FILE, configFile.getAbsolutePath())); + Exception exception = assertThrows(ConfigException.class, () -> configWithOpts(opt(CONFIG_FILE, configFile.getAbsolutePath()))); + + String expectedMessage = format("The '%s' option is disallowed in config files", CONFIG_FILE); + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); } @Test public void whenConfigFileOptionIsSetToExistingFile_thenConfigFilePropertyReflectsItsValue() throws IOException { - File configFile = File.createTempFile("haveno", "properties"); + File configFile = createTempFile("haveno", "properties"); Config config = configWithOpts(opt(CONFIG_FILE, configFile.getAbsolutePath())); assertThat(config.configFile, equalTo(configFile)); } @@ -183,7 +188,7 @@ public class ConfigTests { @Test public void whenAppNameIsSetInConfigFile_thenDataDirPropertiesReflectItsValue() throws IOException { - File configFile = File.createTempFile("haveno", "properties"); + File configFile = createTempFile("haveno", "properties"); try (PrintWriter writer = new PrintWriter(configFile)) { writer.println(new ConfigFileOption(APP_NAME, "My-Haveno")); } @@ -217,8 +222,8 @@ public class ConfigTests { System.setOut(outTest); System.setErr(errTest); new Config(); - assertThat(outBytes.toString(), isEmptyString()); - assertThat(errBytes.toString(), isEmptyString()); + assertThat(outBytes.toString(), is(emptyString())); + assertThat(errBytes.toString(), is(emptyString())); } finally { System.setOut(outOrig); System.setErr(errOrig); @@ -236,18 +241,22 @@ public class ConfigTests { } @Test - public void whenAppDataDirCannotBeCreated_thenUncheckedIoExceptionIsThrown() throws IOException { + public void whenAppDataDirCannotBeCreatedThenUncheckedIoExceptionIsThrown() { // set a userDataDir that is actually a file so appDataDir cannot be created - File aFile = Files.createTempFile("A", "File").toFile(); - exceptionRule.expect(UncheckedIOException.class); - exceptionRule.expectMessage(containsString("Application data directory")); - exceptionRule.expectMessage(containsString("could not be created")); - configWithOpts(opt(USER_DATA_DIR, aFile)); + Exception exception = assertThrows(UncheckedIOException.class, () -> { + File aFile = Files.createTempFile("A", "File").toFile(); + configWithOpts(opt(USER_DATA_DIR, aFile)); + }); + + String expectedMessage = "could not be created"; + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); } @Test public void whenAppDataDirIsSymbolicLink_thenAppDataDirCreationIsNoOp() throws IOException { - Path parentDir = Files.createTempDirectory("parent"); + Path parentDir = createTempDirectory("parent"); Path targetDir = parentDir.resolve("target"); Path symlink = parentDir.resolve("symlink"); Files.createDirectory(targetDir); diff --git a/common/src/test/java/haveno/common/util/MathUtilsTest.java b/common/src/test/java/haveno/common/util/MathUtilsTest.java index eb672ca7..82195b12 100644 --- a/common/src/test/java/haveno/common/util/MathUtilsTest.java +++ b/common/src/test/java/haveno/common/util/MathUtilsTest.java @@ -17,26 +17,27 @@ package haveno.common.util; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; public class MathUtilsTest { - @Test(expected = IllegalArgumentException.class) + @Test public void testRoundDoubleWithInfiniteArg() { - MathUtils.roundDouble(Double.POSITIVE_INFINITY, 2); + assertThrows(IllegalArgumentException.class, () -> MathUtils.roundDouble(Double.POSITIVE_INFINITY, 2)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testRoundDoubleWithNaNArg() { - MathUtils.roundDouble(Double.NaN, 2); + assertThrows(IllegalArgumentException.class, () ->MathUtils.roundDouble(Double.NaN, 2)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testRoundDoubleWithNegativePrecision() { - MathUtils.roundDouble(3, -1); + assertThrows(IllegalArgumentException.class, () ->MathUtils.roundDouble(3, -1)); } @SuppressWarnings("OptionalGetWithoutIsPresent") diff --git a/common/src/test/java/haveno/common/util/PermutationTest.java b/common/src/test/java/haveno/common/util/PermutationTest.java index 2f8aa61a..cab0e4b0 100644 --- a/common/src/test/java/haveno/common/util/PermutationTest.java +++ b/common/src/test/java/haveno/common/util/PermutationTest.java @@ -17,7 +17,7 @@ package haveno.common.util; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -25,7 +25,7 @@ import java.util.Collections; import java.util.List; import java.util.function.BiPredicate; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class PermutationTest { diff --git a/common/src/test/java/haveno/common/util/PreconditionsTests.java b/common/src/test/java/haveno/common/util/PreconditionsTests.java index 8722938d..7e43d94a 100644 --- a/common/src/test/java/haveno/common/util/PreconditionsTests.java +++ b/common/src/test/java/haveno/common/util/PreconditionsTests.java @@ -1,22 +1,20 @@ package haveno.common.util; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import static haveno.common.util.Preconditions.checkDir; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertSame; +import static java.lang.String.format; +import static java.lang.System.getProperty; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class PreconditionsTests { - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); - @Test public void whenDirIsValid_thenDirIsReturned() throws IOException { File dir = Files.createTempDirectory("TestDir").toFile(); @@ -26,12 +24,12 @@ public class PreconditionsTests { @Test public void whenDirDoesNotExist_thenThrow() { - String filepath = "/does/not/exist"; - if (System.getProperty("os.name").startsWith("Windows")) { - filepath = "C:\\does\\not\\exist"; - } - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage(equalTo(String.format("Directory '%s' does not exist", filepath))); - checkDir(new File(filepath)); + String filepath = getProperty("os.name").startsWith("Windows") ? "C:\\does\\not\\exist" : "/does/not/exist"; + Exception exception = assertThrows(IllegalArgumentException.class, () -> checkDir(new File(filepath))); + + String expectedMessage = format("Directory '%s' does not exist", filepath); + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); } } diff --git a/common/src/test/java/haveno/common/util/UtilitiesTest.java b/common/src/test/java/haveno/common/util/UtilitiesTest.java index 8f4b9b18..085d0a34 100644 --- a/common/src/test/java/haveno/common/util/UtilitiesTest.java +++ b/common/src/test/java/haveno/common/util/UtilitiesTest.java @@ -17,10 +17,10 @@ package haveno.common.util; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class UtilitiesTest { diff --git a/core/src/test/java/haveno/core/account/sign/SignedWitnessServiceTest.java b/core/src/test/java/haveno/core/account/sign/SignedWitnessServiceTest.java index c0d70011..40c991ed 100644 --- a/core/src/test/java/haveno/core/account/sign/SignedWitnessServiceTest.java +++ b/core/src/test/java/haveno/core/account/sign/SignedWitnessServiceTest.java @@ -30,8 +30,8 @@ import haveno.network.p2p.P2PService; import haveno.network.p2p.storage.payload.PersistableNetworkPayload; import haveno.network.p2p.storage.persistence.AppendOnlyDataStoreService; import org.bitcoinj.core.ECKey; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.security.KeyPair; @@ -41,8 +41,8 @@ import java.util.Date; import static haveno.core.account.sign.SignedWitness.VerificationMethod.ARBITRATOR; import static haveno.core.account.sign.SignedWitness.VerificationMethod.TRADE; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.mock; @@ -85,7 +85,7 @@ public class SignedWitnessServiceTest { KeyPair peer2KeyPair; KeyPair peer3KeyPair; - @Before + @BeforeEach public void setup() throws Exception { AppendOnlyDataStoreService appendOnlyDataStoreService = mock(AppendOnlyDataStoreService.class); ArbitratorManager arbitratorManager = mock(ArbitratorManager.class); diff --git a/core/src/test/java/haveno/core/account/sign/SignedWitnessTest.java b/core/src/test/java/haveno/core/account/sign/SignedWitnessTest.java index dbbbb4e4..7541b0d1 100644 --- a/core/src/test/java/haveno/core/account/sign/SignedWitnessTest.java +++ b/core/src/test/java/haveno/core/account/sign/SignedWitnessTest.java @@ -5,15 +5,15 @@ import haveno.common.crypto.Sig; import haveno.common.util.Utilities; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Utils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.time.Instant; import static haveno.core.account.sign.SignedWitness.VerificationMethod.ARBITRATOR; import static haveno.core.account.sign.SignedWitness.VerificationMethod.TRADE; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class SignedWitnessTest { @@ -22,7 +22,7 @@ public class SignedWitnessTest { private byte[] witnessHash; private byte[] witnessHashSignature; - @Before + @BeforeEach public void setUp() { arbitrator1Key = new ECKey(); witnessOwner1PubKey = Sig.getPublicKeyBytes(Sig.generateKeyPair().getPublic()); diff --git a/core/src/test/java/haveno/core/account/witness/AccountAgeWitnessServiceTest.java b/core/src/test/java/haveno/core/account/witness/AccountAgeWitnessServiceTest.java index 18dd0a2f..01981488 100644 --- a/core/src/test/java/haveno/core/account/witness/AccountAgeWitnessServiceTest.java +++ b/core/src/test/java/haveno/core/account/witness/AccountAgeWitnessServiceTest.java @@ -43,10 +43,9 @@ import haveno.core.trade.HavenoUtils; import haveno.network.p2p.P2PService; import haveno.network.p2p.storage.persistence.AppendOnlyDataStoreService; import org.bitcoinj.core.ECKey; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -60,9 +59,9 @@ import java.util.List; import java.util.concurrent.TimeUnit; import static haveno.core.payment.payload.PaymentMethod.getPaymentMethod; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -82,7 +81,7 @@ public class AccountAgeWitnessServiceTest { private File dir2; private File dir3; - @Before + @BeforeEach public void setup() throws IOException { KeyRing keyRing = mock(KeyRing.class); setupService(keyRing); @@ -113,12 +112,7 @@ public class AccountAgeWitnessServiceTest { return dir; } - @After - public void tearDown() { - // Do teardown stuff - } - - @Ignore + @Disabled @Test public void testIsTradeDateAfterReleaseDate() { Date ageWitnessReleaseDate = new GregorianCalendar(2017, Calendar.OCTOBER, 23).getTime(); @@ -139,7 +133,7 @@ public class AccountAgeWitnessServiceTest { })); } - @Ignore + @Disabled @Test public void testVerifySignatureOfNonce() throws CryptoException { byte[] nonce = new byte[]{0x01}; diff --git a/core/src/test/java/haveno/core/app/HavenoHelpFormatterTest.java b/core/src/test/java/haveno/core/app/HavenoHelpFormatterTest.java index 76df7d3a..fbed2aa5 100644 --- a/core/src/test/java/haveno/core/app/HavenoHelpFormatterTest.java +++ b/core/src/test/java/haveno/core/app/HavenoHelpFormatterTest.java @@ -19,7 +19,7 @@ package haveno.core.app; import haveno.common.config.HavenoHelpFormatter; import joptsimple.OptionParser; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.File; @@ -30,7 +30,7 @@ import java.nio.file.Files; import java.nio.file.Paths; import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class HavenoHelpFormatterTest { diff --git a/core/src/test/java/haveno/core/arbitration/ArbitratorManagerTest.java b/core/src/test/java/haveno/core/arbitration/ArbitratorManagerTest.java index 3a40148c..184430ce 100644 --- a/core/src/test/java/haveno/core/arbitration/ArbitratorManagerTest.java +++ b/core/src/test/java/haveno/core/arbitration/ArbitratorManagerTest.java @@ -22,21 +22,19 @@ import haveno.core.support.dispute.arbitration.arbitrator.ArbitratorManager; import haveno.core.support.dispute.arbitration.arbitrator.ArbitratorService; import haveno.core.user.User; import haveno.network.p2p.NodeAddress; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; public class ArbitratorManagerTest { - - @Test public void testIsArbitratorAvailableForLanguage() { User user = mock(User.class); diff --git a/core/src/test/java/haveno/core/arbitration/ArbitratorTest.java b/core/src/test/java/haveno/core/arbitration/ArbitratorTest.java index 27cb6d5a..4b6e1624 100644 --- a/core/src/test/java/haveno/core/arbitration/ArbitratorTest.java +++ b/core/src/test/java/haveno/core/arbitration/ArbitratorTest.java @@ -22,14 +22,14 @@ import haveno.common.crypto.PubKeyRing; import haveno.core.support.dispute.arbitration.arbitrator.Arbitrator; import haveno.network.p2p.NodeAddress; import org.apache.commons.lang3.RandomUtils; -import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; import java.util.Date; @SuppressWarnings({"SameParameterValue", "UnusedAssignment"}) public class ArbitratorTest { - @Ignore("TODO InvalidKeySpecException at haveno.common.crypto.Sig.getPublicKeyFromBytes(Sig.java:135)") + @Disabled("TODO InvalidKeySpecException at haveno.common.crypto.Sig.getPublicKeyFromBytes(Sig.java:135)") public void testRoundtrip() { Arbitrator arbitrator = getArbitratorMock(); diff --git a/core/src/test/java/haveno/core/arbitration/MediatorTest.java b/core/src/test/java/haveno/core/arbitration/MediatorTest.java index 5943aa86..8aba525a 100644 --- a/core/src/test/java/haveno/core/arbitration/MediatorTest.java +++ b/core/src/test/java/haveno/core/arbitration/MediatorTest.java @@ -21,7 +21,7 @@ import com.google.common.collect.Lists; import haveno.common.crypto.PubKeyRing; import haveno.core.support.dispute.mediation.mediator.Mediator; import haveno.network.p2p.NodeAddress; -import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; import java.util.Date; @@ -29,7 +29,7 @@ import static haveno.core.arbitration.ArbitratorTest.getBytes; public class MediatorTest { - @Ignore("TODO InvalidKeySpecException at haveno.common.crypto.Sig.getPublicKeyFromBytes(Sig.java:135)") + @Disabled("TODO InvalidKeySpecException at haveno.common.crypto.Sig.getPublicKeyFromBytes(Sig.java:135)") public void testRoundtrip() { Mediator Mediator = getMediatorMock(); diff --git a/core/src/test/java/haveno/core/arbitration/TraderDataItemTest.java b/core/src/test/java/haveno/core/arbitration/TraderDataItemTest.java index 58591758..c6fae6ae 100644 --- a/core/src/test/java/haveno/core/arbitration/TraderDataItemTest.java +++ b/core/src/test/java/haveno/core/arbitration/TraderDataItemTest.java @@ -3,14 +3,14 @@ package haveno.core.arbitration; import haveno.core.account.witness.AccountAgeWitness; import haveno.core.payment.payload.PaymentAccountPayload; import haveno.core.support.dispute.arbitration.TraderDataItem; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.security.PublicKey; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.mockito.Mockito.mock; /* @@ -38,7 +38,7 @@ public class TraderDataItemTest { private byte[] hash1 = "1".getBytes(); private byte[] hash2 = "2".getBytes(); - @Before + @BeforeEach public void setup() { accountAgeWitness1 = new AccountAgeWitness(hash1, 123); accountAgeWitness2 = new AccountAgeWitness(hash2, 124); diff --git a/core/src/test/java/haveno/core/crypto/EncryptionTest.java b/core/src/test/java/haveno/core/crypto/EncryptionTest.java index 5f3c2aac..493ddbe6 100644 --- a/core/src/test/java/haveno/core/crypto/EncryptionTest.java +++ b/core/src/test/java/haveno/core/crypto/EncryptionTest.java @@ -21,10 +21,8 @@ import haveno.common.crypto.CryptoException; import haveno.common.crypto.KeyRing; import haveno.common.crypto.KeyStorage; import haveno.common.file.FileUtil; -import org.junit.After; -import org.junit.Before; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import java.io.File; import java.io.IOException; @@ -33,11 +31,10 @@ import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; public class EncryptionTest { - private static final Logger log = LoggerFactory.getLogger(EncryptionTest.class); private KeyRing keyRing; private File dir; - @Before + @BeforeEach public void setup() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, CryptoException { dir = File.createTempFile("temp_tests", ""); @@ -49,7 +46,7 @@ public class EncryptionTest { keyRing = new KeyRing(keyStorage, null, true); } - @After + @AfterEach public void tearDown() throws IOException { FileUtil.deleteDirectory(dir); } diff --git a/core/src/test/java/haveno/core/crypto/SigTest.java b/core/src/test/java/haveno/core/crypto/SigTest.java index e61963f5..0df69178 100644 --- a/core/src/test/java/haveno/core/crypto/SigTest.java +++ b/core/src/test/java/haveno/core/crypto/SigTest.java @@ -22,9 +22,9 @@ import haveno.common.crypto.KeyRing; import haveno.common.crypto.KeyStorage; import haveno.common.crypto.Sig; import haveno.common.file.FileUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,14 +32,14 @@ import java.io.File; import java.io.IOException; import java.util.Random; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class SigTest { private static final Logger log = LoggerFactory.getLogger(SigTest.class); private KeyRing keyRing; private File dir; - @Before + @BeforeEach public void setup() throws IOException { dir = File.createTempFile("temp_tests", ""); @@ -51,7 +51,7 @@ public class SigTest { keyRing = new KeyRing(keyStorage, null, true); } - @After + @AfterEach public void tearDown() throws IOException { FileUtil.deleteDirectory(dir); } diff --git a/core/src/test/java/haveno/core/locale/BankUtilTest.java b/core/src/test/java/haveno/core/locale/BankUtilTest.java index 60ae9df0..9a4ea571 100644 --- a/core/src/test/java/haveno/core/locale/BankUtilTest.java +++ b/core/src/test/java/haveno/core/locale/BankUtilTest.java @@ -1,17 +1,17 @@ package haveno.core.locale; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Locale; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class BankUtilTest { - @Before + @BeforeEach public void setup() { Locale.setDefault(new Locale("en", "US")); GlobalSettings.setLocale(new Locale("en", "US")); diff --git a/core/src/test/java/haveno/core/locale/CurrencyUtilTest.java b/core/src/test/java/haveno/core/locale/CurrencyUtilTest.java index 59b6cc3f..e3e544df 100644 --- a/core/src/test/java/haveno/core/locale/CurrencyUtilTest.java +++ b/core/src/test/java/haveno/core/locale/CurrencyUtilTest.java @@ -22,9 +22,8 @@ import haveno.asset.AssetRegistry; import haveno.asset.Coin; import haveno.asset.coins.Ether; import haveno.common.config.BaseCurrencyNetwork; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -33,13 +32,14 @@ import java.util.Optional; import java.util.ServiceLoader; import java.util.stream.Stream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class CurrencyUtilTest { - @Before + @BeforeEach public void setup() { Locale.setDefault(new Locale("en", "US")); @@ -55,7 +55,7 @@ public class CurrencyUtilTest { assertTrue(euro.isPresent()); assertTrue(naira.isPresent()); - assertFalse("Fake currency shouldn't exist", fake.isPresent()); + assertFalse(fake.isPresent(), "Fake currency shouldn't exist"); } @Test @@ -68,11 +68,11 @@ public class CurrencyUtilTest { assetRegistry.addAsset(mockTestnetCoin); CurrencyUtil.findAsset(assetRegistry, "MOCK_COIN", BaseCurrencyNetwork.XMR_MAINNET); - Assert.fail("Expected an IllegalArgumentException"); + fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { String wantMessage = "We are on mainnet and we could not find an asset with network type mainnet"; - Assert.assertTrue("Unexpected exception, want message starting with " + - "'" + wantMessage + "', got '" + e.getMessage() + "'", e.getMessage().startsWith(wantMessage)); + assertTrue(e.getMessage().startsWith(wantMessage), "Unexpected exception, want message starting with " + + "'" + wantMessage + "', got '" + e.getMessage() + "'"); } // For testnet its ok diff --git a/core/src/test/java/haveno/core/message/MarshallerTest.java b/core/src/test/java/haveno/core/message/MarshallerTest.java index 00b4b50f..5d45b81d 100644 --- a/core/src/test/java/haveno/core/message/MarshallerTest.java +++ b/core/src/test/java/haveno/core/message/MarshallerTest.java @@ -17,15 +17,14 @@ package haveno.core.message; - import lombok.extern.slf4j.Slf4j; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; @Slf4j public class MarshallerTest { diff --git a/core/src/test/java/haveno/core/monetary/PriceTest.java b/core/src/test/java/haveno/core/monetary/PriceTest.java index 253150f4..ffa65c6e 100644 --- a/core/src/test/java/haveno/core/monetary/PriceTest.java +++ b/core/src/test/java/haveno/core/monetary/PriceTest.java @@ -17,117 +17,121 @@ package haveno.core.monetary; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static haveno.core.monetary.Price.parse; +import static haveno.core.monetary.Price.valueOf; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class PriceTest { @Test public void testParse() { - Price result = Price.parse("USD", "0.1"); - Assert.assertEquals( - "Fiat value should be formatted with two decimals.", + Price result = parse("USD", "0.1"); + assertEquals( "0.10 XMR/USD", - result.toFriendlyString() + result.toFriendlyString(), + "Fiat value should be formatted with two decimals." ); - result = Price.parse("EUR", "0.1234"); - Assert.assertEquals( - "Fiat value should be given two decimals", + result = parse("EUR", "0.1234"); + assertEquals( "0.1234 XMR/EUR", - result.toFriendlyString() + result.toFriendlyString(), + "Fiat value should be given two decimals" ); try { - Price.parse("EUR", "0.12345"); - Assert.fail("Expected IllegalArgumentException to be thrown when too many decimals are used."); + parse("EUR", "0.12345"); + fail("Expected IllegalArgumentException to be thrown when too many decimals are used."); } catch (IllegalArgumentException iae) { - Assert.assertEquals( - "Unexpected exception message.", + assertEquals( "java.lang.ArithmeticException: Rounding necessary", - iae.getMessage() + iae.getMessage(), + "Unexpected exception message." ); } - Assert.assertEquals( - "Negative value should be parsed correctly.", + assertEquals( -100000000L, - Price.parse("LTC", "-1").getValue() + parse("LTC", "-1").getValue(), + "Negative value should be parsed correctly." ); - Assert.assertEquals( - "Comma (',') as decimal separator should be converted to period ('.')", + assertEquals( "0.0001 XMR/USD", - Price.parse("USD", "0,0001").toFriendlyString() + parse("USD", "0,0001").toFriendlyString(), + "Comma (',') as decimal separator should be converted to period ('.')" ); - Assert.assertEquals( - "Too many decimals should get rounded up properly.", + assertEquals( "10000.2346 LTC/XMR", - Price.parse("LTC", "10000,23456789").toFriendlyString() + parse("LTC", "10000,23456789").toFriendlyString(), + "Too many decimals should get rounded up properly." ); - Assert.assertEquals( - "Too many decimals should get rounded down properly.", + assertEquals( "10000.2345 LTC/XMR", - Price.parse("LTC", "10000,23454999").toFriendlyString() + parse("LTC", "10000,23454999").toFriendlyString(), + "Too many decimals should get rounded down properly." ); - Assert.assertEquals( - "Underlying long value should be correct.", + assertEquals( 1000023456789L, - Price.parse("LTC", "10000,23456789").getValue() + parse("LTC", "10000,23456789").getValue(), + "Underlying long value should be correct." ); try { - Price.parse("XMR", "56789.123456789"); - Assert.fail("Expected IllegalArgumentException to be thrown when too many decimals are used."); + parse("XMR", "56789.123456789"); + fail("Expected IllegalArgumentException to be thrown when too many decimals are used."); } catch (IllegalArgumentException iae) { - Assert.assertEquals( - "Unexpected exception message.", + assertEquals( "java.lang.ArithmeticException: Rounding necessary", - iae.getMessage() + iae.getMessage(), + "Unexpected exception message." ); } } @Test public void testValueOf() { - Price result = Price.valueOf("USD", 1); - Assert.assertEquals( - "Fiat value should have four decimals.", + Price result = valueOf("USD", 1); + assertEquals( "0.0001 XMR/USD", - result.toFriendlyString() + result.toFriendlyString(), + "Fiat value should have four decimals." ); - result = Price.valueOf("EUR", 1234); - Assert.assertEquals( - "Fiat value should be given two decimals", + result = valueOf("EUR", 1234); + assertEquals( "0.1234 XMR/EUR", - result.toFriendlyString() + result.toFriendlyString(), + "Fiat value should be given two decimals" ); - Assert.assertEquals( - "Negative value should be parsed correctly.", + assertEquals( -1L, - Price.valueOf("LTC", -1L).getValue() + valueOf("LTC", -1L).getValue(), + "Negative value should be parsed correctly." ); - Assert.assertEquals( - "Too many decimals should get rounded up properly.", + assertEquals( "10000.2346 LTC/XMR", - Price.valueOf("LTC", 1000023456789L).toFriendlyString() + valueOf("LTC", 1000023456789L).toFriendlyString(), + "Too many decimals should get rounded up properly." ); - Assert.assertEquals( - "Too many decimals should get rounded down properly.", + assertEquals( "10000.2345 LTC/XMR", - Price.valueOf("LTC", 1000023454999L).toFriendlyString() + valueOf("LTC", 1000023454999L).toFriendlyString(), + "Too many decimals should get rounded down properly." ); - Assert.assertEquals( - "Underlying long value should be correct.", + assertEquals( 1000023456789L, - Price.valueOf("LTC", 1000023456789L).getValue() + valueOf("LTC", 1000023456789L).getValue(), + "Underlying long value should be correct." ); } } diff --git a/core/src/test/java/haveno/core/network/p2p/seed/DefaultSeedNodeRepositoryTest.java b/core/src/test/java/haveno/core/network/p2p/seed/DefaultSeedNodeRepositoryTest.java index ee1ccbfa..6e72f6d0 100644 --- a/core/src/test/java/haveno/core/network/p2p/seed/DefaultSeedNodeRepositoryTest.java +++ b/core/src/test/java/haveno/core/network/p2p/seed/DefaultSeedNodeRepositoryTest.java @@ -19,17 +19,19 @@ package haveno.core.network.p2p.seed; import haveno.common.config.Config; import haveno.network.p2p.NodeAddress; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static java.lang.String.format; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DefaultSeedNodeRepositoryTest { @Test public void getSeedNodes() { DefaultSeedNodeRepository DUT = new DefaultSeedNodeRepository(new Config()); - Assert.assertFalse(DUT.getSeedNodeAddresses().isEmpty()); + assertFalse(DUT.getSeedNodeAddresses().isEmpty()); } @Test @@ -38,9 +40,9 @@ public class DefaultSeedNodeRepositoryTest { String seed2 = "fdsa:6001"; String seedNodesOption = format("--%s=%s,%s", Config.SEED_NODES, seed1, seed2); DefaultSeedNodeRepository DUT = new DefaultSeedNodeRepository(new Config(seedNodesOption)); - Assert.assertFalse(DUT.getSeedNodeAddresses().isEmpty()); - Assert.assertEquals(2, DUT.getSeedNodeAddresses().size()); - Assert.assertTrue(DUT.getSeedNodeAddresses().contains(new NodeAddress(seed1))); - Assert.assertTrue(DUT.getSeedNodeAddresses().contains(new NodeAddress(seed2))); + assertFalse(DUT.getSeedNodeAddresses().isEmpty()); + assertEquals(2, DUT.getSeedNodeAddresses().size()); + assertTrue(DUT.getSeedNodeAddresses().contains(new NodeAddress(seed1))); + assertTrue(DUT.getSeedNodeAddresses().contains(new NodeAddress(seed2))); } } diff --git a/core/src/test/java/haveno/core/notifications/MobileModelTest.java b/core/src/test/java/haveno/core/notifications/MobileModelTest.java index a2886c15..4f3471d6 100644 --- a/core/src/test/java/haveno/core/notifications/MobileModelTest.java +++ b/core/src/test/java/haveno/core/notifications/MobileModelTest.java @@ -19,12 +19,12 @@ package haveno.core.notifications; import haveno.common.util.Tuple2; import lombok.extern.slf4j.Slf4j; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; +import static common.utils.GenUtils.assertEquals; @Slf4j public class MobileModelTest { diff --git a/core/src/test/java/haveno/core/offer/OfferTest.java b/core/src/test/java/haveno/core/offer/OfferTest.java index 1888b571..80b7778d 100644 --- a/core/src/test/java/haveno/core/offer/OfferTest.java +++ b/core/src/test/java/haveno/core/offer/OfferTest.java @@ -17,10 +17,10 @@ package haveno.core.offer; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/core/src/test/java/haveno/core/offer/OpenOfferManagerTest.java b/core/src/test/java/haveno/core/offer/OpenOfferManagerTest.java index 31cddbd4..26b85d93 100644 --- a/core/src/test/java/haveno/core/offer/OpenOfferManagerTest.java +++ b/core/src/test/java/haveno/core/offer/OpenOfferManagerTest.java @@ -11,16 +11,16 @@ import haveno.core.api.CoreMoneroConnectionsService; import haveno.core.trade.TradableList; import haveno.network.p2p.P2PService; import haveno.network.p2p.peers.PeerManager; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.nio.file.Files; import java.util.concurrent.atomic.AtomicBoolean; import static com.natpryce.makeiteasy.MakeItEasy.make; import static haveno.core.offer.OfferMaker.btcUsdOffer; -import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -33,7 +33,7 @@ public class OpenOfferManagerTest { private PersistenceManager signedOfferPersistenceManager; private CoreContext coreContext; - @Before + @BeforeEach public void setUp() throws Exception { var corruptedStorageFileHandler = mock(CorruptedStorageFileHandler.class); var storageDir = Files.createTempDirectory("storage").toFile(); @@ -43,7 +43,7 @@ public class OpenOfferManagerTest { coreContext = new CoreContext(); } - @After + @AfterEach public void tearDown() { persistenceManager.shutdown(); signedOfferPersistenceManager.shutdown(); diff --git a/core/src/test/java/haveno/core/offer/availability/ArbitratorSelectionTest.java b/core/src/test/java/haveno/core/offer/availability/ArbitratorSelectionTest.java index ab7adc67..89aaa28f 100644 --- a/core/src/test/java/haveno/core/offer/availability/ArbitratorSelectionTest.java +++ b/core/src/test/java/haveno/core/offer/availability/ArbitratorSelectionTest.java @@ -17,14 +17,14 @@ package haveno.core.offer.availability; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ArbitratorSelectionTest { @Test diff --git a/core/src/test/java/haveno/core/payment/PaymentAccountsTest.java b/core/src/test/java/haveno/core/payment/PaymentAccountsTest.java index d0975e7e..fb96d74d 100644 --- a/core/src/test/java/haveno/core/payment/PaymentAccountsTest.java +++ b/core/src/test/java/haveno/core/payment/PaymentAccountsTest.java @@ -21,11 +21,11 @@ import haveno.core.account.witness.AccountAgeWitness; import haveno.core.account.witness.AccountAgeWitnessService; import haveno.core.offer.Offer; import haveno.core.payment.payload.PaymentAccountPayload; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; diff --git a/core/src/test/java/haveno/core/payment/ReceiptPredicatesTest.java b/core/src/test/java/haveno/core/payment/ReceiptPredicatesTest.java index f36190b7..9836b0e0 100644 --- a/core/src/test/java/haveno/core/payment/ReceiptPredicatesTest.java +++ b/core/src/test/java/haveno/core/payment/ReceiptPredicatesTest.java @@ -21,10 +21,10 @@ import com.google.common.collect.Lists; import haveno.core.locale.CryptoCurrency; import haveno.core.offer.Offer; import haveno.core.payment.payload.PaymentMethod; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/core/src/test/java/haveno/core/payment/ReceiptValidatorTest.java b/core/src/test/java/haveno/core/payment/ReceiptValidatorTest.java index 22baedd6..4196ea65 100644 --- a/core/src/test/java/haveno/core/payment/ReceiptValidatorTest.java +++ b/core/src/test/java/haveno/core/payment/ReceiptValidatorTest.java @@ -18,28 +18,25 @@ package haveno.core.payment; import haveno.core.offer.Offer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.StrictStubs.class) public class ReceiptValidatorTest { private ReceiptValidator validator; private PaymentAccount account; private Offer offer; private ReceiptPredicates predicates; - @Before + @BeforeEach public void setUp() { this.predicates = mock(ReceiptPredicates.class); this.account = mock(CountryBasedPaymentAccount.class); @@ -47,7 +44,7 @@ public class ReceiptValidatorTest { this.validator = new ReceiptValidator(offer, account, predicates); } - @After + @AfterEach public void tearDown() { verifyNoMoreInteractions(offer); } diff --git a/core/src/test/java/haveno/core/payment/TradeLimitsTest.java b/core/src/test/java/haveno/core/payment/TradeLimitsTest.java index 0cb636a0..267bbaf0 100644 --- a/core/src/test/java/haveno/core/payment/TradeLimitsTest.java +++ b/core/src/test/java/haveno/core/payment/TradeLimitsTest.java @@ -17,7 +17,7 @@ package haveno.core.payment; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TradeLimitsTest { @Test diff --git a/core/src/test/java/haveno/core/payment/validation/AltCoinAddressValidatorTest.java b/core/src/test/java/haveno/core/payment/validation/AltCoinAddressValidatorTest.java index 1920e237..867bf420 100644 --- a/core/src/test/java/haveno/core/payment/validation/AltCoinAddressValidatorTest.java +++ b/core/src/test/java/haveno/core/payment/validation/AltCoinAddressValidatorTest.java @@ -22,10 +22,10 @@ import haveno.common.config.BaseCurrencyNetwork; import haveno.common.config.Config; import haveno.core.locale.CurrencyUtil; import haveno.core.locale.Res; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AltCoinAddressValidatorTest { diff --git a/core/src/test/java/haveno/core/provider/mempool/TxValidatorTest.java b/core/src/test/java/haveno/core/provider/mempool/TxValidatorTest.java index 7df30485..490a0fc8 100644 --- a/core/src/test/java/haveno/core/provider/mempool/TxValidatorTest.java +++ b/core/src/test/java/haveno/core/provider/mempool/TxValidatorTest.java @@ -20,8 +20,7 @@ package haveno.core.provider.mempool; import com.google.gson.Gson; import org.apache.commons.io.IOUtils; import org.bitcoinj.core.Coin; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,6 +31,9 @@ import java.util.List; import java.util.Map; import java.util.Set; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class TxValidatorTest { private static final Logger log = LoggerFactory.getLogger(TxValidatorTest.class); @@ -70,12 +72,12 @@ public class TxValidatorTest { String jsonTxt = mempoolData.get(txValidator.getTxId()); if (jsonTxt == null || jsonTxt.isEmpty()) { log.warn("{} was not found in the mempool", txValidator.getTxId()); - Assert.assertFalse(expectedResult); // tx was not found in explorer + assertFalse(expectedResult); // tx was not found in explorer } else { //txValidator.parseJsonValidateMakerFeeTx(jsonTxt, btcFeeReceivers); log.warn("expectedResult {}", expectedResult ); log.warn("getResult {}", txValidator.getResult() ); - Assert.assertTrue(expectedResult == txValidator.getResult()); + assertTrue(expectedResult == txValidator.getResult()); } }); } diff --git a/core/src/test/java/haveno/core/provider/price/MarketPriceFeedServiceTest.java b/core/src/test/java/haveno/core/provider/price/MarketPriceFeedServiceTest.java index 8b175202..9effcaa5 100644 --- a/core/src/test/java/haveno/core/provider/price/MarketPriceFeedServiceTest.java +++ b/core/src/test/java/haveno/core/provider/price/MarketPriceFeedServiceTest.java @@ -17,14 +17,14 @@ package haveno.core.provider.price; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -@Ignore +@Disabled public class MarketPriceFeedServiceTest { private static final Logger log = LoggerFactory.getLogger(MarketPriceFeedServiceTest.class); diff --git a/core/src/test/java/haveno/core/trade/TradableListTest.java b/core/src/test/java/haveno/core/trade/TradableListTest.java index e038e0c5..87d3c194 100644 --- a/core/src/test/java/haveno/core/trade/TradableListTest.java +++ b/core/src/test/java/haveno/core/trade/TradableListTest.java @@ -20,9 +20,9 @@ package haveno.core.trade; import haveno.core.offer.Offer; import haveno.core.offer.OfferPayload; import haveno.core.offer.OpenOffer; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static protobuf.PersistableEnvelope.MessageCase.TRADABLE_LIST; diff --git a/core/src/test/java/haveno/core/user/PreferencesTest.java b/core/src/test/java/haveno/core/user/PreferencesTest.java index adc04fee..e1d4a851 100644 --- a/core/src/test/java/haveno/core/user/PreferencesTest.java +++ b/core/src/test/java/haveno/core/user/PreferencesTest.java @@ -27,16 +27,16 @@ import haveno.core.locale.GlobalSettings; import haveno.core.locale.Res; import haveno.core.xmr.nodes.LocalBitcoinNode; import javafx.collections.ObservableList; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Currency; import java.util.List; import java.util.Locale; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -46,7 +46,7 @@ public class PreferencesTest { private Preferences preferences; private PersistenceManager persistenceManager; - @Before + @BeforeEach public void setUp() { final Locale en_US = new Locale("en", "US"); Locale.setDefault(en_US); diff --git a/core/src/test/java/haveno/core/user/UserPayloadModelVOTest.java b/core/src/test/java/haveno/core/user/UserPayloadModelVOTest.java index 745d3762..83aed0e9 100644 --- a/core/src/test/java/haveno/core/user/UserPayloadModelVOTest.java +++ b/core/src/test/java/haveno/core/user/UserPayloadModelVOTest.java @@ -23,19 +23,19 @@ import haveno.core.arbitration.ArbitratorTest; import haveno.core.arbitration.MediatorTest; import haveno.core.filter.Filter; import haveno.core.proto.CoreProtoResolver; -import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; import java.util.HashSet; public class UserPayloadModelVOTest { - @Ignore("TODO InvalidKeySpecException at haveno.common.crypto.Sig.getPublicKeyFromBytes(Sig.java:135)") + @Disabled("TODO InvalidKeySpecException at haveno.common.crypto.Sig.getPublicKeyFromBytes(Sig.java:135)") public void testRoundtrip() { UserPayload vo = new UserPayload(); vo.setAccountId("accountId"); UserPayload newVo = UserPayload.fromProto(vo.toProtoMessage().getUserPayload(), new CoreProtoResolver()); } - @Ignore("TODO InvalidKeySpecException at haveno.common.crypto.Sig.getPublicKeyFromBytes(Sig.java:135)") + @Disabled("TODO InvalidKeySpecException at haveno.common.crypto.Sig.getPublicKeyFromBytes(Sig.java:135)") public void testRoundtripFull() { UserPayload vo = new UserPayload(); vo.setAccountId("accountId"); diff --git a/core/src/test/java/haveno/core/util/FormattingUtilsTest.java b/core/src/test/java/haveno/core/util/FormattingUtilsTest.java index eadd1158..6eb3c49b 100644 --- a/core/src/test/java/haveno/core/util/FormattingUtilsTest.java +++ b/core/src/test/java/haveno/core/util/FormattingUtilsTest.java @@ -6,8 +6,8 @@ import haveno.core.locale.GlobalSettings; import haveno.core.locale.Res; import haveno.core.monetary.Price; import org.bitcoinj.utils.Fiat; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Locale; import java.util.concurrent.TimeUnit; @@ -15,8 +15,8 @@ import java.util.concurrent.TimeUnit; import static com.natpryce.makeiteasy.MakeItEasy.a; import static com.natpryce.makeiteasy.MakeItEasy.make; import static com.natpryce.makeiteasy.MakeItEasy.with; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class FormattingUtilsTest { private static final Property currencyCode = new Property<>(); @@ -24,7 +24,7 @@ public class FormattingUtilsTest { private static final Maker usdPrice = a(lookup -> new Price(Fiat.parseFiat(lookup.valueOf(currencyCode, "USD"), lookup.valueOf(priceString, "100")))); - @Before + @BeforeEach public void setUp() { Locale.setDefault(new Locale("en", "US")); GlobalSettings.setLocale(new Locale("en", "US")); diff --git a/core/src/test/java/haveno/core/util/ProtoUtilTest.java b/core/src/test/java/haveno/core/util/ProtoUtilTest.java index 79255d6c..edee3c1c 100644 --- a/core/src/test/java/haveno/core/util/ProtoUtilTest.java +++ b/core/src/test/java/haveno/core/util/ProtoUtilTest.java @@ -17,13 +17,14 @@ package haveno.core.util; -import haveno.common.proto.ProtoUtil; import haveno.core.offer.OfferDirection; import haveno.core.offer.OpenOffer; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import protobuf.OpenOffer.State; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static haveno.common.proto.ProtoUtil.enumFromProto; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; @SuppressWarnings("UnusedAssignment") public class ProtoUtilTest { @@ -41,9 +42,9 @@ public class ProtoUtilTest { @Test public void testUnknownEnum() { - protobuf.OpenOffer.State result = protobuf.OpenOffer.State.PB_ERROR; + State result = State.PB_ERROR; try { - OpenOffer.State finalResult = OpenOffer.State.valueOf(result.name()); + OpenOffer.State.valueOf(result.name()); fail(); } catch (IllegalArgumentException ignore) { } @@ -51,10 +52,10 @@ public class ProtoUtilTest { @Test public void testUnknownEnumFix() { - protobuf.OpenOffer.State result = protobuf.OpenOffer.State.PB_ERROR; + State result = State.PB_ERROR; try { - OpenOffer.State finalResult = ProtoUtil.enumFromProto(OpenOffer.State.class, result.name()); - assertEquals(OpenOffer.State.AVAILABLE, ProtoUtil.enumFromProto(OpenOffer.State.class, "AVAILABLE")); + enumFromProto(OpenOffer.State.class, result.name()); + assertEquals(OpenOffer.State.AVAILABLE, enumFromProto(OpenOffer.State.class, "AVAILABLE")); } catch (IllegalArgumentException e) { fail(); } diff --git a/core/src/test/java/haveno/core/util/RegexValidatorTest.java b/core/src/test/java/haveno/core/util/RegexValidatorTest.java index e425f3aa..04c725f0 100644 --- a/core/src/test/java/haveno/core/util/RegexValidatorTest.java +++ b/core/src/test/java/haveno/core/util/RegexValidatorTest.java @@ -21,18 +21,18 @@ import haveno.core.locale.GlobalSettings; import haveno.core.locale.Res; import haveno.core.util.validation.RegexValidator; import haveno.core.util.validation.RegexValidatorFactory; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Locale; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class RegexValidatorTest { - @Before + @BeforeEach public void setup() { Locale.setDefault(new Locale("en", "US")); GlobalSettings.setLocale(new Locale("en", "US")); diff --git a/core/src/test/java/haveno/core/util/coin/CoinUtilTest.java b/core/src/test/java/haveno/core/util/coin/CoinUtilTest.java index 14f8e384..9ff4fdf2 100644 --- a/core/src/test/java/haveno/core/util/coin/CoinUtilTest.java +++ b/core/src/test/java/haveno/core/util/coin/CoinUtilTest.java @@ -21,12 +21,12 @@ import haveno.core.monetary.Price; import haveno.core.trade.HavenoUtils; import haveno.core.xmr.wallet.Restrictions; import org.bitcoinj.core.Coin; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.math.BigInteger; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class CoinUtilTest { @@ -64,9 +64,9 @@ public class CoinUtilTest { HavenoUtils.xmrToAtomicUnits(0.2).longValueExact(), 1); assertEquals( - "Minimum trade amount allowed should be adjusted to the smallest trade allowed.", HavenoUtils.formatXmr(Restrictions.MIN_TRADE_AMOUNT, true), - HavenoUtils.formatXmr(result, true) + HavenoUtils.formatXmr(result, true), + "Minimum trade amount allowed should be adjusted to the smallest trade allowed." ); try { @@ -78,9 +78,9 @@ public class CoinUtilTest { fail("Expected IllegalArgumentException to be thrown when amount is too low."); } catch (IllegalArgumentException iae) { assertEquals( - "Unexpected exception message.", "amount needs to be above minimum of 0.0001 xmr", - iae.getMessage() + iae.getMessage(), + "Unexpected exception message." ); } @@ -90,9 +90,9 @@ public class CoinUtilTest { HavenoUtils.xmrToAtomicUnits(0.2).longValueExact(), 1); assertEquals( - "Minimum allowed trade amount should not be adjusted.", "0.10 XMR", - HavenoUtils.formatXmr(result, true) + HavenoUtils.formatXmr(result, true), + "Minimum allowed trade amount should not be adjusted." ); result = CoinUtil.getAdjustedAmount( @@ -101,9 +101,9 @@ public class CoinUtilTest { HavenoUtils.xmrToAtomicUnits(0.25).longValueExact(), 1); assertEquals( - "Minimum trade amount allowed should respect maxTradeLimit and factor, if possible.", "0.10 XMR", - HavenoUtils.formatXmr(result, true) + HavenoUtils.formatXmr(result, true), + "Minimum trade amount allowed should respect maxTradeLimit and factor, if possible." ); // TODO(chirhonul): The following seems like it should raise an exception or otherwise fail. @@ -117,9 +117,9 @@ public class CoinUtilTest { HavenoUtils.xmrToAtomicUnits(0.00005).longValueExact(), 1); assertEquals( - "Minimum trade amount allowed with low maxTradeLimit should still respect that limit, even if result does not respect the factor specified.", "0.00005 XMR", - HavenoUtils.formatXmr(result, true) + HavenoUtils.formatXmr(result, true), + "Minimum trade amount allowed with low maxTradeLimit should still respect that limit, even if result does not respect the factor specified." ); } } diff --git a/core/src/test/java/haveno/core/xmr/nodes/BtcNetworkConfigTest.java b/core/src/test/java/haveno/core/xmr/nodes/BtcNetworkConfigTest.java index ac700193..e0197e54 100644 --- a/core/src/test/java/haveno/core/xmr/nodes/BtcNetworkConfigTest.java +++ b/core/src/test/java/haveno/core/xmr/nodes/BtcNetworkConfigTest.java @@ -22,8 +22,8 @@ import haveno.core.xmr.setup.WalletConfig; import haveno.network.Socks5MultiDiscovery; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.PeerAddress; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; @@ -37,7 +37,7 @@ public class BtcNetworkConfigTest { private WalletConfig delegate; - @Before + @BeforeEach public void setUp() { delegate = mock(WalletConfig.class); } diff --git a/core/src/test/java/haveno/core/xmr/nodes/BtcNodeConverterTest.java b/core/src/test/java/haveno/core/xmr/nodes/BtcNodeConverterTest.java index a27a4958..d3c6ab48 100644 --- a/core/src/test/java/haveno/core/xmr/nodes/BtcNodeConverterTest.java +++ b/core/src/test/java/haveno/core/xmr/nodes/BtcNodeConverterTest.java @@ -22,11 +22,11 @@ import haveno.core.xmr.nodes.BtcNodeConverter.Facade; import haveno.core.xmr.nodes.BtcNodes.BtcNode; import haveno.network.DnsLookupException; import org.bitcoinj.core.PeerAddress; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.net.InetAddress; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; diff --git a/core/src/test/java/haveno/core/xmr/nodes/BtcNodesRepositoryTest.java b/core/src/test/java/haveno/core/xmr/nodes/BtcNodesRepositoryTest.java index ba5d5212..6b37c306 100644 --- a/core/src/test/java/haveno/core/xmr/nodes/BtcNodesRepositoryTest.java +++ b/core/src/test/java/haveno/core/xmr/nodes/BtcNodesRepositoryTest.java @@ -21,14 +21,14 @@ import com.google.common.collect.Lists; import com.runjva.sourceforge.jsocks.protocol.Socks5Proxy; import haveno.core.xmr.nodes.BtcNodes.BtcNode; import org.bitcoinj.core.PeerAddress; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; diff --git a/core/src/test/java/haveno/core/xmr/nodes/BtcNodesSetupPreferencesTest.java b/core/src/test/java/haveno/core/xmr/nodes/BtcNodesSetupPreferencesTest.java index 4989b6c5..04264e44 100644 --- a/core/src/test/java/haveno/core/xmr/nodes/BtcNodesSetupPreferencesTest.java +++ b/core/src/test/java/haveno/core/xmr/nodes/BtcNodesSetupPreferencesTest.java @@ -19,14 +19,14 @@ package haveno.core.xmr.nodes; import haveno.core.user.Preferences; import haveno.core.xmr.nodes.BtcNodes.BtcNode; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; import static haveno.core.xmr.nodes.BtcNodes.BitcoinNodesOption.CUSTOM; import static haveno.core.xmr.nodes.BtcNodes.BitcoinNodesOption.PUBLIC; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/core/src/test/java/haveno/core/xmr/wallet/RestrictionsTest.java b/core/src/test/java/haveno/core/xmr/wallet/RestrictionsTest.java index 73ba3a0a..a815d506 100644 --- a/core/src/test/java/haveno/core/xmr/wallet/RestrictionsTest.java +++ b/core/src/test/java/haveno/core/xmr/wallet/RestrictionsTest.java @@ -18,10 +18,10 @@ package haveno.core.xmr.wallet; import org.bitcoinj.core.Coin; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; @SuppressWarnings("ConstantConditions") public class RestrictionsTest { diff --git a/daemon/src/test/java/haveno/daemon/grpc/interceptor/GrpcServiceRateMeteringConfigTest.java b/daemon/src/test/java/haveno/daemon/grpc/interceptor/GrpcServiceRateMeteringConfigTest.java index 0b39b1f6..af631dac 100644 --- a/daemon/src/test/java/haveno/daemon/grpc/interceptor/GrpcServiceRateMeteringConfigTest.java +++ b/daemon/src/test/java/haveno/daemon/grpc/interceptor/GrpcServiceRateMeteringConfigTest.java @@ -20,10 +20,10 @@ package haveno.daemon.grpc.interceptor; import haveno.daemon.grpc.GrpcVersionService; import io.grpc.ServerInterceptor; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.nio.file.Paths; @@ -49,7 +49,7 @@ public class GrpcServiceRateMeteringConfigTest { @SuppressWarnings("OptionalUsedAsFieldOrParameterType") private static Optional versionServiceInterceptor; - @BeforeClass + @BeforeAll public static void setup() { // This is the tested rate meter, it allows 3 calls every 2 seconds. builder.addCallRateMeter(GrpcVersionService.class.getSimpleName(), @@ -77,7 +77,7 @@ public class GrpcServiceRateMeteringConfigTest { HOURS); } - @Before + @BeforeEach public void buildConfigFile() { if (configFile == null) configFile = builder.build(); @@ -157,7 +157,7 @@ public class GrpcServiceRateMeteringConfigTest { assertEquals(expectedCallsCount, rateMeter.getCallsCount()); } - @AfterClass + @AfterAll public static void teardown() { if (configFile != null) configFile.deleteOnExit(); diff --git a/desktop/src/test/java/haveno/desktop/GuiceSetupTest.java b/desktop/src/test/java/haveno/desktop/GuiceSetupTest.java index 34d637e3..7d97b94b 100644 --- a/desktop/src/test/java/haveno/desktop/GuiceSetupTest.java +++ b/desktop/src/test/java/haveno/desktop/GuiceSetupTest.java @@ -55,18 +55,18 @@ import haveno.desktop.main.presentation.MarketPricePresentation; import haveno.desktop.util.Transitions; import haveno.network.p2p.network.BridgeAddressProvider; import haveno.network.p2p.seed.SeedNodeRepository; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static junit.framework.TestCase.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; public class GuiceSetupTest { private Injector injector; - @Before + @BeforeEach public void setUp() { Res.setup(); CurrencyUtil.setup(); diff --git a/desktop/src/test/java/haveno/desktop/common/fxml/FxmlViewLoaderTests.java b/desktop/src/test/java/haveno/desktop/common/fxml/FxmlViewLoaderTests.java index dd4085fb..4e56e686 100644 --- a/desktop/src/test/java/haveno/desktop/common/fxml/FxmlViewLoaderTests.java +++ b/desktop/src/test/java/haveno/desktop/common/fxml/FxmlViewLoaderTests.java @@ -24,30 +24,28 @@ import haveno.desktop.common.view.View; import haveno.desktop.common.view.ViewFactory; import haveno.desktop.common.view.ViewLoader; import javafx.fxml.LoadException; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.ResourceBundle; import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -// TODO Some refactorings seem to have broken those tests. Investigate and remove @Ignore as soon its fixed. -@Ignore +// TODO Some refactorings seem to have broken those tests. Investigate and remove @Disabled as soon its fixed. +@Disabled public class FxmlViewLoaderTests { private ViewLoader viewLoader; private ViewFactory viewFactory; - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before + @BeforeEach public void setUp() { viewFactory = mock(ViewFactory.class); ResourceBundle resourceBundle = mock(ResourceBundle.class); @@ -73,9 +71,8 @@ public class FxmlViewLoaderTests { @Test public void fxmlFileMissingFxControllerAttributeShouldThrow() { - thrown.expect(ViewfxException.class); - thrown.expectMessage("Does it declare an fx:controller attribute?"); - viewLoader.load(MissingFxController.class); + Throwable exception = assertThrows(ViewfxException.class, () -> viewLoader.load(MissingFxController.class)); + assertEquals("Does it declare an fx:controller attribute?", exception.getMessage()); } @@ -96,10 +93,9 @@ public class FxmlViewLoaderTests { @Test public void malformedFxmlFileShouldThrow() { - thrown.expect(ViewfxException.class); - thrown.expectMessage("Failed to load view from FXML file"); - thrown.expectCause(instanceOf(LoadException.class)); - viewLoader.load(Malformed.class); + Throwable exception = assertThrows(ViewfxException.class, () -> viewLoader.load(Malformed.class)); + assertTrue(exception.getCause() instanceof LoadException); + assertEquals("Failed to load view from FXML file", exception.getMessage()); } @@ -109,9 +105,8 @@ public class FxmlViewLoaderTests { @Test public void missingFxmlFileShouldThrow() { - thrown.expect(ViewfxException.class); - thrown.expectMessage("Does it exist?"); - viewLoader.load(MissingFxmlFile.class); + Throwable exception = assertThrows(ViewfxException.class, () -> viewLoader.load(MissingFxmlFile.class)); + assertEquals("Does it exist?", exception.getMessage()); } @@ -121,11 +116,10 @@ public class FxmlViewLoaderTests { @Test public void customFxmlFileLocationShouldOverrideDefaultConvention() { - thrown.expect(ViewfxException.class); - thrown.expectMessage("Failed to load view class"); - thrown.expectMessage("CustomLocation"); - thrown.expectMessage("[unconventionally/located.fxml] could not be loaded"); - viewLoader.load(CustomLocation.class); + Throwable exception = assertThrows(ViewfxException.class, () -> viewLoader.load(CustomLocation.class)); + assertTrue(exception.getMessage().contains("Failed to load view class")); + assertTrue(exception.getMessage().contains("CustomLocation")); + assertTrue(exception.getMessage().contains("[unconventionally/located.fxml] could not be loaded")); } } diff --git a/desktop/src/test/java/haveno/desktop/common/support/CachingViewLoaderTests.java b/desktop/src/test/java/haveno/desktop/common/support/CachingViewLoaderTests.java index a9035b8e..85b793e3 100644 --- a/desktop/src/test/java/haveno/desktop/common/support/CachingViewLoaderTests.java +++ b/desktop/src/test/java/haveno/desktop/common/support/CachingViewLoaderTests.java @@ -20,7 +20,7 @@ package haveno.desktop.common.support; import haveno.desktop.common.view.AbstractView; import haveno.desktop.common.view.CachingViewLoader; import haveno.desktop.common.view.ViewLoader; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.BDDMockito.then; import static org.mockito.Mockito.mock; diff --git a/desktop/src/test/java/haveno/desktop/components/ColoredDecimalPlacesWithZerosTextTest.java b/desktop/src/test/java/haveno/desktop/components/ColoredDecimalPlacesWithZerosTextTest.java index 29426c23..44f95598 100644 --- a/desktop/src/test/java/haveno/desktop/components/ColoredDecimalPlacesWithZerosTextTest.java +++ b/desktop/src/test/java/haveno/desktop/components/ColoredDecimalPlacesWithZerosTextTest.java @@ -19,13 +19,13 @@ package haveno.desktop.components; import javafx.scene.control.Label; import javafx.scene.text.Text; -import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ColoredDecimalPlacesWithZerosTextTest { - @Ignore + @Disabled public void testOnlyZeroDecimals() { ColoredDecimalPlacesWithZerosText text = new ColoredDecimalPlacesWithZerosText("1.0000", 3); Label beforeZeros = (Label) text.getChildren().get(0); @@ -34,7 +34,7 @@ public class ColoredDecimalPlacesWithZerosTextTest { assertEquals("000", zeroDecimals.getText()); } - @Ignore + @Disabled public void testOneZeroDecimal() { ColoredDecimalPlacesWithZerosText text = new ColoredDecimalPlacesWithZerosText("1.2570", 3); Text beforeZeros = (Text) text.getChildren().get(0); @@ -43,7 +43,7 @@ public class ColoredDecimalPlacesWithZerosTextTest { assertEquals("0", zeroDecimals.getText()); } - @Ignore + @Disabled public void testMultipleZeroDecimal() { ColoredDecimalPlacesWithZerosText text = new ColoredDecimalPlacesWithZerosText("1.2000", 3); Text beforeZeros = (Text) text.getChildren().get(0); @@ -52,7 +52,7 @@ public class ColoredDecimalPlacesWithZerosTextTest { assertEquals("000", zeroDecimals.getText()); } - @Ignore + @Disabled public void testZeroDecimalsWithRange() { ColoredDecimalPlacesWithZerosText text = new ColoredDecimalPlacesWithZerosText("0.1000 - 0.1250", 3); assertEquals(5, text.getChildren().size()); @@ -68,7 +68,7 @@ public class ColoredDecimalPlacesWithZerosTextTest { assertEquals("0", zeroDecimals2.getText()); } - @Ignore + @Disabled public void testNoColorizing() { ColoredDecimalPlacesWithZerosText text = new ColoredDecimalPlacesWithZerosText("1.2570", 0); Text beforeZeros = (Text) text.getChildren().get(0); diff --git a/desktop/src/test/java/haveno/desktop/main/funds/transactions/DisplayedTransactionsTest.java b/desktop/src/test/java/haveno/desktop/main/funds/transactions/DisplayedTransactionsTest.java index ac38364d..773800e2 100644 --- a/desktop/src/test/java/haveno/desktop/main/funds/transactions/DisplayedTransactionsTest.java +++ b/desktop/src/test/java/haveno/desktop/main/funds/transactions/DisplayedTransactionsTest.java @@ -21,12 +21,12 @@ import com.google.common.collect.Lists; import haveno.core.xmr.wallet.XmrWalletService; import javafx.collections.FXCollections; import monero.wallet.model.MoneroTxWallet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; diff --git a/desktop/src/test/java/haveno/desktop/main/funds/transactions/ObservableListDecoratorTest.java b/desktop/src/test/java/haveno/desktop/main/funds/transactions/ObservableListDecoratorTest.java index 9fc0c192..e9966cb6 100644 --- a/desktop/src/test/java/haveno/desktop/main/funds/transactions/ObservableListDecoratorTest.java +++ b/desktop/src/test/java/haveno/desktop/main/funds/transactions/ObservableListDecoratorTest.java @@ -18,12 +18,12 @@ package haveno.desktop.main.funds.transactions; import com.google.common.collect.Lists; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.function.Supplier; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/desktop/src/test/java/haveno/desktop/main/funds/transactions/TransactionAwareTradableFactoryTest.java b/desktop/src/test/java/haveno/desktop/main/funds/transactions/TransactionAwareTradableFactoryTest.java index 073aac62..423e30bd 100644 --- a/desktop/src/test/java/haveno/desktop/main/funds/transactions/TransactionAwareTradableFactoryTest.java +++ b/desktop/src/test/java/haveno/desktop/main/funds/transactions/TransactionAwareTradableFactoryTest.java @@ -22,9 +22,9 @@ import haveno.core.support.dispute.arbitration.ArbitrationManager; import haveno.core.trade.Tradable; import haveno.core.trade.Trade; import monero.wallet.model.MoneroTxWallet; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.Mockito.mock; public class TransactionAwareTradableFactoryTest { diff --git a/desktop/src/test/java/haveno/desktop/main/funds/transactions/TransactionAwareTradeTest.java b/desktop/src/test/java/haveno/desktop/main/funds/transactions/TransactionAwareTradeTest.java index 5542e6b4..21893999 100644 --- a/desktop/src/test/java/haveno/desktop/main/funds/transactions/TransactionAwareTradeTest.java +++ b/desktop/src/test/java/haveno/desktop/main/funds/transactions/TransactionAwareTradeTest.java @@ -25,12 +25,12 @@ import haveno.core.xmr.wallet.XmrWalletService; import javafx.collections.FXCollections; import monero.wallet.model.MoneroTxWallet; import org.bitcoinj.core.Sha256Hash; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Set; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -45,7 +45,7 @@ public class TransactionAwareTradeTest { private RefundManager refundManager; private XmrWalletService xmrWalletService; - @Before + @BeforeEach public void setUp() { this.transaction = mock(MoneroTxWallet.class); when(transaction.getHash()).thenReturn(XID.toString()); diff --git a/desktop/src/test/java/haveno/desktop/main/market/offerbook/OfferBookChartViewModelTest.java b/desktop/src/test/java/haveno/desktop/main/market/offerbook/OfferBookChartViewModelTest.java index b28a102b..ef7fbfb6 100644 --- a/desktop/src/test/java/haveno/desktop/main/market/offerbook/OfferBookChartViewModelTest.java +++ b/desktop/src/test/java/haveno/desktop/main/market/offerbook/OfferBookChartViewModelTest.java @@ -25,8 +25,8 @@ import haveno.desktop.main.offer.offerbook.OfferBookListItemMaker; import javafx.beans.property.SimpleIntegerProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static com.natpryce.makeiteasy.MakeItEasy.make; import static com.natpryce.makeiteasy.MakeItEasy.with; @@ -34,14 +34,14 @@ import static haveno.desktop.main.offer.offerbook.OfferBookListItemMaker.xmrBuyI import static haveno.desktop.main.offer.offerbook.OfferBookListItemMaker.xmrSellItem; import static haveno.desktop.maker.PreferenceMakers.empty; import static haveno.desktop.maker.TradeCurrencyMakers.usd; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class OfferBookChartViewModelTest { - @Before + @BeforeEach public void setUp() { GlobalSettings.setDefaultTradeCurrency(usd); } diff --git a/desktop/src/test/java/haveno/desktop/main/market/spread/SpreadViewModelTest.java b/desktop/src/test/java/haveno/desktop/main/market/spread/SpreadViewModelTest.java index 47e41ba2..1b66e609 100644 --- a/desktop/src/test/java/haveno/desktop/main/market/spread/SpreadViewModelTest.java +++ b/desktop/src/test/java/haveno/desktop/main/market/spread/SpreadViewModelTest.java @@ -27,14 +27,14 @@ import haveno.desktop.main.offer.offerbook.OfferBookListItem; import haveno.desktop.main.offer.offerbook.OfferBookListItemMaker; import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.natpryce.makeiteasy.MakeItEasy.make; import static com.natpryce.makeiteasy.MakeItEasy.with; import static haveno.desktop.main.offer.offerbook.OfferBookListItemMaker.id; import static haveno.desktop.main.offer.offerbook.OfferBookListItemMaker.xmrBuyItem; import static haveno.desktop.main.offer.offerbook.OfferBookListItemMaker.xmrSellItem; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/desktop/src/test/java/haveno/desktop/main/market/trades/TradesChartsViewModelTest.java b/desktop/src/test/java/haveno/desktop/main/market/trades/TradesChartsViewModelTest.java index 4f5da919..b6bfa646 100644 --- a/desktop/src/test/java/haveno/desktop/main/market/trades/TradesChartsViewModelTest.java +++ b/desktop/src/test/java/haveno/desktop/main/market/trades/TradesChartsViewModelTest.java @@ -32,9 +32,9 @@ import javafx.collections.ObservableSet; import javafx.util.Pair; import org.bitcoinj.core.Coin; import org.bitcoinj.utils.Fiat; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -47,7 +47,7 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; public class TradesChartsViewModelTest { @@ -94,7 +94,7 @@ public class TradesChartsViewModelTest { null, null); - @Before + @BeforeEach public void setup() throws IOException { tradeStatisticsManager = mock(TradeStatisticsManager.class); model = new TradesChartsViewModel(tradeStatisticsManager, mock(Preferences.class), mock(PriceFeedService.class), @@ -177,7 +177,7 @@ public class TradesChartsViewModelTest { } // TODO JMOCKIT - @Ignore + @Disabled @Test public void testItemLists() throws ParseException { // Helper class to add historic trades diff --git a/desktop/src/test/java/haveno/desktop/main/offer/createoffer/CreateOfferDataModelTest.java b/desktop/src/test/java/haveno/desktop/main/offer/createoffer/CreateOfferDataModelTest.java index 28ea2e3a..ee8e6335 100644 --- a/desktop/src/test/java/haveno/desktop/main/offer/createoffer/CreateOfferDataModelTest.java +++ b/desktop/src/test/java/haveno/desktop/main/offer/createoffer/CreateOfferDataModelTest.java @@ -17,13 +17,13 @@ import haveno.core.user.User; import haveno.core.xmr.model.XmrAddressEntry; import haveno.core.xmr.wallet.XmrWalletService; import javafx.collections.FXCollections; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.UUID; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -36,7 +36,7 @@ public class CreateOfferDataModelTest { private Preferences preferences; private OfferUtil offerUtil; - @Before + @BeforeEach public void setUp() { final CryptoCurrency xmr = new CryptoCurrency("XMR", "monero"); GlobalSettings.setDefaultTradeCurrency(xmr); diff --git a/desktop/src/test/java/haveno/desktop/main/offer/createoffer/CreateOfferViewModelTest.java b/desktop/src/test/java/haveno/desktop/main/offer/createoffer/CreateOfferViewModelTest.java index 3bfcc3fe..57cb4f44 100644 --- a/desktop/src/test/java/haveno/desktop/main/offer/createoffer/CreateOfferViewModelTest.java +++ b/desktop/src/test/java/haveno/desktop/main/offer/createoffer/CreateOfferViewModelTest.java @@ -44,16 +44,16 @@ import haveno.core.xmr.model.XmrAddressEntry; import haveno.core.xmr.wallet.XmrWalletService; import javafx.beans.property.SimpleIntegerProperty; import javafx.collections.FXCollections; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.time.Instant; import java.util.UUID; import static haveno.desktop.maker.PreferenceMakers.empty; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -65,7 +65,7 @@ public class CreateOfferViewModelTest { private final CoinFormatter coinFormatter = new ImmutableCoinFormatter( Config.baseCurrencyNetworkParameters().getMonetaryFormat()); - @Before + @BeforeEach public void setUp() { final CryptoCurrency btc = new CryptoCurrency("XMR", "monero"); GlobalSettings.setDefaultTradeCurrency(btc); diff --git a/desktop/src/test/java/haveno/desktop/main/offer/offerbook/OfferBookViewModelTest.java b/desktop/src/test/java/haveno/desktop/main/offer/offerbook/OfferBookViewModelTest.java index 0050511c..264fb808 100644 --- a/desktop/src/test/java/haveno/desktop/main/offer/offerbook/OfferBookViewModelTest.java +++ b/desktop/src/test/java/haveno/desktop/main/offer/offerbook/OfferBookViewModelTest.java @@ -51,9 +51,9 @@ import haveno.core.util.coin.ImmutableCoinFormatter; import javafx.beans.property.SimpleIntegerProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -73,10 +73,10 @@ import static haveno.desktop.main.offer.offerbook.OfferBookListItemMaker.xmrBuyI import static haveno.desktop.main.offer.offerbook.OfferBookListItemMaker.xmrItemWithRange; import static haveno.desktop.maker.PreferenceMakers.empty; import static haveno.desktop.maker.TradeCurrencyMakers.usd; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -87,7 +87,7 @@ public class OfferBookViewModelTest { private static final Logger log = LoggerFactory.getLogger(OfferBookViewModelTest.class); private User user; - @Before + @BeforeEach public void setUp() { GlobalSettings.setDefaultTradeCurrency(usd); Res.setBaseCurrencyCode(usd.getCode()); @@ -103,7 +103,7 @@ public class OfferBookViewModelTest { return new PriceUtil(priceFeedService, tradeStatisticsManager, empty); } - @Ignore("PaymentAccountPayload needs to be set (has been changed with PB changes)") + @Disabled("PaymentAccountPayload needs to be set (has been changed with PB changes)") public void testIsAnyPaymentAccountValidForOffer() { Collection paymentAccounts; paymentAccounts = new ArrayList<>(FXCollections.singletonObservableList(getSepaAccount("EUR", "DE", "1212324", diff --git a/desktop/src/test/java/haveno/desktop/main/overlays/OverlayTest.java b/desktop/src/test/java/haveno/desktop/main/overlays/OverlayTest.java index bfee5243..fa86f85b 100644 --- a/desktop/src/test/java/haveno/desktop/main/overlays/OverlayTest.java +++ b/desktop/src/test/java/haveno/desktop/main/overlays/OverlayTest.java @@ -17,7 +17,9 @@ package haveno.desktop.main.overlays; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; public class OverlayTest { @@ -28,9 +30,9 @@ public class OverlayTest { new D<>(); } - @Test(expected = RuntimeException.class) + @Test public void typeUnsafeCreation() { - new B(); + assertThrows(RuntimeException.class, () -> new B()); } private static class A extends Overlay { diff --git a/desktop/src/test/java/haveno/desktop/main/overlays/windows/downloadupdate/HavenoInstallerTest.java b/desktop/src/test/java/haveno/desktop/main/overlays/windows/downloadupdate/HavenoInstallerTest.java index 67cffd56..114241e4 100644 --- a/desktop/src/test/java/haveno/desktop/main/overlays/windows/downloadupdate/HavenoInstallerTest.java +++ b/desktop/src/test/java/haveno/desktop/main/overlays/windows/downloadupdate/HavenoInstallerTest.java @@ -20,13 +20,13 @@ package haveno.desktop.main.overlays.windows.downloadupdate; import com.google.common.collect.Lists; import haveno.desktop.main.overlays.windows.downloadupdate.HavenoInstaller.FileDescriptor; import lombok.extern.slf4j.Slf4j; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.net.URL; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; @Slf4j public class HavenoInstallerTest { diff --git a/desktop/src/test/java/haveno/desktop/main/overlays/windows/downloadupdate/VerifyTaskTest.java b/desktop/src/test/java/haveno/desktop/main/overlays/windows/downloadupdate/VerifyTaskTest.java index b2a54a3c..d586d675 100644 --- a/desktop/src/test/java/haveno/desktop/main/overlays/windows/downloadupdate/VerifyTaskTest.java +++ b/desktop/src/test/java/haveno/desktop/main/overlays/windows/downloadupdate/VerifyTaskTest.java @@ -17,7 +17,7 @@ package haveno.desktop.main.overlays.windows.downloadupdate; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class VerifyTaskTest { diff --git a/desktop/src/test/java/haveno/desktop/main/settings/preferences/PreferencesViewModelTest.java b/desktop/src/test/java/haveno/desktop/main/settings/preferences/PreferencesViewModelTest.java index 20c65a2d..9424d4ec 100644 --- a/desktop/src/test/java/haveno/desktop/main/settings/preferences/PreferencesViewModelTest.java +++ b/desktop/src/test/java/haveno/desktop/main/settings/preferences/PreferencesViewModelTest.java @@ -26,12 +26,12 @@ import haveno.desktop.maker.PreferenceMakers; import haveno.network.p2p.NodeAddress; import javafx.collections.FXCollections; import javafx.collections.ObservableMap; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/desktop/src/test/java/haveno/desktop/util/CurrencyListTest.java b/desktop/src/test/java/haveno/desktop/util/CurrencyListTest.java index ce2c7362..b1bd5de6 100644 --- a/desktop/src/test/java/haveno/desktop/util/CurrencyListTest.java +++ b/desktop/src/test/java/haveno/desktop/util/CurrencyListTest.java @@ -22,15 +22,15 @@ import haveno.core.locale.CryptoCurrency; import haveno.core.locale.FiatCurrency; import haveno.core.locale.TradeCurrency; import haveno.core.user.Preferences; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Currency; import java.util.List; import java.util.Locale; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -46,7 +46,7 @@ public class CurrencyListTest { private List delegate; private CurrencyList testedEntity; - @Before + @BeforeEach public void setUp() { Locale.setDefault(locale); diff --git a/desktop/src/test/java/haveno/desktop/util/DisplayUtilsTest.java b/desktop/src/test/java/haveno/desktop/util/DisplayUtilsTest.java index 2a4db5ab..88d51ace 100644 --- a/desktop/src/test/java/haveno/desktop/util/DisplayUtilsTest.java +++ b/desktop/src/test/java/haveno/desktop/util/DisplayUtilsTest.java @@ -9,8 +9,8 @@ import haveno.core.offer.OfferPayload; import haveno.core.util.VolumeUtil; import haveno.core.util.coin.CoinFormatter; import haveno.core.util.coin.ImmutableCoinFormatter; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.util.Locale; @@ -21,14 +21,14 @@ import static com.natpryce.makeiteasy.MakeItEasy.with; import static haveno.desktop.maker.OfferMaker.xmrUsdOffer; import static haveno.desktop.maker.VolumeMaker.usdVolume; import static haveno.desktop.maker.VolumeMaker.volumeString; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DisplayUtilsTest { private final CoinFormatter formatter = new ImmutableCoinFormatter(Config.baseCurrencyNetworkParameters().getMonetaryFormat()); - @Before + @BeforeEach public void setUp() { Locale.setDefault(Locale.US); GlobalSettings.setLocale(Locale.US); diff --git a/desktop/src/test/java/haveno/desktop/util/GUIUtilTest.java b/desktop/src/test/java/haveno/desktop/util/GUIUtilTest.java index fa3cc72e..f155bdf6 100644 --- a/desktop/src/test/java/haveno/desktop/util/GUIUtilTest.java +++ b/desktop/src/test/java/haveno/desktop/util/GUIUtilTest.java @@ -24,8 +24,8 @@ import haveno.core.trade.HavenoUtils; import haveno.core.user.DontShowAgainLookup; import haveno.core.user.Preferences; import javafx.util.StringConverter; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.util.HashMap; @@ -34,14 +34,14 @@ import java.util.Map; import static haveno.desktop.maker.TradeCurrencyMakers.euro; import static haveno.desktop.maker.TradeCurrencyMakers.monero; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class GUIUtilTest { - @Before + @BeforeEach public void setup() { Locale.setDefault(new Locale("en", "US")); GlobalSettings.setLocale(new Locale("en", "US")); diff --git a/desktop/src/test/java/haveno/desktop/util/ImmutableCoinFormatterTest.java b/desktop/src/test/java/haveno/desktop/util/ImmutableCoinFormatterTest.java index 49a2ffda..4733ce5c 100644 --- a/desktop/src/test/java/haveno/desktop/util/ImmutableCoinFormatterTest.java +++ b/desktop/src/test/java/haveno/desktop/util/ImmutableCoinFormatterTest.java @@ -22,8 +22,8 @@ import haveno.core.locale.Res; import haveno.core.util.coin.CoinFormatter; import haveno.core.util.coin.ImmutableCoinFormatter; import org.bitcoinj.core.CoinMaker; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Locale; @@ -32,13 +32,13 @@ import static com.natpryce.makeiteasy.MakeItEasy.make; import static com.natpryce.makeiteasy.MakeItEasy.with; import static org.bitcoinj.core.CoinMaker.oneBitcoin; import static org.bitcoinj.core.CoinMaker.satoshis; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ImmutableCoinFormatterTest { private final CoinFormatter formatter = new ImmutableCoinFormatter(Config.baseCurrencyNetworkParameters().getMonetaryFormat()); - @Before + @BeforeEach public void setUp() { Locale.setDefault(new Locale("en", "US")); Res.setBaseCurrencyCode("XMR"); diff --git a/desktop/src/test/java/haveno/desktop/util/MovingAverageUtilsTest.java b/desktop/src/test/java/haveno/desktop/util/MovingAverageUtilsTest.java index 7a34bf7a..de6d8d1f 100644 --- a/desktop/src/test/java/haveno/desktop/util/MovingAverageUtilsTest.java +++ b/desktop/src/test/java/haveno/desktop/util/MovingAverageUtilsTest.java @@ -17,12 +17,14 @@ package haveno.desktop.util; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.stream.Stream; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class MovingAverageUtilsTest { private static final int NAN = -99; @@ -50,7 +52,7 @@ public class MovingAverageUtilsTest { private static void testMA(int period, int[] input, int[] expected) { var output = calcMA(period, input); - Assert.assertArrayEquals(output, expected); + assertArrayEquals(output, expected); } @Test @@ -107,24 +109,28 @@ public class MovingAverageUtilsTest { ); } - @Test(expected = IllegalArgumentException.class) + @Test public void nonsensicalPeriod1() { - var impossible = new int[]{}; - testMA( - 0, - new int[]{10, 20}, - impossible - ); + assertThrows(IllegalArgumentException.class, () -> { + var impossible = new int[]{}; + testMA( + 0, + new int[]{10, 20}, + impossible + ); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void nonsensicalPeriod2() { - var impossible = new int[]{}; - testMA( - -1, - new int[]{10, 20}, - impossible - ); + assertThrows(IllegalArgumentException.class, () -> { + var impossible = new int[]{}; + testMA( + -1, + new int[]{10, 20}, + impossible + ); + }); } @Test diff --git a/desktop/src/test/java/haveno/desktop/util/validation/AccountNrValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/AccountNrValidatorTest.java index 93d53c1e..cc28d581 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/AccountNrValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/AccountNrValidatorTest.java @@ -2,16 +2,16 @@ package haveno.desktop.util.validation; import haveno.core.locale.Res; import haveno.core.payment.validation.AccountNrValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Locale; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AccountNrValidatorTest { - @Before + @BeforeEach public void setup() { Locale.setDefault(new Locale("en", "US")); Res.setBaseCurrencyCode("XMR"); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/AdvancedCashValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/AdvancedCashValidatorTest.java index a3eae607..28ba8b29 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/AdvancedCashValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/AdvancedCashValidatorTest.java @@ -7,14 +7,14 @@ import haveno.core.locale.Res; import haveno.core.payment.validation.AdvancedCashValidator; import haveno.core.payment.validation.EmailValidator; import haveno.core.util.validation.RegexValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AdvancedCashValidatorTest { - @Before + @BeforeEach public void setup() { final BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork(); final String currencyCode = baseCurrencyNetwork.getCurrencyCode(); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/BranchIdValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/BranchIdValidatorTest.java index 82279e69..7aea9e6f 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/BranchIdValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/BranchIdValidatorTest.java @@ -2,17 +2,17 @@ package haveno.desktop.util.validation; import haveno.core.locale.Res; import haveno.core.payment.validation.BranchIdValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Locale; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class BranchIdValidatorTest { - @Before + @BeforeEach public void setup() { Locale.setDefault(new Locale("en", "US")); Res.setBaseCurrencyCode("XMR"); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/CapitualValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/CapitualValidatorTest.java index 0e15aef6..016055a4 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/CapitualValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/CapitualValidatorTest.java @@ -6,14 +6,14 @@ import haveno.core.locale.CurrencyUtil; import haveno.core.locale.Res; import haveno.core.payment.validation.CapitualValidator; import haveno.core.util.validation.RegexValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class CapitualValidatorTest { - @Before + @BeforeEach public void setup() { final BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork(); final String currencyCode = baseCurrencyNetwork.getCurrencyCode(); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/FiatVolumeValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/FiatVolumeValidatorTest.java index df7eb775..bf31c7df 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/FiatVolumeValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/FiatVolumeValidatorTest.java @@ -22,15 +22,15 @@ import haveno.common.config.Config; import haveno.core.locale.CurrencyUtil; import haveno.core.locale.Res; import haveno.core.payment.validation.FiatVolumeValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class FiatVolumeValidatorTest { - @Before + @BeforeEach public void setup() { final BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork(); final String currencyCode = baseCurrencyNetwork.getCurrencyCode(); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferAnswerValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferAnswerValidatorTest.java index 6503883d..a397aae8 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferAnswerValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferAnswerValidatorTest.java @@ -24,15 +24,15 @@ import haveno.core.locale.Res; import haveno.core.payment.validation.InteracETransferAnswerValidator; import haveno.core.payment.validation.LengthValidator; import haveno.core.util.validation.RegexValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class InteracETransferAnswerValidatorTest { - @Before + @BeforeEach public void setup() { final BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork(); final String currencyCode = baseCurrencyNetwork.getCurrencyCode(); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferQuestionValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferQuestionValidatorTest.java index b71ce4db..5fc3aa4f 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferQuestionValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferQuestionValidatorTest.java @@ -24,15 +24,15 @@ import haveno.core.locale.Res; import haveno.core.payment.validation.InteracETransferQuestionValidator; import haveno.core.payment.validation.LengthValidator; import haveno.core.util.validation.RegexValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class InteracETransferQuestionValidatorTest { - @Before + @BeforeEach public void setup() { final BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork(); final String currencyCode = baseCurrencyNetwork.getCurrencyCode(); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferValidatorTest.java index 6f3fd055..cb8c3696 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/InteracETransferValidatorTest.java @@ -27,15 +27,15 @@ import haveno.core.payment.validation.InteracETransferQuestionValidator; import haveno.core.payment.validation.InteracETransferValidator; import haveno.core.payment.validation.LengthValidator; import haveno.core.util.validation.RegexValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class InteracETransferValidatorTest { - @Before + @BeforeEach public void setup() { final BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork(); final String currencyCode = baseCurrencyNetwork.getCurrencyCode(); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/LengthValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/LengthValidatorTest.java index e8a94a5e..8664bb76 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/LengthValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/LengthValidatorTest.java @@ -22,15 +22,15 @@ import haveno.common.config.Config; import haveno.core.locale.CurrencyUtil; import haveno.core.locale.Res; import haveno.core.payment.validation.LengthValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class LengthValidatorTest { - @Before + @BeforeEach public void setup() { final BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork(); final String currencyCode = baseCurrencyNetwork.getCurrencyCode(); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/NationalAccountIdValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/NationalAccountIdValidatorTest.java index 1c490ffd..2a1f4d6a 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/NationalAccountIdValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/NationalAccountIdValidatorTest.java @@ -2,17 +2,17 @@ package haveno.desktop.util.validation; import haveno.core.locale.Res; import haveno.core.payment.validation.NationalAccountIdValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Locale; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class NationalAccountIdValidatorTest { - @Before + @BeforeEach public void setup() { Locale.setDefault(new Locale("en", "US")); Res.setBaseCurrencyCode("XMR"); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/PhoneNumberValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/PhoneNumberValidatorTest.java index 076d1afa..5a24861f 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/PhoneNumberValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/PhoneNumberValidatorTest.java @@ -3,19 +3,19 @@ package haveno.desktop.util.validation; import haveno.core.locale.Res; import haveno.core.payment.validation.PhoneNumberValidator; import haveno.core.util.validation.InputValidator.ValidationResult; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class PhoneNumberValidatorTest { private PhoneNumberValidator validator; private ValidationResult validationResult; - @Before + @BeforeEach public void setup() { Res.setup(); } @@ -24,7 +24,7 @@ public class PhoneNumberValidatorTest { public void testMissingCountryCode() { validator = new PhoneNumberValidator(); validationResult = validator.validate("+12124567890"); - assertFalse("Should not be valid if validator's country code is missing", validationResult.isValid); + assertFalse(validationResult.isValid, "Should not be valid if validator's country code is missing"); assertEquals(Res.get("validation.phone.missingCountryCode"), validationResult.errorMessage); assertNull(validator.getNormalizedPhoneNumber()); } @@ -33,12 +33,12 @@ public class PhoneNumberValidatorTest { public void testNoInput() { validator = new PhoneNumberValidator("AT"); validationResult = validator.validate(""); - assertFalse("'' should not be a valid number in AT", validationResult.isValid); + assertFalse(validationResult.isValid, "'' should not be a valid number in AT"); assertEquals(Res.get("validation.empty"), validationResult.errorMessage); assertNull(validator.getNormalizedPhoneNumber()); validationResult = validator.validate(null); - assertFalse("'' should not be a valid number in AT", validationResult.isValid); + assertFalse(validationResult.isValid, "'' should not be a valid number in AT"); assertEquals(Res.get("validation.empty"), validationResult.errorMessage); assertNull(validator.getNormalizedPhoneNumber()); } @@ -69,12 +69,12 @@ public class PhoneNumberValidatorTest { public void testInvalidAustriaNumbers() { validator = new PhoneNumberValidator("AT"); // AT country code is +43 validationResult = validator.validate("+43 1 214"); - assertFalse("+43 1 214 should not be a valid number in AT", validationResult.isValid); + assertFalse(validationResult.isValid, "+43 1 214 should not be a valid number in AT"); assertEquals(Res.get("validation.phone.insufficientDigits", "+43 1 214"), validationResult.errorMessage); assertNull(validator.getNormalizedPhoneNumber()); validationResult = validator.validate("+42 1 650 454 0987"); - assertFalse("+42 1 650 454 0987 should not be a valid number in AT", validationResult.isValid); + assertFalse(validationResult.isValid, "+42 1 650 454 0987 should not be a valid number in AT"); assertEquals(Res.get("validation.phone.invalidDialingCode", "+42 1 650 454 0987", "AT", validator.getCallingCode()), validationResult.errorMessage); assertNull(validator.getNormalizedPhoneNumber()); @@ -136,7 +136,7 @@ public class PhoneNumberValidatorTest { public void testInvalidCanadaNumber() { validator = new PhoneNumberValidator("CA"); validationResult = validator.validate("+2 1 650 454 0987"); - assertFalse("+2 1 650 454 0987 should not be a valid number in CA", validationResult.isValid); + assertFalse(validationResult.isValid, "+2 1 650 454 0987 should not be a valid number in CA"); assertEquals(Res.get("validation.phone.invalidDialingCode", "+2 1 650 454 0987", "CA", validator.getCallingCode()), validationResult.errorMessage); assertNull(validator.getNormalizedPhoneNumber()); @@ -263,13 +263,13 @@ public class PhoneNumberValidatorTest { public void testInvalidUSNumbers() { validator = new PhoneNumberValidator("US"); validationResult = validator.validate("+1 512 GR8 0150"); - assertFalse("+1 512 GR8 0150 should not be a valid number in US", validationResult.isValid); + assertFalse(validationResult.isValid, "+1 512 GR8 0150 should not be a valid number in US"); assertEquals(Res.get("validation.phone.invalidCharacters", "+1 512 GR8 0150", "US", validator.getCallingCode()), validationResult.errorMessage); assertNull(validator.getNormalizedPhoneNumber()); validationResult = validator.validate("+1 212-3456-0150-9832"); - assertFalse("+1 212-3456-0150-9832 should not be a valid number in US", validationResult.isValid); + assertFalse(validationResult.isValid, "+1 212-3456-0150-9832 should not be a valid number in US"); assertEquals(Res.get("validation.phone.tooManyDigits", "+1 212-3456-0150-9832", "US", validator.getCallingCode()), validationResult.errorMessage); assertNull(validator.getNormalizedPhoneNumber()); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/RegexValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/RegexValidatorTest.java index 7e223c51..7fb94a10 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/RegexValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/RegexValidatorTest.java @@ -22,15 +22,15 @@ import haveno.common.config.Config; import haveno.core.locale.CurrencyUtil; import haveno.core.locale.Res; import haveno.core.util.validation.RegexValidator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class RegexValidatorTest { - @Before + @BeforeEach public void setup() { final BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork(); final String currencyCode = baseCurrencyNetwork.getCurrencyCode(); diff --git a/desktop/src/test/java/haveno/desktop/util/validation/XmrValidatorTest.java b/desktop/src/test/java/haveno/desktop/util/validation/XmrValidatorTest.java index 281d5667..42792bef 100644 --- a/desktop/src/test/java/haveno/desktop/util/validation/XmrValidatorTest.java +++ b/desktop/src/test/java/haveno/desktop/util/validation/XmrValidatorTest.java @@ -23,15 +23,15 @@ import haveno.core.locale.CurrencyUtil; import haveno.core.locale.Res; import haveno.core.payment.validation.XmrValidator; import haveno.core.trade.HavenoUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class XmrValidatorTest { - @Before + @BeforeEach public void setup() { final BaseCurrencyNetwork baseCurrencyNetwork = Config.baseCurrencyNetwork(); final String currencyCode = baseCurrencyNetwork.getCurrencyCode(); diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 7aa08be4..0fc40d92 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -2578,6 +2578,11 @@ + + + + + @@ -2586,6 +2591,11 @@ + + + + + @@ -2594,6 +2604,11 @@ + + + + + @@ -2610,6 +2625,11 @@ + + + + + @@ -2626,6 +2646,11 @@ + + + + + diff --git a/p2p/src/test/java/haveno/network/crypto/EncryptionServiceTests.java b/p2p/src/test/java/haveno/network/crypto/EncryptionServiceTests.java index d11ccfd5..56cb5368 100644 --- a/p2p/src/test/java/haveno/network/crypto/EncryptionServiceTests.java +++ b/p2p/src/test/java/haveno/network/crypto/EncryptionServiceTests.java @@ -22,10 +22,8 @@ import haveno.common.crypto.KeyRing; import haveno.common.crypto.KeyStorage; import haveno.common.file.FileUtil; import haveno.common.proto.network.NetworkEnvelope; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,13 +36,10 @@ import java.security.cert.CertificateException; public class EncryptionServiceTests { private static final Logger log = LoggerFactory.getLogger(EncryptionServiceTests.class); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private KeyRing keyRing; private File dir; - @Before + @BeforeEach public void setup() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, CryptoException { dir = File.createTempFile("temp_tests", ""); @@ -56,7 +51,7 @@ public class EncryptionServiceTests { keyRing = new KeyRing(keyStorage, null, true); } - @After + @AfterEach public void tearDown() throws IOException { FileUtil.deleteDirectory(dir); } diff --git a/p2p/src/test/java/haveno/network/p2p/PeerServiceTest.java b/p2p/src/test/java/haveno/network/p2p/PeerServiceTest.java index c1010956..42fc011b 100644 --- a/p2p/src/test/java/haveno/network/p2p/PeerServiceTest.java +++ b/p2p/src/test/java/haveno/network/p2p/PeerServiceTest.java @@ -18,10 +18,10 @@ package haveno.network.p2p; import haveno.network.p2p.network.LocalhostNetworkNode; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,7 +40,7 @@ import java.util.concurrent.CountDownLatch; // TODO deactivated because outdated @SuppressWarnings({"UnusedAssignment", "EmptyMethod"}) -@Ignore +@Disabled public class PeerServiceTest { private static final Logger log = LoggerFactory.getLogger(PeerServiceTest.class); private static final int MAX_CONNECTIONS = 100; @@ -53,7 +53,7 @@ public class PeerServiceTest { private final List seedNodes = new ArrayList<>(); private final String test_dummy_dir = "test_dummy_dir"; - @Before + @BeforeEach public void setup() throws InterruptedException { LocalhostNetworkNode.setSimulateTorDelayTorNode(50); LocalhostNetworkNode.setSimulateTorDelayHiddenService(8); @@ -73,7 +73,7 @@ public class PeerServiceTest { } } - @After + @AfterEach public void tearDown() throws InterruptedException { Thread.sleep(sleepTime); diff --git a/p2p/src/test/java/haveno/network/p2p/network/LocalhostNetworkNodeTest.java b/p2p/src/test/java/haveno/network/p2p/network/LocalhostNetworkNodeTest.java index 0c35524d..f6f0ca15 100644 --- a/p2p/src/test/java/haveno/network/p2p/network/LocalhostNetworkNodeTest.java +++ b/p2p/src/test/java/haveno/network/p2p/network/LocalhostNetworkNodeTest.java @@ -18,8 +18,8 @@ package haveno.network.p2p.network; import haveno.network.p2p.TestUtils; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,7 +31,7 @@ import java.util.concurrent.CountDownLatch; // Connection establishment takes about 4 sec. //TODO P2P network tests are outdated -@Ignore +@Disabled public class LocalhostNetworkNodeTest { private static final Logger log = LoggerFactory.getLogger(LocalhostNetworkNodeTest.class); diff --git a/p2p/src/test/java/haveno/network/p2p/network/TorNetworkNodeTest.java b/p2p/src/test/java/haveno/network/p2p/network/TorNetworkNodeTest.java index ddedb355..2269c020 100644 --- a/p2p/src/test/java/haveno/network/p2p/network/TorNetworkNodeTest.java +++ b/p2p/src/test/java/haveno/network/p2p/network/TorNetworkNodeTest.java @@ -24,8 +24,8 @@ import com.google.common.util.concurrent.SettableFuture; import haveno.network.p2p.TestUtils; import haveno.network.p2p.mocks.MockPayload; import org.jetbrains.annotations.NotNull; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,7 +40,7 @@ import java.util.concurrent.CountDownLatch; // Connection establishment takes about 4 sec. //TODO P2P network tests are outdated @SuppressWarnings("ConstantConditions") -@Ignore +@Disabled public class TorNetworkNodeTest { private static final Logger log = LoggerFactory.getLogger(TorNetworkNodeTest.class); private CountDownLatch latch; diff --git a/p2p/src/test/java/haveno/network/p2p/peers/PeerManagerTest.java b/p2p/src/test/java/haveno/network/p2p/peers/PeerManagerTest.java index f9bf2ee1..5ba55705 100644 --- a/p2p/src/test/java/haveno/network/p2p/peers/PeerManagerTest.java +++ b/p2p/src/test/java/haveno/network/p2p/peers/PeerManagerTest.java @@ -22,19 +22,19 @@ import haveno.network.p2p.network.CloseConnectionReason; import haveno.network.p2p.network.Connection; import haveno.network.p2p.network.InboundConnection; import haveno.network.p2p.network.PeerType; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.never; @@ -46,14 +46,14 @@ public class PeerManagerTest { private int maxConnectionsPeer; private int maxConnectionsNonDirect; - @Before + @BeforeEach public void setUp() throws IOException { node = new MockNode(2); maxConnectionsPeer = Math.max(4, (int) Math.round(node.getMaxConnections() * 1.3)); maxConnectionsNonDirect = Math.max(8, (int) Math.round(node.getMaxConnections() * 1.7)); } - @After + @AfterEach public void tearDown() { node.getPersistenceManager().shutdown(); } @@ -151,7 +151,7 @@ public class PeerManagerTest { } @Test - @Ignore + @Disabled public void testCheckMaxConnectionsNonDirectLimitExceeded() throws InterruptedException { for (int i = 0; i < maxConnectionsNonDirect + 1; i++) { node.addOutboundConnection(PeerType.INITIAL_DATA_EXCHANGE); diff --git a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageBuildGetDataResponseTest.java b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageBuildGetDataResponseTest.java index 58702553..4b50fff5 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageBuildGetDataResponseTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageBuildGetDataResponseTest.java @@ -33,9 +33,8 @@ import haveno.network.p2p.storage.payload.CapabilityRequiringPayload; import haveno.network.p2p.storage.payload.PersistableNetworkPayload; import haveno.network.p2p.storage.payload.ProtectedStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStoragePayload; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -46,6 +45,9 @@ import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -63,7 +65,7 @@ public class P2PDataStorageBuildGetDataResponseTest { private NodeAddress localNodeAddress; - @Before + @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); this.testState = new TestState(); @@ -144,13 +146,13 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 1, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); - Assert.assertTrue(getDataResponse.getDataSet().isEmpty()); + assertFalse(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); + assertTrue(getDataResponse.getDataSet().isEmpty()); } // TESTCASE: Given a GetDataRequest w/ known PNP, nothing is sent back @@ -172,13 +174,13 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 1, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); - Assert.assertTrue(getDataResponse.getDataSet().isEmpty()); + assertFalse(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); + assertTrue(getDataResponse.getDataSet().isEmpty()); } // TESTCASE: Given a GetDataRequest w/o known PNP, send it back @@ -198,13 +200,13 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 1, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().contains(onlyLocal)); - Assert.assertTrue(getDataResponse.getDataSet().isEmpty()); + assertFalse(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().contains(onlyLocal)); + assertTrue(getDataResponse.getDataSet().isEmpty()); } // TESTCASE: Given a GetDataRequest w/o known PNP, don't send more than truncation limit @@ -227,17 +229,17 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 1, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertTrue(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertEquals(1, getDataResponse.getPersistableNetworkPayloadSet().size()); + assertTrue(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertEquals(1, getDataResponse.getPersistableNetworkPayloadSet().size()); Set persistableNetworkPayloadSet = getDataResponse.getPersistableNetworkPayloadSet(); // We use a set at the filter so it is not deterministic which item get truncated - Assert.assertEquals(1, persistableNetworkPayloadSet.size()); - Assert.assertTrue(getDataResponse.getDataSet().isEmpty()); + assertEquals(1, persistableNetworkPayloadSet.size()); + assertTrue(getDataResponse.getDataSet().isEmpty()); } // TESTCASE: Given a GetDataRequest w/o known PNP, but missing required capabilities, nothing is sent back @@ -259,13 +261,13 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 2, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); - Assert.assertTrue(getDataResponse.getDataSet().isEmpty()); + assertFalse(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); + assertTrue(getDataResponse.getDataSet().isEmpty()); } // TESTCASE: Given a GetDataRequest w/o known PNP that requires capabilities (and they match) send it back @@ -287,13 +289,13 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 2, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().contains(onlyLocal)); - Assert.assertTrue(getDataResponse.getDataSet().isEmpty()); + assertFalse(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().contains(onlyLocal)); + assertTrue(getDataResponse.getDataSet().isEmpty()); } // TESTCASE: Given a GetDataRequest w/ unknown PSE, nothing is sent back @@ -312,13 +314,13 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 1, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); - Assert.assertTrue(getDataResponse.getDataSet().isEmpty()); + assertFalse(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); + assertTrue(getDataResponse.getDataSet().isEmpty()); } // TESTCASE: Given a GetDataRequest w/ known PSE, nothing is sent back @@ -340,13 +342,13 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 1, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); - Assert.assertTrue(getDataResponse.getDataSet().isEmpty()); + assertFalse(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); + assertTrue(getDataResponse.getDataSet().isEmpty()); } // TESTCASE: Given a GetDataRequest w/o known PSE, send it back @@ -365,13 +367,13 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 1, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); - Assert.assertTrue(getDataResponse.getDataSet().contains(onlyLocal)); + assertFalse(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); + assertTrue(getDataResponse.getDataSet().contains(onlyLocal)); } // TESTCASE: Given a GetDataRequest w/o known PNP, don't send more than truncation limit @@ -393,14 +395,14 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 1, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertTrue(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); - Assert.assertEquals(1, getDataResponse.getDataSet().size()); - Assert.assertTrue( + assertFalse(outPNPTruncated.get()); + assertTrue(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); + assertEquals(1, getDataResponse.getDataSet().size()); + assertTrue( getDataResponse.getDataSet().contains(onlyLocal1) || getDataResponse.getDataSet().contains(onlyLocal2)); } @@ -422,13 +424,13 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 2, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); - Assert.assertTrue(getDataResponse.getDataSet().isEmpty()); + assertFalse(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); + assertTrue(getDataResponse.getDataSet().isEmpty()); } // TESTCASE: Given a GetDataRequest w/o known PNP that requires capabilities (and they match) send it back @@ -449,13 +451,13 @@ public class P2PDataStorageBuildGetDataResponseTest { GetDataResponse getDataResponse = this.testState.mockedStorage.buildGetDataResponse( getDataRequest, 2, outPNPTruncated, outPSETruncated, peerCapabilities); - Assert.assertFalse(outPNPTruncated.get()); - Assert.assertFalse(outPSETruncated.get()); - Assert.assertEquals(1, getDataResponse.getRequestNonce()); - Assert.assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); - Assert.assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); - Assert.assertTrue(getDataResponse.getDataSet().contains(onlyLocal)); + assertFalse(outPNPTruncated.get()); + assertFalse(outPSETruncated.get()); + assertEquals(1, getDataResponse.getRequestNonce()); + assertEquals(getDataRequest instanceof GetUpdatedDataRequest, getDataResponse.isGetUpdatedDataResponse()); + assertEquals(getDataResponse.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataResponse.getPersistableNetworkPayloadSet().isEmpty()); + assertTrue(getDataResponse.getDataSet().contains(onlyLocal)); } } diff --git a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageClientAPITest.java b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageClientAPITest.java index b7c3bd82..9990cfa7 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageClientAPITest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageClientAPITest.java @@ -28,15 +28,16 @@ import haveno.network.p2p.storage.payload.MailboxStoragePayload; import haveno.network.p2p.storage.payload.ProtectedMailboxStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStoragePayload; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.util.Optional; import static haveno.network.p2p.storage.TestState.SavedTestState; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -49,7 +50,7 @@ import static org.mockito.Mockito.when; public class P2PDataStorageClientAPITest { private TestState testState; - @Before + @BeforeEach public void setUp() { this.testState = new TestState(); @@ -67,9 +68,9 @@ public class P2PDataStorageClientAPITest { ProtectedStorageEntry protectedStorageEntry = this.testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); - Assert.assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); + assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); - this.testState.verifyProtectedStorageAdd(beforeState, protectedStorageEntry, true, true, true, true); + this.testState.assertProtectedStorageAdd(beforeState, protectedStorageEntry, true, true, true, true); } // TESTCASE: Adding an entry from the getProtectedStorageEntry API of an existing item correctly updates the item @@ -80,13 +81,13 @@ public class P2PDataStorageClientAPITest { ProtectedStoragePayload protectedStoragePayload = new ExpirableProtectedStoragePayloadStub(ownerKeys.getPublic()); ProtectedStorageEntry protectedStorageEntry = this.testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); - Assert.assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); + assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); protectedStorageEntry = this.testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null); - this.testState.verifyProtectedStorageAdd(beforeState, protectedStorageEntry, true, true, true, true); + this.testState.assertProtectedStorageAdd(beforeState, protectedStorageEntry, true, true, true, true); } // TESTCASE: Adding an entry from the getProtectedStorageEntry API of an existing item (added from onMessage path) correctly updates the item @@ -104,9 +105,9 @@ public class P2PDataStorageClientAPITest { SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); protectedStorageEntry = this.testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); - Assert.assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); + assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); - this.testState.verifyProtectedStorageAdd(beforeState, protectedStorageEntry, true, true, true, true); + this.testState.assertProtectedStorageAdd(beforeState, protectedStorageEntry, true, true, true, true); } // TESTCASE: Updating an entry from the getRefreshTTLMessage API correctly errors if the item hasn't been seen @@ -119,7 +120,7 @@ public class P2PDataStorageClientAPITest { RefreshOfferMessage refreshOfferMessage = this.testState.mockedStorage.getRefreshTTLMessage(protectedStoragePayload, ownerKeys); SavedTestState beforeState = this.testState.saveTestState(refreshOfferMessage); - Assert.assertFalse(this.testState.mockedStorage.refreshTTL(refreshOfferMessage, TestState.getTestNodeAddress())); + assertFalse(this.testState.mockedStorage.refreshTTL(refreshOfferMessage, TestState.getTestNodeAddress())); this.testState.verifyRefreshTTL(beforeState, refreshOfferMessage, false); } @@ -141,7 +142,7 @@ public class P2PDataStorageClientAPITest { this.testState.incrementClock(); SavedTestState beforeState = this.testState.saveTestState(refreshOfferMessage); - Assert.assertTrue(this.testState.mockedStorage.refreshTTL(refreshOfferMessage, TestState.getTestNodeAddress())); + assertTrue(this.testState.mockedStorage.refreshTTL(refreshOfferMessage, TestState.getTestNodeAddress())); this.testState.verifyRefreshTTL(beforeState, refreshOfferMessage, true); } @@ -165,7 +166,7 @@ public class P2PDataStorageClientAPITest { this.testState.incrementClock(); SavedTestState beforeState = this.testState.saveTestState(refreshOfferMessage); - Assert.assertTrue(this.testState.mockedStorage.refreshTTL(refreshOfferMessage, TestState.getTestNodeAddress())); + assertTrue(this.testState.mockedStorage.refreshTTL(refreshOfferMessage, TestState.getTestNodeAddress())); this.testState.verifyRefreshTTL(beforeState, refreshOfferMessage, true); } @@ -182,7 +183,7 @@ public class P2PDataStorageClientAPITest { this.testState.mockedStorage.getMailboxDataWithSignedSeqNr(mailboxStoragePayload, receiverKeys, receiverKeys.getPublic()); SavedTestState beforeState = this.testState.saveTestState(protectedMailboxStorageEntry); - Assert.assertTrue(this.testState.mockedStorage.remove(protectedMailboxStorageEntry, TestState.getTestNodeAddress())); + assertTrue(this.testState.mockedStorage.remove(protectedMailboxStorageEntry, TestState.getTestNodeAddress())); this.testState.verifyProtectedStorageRemove(beforeState, protectedMailboxStorageEntry, false, false, true, true); } @@ -198,13 +199,13 @@ public class P2PDataStorageClientAPITest { ProtectedMailboxStorageEntry protectedMailboxStorageEntry = this.testState.mockedStorage.getMailboxDataWithSignedSeqNr(mailboxStoragePayload, senderKeys, receiverKeys.getPublic()); - Assert.assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedMailboxStorageEntry, TestState.getTestNodeAddress(), null)); + assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedMailboxStorageEntry, TestState.getTestNodeAddress(), null)); protectedMailboxStorageEntry = this.testState.mockedStorage.getMailboxDataWithSignedSeqNr(mailboxStoragePayload, receiverKeys, receiverKeys.getPublic()); SavedTestState beforeState = this.testState.saveTestState(protectedMailboxStorageEntry); - Assert.assertTrue(this.testState.mockedStorage.remove(protectedMailboxStorageEntry, TestState.getTestNodeAddress())); + assertTrue(this.testState.mockedStorage.remove(protectedMailboxStorageEntry, TestState.getTestNodeAddress())); this.testState.verifyProtectedStorageRemove(beforeState, protectedMailboxStorageEntry, true, true, true, true); } @@ -231,7 +232,7 @@ public class P2PDataStorageClientAPITest { this.testState.mockedStorage.getMailboxDataWithSignedSeqNr(mailboxStoragePayload, receiverKeys, receiverKeys.getPublic()); SavedTestState beforeState = this.testState.saveTestState(protectedMailboxStorageEntry); - Assert.assertTrue(this.testState.mockedStorage.remove(protectedMailboxStorageEntry, TestState.getTestNodeAddress())); + assertTrue(this.testState.mockedStorage.remove(protectedMailboxStorageEntry, TestState.getTestNodeAddress())); this.testState.verifyProtectedStorageRemove(beforeState, protectedMailboxStorageEntry, true, true, true, true); } diff --git a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageGetDataIntegrationTest.java b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageGetDataIntegrationTest.java index 2454d0d9..47c27400 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageGetDataIntegrationTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageGetDataIntegrationTest.java @@ -25,14 +25,14 @@ import haveno.network.p2p.storage.mocks.PersistableExpirableProtectedStoragePayl import haveno.network.p2p.storage.mocks.ProtectedStoragePayloadStub; import haveno.network.p2p.storage.payload.ProtectedStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStoragePayload; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.util.concurrent.atomic.AtomicBoolean; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -84,7 +84,7 @@ public class P2PDataStorageGetDataIntegrationTest { TestState.SavedTestState beforeState = clientNodeTestState.saveTestState(onSeedNode); clientNode.processGetDataResponse(getDataResponse, null); - clientNodeTestState.verifyProtectedStorageAdd( + clientNodeTestState.assertProtectedStorageAdd( beforeState, onSeedNode, true, true, false, true); } @@ -114,7 +114,7 @@ public class P2PDataStorageGetDataIntegrationTest { TestState.SavedTestState beforeState = clientNodeTestState.saveTestState(transientEntry); clientNode.processGetDataResponse(getDataResponse, null); - clientNodeTestState.verifyProtectedStorageAdd( + clientNodeTestState.assertProtectedStorageAdd( beforeState, transientEntry, true, true, false, true); } @@ -147,9 +147,9 @@ public class P2PDataStorageGetDataIntegrationTest { TestState.SavedTestState beforeState = clientNodeTestState.saveTestState(persistentEntry); clientNode.processGetDataResponse(getDataResponse, null); - clientNodeTestState.verifyProtectedStorageAdd( + clientNodeTestState.assertProtectedStorageAdd( beforeState, persistentEntry, false, false, false, false); - Assert.assertTrue(clientNodeTestState.mockedStorage.getMap().containsValue(persistentEntry)); + assertTrue(clientNodeTestState.mockedStorage.getMap().containsValue(persistentEntry)); } // TESTCASE: Removes seen only by the seednode should be replayed on the client node diff --git a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageOnMessageHandlerTest.java b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageOnMessageHandlerTest.java index b55ad157..80a7a99f 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageOnMessageHandlerTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageOnMessageHandlerTest.java @@ -25,8 +25,8 @@ import haveno.network.p2p.storage.messages.AddPersistableNetworkPayloadMessage; import haveno.network.p2p.storage.messages.BroadcastMessage; import haveno.network.p2p.storage.mocks.PersistableNetworkPayloadStub; import haveno.network.p2p.storage.payload.PersistableNetworkPayload; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Optional; @@ -43,7 +43,7 @@ import static org.mockito.Mockito.when; public class P2PDataStorageOnMessageHandlerTest { private TestState testState; - @Before + @BeforeEach public void setup() { this.testState = new TestState(); } diff --git a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStoragePersistableNetworkPayloadTest.java b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStoragePersistableNetworkPayloadTest.java index 3897f5f0..8d1bafe4 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStoragePersistableNetworkPayloadTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStoragePersistableNetworkPayloadTest.java @@ -22,49 +22,40 @@ import haveno.network.p2p.storage.messages.AddPersistableNetworkPayloadMessage; import haveno.network.p2p.storage.mocks.DateTolerantPayloadStub; import haveno.network.p2p.storage.mocks.PersistableNetworkPayloadStub; import haveno.network.p2p.storage.payload.PersistableNetworkPayload; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; import java.util.Optional; +import java.util.stream.Stream; import static haveno.network.p2p.storage.TestState.SavedTestState; +import static haveno.network.p2p.storage.TestState.getTestNodeAddress; +import static java.util.stream.Stream.of; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests of the P2PDataStore entry points that use the PersistableNetworkPayload type - * + *

* The abstract base class AddPersistableNetworkPayloadTest defines the common test cases and Payload type * that needs to be tested is set up through extending the base class and overriding the createInstance() methods to * give the common tests a different payload to test. - * + *

* Each subclass (Payload type) can optionally add additional tests that verify functionality only relevant * to that payload. - * + *

* Each test case is run through 3 entry points to verify the correct behavior: - * + *

* 1 & 2 Client API [addPersistableNetworkPayload(reBroadcast=(true && false))] * 3. onMessage() [onMessage(AddPersistableNetworkPayloadMessage)] */ -@SuppressWarnings("unused") public class P2PDataStoragePersistableNetworkPayloadTest { - @RunWith(Parameterized.class) public abstract static class AddPersistableNetworkPayloadTest { TestState testState; - @Parameterized.Parameter(0) - public TestCase testCase; - - @Parameterized.Parameter(1) - public boolean reBroadcast; - PersistableNetworkPayload persistableNetworkPayload; abstract PersistableNetworkPayload createInstance(); @@ -74,62 +65,54 @@ public class P2PDataStoragePersistableNetworkPayloadTest { ON_MESSAGE, } - void doAddAndVerify(PersistableNetworkPayload persistableNetworkPayload, + @BeforeEach + public void setup() { + persistableNetworkPayload = createInstance(); + testState = new TestState(); + } + + void assertAndDoAdd(PersistableNetworkPayload persistableNetworkPayload, + TestCase testCase, + boolean reBroadcast, boolean expectedReturnValue, boolean expectedHashMapAndDataStoreUpdated, boolean expectedListenersSignaled, boolean expectedBroadcast) { - SavedTestState beforeState = this.testState.saveTestState(persistableNetworkPayload); + SavedTestState beforeState = testState.saveTestState(persistableNetworkPayload); - if (this.testCase == TestCase.PUBLIC_API) { - Assert.assertEquals(expectedReturnValue, - this.testState.mockedStorage.addPersistableNetworkPayload(persistableNetworkPayload, TestState.getTestNodeAddress(), this.reBroadcast)); + if (testCase == TestCase.PUBLIC_API) { + assertEquals(expectedReturnValue, + testState.mockedStorage.addPersistableNetworkPayload(persistableNetworkPayload, getTestNodeAddress(), reBroadcast)); } else { // onMessage - Connection mockedConnection = mock(Connection.class); - when(mockedConnection.getPeersNodeAddressOptional()).thenReturn(Optional.of(TestState.getTestNodeAddress())); + Connection mockedConnection = mock(); + when(mockedConnection.getPeersNodeAddressOptional()).thenReturn(Optional.of(getTestNodeAddress())); testState.mockedStorage.onMessage(new AddPersistableNetworkPayloadMessage(persistableNetworkPayload), mockedConnection); } - - this.testState.verifyPersistableAdd(beforeState, persistableNetworkPayload, expectedHashMapAndDataStoreUpdated, expectedListenersSignaled, expectedBroadcast); + testState.verifyPersistableAdd(beforeState, persistableNetworkPayload, expectedHashMapAndDataStoreUpdated, expectedListenersSignaled, expectedBroadcast); } - @Before - public void setup() { - this.persistableNetworkPayload = this.createInstance(); - - this.testState = new TestState(); + static Stream data() { + return of( + new Object[]{TestCase.ON_MESSAGE, false}, + new Object[]{TestCase.PUBLIC_API, true}, + new Object[]{TestCase.PUBLIC_API, false} + ); } - @Parameterized.Parameters(name = "{index}: Test with TestCase={0} allowBroadcast={1} reBroadcast={2} checkDate={3}") - public static Collection data() { - List data = new ArrayList<>(); - - // onMessage doesn't use other parameters - data.add(new Object[] { TestCase.ON_MESSAGE, false }); - - // Client API uses two permutations - // Normal path - data.add(new Object[] { TestCase.PUBLIC_API, true }); - - // Refresh path - data.add(new Object[] { TestCase.PUBLIC_API, false }); - - return data; + @MethodSource("data") + @ParameterizedTest(name = "{index}: Test with TestCase={0} allowBroadcast={1} reBroadcast={2} checkDate={3}") + public void addPersistableNetworkPayload(TestCase testCase, boolean reBroadcast) { + assertAndDoAdd(persistableNetworkPayload, testCase, reBroadcast, true, true, true, true); } - @Test - public void addPersistableNetworkPayload() { - // First add should succeed regardless of parameters - doAddAndVerify(this.persistableNetworkPayload, true, true, true, true); - } - - @Test - public void addPersistableNetworkPayloadDuplicate() { - doAddAndVerify(this.persistableNetworkPayload, true, true, true, true); + @MethodSource("data") + @ParameterizedTest(name = "{index}: Test with TestCase={0} allowBroadcast={1} reBroadcast={2} checkDate={3}") + public void addPersistableNetworkPayloadDuplicate(TestCase testCase, boolean reBroadcast) { + assertAndDoAdd(persistableNetworkPayload, testCase, reBroadcast, true, true, true, true); // We return true and broadcast if reBroadcast is set - // doAddAndVerify(this.persistableNetworkPayload, this.reBroadcast, false, false, this.reBroadcast); + // assertAndDoAdd(persistableNetworkPayload, testCase, reBroadcast, reBroadcast, false, false, reBroadcast); } } @@ -142,11 +125,11 @@ public class P2PDataStoragePersistableNetworkPayloadTest { return new PersistableNetworkPayloadStub(true); } - @Test - public void invalidHash() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: Test with TestCase={0} allowBroadcast={1} reBroadcast={2} checkDate={3}") + public void invalidHash(TestCase testCase, boolean reBroadcast) { PersistableNetworkPayload persistableNetworkPayload = new PersistableNetworkPayloadStub(false); - - doAddAndVerify(persistableNetworkPayload, false, false, false, false); + assertAndDoAdd(persistableNetworkPayload, testCase, reBroadcast, false, false, false, false); } } @@ -159,17 +142,17 @@ public class P2PDataStoragePersistableNetworkPayloadTest { @Override DateTolerantPayloadStub createInstance() { return new DateTolerantPayloadStub(true); - } - @Test - public void outOfTolerance() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: Test with TestCase={0} allowBroadcast={1} reBroadcast={2} checkDate={3}") + public void outOfTolerance(TestCase testCase, boolean reBroadcast) { PersistableNetworkPayload persistableNetworkPayload = new DateTolerantPayloadStub(false); // The onMessage path checks for tolerance - boolean expectedReturn = this.testCase != TestCase.ON_MESSAGE; + boolean expectedReturn = testCase != TestCase.ON_MESSAGE; - doAddAndVerify(persistableNetworkPayload, expectedReturn, expectedReturn, expectedReturn, expectedReturn); + assertAndDoAdd(persistableNetworkPayload, testCase, reBroadcast, expectedReturn, expectedReturn, expectedReturn, expectedReturn); } } } diff --git a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageProcessGetDataResponse.java b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageProcessGetDataResponse.java index 1148b136..3a2c7b41 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageProcessGetDataResponse.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageProcessGetDataResponse.java @@ -26,8 +26,8 @@ import haveno.network.p2p.storage.payload.PersistableNetworkPayload; import haveno.network.p2p.storage.payload.ProcessOncePersistableNetworkPayload; import haveno.network.p2p.storage.payload.ProtectedStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStoragePayload; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import java.security.KeyPair; @@ -45,7 +45,7 @@ public class P2PDataStorageProcessGetDataResponse { private NodeAddress peerNodeAddress; - @Before + @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); this.testState = new TestState(); @@ -221,7 +221,7 @@ public class P2PDataStorageProcessGetDataResponse { TestState.SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); this.testState.mockedStorage.processGetDataResponse(getDataResponse, this.peerNodeAddress); - this.testState.verifyProtectedStorageAdd( + this.testState.assertProtectedStorageAdd( beforeState, protectedStorageEntry, true, true, false, true); } @@ -235,7 +235,7 @@ public class P2PDataStorageProcessGetDataResponse { this.testState.mockedStorage.processGetDataResponse(getDataResponse, this.peerNodeAddress); TestState.SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); - this.testState.verifyProtectedStorageAdd( + this.testState.assertProtectedStorageAdd( beforeState, protectedStorageEntry, false, false, false, false); } @@ -248,14 +248,14 @@ public class P2PDataStorageProcessGetDataResponse { TestState.SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); this.testState.mockedStorage.processGetDataResponse(getDataResponse, this.peerNodeAddress); - this.testState.verifyProtectedStorageAdd( + this.testState.assertProtectedStorageAdd( beforeState, protectedStorageEntry, true, true, false, true); protectedStorageEntry = getProtectedStorageEntryForAdd(); getDataResponse = buildGetDataResponse(protectedStorageEntry); beforeState = this.testState.saveTestState(protectedStorageEntry); this.testState.mockedStorage.processGetDataResponse(getDataResponse, this.peerNodeAddress); - this.testState.verifyProtectedStorageAdd( + this.testState.assertProtectedStorageAdd( beforeState, protectedStorageEntry, true, true, false, true); } } diff --git a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageProtectedStorageEntryTest.java b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageProtectedStorageEntryTest.java index 0bc2c5b9..f26c18e5 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageProtectedStorageEntryTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageProtectedStorageEntryTest.java @@ -31,27 +31,23 @@ import haveno.network.p2p.storage.mocks.ProtectedStoragePayloadStub; import haveno.network.p2p.storage.payload.ProtectedMailboxStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStoragePayload; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; import java.util.Map; -import java.util.Optional; import static haveno.network.p2p.storage.TestState.SavedTestState; +import static haveno.network.p2p.storage.TestState.getTestNodeAddress; +import static java.util.Optional.of; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - /** * Tests of the P2PDataStore entry points that use the ProtectedStorageEntry type * @@ -68,7 +64,6 @@ import static org.mockito.Mockito.when; */ @SuppressWarnings("unused") public class P2PDataStorageProtectedStorageEntryTest { - @RunWith(Parameterized.class) abstract public static class ProtectedStorageEntryTestBase { TestState testState; Class entryClass; @@ -80,73 +75,61 @@ public class P2PDataStorageProtectedStorageEntryTest { private ProtectedStoragePayload protectedStoragePayload; KeyPair payloadOwnerKeys; - @Parameterized.Parameter(0) public boolean useMessageHandler; - @Parameterized.Parameters(name = "{index}: Test with useMessageHandler={0}") - public static Collection data() { - List data = new ArrayList<>(); - boolean[] vals = new boolean[]{true, false}; - - for (boolean useMessageHandler : vals) - data.add(new Object[]{useMessageHandler}); - - return data; - } - - @Before + @BeforeEach public void setUp() throws CryptoException, NoSuchAlgorithmException { - this.testState = new TestState(); + testState = new TestState(); - this.payloadOwnerKeys = TestUtils.generateKeyPair(); - this.protectedStoragePayload = createInstance(this.payloadOwnerKeys); - this.entryClass = this.getEntryClass(); + payloadOwnerKeys = TestUtils.generateKeyPair(); + protectedStoragePayload = createInstance(payloadOwnerKeys); + entryClass = getEntryClass(); } boolean doRemove(ProtectedStorageEntry entry) { - if (this.useMessageHandler) { + if (useMessageHandler) { Connection mockedConnection = mock(Connection.class); - when(mockedConnection.getPeersNodeAddressOptional()).thenReturn(Optional.of(TestState.getTestNodeAddress())); + when(mockedConnection.getPeersNodeAddressOptional()).thenReturn(of(getTestNodeAddress())); testState.mockedStorage.onMessage(new RemoveDataMessage(entry), mockedConnection); return true; } else { - return testState.mockedStorage.remove(entry, TestState.getTestNodeAddress()); + return testState.mockedStorage.remove(entry, getTestNodeAddress()); } } boolean doAdd(ProtectedStorageEntry protectedStorageEntry) { - if (this.useMessageHandler) { + if (useMessageHandler) { Connection mockedConnection = mock(Connection.class); - when(mockedConnection.getPeersNodeAddressOptional()).thenReturn(Optional.of(TestState.getTestNodeAddress())); + when(mockedConnection.getPeersNodeAddressOptional()).thenReturn(of(getTestNodeAddress())); testState.mockedStorage.onMessage(new AddDataMessage(protectedStorageEntry), mockedConnection); return true; } else { - return this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, - TestState.getTestNodeAddress(), null); + return testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, + getTestNodeAddress(), null); } } boolean doRefreshTTL(RefreshOfferMessage refreshOfferMessage) { - if (this.useMessageHandler) { + if (useMessageHandler) { Connection mockedConnection = mock(Connection.class); - when(mockedConnection.getPeersNodeAddressOptional()).thenReturn(Optional.of(TestState.getTestNodeAddress())); + when(mockedConnection.getPeersNodeAddressOptional()).thenReturn(of(getTestNodeAddress())); testState.mockedStorage.onMessage(refreshOfferMessage, mockedConnection); return true; } else { - return this.testState.mockedStorage.refreshTTL(refreshOfferMessage, TestState.getTestNodeAddress()); + return testState.mockedStorage.refreshTTL(refreshOfferMessage, getTestNodeAddress()); } } ProtectedStorageEntry getProtectedStorageEntryForAdd(int sequenceNumber, boolean validForAdd, boolean matchesRelevantPubKey) { ProtectedStorageEntry stub = mock(entryClass); - when(stub.getOwnerPubKey()).thenReturn(this.payloadOwnerKeys.getPublic()); + when(stub.getOwnerPubKey()).thenReturn(payloadOwnerKeys.getPublic()); when(stub.isValidForAddOperation()).thenReturn(validForAdd); when(stub.matchesRelevantPubKey(any(ProtectedStorageEntry.class))).thenReturn(matchesRelevantPubKey); when(stub.getSequenceNumber()).thenReturn(sequenceNumber); @@ -162,12 +145,12 @@ public class P2PDataStorageProtectedStorageEntryTest { // Return a ProtectedStorageEntry that will pass all validity checks for remove. ProtectedStorageEntry getProtectedStorageEntryForRemove(int sequenceNumber, boolean validForRemove, boolean matchesRelevantPubKey) { - ProtectedStorageEntry stub = mock(this.entryClass); - when(stub.getOwnerPubKey()).thenReturn(this.payloadOwnerKeys.getPublic()); + ProtectedStorageEntry stub = mock(entryClass); + when(stub.getOwnerPubKey()).thenReturn(payloadOwnerKeys.getPublic()); when(stub.isValidForRemoveOperation()).thenReturn(validForRemove); when(stub.matchesRelevantPubKey(any(ProtectedStorageEntry.class))).thenReturn(matchesRelevantPubKey); when(stub.getSequenceNumber()).thenReturn(sequenceNumber); - when(stub.getProtectedStoragePayload()).thenReturn(this.protectedStoragePayload); + when(stub.getProtectedStoragePayload()).thenReturn(protectedStoragePayload); return stub; } @@ -176,274 +159,314 @@ public class P2PDataStorageProtectedStorageEntryTest { return getProtectedStorageEntryForRemove(sequenceNumber, true, true); } - void doProtectedStorageAddAndVerify(ProtectedStorageEntry protectedStorageEntry, + void assertAndDoProtectedStorageAdd(ProtectedStorageEntry protectedStorageEntry, boolean expectedReturnValue, boolean expectedStateChange) { - SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); + SavedTestState beforeState = testState.saveTestState(protectedStorageEntry); - boolean addResult = this.doAdd(protectedStorageEntry); + boolean addResult = doAdd(protectedStorageEntry); - if (!this.useMessageHandler) - Assert.assertEquals(expectedReturnValue, addResult); + if (!useMessageHandler) + assertEquals(expectedReturnValue, addResult); if (expectedStateChange) { - this.testState.verifyProtectedStorageAdd( + testState.assertProtectedStorageAdd( beforeState, protectedStorageEntry, true, true, true, true); } else{ - this.testState.verifyProtectedStorageAdd( + testState.assertProtectedStorageAdd( beforeState, protectedStorageEntry, false, false, false, false); } } - void doProtectedStorageRemoveAndVerify(ProtectedStorageEntry entry, + void assertAndDoProtectedStorageRemove(ProtectedStorageEntry entry, boolean expectedReturnValue, boolean expectedHashMapAndDataStoreUpdated, boolean expectedListenersSignaled, boolean expectedBroadcast, boolean expectedSeqNrWrite) { - SavedTestState beforeState = this.testState.saveTestState(entry); + SavedTestState beforeState = testState.saveTestState(entry); + boolean addResult = doRemove(entry); + if (!useMessageHandler) + assertEquals(expectedReturnValue, addResult); - boolean addResult = this.doRemove(entry); - - if (!this.useMessageHandler) - Assert.assertEquals(expectedReturnValue, addResult); - - this.testState.verifyProtectedStorageRemove(beforeState, entry, expectedHashMapAndDataStoreUpdated, expectedListenersSignaled, expectedBroadcast, expectedSeqNrWrite); + testState.verifyProtectedStorageRemove(beforeState, entry, expectedHashMapAndDataStoreUpdated, expectedListenersSignaled, expectedBroadcast, expectedSeqNrWrite); } - /// Valid Add Tests (isValidForAdd() and matchesRelevantPubKey() return true) - @Test - public void addProtectedStorageEntry() { - - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntry(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); } // TESTCASE: Adding duplicate payload w/ same sequence number - @Test - public void addProtectedStorageEntry_duplicateSeqNrGt0() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); - doProtectedStorageAddAndVerify(entryForAdd, false, false); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryDuplicateSeqNrGt0(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); + assertAndDoProtectedStorageAdd(entryForAdd, false, false); } // TESTCASE: Adding duplicate payload w/ 0 sequence number (special branch in code for logging) - @Test - public void addProtectedStorageEntry_duplicateSeqNrEq0() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(0); - doProtectedStorageAddAndVerify(entryForAdd, true, true); - doProtectedStorageAddAndVerify(entryForAdd, false, false); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryDuplicateSeqNrEq0(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(0); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); + assertAndDoProtectedStorageAdd(entryForAdd, false, false); } // TESTCASE: Adding duplicate payload for w/ lower sequence number - @Test - public void addProtectedStorageEntry_lowerSeqNr() { - ProtectedStorageEntry entryForAdd2 = this.getProtectedStorageEntryForAdd(2); - ProtectedStorageEntry entryForAdd1 = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd2, true, true); - doProtectedStorageAddAndVerify(entryForAdd1, false, false); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryLowerSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd2 = getProtectedStorageEntryForAdd(2); + ProtectedStorageEntry entryForAdd1 = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd2, true, true); + assertAndDoProtectedStorageAdd(entryForAdd1, false, false); } // TESTCASE: Adding duplicate payload for w/ greater sequence number - @Test - public void addProtectedStorageEntry_greaterSeqNr() { - ProtectedStorageEntry entryForAdd2 = this.getProtectedStorageEntryForAdd(1); - ProtectedStorageEntry entryForAdd1 = this.getProtectedStorageEntryForAdd(2); - doProtectedStorageAddAndVerify(entryForAdd2, true, true); - doProtectedStorageAddAndVerify(entryForAdd1, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryGreaterSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd2 = getProtectedStorageEntryForAdd(1); + ProtectedStorageEntry entryForAdd1 = getProtectedStorageEntryForAdd(2); + assertAndDoProtectedStorageAdd(entryForAdd2, true, true); + assertAndDoProtectedStorageAdd(entryForAdd1, true, true); } // TESTCASE: Add w/ same sequence number after remove of sequence number // Regression test for old remove() behavior that succeeded if add.seq# == remove.seq# - @Test - public void addProtectectedStorageEntry_afterRemoveSameSeqNr() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(1); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryAfterRemoveSameSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); - doProtectedStorageRemoveAndVerify(entryForRemove, false, false, false, false, false); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); + assertAndDoProtectedStorageRemove(entryForRemove, false, false, false, false, false); - doProtectedStorageAddAndVerify(entryForAdd, false, false); + assertAndDoProtectedStorageAdd(entryForAdd, false, false); } // Invalid add tests (isValidForAddOperation() || matchesRelevantPubKey()) returns false // TESTCASE: Add fails if Entry is not valid for add - @Test - public void addProtectedStorageEntry_EntryNotisValidForAddOperation() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1, false, true); - doProtectedStorageAddAndVerify(entryForAdd, false, false); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryNotisValidForAddOperation(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1, false, true); + assertAndDoProtectedStorageAdd(entryForAdd, false, false); } // TESTCASE: Add fails if Entry metadata does not match existing Entry - @Test - public void addProtectedStorageEntry_EntryNotmatchesRelevantPubKey() { + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryNotMatchesRelevantPubKey(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; // Add a valid entry - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); // Add an entry where metadata is different from first add, but otherwise is valid - entryForAdd = this.getProtectedStorageEntryForAdd(2, true, false); - doProtectedStorageAddAndVerify(entryForAdd, false, false); + entryForAdd = getProtectedStorageEntryForAdd(2, true, false); + assertAndDoProtectedStorageAdd(entryForAdd, false, false); } // TESTCASE: Add fails if Entry metadata does not match existing Entry and is not valid for add - @Test - public void addProtectedStorageEntry_EntryNotmatchesRelevantPubKeyNotisValidForAddOperation() { + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryNotMatchesRelevantPubKeyNotisValidForAddOperation(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; // Add a valid entry - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); // Add an entry where entry is not valid and metadata is different from first add - entryForAdd = this.getProtectedStorageEntryForAdd(2, false, false); - doProtectedStorageAddAndVerify(entryForAdd, false, false); + entryForAdd = getProtectedStorageEntryForAdd(2, false, false); + assertAndDoProtectedStorageAdd(entryForAdd, false, false); } /// Valid remove tests (isValidForRemove() and isMetadataEquals() return true) // TESTCASE: Removing an item after successfully added (remove seq # == add seq #) - @Test - public void remove_seqNrEqAddSeqNr() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(1); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void removeSeqNrEqAddSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); - doProtectedStorageRemoveAndVerify(entryForRemove, false, false, false, false, false); + assertAndDoProtectedStorageRemove(entryForRemove, false, false, false, false, false); } // TESTCASE: Removing an item after successfully added (remove seq # > add seq #) - @Test - public void remove_seqNrGtAddSeqNr() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(2); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void removeSeqNrGtAddSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(2); - doProtectedStorageAddAndVerify(entryForAdd, true, true); - doProtectedStorageRemoveAndVerify(entryForRemove, true, true, true, true, true); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); + assertAndDoProtectedStorageRemove(entryForRemove, true, true, true, true, true); } // TESTCASE: Removing an item before it was added. This triggers a SequenceNumberMap write and broadcast - @Test - public void remove_notExists() { - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(1); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void removeNotExists(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(1); - doProtectedStorageRemoveAndVerify(entryForRemove, true, false, false, true, true); + assertAndDoProtectedStorageRemove(entryForRemove, true, false, false, true, true); } // TESTCASE: Removing an item after successfully adding (remove seq # < add seq #) - @Test - public void remove_seqNrLessAddSeqNr() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(2); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(1); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void removeSeqNrLessAddSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(2); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); - doProtectedStorageRemoveAndVerify(entryForRemove, false, false, false, false, false); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); + assertAndDoProtectedStorageRemove(entryForRemove, false, false, false, false, false); } // TESTCASE: Add after removed (same seq #) - @Test - public void add_afterRemoveSameSeqNr() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addAfterRemoveSameSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(2); - doProtectedStorageRemoveAndVerify(entryForRemove, true, true, true, true, true); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(2); + assertAndDoProtectedStorageRemove(entryForRemove, true, true, true, true, true); - doProtectedStorageAddAndVerify(entryForAdd, false, false); + assertAndDoProtectedStorageAdd(entryForAdd, false, false); } // TESTCASE: Add after removed (greater seq #) - @Test - public void add_afterRemoveGreaterSeqNr() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addAfterRemoveGreaterSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(2); - doProtectedStorageRemoveAndVerify(entryForRemove, true, true, true, true, true); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(2); + assertAndDoProtectedStorageRemove(entryForRemove, true, true, true, true, true); - entryForAdd = this.getProtectedStorageEntryForAdd(3); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + entryForAdd = getProtectedStorageEntryForAdd(3); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); } /// Invalid remove tests (isValidForRemoveOperation() || matchesRelevantPubKey()) returns false // TESTCASE: Remove fails if Entry isn't valid for remove - @Test - public void remove_EntryNotisValidForRemoveOperation() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void removeEntryNotisValidForRemoveOperation(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(2, false, true); - doProtectedStorageRemoveAndVerify(entryForRemove, false, false, false, false, false); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(2, false, true); + assertAndDoProtectedStorageRemove(entryForRemove, false, false, false, false, false); } // TESTCASE: Remove fails if Entry is valid for remove, but metadata doesn't match remove target - @Test - public void remove_EntryNotmatchesRelevantPubKey() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void removeEntryNotMatchesRelevantPubKey(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(2, true, false); - doProtectedStorageRemoveAndVerify(entryForRemove, false, false, false, false, false); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(2, true, false); + assertAndDoProtectedStorageRemove(entryForRemove, false, false, false, false, false); } // TESTCASE: Remove fails if Entry is not valid for remove and metadata doesn't match remove target - @Test - public void remove_EntryNotisValidForRemoveOperationNotmatchesRelevantPubKey() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void removeEntryNotisValidForRemoveOperationNotMatchesRelevantPubKey(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(2, false, false); - doProtectedStorageRemoveAndVerify(entryForRemove, false, false, false, false, false); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(2, false, false); + assertAndDoProtectedStorageRemove(entryForRemove, false, false, false, false, false); } // TESTCASE: Add after removed (lower seq #) - @Test - public void add_afterRemoveLessSeqNr() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(2); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addAfterRemoveLessSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(2); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(3); - doProtectedStorageRemoveAndVerify(entryForRemove, true, true, true, true, true); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(3); + assertAndDoProtectedStorageRemove(entryForRemove, true, true, true, true, true); - entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, false, false); + entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, false, false); } // TESTCASE: Received remove for nonexistent item that was later received - @Test - public void remove_lateAdd() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(2); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void removeLateAdd(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(2); - this.doRemove(entryForRemove); + doRemove(entryForRemove); - doProtectedStorageAddAndVerify(entryForAdd, false, false); + assertAndDoProtectedStorageAdd(entryForAdd, false, false); } // TESTCASE: Invalid remove doesn't block a valid add (isValidForRemove == false | matchesRelevantPubKey == false) - @Test - public void remove_entryNotIsValidForRemoveDoesntBlockAdd1() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(1, false, false); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void removeEntryNotIsValidForRemoveDoesNotBlockAdd1(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(1, false, false); - this.doRemove(entryForRemove); + doRemove(entryForRemove); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); } // TESTCASE: Invalid remove doesn't block a valid add (isValidForRemove == false | matchesRelevantPubKey == true) - @Test - public void remove_entryNotIsValidForRemoveDoesntBlockAdd2() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(1, false, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void removeEntryNotIsValidForRemoveDoesNotBlockAdd2(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(1, false, true); - this.doRemove(entryForRemove); + doRemove(entryForRemove); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); } } @@ -478,127 +501,145 @@ public class P2PDataStorageProtectedStorageEntryTest { return buildRefreshOfferMessage(protectedStorageEntry.getProtectedStoragePayload(), ownerKeys, sequenceNumber); } - void doRefreshTTLAndVerify(RefreshOfferMessage refreshOfferMessage, boolean expectedReturnValue, boolean expectStateChange) { - SavedTestState beforeState = this.testState.saveTestState(refreshOfferMessage); + void assertAndDoRefreshTTL(RefreshOfferMessage refreshOfferMessage, boolean expectedReturnValue, boolean expectStateChange) { + SavedTestState beforeState = testState.saveTestState(refreshOfferMessage); - boolean returnValue = this.doRefreshTTL(refreshOfferMessage); + boolean returnValue = doRefreshTTL(refreshOfferMessage); - if (!this.useMessageHandler) - Assert.assertEquals(expectedReturnValue, returnValue); + if (!useMessageHandler) + assertEquals(expectedReturnValue, returnValue); - this.testState.verifyRefreshTTL(beforeState, refreshOfferMessage, expectStateChange); + testState.verifyRefreshTTL(beforeState, refreshOfferMessage, expectStateChange); } // TESTCASE: Refresh an entry that doesn't exist - @Test - public void refreshTTL_noExist() throws CryptoException { - ProtectedStorageEntry entry = this.getProtectedStorageEntryForAdd(1); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void refreshTTLNoExist(boolean useMessageHandler) throws CryptoException { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entry = getProtectedStorageEntryForAdd(1); - doRefreshTTLAndVerify(buildRefreshOfferMessage(entry, this.payloadOwnerKeys,1), false, false); + assertAndDoRefreshTTL(buildRefreshOfferMessage(entry, payloadOwnerKeys,1), false, false); } // TESTCASE: Refresh an entry where seq # is equal to last seq # seen - @Test - public void refreshTTL_existingEntry() throws CryptoException { - ProtectedStorageEntry entry = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entry, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void refreshTTLExistingEntry(boolean useMessageHandler) throws CryptoException { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entry = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entry, true, true); - doRefreshTTLAndVerify(buildRefreshOfferMessage(entry, this.payloadOwnerKeys,1), false, false); + assertAndDoRefreshTTL(buildRefreshOfferMessage(entry, payloadOwnerKeys,1), false, false); } // TESTCASE: Duplicate refresh message (same seq #) - @Test - public void refreshTTL_duplicateRefreshSeqNrEqual() throws CryptoException { - ProtectedStorageEntry entry = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entry, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void refreshTTLDuplicateRefreshSeqNrEqual(boolean useMessageHandler) throws CryptoException { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entry = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entry, true, true); - this.testState.incrementClock(); + testState.incrementClock(); - doRefreshTTLAndVerify(buildRefreshOfferMessage(entry, this.payloadOwnerKeys, 2), true, true); + assertAndDoRefreshTTL(buildRefreshOfferMessage(entry, payloadOwnerKeys, 2), true, true); - this.testState.incrementClock(); + testState.incrementClock(); - doRefreshTTLAndVerify(buildRefreshOfferMessage(entry, this.payloadOwnerKeys, 2), false, false); + assertAndDoRefreshTTL(buildRefreshOfferMessage(entry, payloadOwnerKeys, 2), false, false); } // TESTCASE: Duplicate refresh message (greater seq #) - @Test - public void refreshTTL_duplicateRefreshSeqNrGreater() throws CryptoException { - ProtectedStorageEntry entry = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entry, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void refreshTTLDuplicateRefreshSeqNrGreater(boolean useMessageHandler) throws CryptoException { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entry = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entry, true, true); - this.testState.incrementClock(); + testState.incrementClock(); - doRefreshTTLAndVerify(buildRefreshOfferMessage(entry, this.payloadOwnerKeys,2), true, true); + assertAndDoRefreshTTL(buildRefreshOfferMessage(entry, payloadOwnerKeys,2), true, true); - this.testState.incrementClock(); + testState.incrementClock(); - doRefreshTTLAndVerify(buildRefreshOfferMessage(entry, this.payloadOwnerKeys,3), true, true); + assertAndDoRefreshTTL(buildRefreshOfferMessage(entry, payloadOwnerKeys,3), true, true); } // TESTCASE: Duplicate refresh message (lower seq #) - @Test - public void refreshTTL_duplicateRefreshSeqNrLower() throws CryptoException { - ProtectedStorageEntry entry = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entry, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void refreshTTLDuplicateRefreshSeqNrLower(boolean useMessageHandler) throws CryptoException { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entry = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entry, true, true); - this.testState.incrementClock(); + testState.incrementClock(); - doRefreshTTLAndVerify(buildRefreshOfferMessage(entry, this.payloadOwnerKeys,3), true, true); + assertAndDoRefreshTTL(buildRefreshOfferMessage(entry, payloadOwnerKeys,3), true, true); - this.testState.incrementClock(); + testState.incrementClock(); - doRefreshTTLAndVerify(buildRefreshOfferMessage(entry, this.payloadOwnerKeys,2), false, false); + assertAndDoRefreshTTL(buildRefreshOfferMessage(entry, payloadOwnerKeys,2), false, false); } // TESTCASE: Refresh previously removed entry - @Test - public void refreshTTL_refreshAfterRemove() throws CryptoException { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(2); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void refreshTTLRefreshAfterRemove(boolean useMessageHandler) throws CryptoException { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(2); - doProtectedStorageAddAndVerify(entryForAdd, true, true); - doProtectedStorageRemoveAndVerify(entryForRemove, true, true, true, true, true); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); + assertAndDoProtectedStorageRemove(entryForRemove, true, true, true, true, true); - doRefreshTTLAndVerify(buildRefreshOfferMessage(entryForAdd, this.payloadOwnerKeys,3), false, false); + assertAndDoRefreshTTL(buildRefreshOfferMessage(entryForAdd, payloadOwnerKeys,3), false, false); } // TESTCASE: Refresh an entry, but owner doesn't match PubKey of original add owner - @Test - public void refreshTTL_refreshEntryOwnerOriginalOwnerMismatch() throws CryptoException, NoSuchAlgorithmException { - ProtectedStorageEntry entry = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entry, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void refreshTTLRefreshEntryOwnerOriginalOwnerMismatch(boolean useMessageHandler) throws CryptoException, NoSuchAlgorithmException { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entry = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entry, true, true); KeyPair notOwner = TestUtils.generateKeyPair(); - doRefreshTTLAndVerify(buildRefreshOfferMessage(entry, notOwner, 2), false, false); + assertAndDoRefreshTTL(buildRefreshOfferMessage(entry, notOwner, 2), false, false); } // TESTCASE: After restart, identical sequence numbers are accepted ONCE. We need a way to reconstruct // in-memory ProtectedStorageEntrys from seed and peer nodes around startup time. - @Test - public void addProtectedStorageEntry_afterRestartCanAddDuplicateSeqNr() { - ProtectedStorageEntry toAdd1 = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(toAdd1, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryAfterRestartCanAddDuplicateSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry toAdd1 = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(toAdd1, true, true); - this.testState.simulateRestart(); + testState.simulateRestart(); // Can add equal seqNr only once - doProtectedStorageAddAndVerify(toAdd1, true, true); + assertAndDoProtectedStorageAdd(toAdd1, true, true); // Can't add equal seqNr twice - doProtectedStorageAddAndVerify(toAdd1, false, false); + assertAndDoProtectedStorageAdd(toAdd1, false, false); } // TESTCASE: After restart, old sequence numbers are not accepted - @Test - public void addProtectedStorageEntry_afterRestartCanNotAddLowerSeqNr() { - ProtectedStorageEntry toAdd1 = this.getProtectedStorageEntryForAdd(1); - ProtectedStorageEntry toAdd2 = this.getProtectedStorageEntryForAdd(2); - doProtectedStorageAddAndVerify(toAdd2, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryAfterRestartCanNotAddLowerSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry toAdd1 = getProtectedStorageEntryForAdd(1); + ProtectedStorageEntry toAdd2 = getProtectedStorageEntryForAdd(2); + assertAndDoProtectedStorageAdd(toAdd2, true, true); - this.testState.simulateRestart(); + testState.simulateRestart(); - doProtectedStorageAddAndVerify(toAdd1, false, false); + assertAndDoProtectedStorageAdd(toAdd1, false, false); } } @@ -621,28 +662,30 @@ public class P2PDataStorageProtectedStorageEntryTest { // Tests that just apply to PersistablePayload objects // TESTCASE: Ensure the HashMap is the same before and after a restart - @Test - public void addProtectedStorageEntry_afterReadFromResourcesWithDuplicate_3629RegressionTest() { - ProtectedStorageEntry protectedStorageEntry = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(protectedStorageEntry, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryAfterReadFromResourcesWithDuplicate3629RegressionTest(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry protectedStorageEntry = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(protectedStorageEntry, true, true); - Map beforeRestart = this.testState.mockedStorage.getMap(); + Map beforeRestart = testState.mockedStorage.getMap(); - this.testState.simulateRestart(); + testState.simulateRestart(); - Assert.assertEquals(beforeRestart, this.testState.mockedStorage.getMap()); + assertEquals(beforeRestart, testState.mockedStorage.getMap()); } // TESTCASE: After restart, identical sequence numbers are not accepted for persistent payloads - @Test - public void addProtectedStorageEntry_afterRestartCanNotAddDuplicateSeqNr() { - ProtectedStorageEntry toAdd1 = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(toAdd1, true, true); - - this.testState.simulateRestart(); - + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + public void addProtectedStorageEntryAfterRestartCanNotAddDuplicateSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry toAdd1 = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(toAdd1, true, true); + testState.simulateRestart(); // Can add equal seqNr only once - doProtectedStorageAddAndVerify(toAdd1, false, false); + assertAndDoProtectedStorageAdd(toAdd1, false, false); } } @@ -663,7 +706,7 @@ public class P2PDataStorageProtectedStorageEntryTest { } @Override - @Before + @BeforeEach public void setUp() throws CryptoException, NoSuchAlgorithmException { super.setUp(); @@ -674,31 +717,33 @@ public class P2PDataStorageProtectedStorageEntryTest { @Override boolean doRemove(ProtectedStorageEntry entry) { - if (this.useMessageHandler) { + if (useMessageHandler) { Connection mockedConnection = mock(Connection.class); - when(mockedConnection.getPeersNodeAddressOptional()).thenReturn(Optional.of(TestState.getTestNodeAddress())); + when(mockedConnection.getPeersNodeAddressOptional()).thenReturn(of(getTestNodeAddress())); testState.mockedStorage.onMessage(new RemoveMailboxDataMessage((ProtectedMailboxStorageEntry) entry), mockedConnection); return true; } else { - return testState.mockedStorage.remove(entry, TestState.getTestNodeAddress()); + return testState.mockedStorage.remove(entry, getTestNodeAddress()); } } // TESTCASE: Add after removed when add-once required (greater seq #) @Override - @Test - @Ignore //TODO fix test - public void add_afterRemoveGreaterSeqNr() { - ProtectedStorageEntry entryForAdd = this.getProtectedStorageEntryForAdd(1); - doProtectedStorageAddAndVerify(entryForAdd, true, true); + @ValueSource(booleans = {true, false}) + @ParameterizedTest(name = "{index}: Test with useMessageHandler={0}") + @Disabled //TODO fix test + public void addAfterRemoveGreaterSeqNr(boolean useMessageHandler) { + this.useMessageHandler = useMessageHandler; + ProtectedStorageEntry entryForAdd = getProtectedStorageEntryForAdd(1); + assertAndDoProtectedStorageAdd(entryForAdd, true, true); - ProtectedStorageEntry entryForRemove = this.getProtectedStorageEntryForRemove(2); - doProtectedStorageRemoveAndVerify(entryForRemove, true, true, true, true, true); + ProtectedStorageEntry entryForRemove = getProtectedStorageEntryForRemove(2); + assertAndDoProtectedStorageRemove(entryForRemove, true, true, true, true, true); - entryForAdd = this.getProtectedStorageEntryForAdd(3); - doProtectedStorageAddAndVerify(entryForAdd, false, false); + entryForAdd = getProtectedStorageEntryForAdd(3); + assertAndDoProtectedStorageAdd(entryForAdd, false, false); } } } diff --git a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageRemoveExpiredTest.java b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageRemoveExpiredTest.java index 54b7833a..3f78de84 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageRemoveExpiredTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageRemoveExpiredTest.java @@ -27,9 +27,8 @@ import haveno.network.p2p.storage.mocks.ProtectedStoragePayloadStub; import haveno.network.p2p.storage.payload.PersistableNetworkPayload; import haveno.network.p2p.storage.payload.ProtectedStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStoragePayload; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; @@ -39,16 +38,17 @@ import java.util.concurrent.TimeUnit; import static haveno.network.p2p.storage.TestState.MAX_SEQUENCE_NUMBER_MAP_SIZE_BEFORE_PURGE; import static haveno.network.p2p.storage.TestState.SavedTestState; import static haveno.network.p2p.storage.TestState.getTestNodeAddress; +import static org.junit.jupiter.api.Assertions.assertTrue; /** - * Tests of the P2PDataStore behavior that expires old Entrys periodically. + * Tests of the P2PDataStore behavior that expires old Entries periodically. */ public class P2PDataStorageRemoveExpiredTest { private TestState testState; - @Before + @BeforeEach public void setUp() { - this.testState = new TestState(); + testState = new TestState(); // Deep in the bowels of protobuf we grab the messageID from the version module. This is required to hash the // full MailboxStoragePayload so make sure it is initialized. @@ -60,13 +60,13 @@ public class P2PDataStorageRemoveExpiredTest { public void removeExpiredEntries_SkipsNonExpirableEntries() throws NoSuchAlgorithmException, CryptoException { KeyPair ownerKeys = TestUtils.generateKeyPair(); ProtectedStoragePayload protectedStoragePayload = new ProtectedStoragePayloadStub(ownerKeys.getPublic()); - ProtectedStorageEntry protectedStorageEntry = this.testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); - Assert.assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); + ProtectedStorageEntry protectedStorageEntry = testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); + assertTrue(testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, getTestNodeAddress(), null)); - SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); - this.testState.mockedStorage.removeExpiredEntries(); + SavedTestState beforeState = testState.saveTestState(protectedStorageEntry); + testState.mockedStorage.removeExpiredEntries(); - this.testState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, false, false, false, false); + testState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, false, false, false, false); } // TESTCASE: Correctly skips all PersistableNetworkPayloads since they are not expirable @@ -74,11 +74,11 @@ public class P2PDataStorageRemoveExpiredTest { public void removeExpiredEntries_skipsPersistableNetworkPayload() { PersistableNetworkPayload persistableNetworkPayload = new PersistableNetworkPayloadStub(true); - Assert.assertTrue(this.testState.mockedStorage.addPersistableNetworkPayload(persistableNetworkPayload,getTestNodeAddress(), false)); + assertTrue(testState.mockedStorage.addPersistableNetworkPayload(persistableNetworkPayload, getTestNodeAddress(), false)); - this.testState.mockedStorage.removeExpiredEntries(); + testState.mockedStorage.removeExpiredEntries(); - Assert.assertTrue(this.testState.mockedStorage.appendOnlyDataStoreService.getMap(persistableNetworkPayload).containsKey(new P2PDataStorage.ByteArray(persistableNetworkPayload.getHash()))); + assertTrue(testState.mockedStorage.appendOnlyDataStoreService.getMap(persistableNetworkPayload).containsKey(new P2PDataStorage.ByteArray(persistableNetworkPayload.getHash()))); } // TESTCASE: Correctly skips non-persistable entries that are not expired @@ -86,13 +86,13 @@ public class P2PDataStorageRemoveExpiredTest { public void removeExpiredEntries_SkipNonExpiredExpirableEntries() throws CryptoException, NoSuchAlgorithmException { KeyPair ownerKeys = TestUtils.generateKeyPair(); ProtectedStoragePayload protectedStoragePayload = new ExpirableProtectedStoragePayloadStub(ownerKeys.getPublic()); - ProtectedStorageEntry protectedStorageEntry = this.testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); - Assert.assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); + ProtectedStorageEntry protectedStorageEntry = testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); + assertTrue(testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, getTestNodeAddress(), null)); - SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); - this.testState.mockedStorage.removeExpiredEntries(); + SavedTestState beforeState = testState.saveTestState(protectedStorageEntry); + testState.mockedStorage.removeExpiredEntries(); - this.testState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, false, false, false, false); + testState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, false, false, false, false); } // TESTCASE: Correctly expires non-persistable entries that are expired @@ -100,16 +100,16 @@ public class P2PDataStorageRemoveExpiredTest { public void removeExpiredEntries_ExpiresExpiredExpirableEntries() throws CryptoException, NoSuchAlgorithmException { KeyPair ownerKeys = TestUtils.generateKeyPair(); ProtectedStoragePayload protectedStoragePayload = new ExpirableProtectedStoragePayloadStub(ownerKeys.getPublic(), 0); - ProtectedStorageEntry protectedStorageEntry = this.testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); - Assert.assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); + ProtectedStorageEntry protectedStorageEntry = testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); + assertTrue(testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, getTestNodeAddress(), null)); // Increment the clock by an hour which will cause the Payloads to be outside the TTL range - this.testState.incrementClock(); + testState.incrementClock(); - SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); - this.testState.mockedStorage.removeExpiredEntries(); + SavedTestState beforeState = testState.saveTestState(protectedStorageEntry); + testState.mockedStorage.removeExpiredEntries(); - this.testState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, true, true, false, false); + testState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, true, true, false, false); } // TESTCASE: Correctly skips persistable entries that are not expired @@ -117,13 +117,13 @@ public class P2PDataStorageRemoveExpiredTest { public void removeExpiredEntries_SkipNonExpiredPersistableExpirableEntries() throws CryptoException, NoSuchAlgorithmException { KeyPair ownerKeys = TestUtils.generateKeyPair(); ProtectedStoragePayload protectedStoragePayload = new PersistableExpirableProtectedStoragePayloadStub(ownerKeys.getPublic()); - ProtectedStorageEntry protectedStorageEntry = this.testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); - Assert.assertTrue(this.testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); + ProtectedStorageEntry protectedStorageEntry = testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); + assertTrue(testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, getTestNodeAddress(), null)); - SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); - this.testState.mockedStorage.removeExpiredEntries(); + SavedTestState beforeState = testState.saveTestState(protectedStorageEntry); + testState.mockedStorage.removeExpiredEntries(); - this.testState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, false, false, false, false); + testState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, false, false, false, false); } // TESTCASE: Correctly expires persistable entries that are expired @@ -132,15 +132,15 @@ public class P2PDataStorageRemoveExpiredTest { KeyPair ownerKeys = TestUtils.generateKeyPair(); ProtectedStoragePayload protectedStoragePayload = new PersistableExpirableProtectedStoragePayloadStub(ownerKeys.getPublic(), 0); ProtectedStorageEntry protectedStorageEntry = testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); - Assert.assertTrue(testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, TestState.getTestNodeAddress(), null)); + assertTrue(testState.mockedStorage.addProtectedStorageEntry(protectedStorageEntry, getTestNodeAddress(), null)); // Increment the clock by an hour which will cause the Payloads to be outside the TTL range - this.testState.incrementClock(); + testState.incrementClock(); - SavedTestState beforeState = this.testState.saveTestState(protectedStorageEntry); - this.testState.mockedStorage.removeExpiredEntries(); + SavedTestState beforeState = testState.saveTestState(protectedStorageEntry); + testState.mockedStorage.removeExpiredEntries(); - this.testState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, true, true, false, false); + testState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, true, true, false, false); } // TESTCASE: Ensure we try to purge old entries sequence number map when size exceeds the maximum size @@ -157,19 +157,19 @@ public class P2PDataStorageRemoveExpiredTest { ProtectedStorageEntry purgedProtectedStorageEntry = testState.mockedStorage.getProtectedStorageEntry(purgedProtectedStoragePayload, purgedOwnerKeys); expectedRemoves.add(purgedProtectedStorageEntry); - Assert.assertTrue(testState.mockedStorage.addProtectedStorageEntry(purgedProtectedStorageEntry, TestState.getTestNodeAddress(), null)); + assertTrue(testState.mockedStorage.addProtectedStorageEntry(purgedProtectedStorageEntry, getTestNodeAddress(), null)); for (int i = 0; i < MAX_SEQUENCE_NUMBER_MAP_SIZE_BEFORE_PURGE - 1; ++i) { KeyPair ownerKeys = TestUtils.generateKeyPair(); ProtectedStoragePayload protectedStoragePayload = new PersistableExpirableProtectedStoragePayloadStub(ownerKeys.getPublic(), 0); ProtectedStorageEntry tmpEntry = testState.mockedStorage.getProtectedStorageEntry(protectedStoragePayload, ownerKeys); expectedRemoves.add(tmpEntry); - Assert.assertTrue(testState.mockedStorage.addProtectedStorageEntry(tmpEntry, TestState.getTestNodeAddress(), null)); + assertTrue(testState.mockedStorage.addProtectedStorageEntry(tmpEntry, getTestNodeAddress(), null)); } // Increment the time by 5 days which is less than the purge requirement. This will allow the map to have // some values that will be purged and others that will stay. - this.testState.clockFake.increment(TimeUnit.DAYS.toMillis(initialClockIncrement)); + testState.clockFake.increment(TimeUnit.DAYS.toMillis(initialClockIncrement)); // Add a final entry that will not be purged KeyPair keepOwnerKeys = TestUtils.generateKeyPair(); @@ -177,15 +177,15 @@ public class P2PDataStorageRemoveExpiredTest { ProtectedStorageEntry keepProtectedStorageEntry = testState.mockedStorage.getProtectedStorageEntry(keepProtectedStoragePayload, keepOwnerKeys); expectedRemoves.add(keepProtectedStorageEntry); - Assert.assertTrue(testState.mockedStorage.addProtectedStorageEntry(keepProtectedStorageEntry, TestState.getTestNodeAddress(), null)); + assertTrue(testState.mockedStorage.addProtectedStorageEntry(keepProtectedStorageEntry, getTestNodeAddress(), null)); // P2PDataStorage::PURGE_AGE_DAYS == 10 days // Advance time past it so they will be valid purge targets - this.testState.clockFake.increment(TimeUnit.DAYS.toMillis(P2PDataStorage.PURGE_AGE_DAYS + 1 - initialClockIncrement)); + testState.clockFake.increment(TimeUnit.DAYS.toMillis(P2PDataStorage.PURGE_AGE_DAYS + 1 - initialClockIncrement)); // The first 4 entries (11 days old) should be purged from the SequenceNumberMap - SavedTestState beforeState = this.testState.saveTestState(purgedProtectedStorageEntry); - this.testState.mockedStorage.removeExpiredEntries(); - this.testState.verifyProtectedStorageRemove(beforeState, expectedRemoves, true, true, false, false); + SavedTestState beforeState = testState.saveTestState(purgedProtectedStorageEntry); + testState.mockedStorage.removeExpiredEntries(); + testState.verifyProtectedStorageRemove(beforeState, expectedRemoves, true, true, false, false); } } diff --git a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageRequestDataTest.java b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageRequestDataTest.java index c027221a..d99d82d9 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageRequestDataTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStorageRequestDataTest.java @@ -28,15 +28,16 @@ import haveno.network.p2p.storage.mocks.ProtectedStoragePayloadStub; import haveno.network.p2p.storage.payload.PersistableNetworkPayload; import haveno.network.p2p.storage.payload.ProtectedStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStoragePayload; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.util.Set; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -46,7 +47,7 @@ public class P2PDataStorageRequestDataTest { private NodeAddress localNodeAddress; - @Before + @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); this.testState = new TestState(); @@ -94,9 +95,9 @@ public class P2PDataStorageRequestDataTest { public void buildPreliminaryGetDataRequest_EmptyP2PDataStore() { PreliminaryGetDataRequest getDataRequest = this.testState.mockedStorage.buildPreliminaryGetDataRequest(1); - Assert.assertEquals(getDataRequest.getNonce(), 1); - Assert.assertEquals(getDataRequest.getSupportedCapabilities(), Capabilities.app); - Assert.assertTrue(getDataRequest.getExcludedKeys().isEmpty()); + assertEquals(getDataRequest.getNonce(), 1); + assertEquals(getDataRequest.getSupportedCapabilities(), Capabilities.app); + assertTrue(getDataRequest.getExcludedKeys().isEmpty()); } // TESTCASE: P2PDataStorage with no entries returns an empty PreliminaryGetDataRequest @@ -105,9 +106,9 @@ public class P2PDataStorageRequestDataTest { GetUpdatedDataRequest getDataRequest = this.testState.mockedStorage.buildGetUpdatedDataRequest(this.localNodeAddress, 1); - Assert.assertEquals(getDataRequest.getNonce(), 1); - Assert.assertEquals(getDataRequest.getSenderNodeAddress(), this.localNodeAddress); - Assert.assertTrue(getDataRequest.getExcludedKeys().isEmpty()); + assertEquals(getDataRequest.getNonce(), 1); + assertEquals(getDataRequest.getSenderNodeAddress(), this.localNodeAddress); + assertTrue(getDataRequest.getExcludedKeys().isEmpty()); } // TESTCASE: P2PDataStorage with PersistableNetworkPayloads and ProtectedStorageEntry generates @@ -127,14 +128,14 @@ public class P2PDataStorageRequestDataTest { PreliminaryGetDataRequest getDataRequest = this.testState.mockedStorage.buildPreliminaryGetDataRequest(1); - Assert.assertEquals(getDataRequest.getNonce(), 1); - Assert.assertEquals(getDataRequest.getSupportedCapabilities(), Capabilities.app); - Assert.assertEquals(4, getDataRequest.getExcludedKeys().size()); - Assert.assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), toAdd1.getHash())); - Assert.assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), toAdd2.getHash())); - Assert.assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), + assertEquals(getDataRequest.getNonce(), 1); + assertEquals(getDataRequest.getSupportedCapabilities(), Capabilities.app); + assertEquals(4, getDataRequest.getExcludedKeys().size()); + assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), toAdd1.getHash())); + assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), toAdd2.getHash())); + assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), P2PDataStorage.get32ByteHash(toAdd3.getProtectedStoragePayload()))); - Assert.assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), + assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), P2PDataStorage.get32ByteHash(toAdd4.getProtectedStoragePayload()))); } @@ -156,14 +157,14 @@ public class P2PDataStorageRequestDataTest { GetUpdatedDataRequest getDataRequest = this.testState.mockedStorage.buildGetUpdatedDataRequest(this.localNodeAddress, 1); - Assert.assertEquals(getDataRequest.getNonce(), 1); - Assert.assertEquals(getDataRequest.getSenderNodeAddress(), this.localNodeAddress); - Assert.assertEquals(4, getDataRequest.getExcludedKeys().size()); - Assert.assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), toAdd1.getHash())); - Assert.assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), toAdd2.getHash())); - Assert.assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), + assertEquals(getDataRequest.getNonce(), 1); + assertEquals(getDataRequest.getSenderNodeAddress(), this.localNodeAddress); + assertEquals(4, getDataRequest.getExcludedKeys().size()); + assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), toAdd1.getHash())); + assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), toAdd2.getHash())); + assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), P2PDataStorage.get32ByteHash(toAdd3.getProtectedStoragePayload()))); - Assert.assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), + assertTrue(byteSetContains(getDataRequest.getExcludedKeys(), P2PDataStorage.get32ByteHash(toAdd4.getProtectedStoragePayload()))); } } diff --git a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStoreDisconnectTest.java b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStoreDisconnectTest.java index b6a5db3c..65321368 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStoreDisconnectTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/P2PDataStoreDisconnectTest.java @@ -25,9 +25,8 @@ import haveno.network.p2p.network.Connection; import haveno.network.p2p.storage.mocks.ExpirableProtectedStoragePayloadStub; import haveno.network.p2p.storage.payload.ProtectedStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStoragePayload; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; @@ -36,6 +35,8 @@ import java.util.concurrent.TimeUnit; import static haveno.network.p2p.storage.TestState.SavedTestState; import static haveno.network.p2p.storage.TestState.getTestNodeAddress; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -65,13 +66,14 @@ public class P2PDataStoreDisconnectTest { currentState.verifyProtectedStorageRemove(beforeState, protectedStorageEntry, false, false, false, false); - if (wasTTLReduced) - Assert.assertTrue(protectedStorageEntry.getCreationTimeStamp() < beforeState.creationTimestampBeforeUpdate); - else - Assert.assertEquals(protectedStorageEntry.getCreationTimeStamp(), beforeState.creationTimestampBeforeUpdate); + if (wasTTLReduced) { + assertTrue(protectedStorageEntry.getCreationTimeStamp() < beforeState.creationTimestampBeforeUpdate); + } else { + assertEquals(protectedStorageEntry.getCreationTimeStamp(), beforeState.creationTimestampBeforeUpdate); + } } - @Before + @BeforeEach public void setUp() { this.mockedConnection = mock(Connection.class); this.testState = new TestState(); diff --git a/p2p/src/test/java/haveno/network/p2p/storage/TestState.java b/p2p/src/test/java/haveno/network/p2p/storage/TestState.java index 17914cc3..d43acc54 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/TestState.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/TestState.java @@ -41,7 +41,6 @@ import haveno.network.p2p.storage.persistence.ProtectedDataStoreService; import haveno.network.p2p.storage.persistence.RemovedPayloadsService; import haveno.network.p2p.storage.persistence.ResourceDataStoreService; import haveno.network.p2p.storage.persistence.SequenceNumberMap; -import org.junit.Assert; import org.mockito.ArgumentCaptor; import java.security.PublicKey; @@ -51,6 +50,10 @@ import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.isNull; import static org.mockito.Mockito.mock; @@ -62,7 +65,7 @@ import static org.mockito.Mockito.when; /** * Test object that stores a P2PDataStore instance as well as the mock objects necessary for state validation. - * + *

* Used in the P2PDataStorage*Test(s) in order to leverage common test set up and validation. */ public class TestState { @@ -79,36 +82,36 @@ public class TestState { private RemovedPayloadsService removedPayloadsService; TestState() { - this.mockBroadcaster = mock(Broadcaster.class); - this.mockSeqNrPersistenceManager = mock(PersistenceManager.class); - this.removedPayloadsService = mock(RemovedPayloadsService.class); - this.clockFake = new ClockFake(); - this.protectedDataStoreService = new ProtectedDataStoreService(); + mockBroadcaster = mock(Broadcaster.class); + mockSeqNrPersistenceManager = mock(PersistenceManager.class); + removedPayloadsService = mock(RemovedPayloadsService.class); + clockFake = new ClockFake(); + protectedDataStoreService = new ProtectedDataStoreService(); - this.mockedStorage = new P2PDataStorage(mock(NetworkNode.class), - this.mockBroadcaster, + mockedStorage = new P2PDataStorage(mock(NetworkNode.class), + mockBroadcaster, new AppendOnlyDataStoreServiceFake(), - this.protectedDataStoreService, mock(ResourceDataStoreService.class), - this.mockSeqNrPersistenceManager, + protectedDataStoreService, mock(ResourceDataStoreService.class), + mockSeqNrPersistenceManager, removedPayloadsService, - this.clockFake, + clockFake, MAX_SEQUENCE_NUMBER_MAP_SIZE_BEFORE_PURGE); - this.appendOnlyDataStoreListener = mock(AppendOnlyDataStoreListener.class); - this.hashMapChangedListener = mock(HashMapChangedListener.class); - this.protectedDataStoreService.addService(new MapStoreServiceFake()); + appendOnlyDataStoreListener = mock(AppendOnlyDataStoreListener.class); + hashMapChangedListener = mock(HashMapChangedListener.class); + protectedDataStoreService.addService(new MapStoreServiceFake()); - this.mockedStorage = createP2PDataStorageForTest( - this.mockBroadcaster, - this.protectedDataStoreService, - this.mockSeqNrPersistenceManager, - this.clockFake, - this.hashMapChangedListener, - this.appendOnlyDataStoreListener, + mockedStorage = createP2PDataStorageForTest( + mockBroadcaster, + protectedDataStoreService, + mockSeqNrPersistenceManager, + clockFake, + hashMapChangedListener, + appendOnlyDataStoreListener, removedPayloadsService); - when(this.mockSeqNrPersistenceManager.getPersisted()) - .thenReturn(this.mockedStorage.sequenceNumberMap); + when(mockSeqNrPersistenceManager.getPersisted()) + .thenReturn(mockedStorage.sequenceNumberMap); } @@ -118,18 +121,18 @@ public class TestState { * not running the entire storage code paths. */ void simulateRestart() { - this.removedPayloadsService = mock(RemovedPayloadsService.class); - this.mockedStorage = createP2PDataStorageForTest( - this.mockBroadcaster, - this.protectedDataStoreService, - this.mockSeqNrPersistenceManager, - this.clockFake, - this.hashMapChangedListener, - this.appendOnlyDataStoreListener, + removedPayloadsService = mock(RemovedPayloadsService.class); + mockedStorage = createP2PDataStorageForTest( + mockBroadcaster, + protectedDataStoreService, + mockSeqNrPersistenceManager, + clockFake, + hashMapChangedListener, + appendOnlyDataStoreListener, removedPayloadsService); - when(this.mockSeqNrPersistenceManager.getPersisted()) - .thenReturn(this.mockedStorage.sequenceNumberMap); + when(mockSeqNrPersistenceManager.getPersisted()) + .thenReturn(mockedStorage.sequenceNumberMap); } private static P2PDataStorage createP2PDataStorageForTest( @@ -162,13 +165,13 @@ public class TestState { } private void resetState() { - reset(this.mockBroadcaster); - reset(this.appendOnlyDataStoreListener); - reset(this.hashMapChangedListener); + reset(mockBroadcaster); + reset(appendOnlyDataStoreListener); + reset(hashMapChangedListener); } void incrementClock() { - this.clockFake.increment(TimeUnit.HOURS.toMillis(1)); + clockFake.increment(TimeUnit.HOURS.toMillis(1)); } public static NodeAddress getTestNodeAddress() { @@ -179,7 +182,7 @@ public class TestState { * Common test helpers that verify the correct events were signaled based on the test expectation and before/after states. */ private void verifySequenceNumberMapWriteContains(P2PDataStorage.ByteArray payloadHash, int sequenceNumber) { - Assert.assertEquals(sequenceNumber, mockSeqNrPersistenceManager.getPersisted().get(payloadHash).sequenceNr); + assertEquals(sequenceNumber, mockSeqNrPersistenceManager.getPersisted().get(payloadHash).sequenceNr); } void verifyPersistableAdd(SavedTestState beforeState, @@ -190,22 +193,22 @@ public class TestState { P2PDataStorage.ByteArray hash = new P2PDataStorage.ByteArray(persistableNetworkPayload.getHash()); if (expectedHashMapAndDataStoreUpdated) - Assert.assertEquals(persistableNetworkPayload, this.mockedStorage.appendOnlyDataStoreService.getMap(persistableNetworkPayload).get(hash)); + assertEquals(persistableNetworkPayload, mockedStorage.appendOnlyDataStoreService.getMap(persistableNetworkPayload).get(hash)); else - Assert.assertEquals(beforeState.persistableNetworkPayloadBeforeOp, this.mockedStorage.appendOnlyDataStoreService.getMap(persistableNetworkPayload).get(hash)); + assertEquals(beforeState.persistableNetworkPayloadBeforeOp, mockedStorage.appendOnlyDataStoreService.getMap(persistableNetworkPayload).get(hash)); if (expectedListenersSignaled) - verify(this.appendOnlyDataStoreListener).onAdded(persistableNetworkPayload); + verify(appendOnlyDataStoreListener).onAdded(persistableNetworkPayload); else - verify(this.appendOnlyDataStoreListener, never()).onAdded(persistableNetworkPayload); + verify(appendOnlyDataStoreListener, never()).onAdded(persistableNetworkPayload); if (expectedBroadcast) - verify(this.mockBroadcaster).broadcast(any(AddPersistableNetworkPayloadMessage.class), nullable(NodeAddress.class)); + verify(mockBroadcaster).broadcast(any(AddPersistableNetworkPayloadMessage.class), nullable(NodeAddress.class)); else - verify(this.mockBroadcaster, never()).broadcast(any(BroadcastMessage.class), nullable(NodeAddress.class)); + verify(mockBroadcaster, never()).broadcast(any(BroadcastMessage.class), nullable(NodeAddress.class)); } - void verifyProtectedStorageAdd(SavedTestState beforeState, + void assertProtectedStorageAdd(SavedTestState beforeState, ProtectedStorageEntry protectedStorageEntry, boolean expectedHashMapAndDataStoreUpdated, boolean expectedListenersSignaled, @@ -214,19 +217,19 @@ public class TestState { P2PDataStorage.ByteArray hashMapHash = P2PDataStorage.get32ByteHashAsByteArray(protectedStorageEntry.getProtectedStoragePayload()); if (expectedHashMapAndDataStoreUpdated) { - Assert.assertEquals(protectedStorageEntry, this.mockedStorage.getMap().get(hashMapHash)); + assertEquals(protectedStorageEntry, mockedStorage.getMap().get(hashMapHash)); if (protectedStorageEntry.getProtectedStoragePayload() instanceof PersistablePayload) - Assert.assertEquals(protectedStorageEntry, this.protectedDataStoreService.getMap().get(hashMapHash)); + assertEquals(protectedStorageEntry, protectedDataStoreService.getMap().get(hashMapHash)); } else { - Assert.assertEquals(beforeState.protectedStorageEntryBeforeOp, this.mockedStorage.getMap().get(hashMapHash)); - Assert.assertEquals(beforeState.protectedStorageEntryBeforeOpDataStoreMap, this.protectedDataStoreService.getMap().get(hashMapHash)); + assertEquals(beforeState.protectedStorageEntryBeforeOp, mockedStorage.getMap().get(hashMapHash)); + assertEquals(beforeState.protectedStorageEntryBeforeOpDataStoreMap, protectedDataStoreService.getMap().get(hashMapHash)); } if (expectedListenersSignaled) { - verify(this.hashMapChangedListener).onAdded(Collections.singletonList(protectedStorageEntry)); + verify(hashMapChangedListener).onAdded(Collections.singletonList(protectedStorageEntry)); } else { - verify(this.hashMapChangedListener, never()).onAdded(Collections.singletonList(protectedStorageEntry)); + verify(hashMapChangedListener, never()).onAdded(Collections.singletonList(protectedStorageEntry)); } if (expectedBroadcast) { @@ -235,17 +238,17 @@ public class TestState { // overloaded method with nullable listener. Seems a testframework issue as it should not matter if the // method with listener is called with null argument or the other method with no listener. We removed the // null value from all other calls but here we can't as it breaks the test. - verify(this.mockBroadcaster).broadcast(captor.capture(), nullable(NodeAddress.class), isNull()); + verify(mockBroadcaster).broadcast(captor.capture(), nullable(NodeAddress.class), isNull()); BroadcastMessage broadcastMessage = captor.getValue(); - Assert.assertTrue(broadcastMessage instanceof AddDataMessage); - Assert.assertEquals(protectedStorageEntry, ((AddDataMessage) broadcastMessage).getProtectedStorageEntry()); + assertTrue(broadcastMessage instanceof AddDataMessage); + assertEquals(protectedStorageEntry, ((AddDataMessage) broadcastMessage).getProtectedStorageEntry()); } else { - verify(this.mockBroadcaster, never()).broadcast(any(BroadcastMessage.class), nullable(NodeAddress.class)); + verify(mockBroadcaster, never()).broadcast(any(BroadcastMessage.class), nullable(NodeAddress.class)); } if (expectedSequenceNrMapWrite) { - this.verifySequenceNumberMapWriteContains(P2PDataStorage.get32ByteHashAsByteArray(protectedStorageEntry.getProtectedStoragePayload()), protectedStorageEntry.getSequenceNumber()); + verifySequenceNumberMapWriteContains(P2PDataStorage.get32ByteHashAsByteArray(protectedStorageEntry.getProtectedStoragePayload()), protectedStorageEntry.getSequenceNumber()); } } @@ -272,46 +275,46 @@ public class TestState { // we don't care about the order. if (expectedListenersSignaled) { final ArgumentCaptor> argument = ArgumentCaptor.forClass(Collection.class); - verify(this.hashMapChangedListener).onRemoved(argument.capture()); + verify(hashMapChangedListener).onRemoved(argument.capture()); Set actual = new HashSet<>(argument.getValue()); Set expected = new HashSet<>(protectedStorageEntries); // Ensure we didn't remove duplicates - Assert.assertEquals(protectedStorageEntries.size(), expected.size()); - Assert.assertEquals(argument.getValue().size(), actual.size()); - Assert.assertEquals(expected, actual); + assertEquals(protectedStorageEntries.size(), expected.size()); + assertEquals(argument.getValue().size(), actual.size()); + assertEquals(expected, actual); } else { - verify(this.hashMapChangedListener, never()).onRemoved(any()); + verify(hashMapChangedListener, never()).onRemoved(any()); } if (!expectedBroadcast) - verify(this.mockBroadcaster, never()).broadcast(any(BroadcastMessage.class), nullable(NodeAddress.class)); + verify(mockBroadcaster, never()).broadcast(any(BroadcastMessage.class), nullable(NodeAddress.class)); protectedStorageEntries.forEach(protectedStorageEntry -> { P2PDataStorage.ByteArray hashMapHash = P2PDataStorage.get32ByteHashAsByteArray(protectedStorageEntry.getProtectedStoragePayload()); if (expectedSeqNrWrite) - this.verifySequenceNumberMapWriteContains(P2PDataStorage.get32ByteHashAsByteArray( + verifySequenceNumberMapWriteContains(P2PDataStorage.get32ByteHashAsByteArray( protectedStorageEntry.getProtectedStoragePayload()), protectedStorageEntry.getSequenceNumber()); if (expectedBroadcast) { if (protectedStorageEntry instanceof ProtectedMailboxStorageEntry) - verify(this.mockBroadcaster).broadcast(any(RemoveMailboxDataMessage.class), nullable(NodeAddress.class)); + verify(mockBroadcaster).broadcast(any(RemoveMailboxDataMessage.class), nullable(NodeAddress.class)); else - verify(this.mockBroadcaster).broadcast(any(RemoveDataMessage.class), nullable(NodeAddress.class)); + verify(mockBroadcaster).broadcast(any(RemoveDataMessage.class), nullable(NodeAddress.class)); } if (expectedHashMapAndDataStoreUpdated) { - Assert.assertNull(this.mockedStorage.getMap().get(hashMapHash)); + assertNull(mockedStorage.getMap().get(hashMapHash)); if (protectedStorageEntry.getProtectedStoragePayload() instanceof PersistablePayload) - Assert.assertNull(this.protectedDataStoreService.getMap().get(hashMapHash)); + assertNull(protectedDataStoreService.getMap().get(hashMapHash)); } else { - Assert.assertEquals(beforeState.protectedStorageEntryBeforeOp, this.mockedStorage.getMap().get(hashMapHash)); + assertEquals(beforeState.protectedStorageEntryBeforeOp, mockedStorage.getMap().get(hashMapHash)); } }); } @@ -321,33 +324,33 @@ public class TestState { boolean expectedStateChange) { P2PDataStorage.ByteArray payloadHash = new P2PDataStorage.ByteArray(refreshOfferMessage.getHashOfPayload()); - ProtectedStorageEntry entryAfterRefresh = this.mockedStorage.getMap().get(payloadHash); + ProtectedStorageEntry entryAfterRefresh = mockedStorage.getMap().get(payloadHash); if (expectedStateChange) { - Assert.assertNotNull(entryAfterRefresh); - Assert.assertEquals(refreshOfferMessage.getSequenceNumber(), entryAfterRefresh.getSequenceNumber()); - Assert.assertEquals(refreshOfferMessage.getSignature(), entryAfterRefresh.getSignature()); - Assert.assertTrue(entryAfterRefresh.getCreationTimeStamp() > beforeState.creationTimestampBeforeUpdate); + assertNotNull(entryAfterRefresh); + assertEquals(refreshOfferMessage.getSequenceNumber(), entryAfterRefresh.getSequenceNumber()); + assertEquals(refreshOfferMessage.getSignature(), entryAfterRefresh.getSignature()); + assertTrue(entryAfterRefresh.getCreationTimeStamp() > beforeState.creationTimestampBeforeUpdate); final ArgumentCaptor captor = ArgumentCaptor.forClass(BroadcastMessage.class); - verify(this.mockBroadcaster).broadcast(captor.capture(), nullable(NodeAddress.class)); + verify(mockBroadcaster).broadcast(captor.capture(), nullable(NodeAddress.class)); BroadcastMessage broadcastMessage = captor.getValue(); - Assert.assertTrue(broadcastMessage instanceof RefreshOfferMessage); - Assert.assertEquals(refreshOfferMessage, broadcastMessage); + assertTrue(broadcastMessage instanceof RefreshOfferMessage); + assertEquals(refreshOfferMessage, broadcastMessage); - this.verifySequenceNumberMapWriteContains(payloadHash, refreshOfferMessage.getSequenceNumber()); + verifySequenceNumberMapWriteContains(payloadHash, refreshOfferMessage.getSequenceNumber()); } else { // Verify the existing entry is unchanged if (beforeState.protectedStorageEntryBeforeOp != null) { - Assert.assertEquals(entryAfterRefresh, beforeState.protectedStorageEntryBeforeOp); - Assert.assertEquals(beforeState.protectedStorageEntryBeforeOp.getSequenceNumber(), entryAfterRefresh.getSequenceNumber()); - Assert.assertEquals(beforeState.protectedStorageEntryBeforeOp.getSignature(), entryAfterRefresh.getSignature()); - Assert.assertEquals(beforeState.creationTimestampBeforeUpdate, entryAfterRefresh.getCreationTimeStamp()); + assertEquals(entryAfterRefresh, beforeState.protectedStorageEntryBeforeOp); + assertEquals(beforeState.protectedStorageEntryBeforeOp.getSequenceNumber(), entryAfterRefresh.getSequenceNumber()); + assertEquals(beforeState.protectedStorageEntryBeforeOp.getSignature(), entryAfterRefresh.getSignature()); + assertEquals(beforeState.creationTimestampBeforeUpdate, entryAfterRefresh.getCreationTimeStamp()); } - verify(this.mockBroadcaster, never()).broadcast(any(BroadcastMessage.class), nullable(NodeAddress.class)); + verify(mockBroadcaster, never()).broadcast(any(BroadcastMessage.class), nullable(NodeAddress.class)); } } @@ -394,34 +397,34 @@ public class TestState { private SavedTestState(TestState state) { this.state = state; - this.creationTimestampBeforeUpdate = 0; - this.state.resetState(); + creationTimestampBeforeUpdate = 0; + state.resetState(); } private SavedTestState(TestState testState, PersistableNetworkPayload persistableNetworkPayload) { this(testState); P2PDataStorage.ByteArray hash = new P2PDataStorage.ByteArray(persistableNetworkPayload.getHash()); - this.persistableNetworkPayloadBeforeOp = testState.mockedStorage.appendOnlyDataStoreService.getMap(persistableNetworkPayload).get(hash); + persistableNetworkPayloadBeforeOp = testState.mockedStorage.appendOnlyDataStoreService.getMap(persistableNetworkPayload).get(hash); } private SavedTestState(TestState testState, ProtectedStorageEntry protectedStorageEntry) { this(testState); P2PDataStorage.ByteArray hashMapHash = P2PDataStorage.get32ByteHashAsByteArray(protectedStorageEntry.getProtectedStoragePayload()); - this.protectedStorageEntryBeforeOp = testState.mockedStorage.getMap().get(hashMapHash); - this.protectedStorageEntryBeforeOpDataStoreMap = testState.protectedDataStoreService.getMap().get(hashMapHash); + protectedStorageEntryBeforeOp = testState.mockedStorage.getMap().get(hashMapHash); + protectedStorageEntryBeforeOpDataStoreMap = testState.protectedDataStoreService.getMap().get(hashMapHash); - this.creationTimestampBeforeUpdate = (this.protectedStorageEntryBeforeOp != null) ? this.protectedStorageEntryBeforeOp.getCreationTimeStamp() : 0; + creationTimestampBeforeUpdate = (protectedStorageEntryBeforeOp != null) ? protectedStorageEntryBeforeOp.getCreationTimeStamp() : 0; } private SavedTestState(TestState testState, RefreshOfferMessage refreshOfferMessage) { this(testState); P2PDataStorage.ByteArray hashMapHash = new P2PDataStorage.ByteArray(refreshOfferMessage.getHashOfPayload()); - this.protectedStorageEntryBeforeOp = testState.mockedStorage.getMap().get(hashMapHash); + protectedStorageEntryBeforeOp = testState.mockedStorage.getMap().get(hashMapHash); - this.creationTimestampBeforeUpdate = (this.protectedStorageEntryBeforeOp != null) ? this.protectedStorageEntryBeforeOp.getCreationTimeStamp() : 0; + creationTimestampBeforeUpdate = (protectedStorageEntryBeforeOp != null) ? protectedStorageEntryBeforeOp.getCreationTimeStamp() : 0; } } } diff --git a/p2p/src/test/java/haveno/network/p2p/storage/messages/AddDataMessageTest.java b/p2p/src/test/java/haveno/network/p2p/storage/messages/AddDataMessageTest.java index cac216ff..99181e01 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/messages/AddDataMessageTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/messages/AddDataMessageTest.java @@ -29,8 +29,8 @@ import haveno.network.p2p.storage.payload.ProtectedMailboxStorageEntry; import haveno.network.p2p.storage.payload.ProtectedStorageEntry; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -47,8 +47,7 @@ public class AddDataMessageTest { private KeyRing keyRing1; private File dir1; - - @Before + @BeforeEach public void setup() throws InterruptedException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException, CryptoException, SignatureException, InvalidKeyException { dir1 = File.createTempFile("temp_tests1", ""); diff --git a/p2p/src/test/java/haveno/network/p2p/storage/payload/ProtectedMailboxStorageEntryTest.java b/p2p/src/test/java/haveno/network/p2p/storage/payload/ProtectedMailboxStorageEntryTest.java index a7d22db5..9f313835 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/payload/ProtectedMailboxStorageEntryTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/payload/ProtectedMailboxStorageEntryTest.java @@ -23,15 +23,16 @@ import haveno.common.crypto.Sig; import haveno.network.p2p.PrefixedSealedAndSignedMessage; import haveno.network.p2p.TestUtils; import haveno.network.p2p.storage.P2PDataStorage; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.time.Clock; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -63,7 +64,7 @@ public class ProtectedMailboxStorageEntryTest { return new ProtectedMailboxStorageEntry(mailboxStoragePayload, ownerKey.getPublic(), sequenceNumber, signature, receiverKey, Clock.systemDefaultZone()); } - @Before + @BeforeEach public void SetUp() { // Deep in the bowels of protobuf we grab the messageID from the version module. This is required to hash the // full MailboxStoragePayload so make sure it is initialized. @@ -79,7 +80,7 @@ public class ProtectedMailboxStorageEntryTest { MailboxStoragePayload mailboxStoragePayload = buildMailboxStoragePayload(senderKeys.getPublic(), receiverKeys.getPublic()); ProtectedStorageEntry protectedStorageEntry = buildProtectedMailboxStorageEntry(mailboxStoragePayload, senderKeys, receiverKeys.getPublic(), 1); - Assert.assertTrue(protectedStorageEntry.isValidForAddOperation()); + assertTrue(protectedStorageEntry.isValidForAddOperation()); } // TESTCASE: validForAddOperation() should return false if the Entry owner and sender key specified in payload don't match @@ -91,7 +92,7 @@ public class ProtectedMailboxStorageEntryTest { MailboxStoragePayload mailboxStoragePayload = buildMailboxStoragePayload(senderKeys.getPublic(), receiverKeys.getPublic()); ProtectedStorageEntry protectedStorageEntry = buildProtectedMailboxStorageEntry(mailboxStoragePayload, receiverKeys, receiverKeys.getPublic(), 1); - Assert.assertFalse(protectedStorageEntry.isValidForAddOperation()); + assertFalse(protectedStorageEntry.isValidForAddOperation()); } // TESTCASE: validForAddOperation() should fail if Entry.receiversPubKey and Payload.ownerPubKey don't match @@ -103,7 +104,7 @@ public class ProtectedMailboxStorageEntryTest { MailboxStoragePayload mailboxStoragePayload = buildMailboxStoragePayload(senderKeys.getPublic(), receiverKeys.getPublic()); ProtectedStorageEntry protectedStorageEntry = buildProtectedMailboxStorageEntry(mailboxStoragePayload, senderKeys, senderKeys.getPublic(), 1); - Assert.assertFalse(protectedStorageEntry.isValidForAddOperation()); + assertFalse(protectedStorageEntry.isValidForAddOperation()); } // TESTCASE: validForAddOperation() should fail if the signature isn't valid @@ -116,7 +117,7 @@ public class ProtectedMailboxStorageEntryTest { ProtectedStorageEntry protectedStorageEntry = new ProtectedMailboxStorageEntry( mailboxStoragePayload, senderKeys.getPublic(), 1, new byte[] { 0 }, receiverKeys.getPublic(), Clock.systemDefaultZone()); - Assert.assertFalse(protectedStorageEntry.isValidForAddOperation()); + assertFalse(protectedStorageEntry.isValidForAddOperation()); } // TESTCASE: validForRemoveOperation() should return true if the Entry owner and payload owner match @@ -128,7 +129,7 @@ public class ProtectedMailboxStorageEntryTest { MailboxStoragePayload mailboxStoragePayload = buildMailboxStoragePayload(senderKeys.getPublic(), receiverKeys.getPublic()); ProtectedStorageEntry protectedStorageEntry = buildProtectedMailboxStorageEntry(mailboxStoragePayload, receiverKeys, receiverKeys.getPublic(), 1); - Assert.assertTrue(protectedStorageEntry.isValidForRemoveOperation()); + assertTrue(protectedStorageEntry.isValidForRemoveOperation()); } // TESTCASE: validForRemoveOperation() should return false if the Entry owner and payload owner don't match @@ -140,7 +141,7 @@ public class ProtectedMailboxStorageEntryTest { MailboxStoragePayload mailboxStoragePayload = buildMailboxStoragePayload(senderKeys.getPublic(), receiverKeys.getPublic()); ProtectedStorageEntry protectedStorageEntry = buildProtectedMailboxStorageEntry(mailboxStoragePayload, senderKeys, receiverKeys.getPublic(), 1); - Assert.assertFalse(protectedStorageEntry.isValidForRemoveOperation()); + assertFalse(protectedStorageEntry.isValidForRemoveOperation()); } // TESTCASE: isValidForRemoveOperation() should fail if the signature is bad @@ -154,7 +155,7 @@ public class ProtectedMailboxStorageEntryTest { new ProtectedMailboxStorageEntry(mailboxStoragePayload, receiverKeys.getPublic(), 1, new byte[] { 0 }, receiverKeys.getPublic(), Clock.systemDefaultZone()); - Assert.assertFalse(protectedStorageEntry.isValidForRemoveOperation()); + assertFalse(protectedStorageEntry.isValidForRemoveOperation()); } // TESTCASE: isValidForRemoveOperation() should fail if the receiversPubKey does not match the Entry owner @@ -166,7 +167,7 @@ public class ProtectedMailboxStorageEntryTest { MailboxStoragePayload mailboxStoragePayload = buildMailboxStoragePayload(senderKeys.getPublic(), receiverKeys.getPublic()); ProtectedStorageEntry protectedStorageEntry = buildProtectedMailboxStorageEntry(mailboxStoragePayload, receiverKeys, senderKeys.getPublic(), 1); - Assert.assertFalse(protectedStorageEntry.isValidForRemoveOperation()); + assertFalse(protectedStorageEntry.isValidForRemoveOperation()); } // TESTCASE: isMetadataEquals() should succeed if the sequence number changes @@ -180,7 +181,7 @@ public class ProtectedMailboxStorageEntryTest { ProtectedStorageEntry seqNrTwo = buildProtectedMailboxStorageEntry(mailboxStoragePayload, senderKeys, receiverKeys.getPublic(), 2); - Assert.assertTrue(seqNrOne.matchesRelevantPubKey(seqNrTwo)); + assertTrue(seqNrOne.matchesRelevantPubKey(seqNrTwo)); } // TESTCASE: isMetadataEquals() should fail if the receiversPubKey changes @@ -194,6 +195,6 @@ public class ProtectedMailboxStorageEntryTest { ProtectedStorageEntry seqNrTwo = buildProtectedMailboxStorageEntry(mailboxStoragePayload, senderKeys, senderKeys.getPublic(), 1); - Assert.assertFalse(seqNrOne.matchesRelevantPubKey(seqNrTwo)); + assertFalse(seqNrOne.matchesRelevantPubKey(seqNrTwo)); } } diff --git a/p2p/src/test/java/haveno/network/p2p/storage/payload/ProtectedStorageEntryTest.java b/p2p/src/test/java/haveno/network/p2p/storage/payload/ProtectedStorageEntryTest.java index 9f745465..3b056ef2 100644 --- a/p2p/src/test/java/haveno/network/p2p/storage/payload/ProtectedStorageEntryTest.java +++ b/p2p/src/test/java/haveno/network/p2p/storage/payload/ProtectedStorageEntryTest.java @@ -24,9 +24,8 @@ import haveno.network.p2p.PrefixedSealedAndSignedMessage; import haveno.network.p2p.TestUtils; import haveno.network.p2p.storage.P2PDataStorage; import haveno.network.p2p.storage.mocks.ProtectedStoragePayloadStub; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; @@ -34,6 +33,9 @@ import java.security.PublicKey; import java.time.Clock; import java.time.Duration; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -70,7 +72,7 @@ public class ProtectedStorageEntryTest { MailboxStoragePayload.TTL); } - @Before + @BeforeEach public void SetUp() { // Deep in the bowels of protobuf we grab the messageID from the version module. This is required to hash the // full MailboxStoragePayload so make sure it is initialized. @@ -83,7 +85,7 @@ public class ProtectedStorageEntryTest { KeyPair ownerKeys = TestUtils.generateKeyPair(); ProtectedStorageEntry protectedStorageEntry = buildProtectedStorageEntry(ownerKeys, ownerKeys, 1); - Assert.assertTrue(protectedStorageEntry.isValidForAddOperation()); + assertTrue(protectedStorageEntry.isValidForAddOperation()); } // TESTCASE: validForAddOperation() should return false if the Entry owner and payload owner don't match @@ -93,7 +95,7 @@ public class ProtectedStorageEntryTest { KeyPair notOwnerKeys = TestUtils.generateKeyPair(); ProtectedStorageEntry protectedStorageEntry = buildProtectedStorageEntry(ownerKeys, notOwnerKeys, 1); - Assert.assertFalse(protectedStorageEntry.isValidForAddOperation()); + assertFalse(protectedStorageEntry.isValidForAddOperation()); } // TESTCASE: validForAddOperation() should fail if the entry is a MailboxStoragePayload wrapped in a @@ -108,7 +110,7 @@ public class ProtectedStorageEntryTest { buildMailboxStoragePayload(senderKeys.getPublic(), receiverKeys.getPublic()), senderKeys, 1); // should be assertFalse - Assert.assertTrue(protectedStorageEntry.isValidForAddOperation()); + assertTrue(protectedStorageEntry.isValidForAddOperation()); } // TESTCASE: validForAddOperation() should fail if the entry is a MailboxStoragePayload wrapped in a @@ -121,7 +123,7 @@ public class ProtectedStorageEntryTest { ProtectedStorageEntry protectedStorageEntry = buildProtectedStorageEntry( buildMailboxStoragePayload(senderKeys.getPublic(), receiverKeys.getPublic()), receiverKeys, 1); - Assert.assertFalse(protectedStorageEntry.isValidForAddOperation()); + assertFalse(protectedStorageEntry.isValidForAddOperation()); } // TESTCASE: validForAddOperation() should fail if the signature isn't valid @@ -134,7 +136,7 @@ public class ProtectedStorageEntryTest { new ProtectedStorageEntry(protectedStoragePayload, ownerKeys.getPublic(), 1, new byte[] { 0 }, Clock.systemDefaultZone()); - Assert.assertFalse(protectedStorageEntry.isValidForAddOperation()); + assertFalse(protectedStorageEntry.isValidForAddOperation()); } // TESTCASE: validForRemoveOperation() should return true if the Entry owner and payload owner match @@ -143,7 +145,7 @@ public class ProtectedStorageEntryTest { KeyPair ownerKeys = TestUtils.generateKeyPair(); ProtectedStorageEntry protectedStorageEntry = buildProtectedStorageEntry(ownerKeys, ownerKeys, 1); - Assert.assertTrue(protectedStorageEntry.isValidForRemoveOperation()); + assertTrue(protectedStorageEntry.isValidForRemoveOperation()); } // TESTCASE: validForRemoveOperation() should return false if the Entry owner and payload owner don't match @@ -153,7 +155,7 @@ public class ProtectedStorageEntryTest { KeyPair notOwnerKeys = TestUtils.generateKeyPair(); ProtectedStorageEntry protectedStorageEntry = buildProtectedStorageEntry(ownerKeys, notOwnerKeys, 1); - Assert.assertFalse(protectedStorageEntry.isValidForRemoveOperation()); + assertFalse(protectedStorageEntry.isValidForRemoveOperation()); } // TESTCASE: validForRemoveOperation() should fail if the entry is a MailboxStoragePayload wrapped in a @@ -168,7 +170,7 @@ public class ProtectedStorageEntryTest { buildMailboxStoragePayload(senderKeys.getPublic(), receiverKeys.getPublic()), senderKeys, 1); // should be assertFalse - Assert.assertTrue(protectedStorageEntry.isValidForRemoveOperation()); + assertTrue(protectedStorageEntry.isValidForRemoveOperation()); } @Test @@ -179,7 +181,7 @@ public class ProtectedStorageEntryTest { ProtectedStorageEntry protectedStorageEntry = buildProtectedStorageEntry( buildMailboxStoragePayload(senderKeys.getPublic(), receiverKeys.getPublic()), receiverKeys, 1); - Assert.assertFalse(protectedStorageEntry.isValidForRemoveOperation()); + assertFalse(protectedStorageEntry.isValidForRemoveOperation()); } // TESTCASE: isValidForRemoveOperation() should fail if the signature is bad @@ -192,7 +194,7 @@ public class ProtectedStorageEntryTest { new ProtectedStorageEntry(protectedStoragePayload, ownerKeys.getPublic(), 1, new byte[] { 0 }, Clock.systemDefaultZone()); - Assert.assertFalse(protectedStorageEntry.isValidForRemoveOperation()); + assertFalse(protectedStorageEntry.isValidForRemoveOperation()); } // TESTCASE: isMetadataEquals() should succeed if the sequence number changes @@ -203,7 +205,7 @@ public class ProtectedStorageEntryTest { ProtectedStorageEntry seqNrTwo = buildProtectedStorageEntry(ownerKeys, ownerKeys, 2); - Assert.assertTrue(seqNrOne.matchesRelevantPubKey(seqNrTwo)); + assertTrue(seqNrOne.matchesRelevantPubKey(seqNrTwo)); } // TESTCASE: isMetadataEquals() should fail if the OwnerPubKey changes @@ -216,7 +218,7 @@ public class ProtectedStorageEntryTest { ProtectedStorageEntry protectedStorageEntryTwo = buildProtectedStorageEntry(ownerKeys, notOwner, 1); - Assert.assertFalse(protectedStorageEntryOne.matchesRelevantPubKey(protectedStorageEntryTwo)); + assertFalse(protectedStorageEntryOne.matchesRelevantPubKey(protectedStorageEntryTwo)); } // TESTCASE: Payload implementing ProtectedStoragePayload & PersistableNetworkPayload is invalid @@ -225,8 +227,8 @@ public class ProtectedStorageEntryTest { // // We also want to guarantee that ONLY ProtectedStoragePayload objects are valid as payloads in // ProtectedStorageEntrys. This test will give a defense in case future development work breaks that expectation. - @Test(expected = IllegalArgumentException.class) - public void ProtectedStoragePayload_PersistableNetworkPayload_incompatible() throws NoSuchAlgorithmException { + @Test + public void protectedStoragePayloadPersistableNetworkPayloadIncompatible() throws NoSuchAlgorithmException { class IncompatiblePayload extends ProtectedStoragePayloadStub implements PersistableNetworkPayload { private IncompatiblePayload(PublicKey ownerPubKey) { @@ -251,8 +253,10 @@ public class ProtectedStorageEntryTest { KeyPair ownerKeys = TestUtils.generateKeyPair(); IncompatiblePayload incompatiblePayload = new IncompatiblePayload(ownerKeys.getPublic()); - new ProtectedStorageEntry(incompatiblePayload,ownerKeys.getPublic(), 1, - new byte[] { 0 }, Clock.systemDefaultZone()); + assertThrows(IllegalArgumentException.class, () -> + new ProtectedStorageEntry(incompatiblePayload,ownerKeys.getPublic(), 1, + new byte[] { 0 }, Clock.systemDefaultZone()) + ); } // TESTCASE: PSEs received with future-dated timestamps are updated to be min(currentTime, creationTimeStamp) @@ -268,6 +272,6 @@ public class ProtectedStorageEntryTest { new ProtectedStorageEntry(protectedStoragePayload, Sig.getPublicKeyBytes(ownerKeys.getPublic()), ownerKeys.getPublic(), 1, new byte[] { 0 }, futureClock.millis(), baseClock); - Assert.assertTrue(protectedStorageEntry.getCreationTimeStamp() <= baseClock.millis()); + assertTrue(protectedStorageEntry.getCreationTimeStamp() <= baseClock.millis()); } } diff --git a/p2p/src/test/java/haveno/network/utils/UtilsTest.java b/p2p/src/test/java/haveno/network/utils/UtilsTest.java index e986fb11..c255197e 100644 --- a/p2p/src/test/java/haveno/network/utils/UtilsTest.java +++ b/p2p/src/test/java/haveno/network/utils/UtilsTest.java @@ -17,10 +17,10 @@ package haveno.network.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class UtilsTest { diff --git a/seednode/src/test/java/haveno/seednode/GuiceSetupTest.java b/seednode/src/test/java/haveno/seednode/GuiceSetupTest.java index f251385f..3bb4dd69 100644 --- a/seednode/src/test/java/haveno/seednode/GuiceSetupTest.java +++ b/seednode/src/test/java/haveno/seednode/GuiceSetupTest.java @@ -6,7 +6,7 @@ import haveno.core.app.misc.AppSetupWithP2PAndDAO; import haveno.core.app.misc.ModuleForAppWithP2p; import haveno.core.locale.CurrencyUtil; import haveno.core.locale.Res; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class GuiceSetupTest { @Test