moving away from JUnit 4 completely to JUnit 5 Jupiter

This commit is contained in:
napoly 2023-03-25 18:11:58 +01:00 committed by woodser
parent a052fd7767
commit 65bc78d3d7
114 changed files with 1352 additions and 1338 deletions

View file

@ -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);
}

View file

@ -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<DummySeedNode> 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);

View file

@ -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);

View file

@ -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;

View file

@ -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);

View file

@ -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<PersistableNetworkPayload> 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));
}
}

View file

@ -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);
}

View file

@ -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

View file

@ -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();
}

View file

@ -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
*
* <p>
* 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.
*
* <p>
* Each subclass (Payload type) can optionally add additional tests that verify functionality only relevant
* to that payload.
*
* <p>
* Each test case is run through 3 entry points to verify the correct behavior:
*
* <p>
* 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<Object[]> 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<Object[]> data() {
List<Object[]> 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);
}
}
}

View file

@ -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);
}
}

View file

@ -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<? extends ProtectedStorageEntry> 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<Object[]> data() {
List<Object[]> 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<P2PDataStorage.ByteArray, ProtectedStorageEntry> beforeRestart = this.testState.mockedStorage.getMap();
Map<P2PDataStorage.ByteArray, ProtectedStorageEntry> 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);
}
}
}

View file

@ -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);
}
}

View file

@ -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())));
}
}

View file

@ -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();

View file

@ -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.
*
* <p>
* 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<Collection<ProtectedStorageEntry>> argument = ArgumentCaptor.forClass(Collection.class);
verify(this.hashMapChangedListener).onRemoved(argument.capture());
verify(hashMapChangedListener).onRemoved(argument.capture());
Set<ProtectedStorageEntry> actual = new HashSet<>(argument.getValue());
Set<ProtectedStorageEntry> 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<BroadcastMessage> 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;
}
}
}

View file

@ -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", "");

View file

@ -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));
}
}

View file

@ -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());
}
}

View file

@ -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 {