You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by kh...@apache.org on 2018/09/06 15:46:17 UTC
[geode] branch develop updated: GEODE-5607: Replace Jmock with
Mockito (#2414)
This is an automated email from the ASF dual-hosted git repository.
khowe pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git
The following commit(s) were added to refs/heads/develop by this push:
new b73f8bb GEODE-5607: Replace Jmock with Mockito (#2414)
b73f8bb is described below
commit b73f8bbde3e19942093e14f090789ee7bec5a299
Author: Juan José Ramos <ju...@users.noreply.github.com>
AuthorDate: Thu Sep 6 16:46:08 2018 +0100
GEODE-5607: Replace Jmock with Mockito (#2414)
* GEODE-5607: Replace Jmock with Mockito
- Removed dependency to `org.jmock`.
- Migrated several test classes to use `Mockito` instead `Jmock`.
- Changed same classes to use `assertj` instead of `junit.Assert`.
- Changed same classes to use `Awaitility` instead of `WaitCriterion`.
* Minor fixes in test asserts
Several test methods had the wrong order in the `assertThat` calls.
Asserts were written as `assertThat(<exepcted>).is*(<actual>)`, now
they have been corrected to `assertThat(<actual>).is*(<expected>)`.
* Minor fixes in test classes
---
.../internal/cache/DiskInitFileJUnitTest.java | 177 +-
.../geode/internal/cache/OplogRVVJUnitTest.java | 153 +-
.../internal/statistics/LinuxSystemStatsTest.java | 23 +-
.../statistics/ValueMonitorIntegrationTest.java | 365 ++--
.../CompiledAggregateFunctionJUnitTest.java | 69 +-
.../geode/internal/cache/TxCommitMessageTest.java | 1368 ++++-----------
.../io/CompositeOutputStreamJUnitTest.java | 593 ++-----
.../geode/internal/net/SocketUtilsJUnitTest.java | 103 +-
.../geode/internal/util/IOUtilsJUnitTest.java | 294 ++--
.../management/internal/JettyHelperJUnitTest.java | 47 +-
.../cli/commands/DiskStoreCommandsJUnitTest.java | 424 ++---
.../cli/commands/ListIndexCommandJUnitTest.java | 190 +--
.../DescribeDiskStoreFunctionJUnitTest.java | 1773 +++++++-------------
.../functions/ListDiskStoresFunctionJUnitTest.java | 257 +--
.../cli/functions/ListIndexFunctionJUnitTest.java | 421 ++---
.../internal/cli/LuceneIndexCommandsJUnitTest.java | 235 ++-
.../internal/distributed/TopEntriesJUnitTest.java | 60 +-
.../geode/cache/util/AutoBalancerJUnitTest.java | 539 +++---
.../support/LoginHandlerInterceptorJUnitTest.java | 317 ++--
...lizableObjectHttpMessageConverterJUnitTest.java | 137 +-
gradle/dependency-versions.properties | 1 -
gradle/test.gradle | 5 -
22 files changed, 2342 insertions(+), 5209 deletions(-)
diff --git a/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/DiskInitFileJUnitTest.java b/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/DiskInitFileJUnitTest.java
index 0eeca0c..927616d 100644
--- a/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/DiskInitFileJUnitTest.java
+++ b/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/DiskInitFileJUnitTest.java
@@ -14,41 +14,57 @@
*/
package org.apache.geode.internal.cache;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
import java.io.File;
import java.util.Collections;
+import java.util.EnumSet;
+import java.util.concurrent.locks.ReentrantLock;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.apache.geode.Statistics;
import org.apache.geode.StatisticsFactory;
import org.apache.geode.internal.cache.persistence.DiskRegionView;
+import org.apache.geode.internal.cache.persistence.DiskStoreID;
public class DiskInitFileJUnitTest {
-
- private File testDirectory;
- private Mockery context = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
+ private DiskStoreImpl mockedDiskStoreImpl;
+ private DiskRegionView mockDiskRegionView;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
public void setUp() throws Exception {
- testDirectory = temporaryFolder.newFolder("_" + getClass().getSimpleName());
+ File testDirectory = temporaryFolder.newFolder("_" + getClass().getSimpleName());
+
+ // Mock statistics factory for creating directory holders.
+ final StatisticsFactory mockStatisticsFactory = mock(StatisticsFactory.class);
+ when(mockStatisticsFactory.createStatistics(any(), anyString()))
+ .thenReturn(mock(Statistics.class));
+
+ // Mock disk store impl. All we need to do is return this init file directory.
+ mockedDiskStoreImpl = mock(DiskStoreImpl.class);
+ DirectoryHolder holder = new DirectoryHolder(mockStatisticsFactory, testDirectory, 0, 0);
+ when(mockedDiskStoreImpl.getInfoFileDir()).thenReturn(holder);
+ when(mockedDiskStoreImpl.getDiskStoreID()).thenReturn(mock(DiskStoreID.class));
+ when(mockedDiskStoreImpl.getBackupLock()).thenReturn(mock(ReentrantLock.class));
+
+ // Mock required for the init file so it doesn't delete the file when the init file is closed.
+ mockDiskRegionView = spy(DiskRegionView.class);
+ when(mockDiskRegionView.getName()).thenReturn("diskRegionView");
+ when(mockDiskRegionView.getPartitionName()).thenReturn("diskRegionViewPartition");
+ when(mockDiskRegionView.getFlags())
+ .thenReturn(EnumSet.noneOf(DiskInitFile.DiskRegionFlag.class));
}
/**
@@ -56,123 +72,66 @@ public class DiskInitFileJUnitTest {
*/
@Test
public void testCanonicalIds() {
- // create a mock statistics factory for creating directory holders
- final StatisticsFactory sf = context.mock(StatisticsFactory.class);
- context.checking(new Expectations() {
- {
- ignoring(sf);
- }
- });
-
- // Create a mock disk store impl. All we need to do is return
- // this init file directory.
- final DiskStoreImpl parent = context.mock(DiskStoreImpl.class);
- context.checking(new Expectations() {
- {
- allowing(parent).getInfoFileDir();
- will(returnValue(new DirectoryHolder(sf, testDirectory, 0, 0)));
- ignoring(parent);
- }
- });
-
- // Create an init file and add some canonical ids
- DiskInitFile dif = new DiskInitFile("testFile", parent, false, Collections.<File>emptySet());
- assertEquals(null, dif.getCanonicalObject(5));
- assertNull(dif.getCanonicalObject(0));
+ // Create an init file and add some canonical ids.
+ DiskInitFile dif =
+ new DiskInitFile("testFile", mockedDiskStoreImpl, false, Collections.emptySet());
+ assertThat(dif.getCanonicalObject(5)).isNull();
+ assertThat(dif.getCanonicalObject(0)).isNull();
int id1 = dif.getOrCreateCanonicalId("object1");
int id2 = dif.getOrCreateCanonicalId("object2");
+ assertThat(dif.getCanonicalObject(id1)).isEqualTo("object1");
+ assertThat(dif.getCanonicalObject(id2)).isEqualTo("object2");
+ assertThat(dif.getOrCreateCanonicalId("object2")).isEqualTo(id2);
+ dif.createRegion(mockDiskRegionView);
- assertEquals("object1", dif.getCanonicalObject(id1));
- assertEquals("object2", dif.getCanonicalObject(id2));
- assertEquals(id2, dif.getOrCreateCanonicalId("object2"));
-
-
- // Add a mock region to the init file so it doesn't
- // delete the file when the init file is closed
- final DiskRegionView drv = context.mock(DiskRegionView.class);
- context.checking(new Expectations() {
- {
- ignoring(drv);
- }
- });
- dif.createRegion(drv);
-
- // close the init file
+ // Close the init file and recover the init file from disk
dif.close();
+ dif = new DiskInitFile("testFile", mockedDiskStoreImpl, true, Collections.emptySet());
- // recover the init file from disk
- dif = new DiskInitFile("testFile", parent, true, Collections.<File>emptySet());
-
- // make sure we can recover the ids from disk
- assertEquals("object1", dif.getCanonicalObject(id1));
- assertEquals("object2", dif.getCanonicalObject(id2));
- assertEquals(id2, dif.getOrCreateCanonicalId("object2"));
+ // Make sure we can recover the ids from disk
+ assertThat(dif.getCanonicalObject(id1)).isEqualTo("object1");
+ assertThat(dif.getCanonicalObject(id2)).isEqualTo("object2");
+ assertThat(dif.getOrCreateCanonicalId("object2")).isEqualTo(id2);
// Make sure we can add new ids
int id3 = dif.getOrCreateCanonicalId("object3");
- assertTrue(id3 > id2);
- assertEquals("object1", dif.getCanonicalObject(id1));
- assertEquals("object2", dif.getCanonicalObject(id2));
- assertEquals("object3", dif.getCanonicalObject(id3));
+ assertThat(id3).isGreaterThan(id2);
+ assertThat(dif.getCanonicalObject(id1)).isEqualTo("object1");
+ assertThat(dif.getCanonicalObject(id2)).isEqualTo("object2");
+ assertThat(dif.getCanonicalObject(id3)).isEqualTo("object3");
dif.close();
}
@Test
public void testKrfIds() {
- // create a mock statistics factory for creating directory holders
- final StatisticsFactory sf = context.mock(StatisticsFactory.class);
- context.checking(new Expectations() {
- {
- ignoring(sf);
- }
- });
- // Add a mock region to the init file so it doesn't
- // delete the file when the init file is closed
- final DiskRegionView drv = context.mock(DiskRegionView.class);
- context.checking(new Expectations() {
- {
- ignoring(drv);
- }
- });
- // Create a mock disk store impl. All we need to do is return
- // this init file directory.
- final DiskStoreImpl parent = context.mock(DiskStoreImpl.class);
- context.checking(new Expectations() {
- {
- allowing(parent).getInfoFileDir();
- will(returnValue(new DirectoryHolder(sf, testDirectory, 0, 0)));
- ignoring(parent);
- }
- });
-
- DiskInitFile dif = new DiskInitFile("testKrfIds", parent, false, Collections.<File>emptySet());
- assertEquals(false, dif.hasKrf(1));
+ DiskInitFile dif =
+ new DiskInitFile("testKrfIds", mockedDiskStoreImpl, false, Collections.emptySet());
+ assertThat(dif.hasKrf(1)).isFalse();
dif.cmnKrfCreate(1);
- assertEquals(true, dif.hasKrf(1));
- assertEquals(false, dif.hasKrf(2));
+ assertThat(dif.hasKrf(1)).isTrue();
+ assertThat(dif.hasKrf(2)).isFalse();
dif.cmnKrfCreate(2);
- assertEquals(true, dif.hasKrf(2));
- dif.createRegion(drv);
+ assertThat(dif.hasKrf(2)).isTrue();
+ dif.createRegion(mockDiskRegionView);
dif.forceCompaction();
dif.close();
- dif = new DiskInitFile("testKrfIds", parent, true, Collections.<File>emptySet());
- assertEquals(true, dif.hasKrf(1));
- assertEquals(true, dif.hasKrf(2));
+ dif = new DiskInitFile("testKrfIds", mockedDiskStoreImpl, true, Collections.emptySet());
+ assertThat(dif.hasKrf(1)).isTrue();
+ assertThat(dif.hasKrf(2)).isTrue();
dif.cmnCrfDelete(1);
- assertEquals(false, dif.hasKrf(1));
- assertEquals(true, dif.hasKrf(2));
+ assertThat(dif.hasKrf(1)).isFalse();
+ assertThat(dif.hasKrf(2)).isTrue();
dif.cmnCrfDelete(2);
- assertEquals(false, dif.hasKrf(2));
- dif.createRegion(drv);
+ assertThat(dif.hasKrf(2)).isFalse();
+ dif.createRegion(mockDiskRegionView);
dif.forceCompaction();
dif.close();
- dif = new DiskInitFile("testKrfIds", parent, true, Collections.<File>emptySet());
- assertEquals(false, dif.hasKrf(1));
- assertEquals(false, dif.hasKrf(2));
+ dif = new DiskInitFile("testKrfIds", mockedDiskStoreImpl, true, Collections.emptySet());
+ assertThat(dif.hasKrf(1)).isFalse();
+ assertThat(dif.hasKrf(2)).isFalse();
dif.destroy();
}
-
}
diff --git a/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/OplogRVVJUnitTest.java b/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/OplogRVVJUnitTest.java
index c3f3cd3..1d6baaf 100644
--- a/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/OplogRVVJUnitTest.java
+++ b/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/OplogRVVJUnitTest.java
@@ -14,29 +14,32 @@
*/
package org.apache.geode.internal.cache;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import java.io.File;
-import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.io.FileUtils;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.apache.geode.CancelCriterion;
+import org.apache.geode.Statistics;
import org.apache.geode.StatisticsFactory;
-import org.apache.geode.i18n.LogWriterI18n;
import org.apache.geode.internal.cache.DiskInitFile.DiskRegionFlag;
import org.apache.geode.internal.cache.DiskStoreImpl.OplogEntryIdSet;
import org.apache.geode.internal.cache.persistence.DiskRecoveryStore;
@@ -44,14 +47,7 @@ import org.apache.geode.internal.cache.persistence.DiskStoreID;
import org.apache.geode.internal.cache.versions.DiskRegionVersionVector;
public class OplogRVVJUnitTest {
-
private File testDirectory;
- private Mockery context = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@@ -68,59 +64,37 @@ public class OplogRVVJUnitTest {
}
@Test
- public void testRecoverRVV() throws UnknownHostException {
- final DiskInitFile df = context.mock(DiskInitFile.class);
- final LogWriterI18n logger = context.mock(LogWriterI18n.class);
- final GemFireCacheImpl cache = context.mock(GemFireCacheImpl.class);
+ public void testRecoverRVV() {
+ final DiskInitFile df = mock(DiskInitFile.class);
+ final GemFireCacheImpl cache = mock(GemFireCacheImpl.class);
+
// Create a mock disk store impl.
- final DiskStoreImpl parent = context.mock(DiskStoreImpl.class);
- final StatisticsFactory sf = context.mock(StatisticsFactory.class);
+ final DiskStoreImpl parent = mock(DiskStoreImpl.class);
+ final StatisticsFactory sf = mock(StatisticsFactory.class);
final DiskStoreID ownerId = DiskStoreID.random();
final DiskStoreID m1 = DiskStoreID.random();
final DiskStoreID m2 = DiskStoreID.random();
- final DiskRecoveryStore drs = context.mock(DiskRecoveryStore.class);
+ final DiskRecoveryStore drs = mock(DiskRecoveryStore.class);
+ when(df.getOrCreateCanonicalId(m1)).thenReturn(1);
+ when(df.getOrCreateCanonicalId(m2)).thenReturn(2);
+ when(df.getOrCreateCanonicalId(ownerId)).thenReturn(3);
+ when(df.getCanonicalObject(1)).thenReturn(m1);
+ when(df.getCanonicalObject(2)).thenReturn(m2);
+ when(df.getCanonicalObject(3)).thenReturn(ownerId);
+ when(sf.createStatistics(any(), anyString())).thenReturn(mock(Statistics.class));
+ when(sf.createAtomicStatistics(any(), anyString())).thenReturn(mock(Statistics.class));
- context.checking(new Expectations() {
- {
- ignoring(sf);
- allowing(df).getOrCreateCanonicalId(m1);
- will(returnValue(1));
- allowing(df).getOrCreateCanonicalId(m2);
- will(returnValue(2));
- allowing(df).getOrCreateCanonicalId(ownerId);
- will(returnValue(3));
- allowing(df).getCanonicalObject(1);
- will(returnValue(m1));
- allowing(df).getCanonicalObject(2);
- will(returnValue(m2));
- allowing(df).getCanonicalObject(3);
- will(returnValue(ownerId));
- ignoring(df);
- }
- });
DirectoryHolder dirHolder = new DirectoryHolder(sf, testDirectory, 0, 0);
-
- context.checking(new Expectations() {
- {
- ignoring(logger);
- allowing(cache).getLoggerI18n();
- will(returnValue(logger));
- allowing(cache).cacheTimeMillis();
- will(returnValue(System.currentTimeMillis()));
- allowing(parent).getCache();
- will(returnValue(cache));
- allowing(parent).getMaxOplogSizeInBytes();
- will(returnValue(10000L));
- allowing(parent).getName();
- will(returnValue("test"));
- allowing(parent).getStats();
- will(returnValue(new DiskStoreStats(sf, "stats")));
- allowing(parent).getDiskInitFile();
- will(returnValue(df));
- allowing(parent).getDiskStoreID();
- will(returnValue(DiskStoreID.random()));
- }
- });
+ when(cache.cacheTimeMillis()).thenReturn(System.currentTimeMillis());
+ when(parent.getCache()).thenReturn(cache);
+ when(parent.getMaxOplogSizeInBytes()).thenReturn(10000L);
+ when(parent.getName()).thenReturn("test");
+ DiskStoreStats diskStoreStats = new DiskStoreStats(sf, "stats");
+ when(parent.getStats()).thenReturn(diskStoreStats);
+ when(parent.getDiskInitFile()).thenReturn(df);
+ when(parent.getDiskStoreID()).thenReturn(DiskStoreID.random());
+ when(parent.getBackupLock()).thenReturn(mock(ReentrantLock.class));
+ when(parent.getCancelCriterion()).thenReturn(mock(CancelCriterion.class));
final DiskRegionVersionVector rvv = new DiskRegionVersionVector(ownerId);
rvv.recordVersion(m1, 0);
@@ -135,57 +109,36 @@ public class OplogRVVJUnitTest {
rvv.recordGCVersion(m2, 0);
// create the oplog
-
- final AbstractDiskRegion diskRegion = context.mock(AbstractDiskRegion.class);
- final PersistentOplogSet oplogSet = context.mock(PersistentOplogSet.class);
- final Map<Long, AbstractDiskRegion> map = new HashMap<Long, AbstractDiskRegion>();
+ final AbstractDiskRegion diskRegion = mock(AbstractDiskRegion.class);
+ final PersistentOplogSet oplogSet = mock(PersistentOplogSet.class);
+ final Map<Long, AbstractDiskRegion> map = new HashMap<>();
map.put(5L, diskRegion);
- context.checking(new Expectations() {
- {
- allowing(diskRegion).getRegionVersionVector();
- will(returnValue(rvv));
- allowing(diskRegion).getRVVTrusted();
- will(returnValue(true));
- allowing(parent).getAllDiskRegions();
- will(returnValue(map));
- allowing(oplogSet).getCurrentlyRecovering(5L);
- will(returnValue(drs));
- allowing(oplogSet).getParent();
- will(returnValue(parent));
- ignoring(oplogSet);
- ignoring(parent);
- allowing(diskRegion).getFlags();
- will(returnValue(EnumSet.of(DiskRegionFlag.IS_WITH_VERSIONING)));
- }
- });
-
- Map<Long, AbstractDiskRegion> regions = parent.getAllDiskRegions();
+ when(diskRegion.getRegionVersionVector()).thenReturn(rvv);
+ when(diskRegion.getRVVTrusted()).thenReturn(true);
+ when(parent.getAllDiskRegions()).thenReturn(map);
+ when(oplogSet.getCurrentlyRecovering(5L)).thenReturn(drs);
+ when(oplogSet.getParent()).thenReturn(parent);
+ when(diskRegion.getFlags()).thenReturn(EnumSet.of(DiskRegionFlag.IS_WITH_VERSIONING));
Oplog oplog = new Oplog(1, oplogSet, dirHolder);
oplog.close();
- context.checking(new Expectations() {
- {
- one(drs).recordRecoveredGCVersion(m1, 1);
- one(drs).recordRecoveredGCVersion(m2, 0);
- one(drs).recordRecoveredVersonHolder(ownerId, rvv.getMemberToVersion().get(ownerId), true);
- one(drs).recordRecoveredVersonHolder(m1, rvv.getMemberToVersion().get(m1), true);
- one(drs).recordRecoveredVersonHolder(m2, rvv.getMemberToVersion().get(m2), true);
- one(drs).setRVVTrusted(true);
- }
- });
-
oplog = new Oplog(1, oplogSet);
Collection<File> drfFiles = FileUtils.listFiles(testDirectory, new String[] {"drf"}, true);
- assertEquals(1, drfFiles.size());
+ assertThat(drfFiles.size()).isEqualTo(1);
Collection<File> crfFiles = FileUtils.listFiles(testDirectory, new String[] {"crf"}, true);
- assertEquals(1, crfFiles.size());
+ assertThat(crfFiles.size()).isEqualTo(1);
oplog.addRecoveredFile(drfFiles.iterator().next(), dirHolder);
oplog.addRecoveredFile(crfFiles.iterator().next(), dirHolder);
OplogEntryIdSet deletedIds = new OplogEntryIdSet();
oplog.recoverDrf(deletedIds, false, true);
oplog.recoverCrf(deletedIds, true, true, false, Collections.singleton(oplog), true);
- context.assertIsSatisfied();
+ verify(drs, times(1)).recordRecoveredGCVersion(m1, 1);
+ verify(drs, times(1)).recordRecoveredGCVersion(m2, 0);
+ verify(drs, times(1)).recordRecoveredVersonHolder(ownerId,
+ rvv.getMemberToVersion().get(ownerId), true);
+ verify(drs, times(1)).recordRecoveredVersonHolder(m1, rvv.getMemberToVersion().get(m1), true);
+ verify(drs, times(1)).recordRecoveredVersonHolder(m2, rvv.getMemberToVersion().get(m2), true);
+ verify(drs, times(1)).setRVVTrusted(true);
}
-
}
diff --git a/geode-core/src/integrationTest/java/org/apache/geode/internal/statistics/LinuxSystemStatsTest.java b/geode-core/src/integrationTest/java/org/apache/geode/internal/statistics/LinuxSystemStatsTest.java
index 21b29ca..62bdc84 100644
--- a/geode-core/src/integrationTest/java/org/apache/geode/internal/statistics/LinuxSystemStatsTest.java
+++ b/geode-core/src/integrationTest/java/org/apache/geode/internal/statistics/LinuxSystemStatsTest.java
@@ -14,18 +14,17 @@
*/
package org.apache.geode.internal.statistics;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
+import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
-import org.apache.commons.io.IOUtils;
-import org.apache.tools.ant.filters.StringInputStream;
+import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
@@ -47,11 +46,12 @@ import org.apache.geode.internal.statistics.platform.LinuxProcFsStatistics;
import org.apache.geode.internal.statistics.platform.LinuxSystemStats;
import org.apache.geode.test.junit.categories.StatisticsTest;
+
/**
* Technically a linux only test - the file handling is all mocked up so the test can run on any
* host os.
*/
-@Category({StatisticsTest.class})
+@Category(StatisticsTest.class)
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("*.IntegrationTest")
@PrepareForTest(LinuxProcFsStatistics.class)
@@ -67,13 +67,12 @@ public class LinuxSystemStatsTest extends StatSamplerTestCase {
private long[] longs;
private double[] doubles;
private LocalStatisticsFactory statisticsFactory;
- private File testDir;
@Before
public void setUp() throws Exception {
- this.testDir = this.temporaryFolder.getRoot();
- assertTrue(this.testDir.exists());
- System.setProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY, this.testDir.getAbsolutePath()
+ File testDir = this.temporaryFolder.getRoot();
+ assertThat(testDir.exists()).isTrue();
+ System.setProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY, testDir.getAbsolutePath()
+ File.separator + SimpleStatSampler.DEFAULT_ARCHIVE_FILE_NAME);
LinuxProcFsStatistics.init();
initStats();
@@ -162,10 +161,8 @@ public class LinuxSystemStatsTest extends StatSamplerTestCase {
*/
private File writeStringToFile(String mockProcStatFileContents) throws IOException {
File mockFile = temporaryFolder.newFile();
- StringInputStream sis = new StringInputStream(mockProcStatFileContents);
- FileOutputStream mockFileOutputStream = new FileOutputStream(mockFile);
- IOUtils.copy(sis, mockFileOutputStream);
- IOUtils.closeQuietly(mockFileOutputStream);
+ FileUtils.writeStringToFile(mockFile, mockProcStatFileContents, (Charset) null);
+
return mockFile;
}
diff --git a/geode-core/src/integrationTest/java/org/apache/geode/internal/statistics/ValueMonitorIntegrationTest.java b/geode-core/src/integrationTest/java/org/apache/geode/internal/statistics/ValueMonitorIntegrationTest.java
index 43392b5..489cd53 100755
--- a/geode-core/src/integrationTest/java/org/apache/geode/internal/statistics/ValueMonitorIntegrationTest.java
+++ b/geode-core/src/integrationTest/java/org/apache/geode/internal/statistics/ValueMonitorIntegrationTest.java
@@ -14,10 +14,9 @@
*/
package org.apache.geode.internal.statistics;
-import static org.apache.geode.test.dunit.Wait.waitForCriterion;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import java.io.File;
import java.util.ArrayList;
@@ -25,12 +24,9 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.TimeUnit;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
+import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -43,7 +39,6 @@ import org.apache.geode.StatisticsType;
import org.apache.geode.internal.NanoTimer;
import org.apache.geode.internal.io.MainWithChildrenRollingFileHandler;
import org.apache.geode.internal.statistics.StatisticsNotification.Type;
-import org.apache.geode.test.dunit.WaitCriterion;
import org.apache.geode.test.junit.categories.StatisticsTest;
/**
@@ -51,82 +46,81 @@ import org.apache.geode.test.junit.categories.StatisticsTest;
*
* @since GemFire 7.0
*/
-@Category({StatisticsTest.class})
+@Category(StatisticsTest.class)
public class ValueMonitorIntegrationTest {
-
- private Mockery mockContext;
+ private StatArchiveHandlerConfig mockStatArchiveHandlerConfig;
@Rule
public TestName testName = new TestName();
@Before
- public void setUp() throws Exception {
- this.mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
+ public void setUp() {
+ mockStatArchiveHandlerConfig = mock(StatArchiveHandlerConfig.class,
+ testName.getMethodName() + "$StatArchiveHandlerConfig");
+ when(mockStatArchiveHandlerConfig.getArchiveFileName()).thenReturn(new File(""));
+ when(mockStatArchiveHandlerConfig.getArchiveFileSizeLimit()).thenReturn(0L);
+ when(mockStatArchiveHandlerConfig.getArchiveDiskSpaceLimit()).thenReturn(0L);
+ when(mockStatArchiveHandlerConfig.getSystemId()).thenReturn(1L);
+ when(mockStatArchiveHandlerConfig.getSystemDirectoryPath()).thenReturn("");
+ when(mockStatArchiveHandlerConfig.getProductDescription()).thenReturn("Geode");
}
- @After
- public void tearDown() throws Exception {
- this.mockContext.assertIsSatisfied();
- this.mockContext = null;
+ private StatisticsNotification createStatisticsNotification(final long timeStamp, final Type type,
+ final Number value) {
+ return new StatisticsNotification() {
+
+ @Override
+ public long getTimeStamp() {
+ return timeStamp;
+ }
+
+ @Override
+ public Type getType() {
+ return type;
+ }
+
+ @Override
+ public Iterator<StatisticId> iterator() {
+ return null;
+ }
+
+ @Override
+ public Iterator<StatisticId> iterator(final StatisticDescriptor statDesc) {
+ return null;
+ }
+
+ @Override
+ public Iterator<StatisticId> iterator(final Statistics statistics) {
+ return null;
+ }
+
+ @Override
+ public Iterator<StatisticId> iterator(final StatisticsType statisticsType) {
+ return null;
+ }
+
+ @Override
+ public Number getValue(final StatisticId statId) {
+ return value;
+ }
+ };
}
@Test
public void testAddRemoveListener() throws Exception {
long startTime = System.currentTimeMillis();
- List<Statistics> statsList = new ArrayList<Statistics>();
- StatisticsManager mockStatisticsManager = this.mockContext.mock(StatisticsManager.class,
- testName.getMethodName() + "$StatisticsManager");
- this.mockContext.checking(new Expectations() {
- {
- allowing(mockStatisticsManager).getName();
- will(returnValue("mockStatisticsManager"));
- allowing(mockStatisticsManager).getId();
- will(returnValue(1));
- allowing(mockStatisticsManager).getStartTime();
- will(returnValue(startTime));
- allowing(mockStatisticsManager).getStatListModCount();
- will(returnValue(0));
- allowing(mockStatisticsManager).getStatsList();
- will(returnValue(statsList));
- }
- });
-
- StatisticsSampler mockStatisticsSampler = this.mockContext.mock(StatisticsSampler.class,
- testName.getMethodName() + "$StatisticsSampler");
- this.mockContext.checking(new Expectations() {
- {
- allowing(mockStatisticsSampler).getStatisticsModCount();
- will(returnValue(0));
- allowing(mockStatisticsSampler).getStatistics();
- will(returnValue(new Statistics[] {}));
- }
- });
-
- StatArchiveHandlerConfig mockStatArchiveHandlerConfig = this.mockContext.mock(
- StatArchiveHandlerConfig.class, testName.getMethodName() + "$StatArchiveHandlerConfig");
- this.mockContext.checking(new Expectations() {
- {
- allowing(mockStatArchiveHandlerConfig).getArchiveFileName();
- will(returnValue(new File("")));
- allowing(mockStatArchiveHandlerConfig).getArchiveFileSizeLimit();
- will(returnValue(0));
- allowing(mockStatArchiveHandlerConfig).getArchiveDiskSpaceLimit();
- will(returnValue(0));
- allowing(mockStatArchiveHandlerConfig).getSystemId();
- will(returnValue(1));
- allowing(mockStatArchiveHandlerConfig).getSystemStartTime();
- will(returnValue(startTime));
- allowing(mockStatArchiveHandlerConfig).getSystemDirectoryPath();
- will(returnValue(""));
- allowing(mockStatArchiveHandlerConfig).getProductDescription();
- will(returnValue("testAddRemoveListener"));
- }
- });
+ StatisticsManager mockStatisticsManager =
+ mock(StatisticsManager.class, testName.getMethodName() + "$StatisticsManager");
+ when(mockStatisticsManager.getName()).thenReturn("mockStatisticsManager");
+ when(mockStatisticsManager.getId()).thenReturn(1L);
+ when(mockStatisticsManager.getStartTime()).thenReturn(startTime);
+ when(mockStatisticsManager.getStatListModCount()).thenReturn(0);
+ when(mockStatisticsManager.getStatsList()).thenReturn(new ArrayList<>());
+
+ StatisticsSampler mockStatisticsSampler =
+ mock(StatisticsSampler.class, testName.getMethodName() + "$StatisticsSampler");
+ when(mockStatisticsSampler.getStatisticsModCount()).thenReturn(0);
+ when(mockStatisticsSampler.getStatistics()).thenReturn(new Statistics[] {});
// need a real SampleCollector for this test or the monitor can't get the handler
SampleCollector sampleCollector = new SampleCollector(mockStatisticsSampler);
@@ -134,36 +128,42 @@ public class ValueMonitorIntegrationTest {
new MainWithChildrenRollingFileHandler());
List<StatisticsNotification> notifications = new ArrayList<>();
- StatisticsListener listener = (final StatisticsNotification notification) -> {
- notifications.add(notification);
- };
- ValueMonitor monitor = new ValueMonitor();
+ StatisticsListener listener = notifications::add;
- long timeStamp = System.currentTimeMillis();
- Type type = Type.VALUE_CHANGED;
+ ValueMonitor monitor = new ValueMonitor();
Number value = 43;
-
+ Type type = Type.VALUE_CHANGED;
+ long timeStamp = System.currentTimeMillis();
StatisticsNotification notification = createStatisticsNotification(timeStamp, type, value);
monitor.notifyListeners(notification);
-
- assertTrue(notifications.isEmpty());
+ assertThat(notifications.isEmpty()).isTrue();
monitor.addListener(listener);
monitor.notifyListeners(notification);
-
- assertEquals(1, notifications.size());
+ assertThat(notifications.size()).isEqualTo(1);
notification = notifications.remove(0);
- assertNotNull(notification);
-
- assertEquals(timeStamp, notification.getTimeStamp());
- assertEquals(type, notification.getType());
- StatisticId statId = createStatisticId(null, null);
- assertEquals(value, notification.getValue(statId));
+ assertThat(notification).isNotNull();
+ assertThat(notification.getTimeStamp()).isEqualTo(timeStamp);
+ assertThat(notification.getType()).isEqualTo(type);
+ StatisticId statId = mock(StatisticId.class);
+ assertThat(notification.getValue(statId)).isEqualTo(value);
monitor.removeListener(listener);
monitor.notifyListeners(notification);
+ assertThat(notifications.isEmpty()).isTrue();
+ }
+
+ private int assertStatisticsNotification(StatisticsNotification notification,
+ Map<String, Number> expectedValues) throws StatisticNotFoundException {
+ int statCount = 0;
+ for (StatisticId statId : notification) {
+ Number value = expectedValues.remove(statId.getStatisticDescriptor().getName());
+ assertThat(value).isNotNull();
+ assertThat(notification.getValue(statId)).isEqualTo(value);
+ statCount++;
+ }
- assertTrue(notifications.isEmpty());
+ return statCount;
}
@Test
@@ -172,28 +172,6 @@ public class ValueMonitorIntegrationTest {
TestStatisticsManager manager =
new TestStatisticsManager(1, "ValueMonitorIntegrationTest", startTime);
StatisticsSampler sampler = new TestStatisticsSampler(manager);
-
- StatArchiveHandlerConfig mockStatArchiveHandlerConfig = this.mockContext.mock(
- StatArchiveHandlerConfig.class, testName.getMethodName() + "$StatArchiveHandlerConfig");
- this.mockContext.checking(new Expectations() {
- {
- allowing(mockStatArchiveHandlerConfig).getArchiveFileName();
- will(returnValue(new File("")));
- allowing(mockStatArchiveHandlerConfig).getArchiveFileSizeLimit();
- will(returnValue(0));
- allowing(mockStatArchiveHandlerConfig).getArchiveDiskSpaceLimit();
- will(returnValue(0));
- allowing(mockStatArchiveHandlerConfig).getSystemId();
- will(returnValue(1));
- allowing(mockStatArchiveHandlerConfig).getSystemStartTime();
- will(returnValue(startTime));
- allowing(mockStatArchiveHandlerConfig).getSystemDirectoryPath();
- will(returnValue(""));
- allowing(mockStatArchiveHandlerConfig).getProductDescription();
- will(returnValue("testFoo"));
- }
- });
-
SampleCollector sampleCollector = new SampleCollector(sampler);
sampleCollector.initialize(mockStatArchiveHandlerConfig, NanoTimer.getTime(),
new MainWithChildrenRollingFileHandler());
@@ -204,188 +182,83 @@ public class ValueMonitorIntegrationTest {
manager.createIntCounter("int_counter_2", "int_counter_2_desc", "int_counter_2_units"),
manager.createLongCounter("long_counter_3", "long_counter_3_desc", "long_counter_3_units")};
StatisticsType ST1 = manager.createType("ST1_name", "ST1_desc", statsST1);
- Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1_text", 1);
- Statistics st1_2 = manager.createAtomicStatistics(ST1, "st1_2_text", 2);
+ Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1_text", 1);
st1_1.incDouble("double_counter_1", 1000.0001);
st1_1.incInt("int_counter_2", 2);
st1_1.incLong("long_counter_3", 3333333333L);
+ Statistics st1_2 = manager.createAtomicStatistics(ST1, "st1_2_text", 2);
st1_2.incDouble("double_counter_1", 2000.0002);
st1_2.incInt("int_counter_2", 3);
st1_2.incLong("long_counter_3", 4444444444L);
List<StatisticsNotification> notifications = new ArrayList<>();
- StatisticsListener listener = (final StatisticsNotification notification) -> {
- notifications.add(notification);
- };
+ StatisticsListener listener = notifications::add;
+
ValueMonitor monitor = new ValueMonitor().addStatistics(st1_1);
monitor.addListener(listener);
-
- assertTrue("Unexpected notifications: " + notifications, notifications.isEmpty());
+ assertThat(notifications.isEmpty()).isTrue();
long timeStamp = NanoTimer.getTime();
sampleCollector.sample(timeStamp);
-
- awaitAtLeastTimeoutOrUntilNotifications(notifications, 2 * 1000);
- assertEquals("Unexpected notifications: " + notifications, 1, notifications.size());
+ Awaitility.await().atMost(2, TimeUnit.SECONDS).pollInterval(10, TimeUnit.MILLISECONDS)
+ .until(() -> notifications.size() > 0);
+ assertThat(notifications.size()).isEqualTo(1);
StatisticsNotification notification = notifications.remove(0);
- assertEquals(StatisticsNotification.Type.VALUE_CHANGED, notification.getType());
+ assertThat(notification.getType()).isEqualTo(StatisticsNotification.Type.VALUE_CHANGED);
// validate 1 notification occurs with all 3 stats of st1_1
-
st1_1.incDouble("double_counter_1", 1.1);
st1_1.incInt("int_counter_2", 2);
st1_1.incLong("long_counter_3", 3);
-
timeStamp += NanoTimer.millisToNanos(1000);
sampleCollector.sample(timeStamp);
-
- awaitAtLeastTimeoutOrUntilNotifications(notifications, 2 * 1000);
- assertEquals("Unexpected notifications: " + notifications, 1, notifications.size());
-
+ Awaitility.await().atMost(2, TimeUnit.SECONDS).pollInterval(10, TimeUnit.MILLISECONDS)
+ .until(() -> notifications.size() > 0);
+ assertThat(notifications.size()).isEqualTo(1);
notification = notifications.remove(0);
- assertEquals(StatisticsNotification.Type.VALUE_CHANGED, notification.getType());
+ assertThat(notification.getType()).isEqualTo(StatisticsNotification.Type.VALUE_CHANGED);
- int statCount = 0;
Map<String, Number> expectedValues = new HashMap<>();
expectedValues.put("double_counter_1", 1001.1001);
expectedValues.put("int_counter_2", 4);
expectedValues.put("long_counter_3", 3333333336L);
-
- for (StatisticId statId : notification) {
- Number value = expectedValues.remove(statId.getStatisticDescriptor().getName());
- assertNotNull(value);
- assertEquals(value, notification.getValue(statId));
- statCount++;
- }
- assertEquals(3, statCount);
+ int statCount = assertStatisticsNotification(notification, expectedValues);
+ assertThat(statCount).isEqualTo(3);
// validate no notification occurs when no stats are updated
-
timeStamp += NanoTimer.millisToNanos(1000);
sampleCollector.sample(timeStamp);
-
- awaitAtLeastTimeoutOrUntilNotifications(notifications, 2 * 1000);
- assertTrue("Unexpected notifications: " + notifications, notifications.isEmpty());
+ Awaitility.await().atMost(2, TimeUnit.SECONDS).pollInterval(10, TimeUnit.MILLISECONDS)
+ .until(() -> notifications.size() == 0);
+ assertThat(notifications.isEmpty()).isTrue();
// validate no notification occurs when only other stats are updated
-
st1_2.incDouble("double_counter_1", 3.3);
st1_2.incInt("int_counter_2", 1);
st1_2.incLong("long_counter_3", 2);
-
timeStamp += NanoTimer.millisToNanos(1000);
sampleCollector.sample(timeStamp);
-
- awaitAtLeastTimeoutOrUntilNotifications(notifications, 2 * 1000);
- assertTrue("Unexpected notifications: " + notifications, notifications.isEmpty());
+ Awaitility.await().atMost(2, TimeUnit.SECONDS).pollInterval(10, TimeUnit.MILLISECONDS)
+ .until(() -> notifications.size() == 0);
+ assertThat(notifications.isEmpty()).isTrue();
// validate notification only contains stats added to monitor
-
st1_1.incInt("int_counter_2", 100);
st1_2.incInt("int_counter_2", 200);
-
- assertEquals(2, sampleCollector.currentHandlersForTesting().size());
-
+ assertThat(sampleCollector.currentHandlersForTesting().size()).isEqualTo(2);
timeStamp += NanoTimer.millisToNanos(1000);
sampleCollector.sample(timeStamp);
-
- awaitAtLeastTimeoutOrUntilNotifications(notifications, 2 * 1000);
- assertEquals("Unexpected notifications: " + notifications, 1, notifications.size());
-
+ Awaitility.await().atMost(2, TimeUnit.SECONDS).pollInterval(10, TimeUnit.MILLISECONDS)
+ .until(() -> notifications.size() > 0);
+ assertThat(notifications.size()).isEqualTo(1);
notification = notifications.remove(0);
- assertEquals(StatisticsNotification.Type.VALUE_CHANGED, notification.getType());
-
- statCount = 0;
+ assertThat(notification.getType()).isEqualTo(StatisticsNotification.Type.VALUE_CHANGED);
expectedValues = new HashMap<>();
expectedValues.put("int_counter_2", 104);
-
- for (StatisticId statId : notification) {
- Number value = expectedValues.remove(statId.getStatisticDescriptor().getName());
- assertNotNull(value);
- assertEquals(value, notification.getValue(statId));
- statCount++;
- }
- assertEquals(1, statCount);
- }
-
- private StatisticId createStatisticId(final StatisticDescriptor descriptor,
- final Statistics stats) {
- return new StatisticId() {
-
- @Override
- public StatisticDescriptor getStatisticDescriptor() {
- return descriptor;
- }
-
- @Override
- public Statistics getStatistics() {
- return stats;
- }
- };
- }
-
- protected StatisticsNotification createStatisticsNotification(final long timeStamp,
- final Type type, final Number value) {
- return new StatisticsNotification() {
-
- @Override
- public long getTimeStamp() {
- return timeStamp;
- }
-
- @Override
- public Type getType() {
- return type;
- }
-
- @Override
- public Iterator<StatisticId> iterator() {
- return null;
- }
-
- @Override
- public Iterator<StatisticId> iterator(final StatisticDescriptor statDesc) {
- return null;
- }
-
- @Override
- public Iterator<StatisticId> iterator(final Statistics statistics) {
- return null;
- }
-
- @Override
- public Iterator<StatisticId> iterator(final StatisticsType statisticsType) {
- return null;
- }
-
- @Override
- public Number getValue(final StatisticId statId) throws StatisticNotFoundException {
- return value;
- }
- };
- }
-
- /**
- * Wait for at least the specified time or until notifications is >0.
- */
- private static void awaitAtLeastTimeoutOrUntilNotifications(
- final List<StatisticsNotification> notifications, final long timeoutMillis) {
- long pollingIntervalMillis = 10;
- boolean throwOnTimeout = false;
- WaitCriterion wc = new WaitCriterion() {
- @Override
- public boolean done() {
- return notifications.size() > 0;
- }
-
- @Override
- public String description() {
- return "waiting for notification";
- }
- };
- waitForCriterion(wc, timeoutMillis, pollingIntervalMillis, throwOnTimeout);
+ statCount = assertStatisticsNotification(notification, expectedValues);
+ assertThat(statCount).isEqualTo(1);
}
}
diff --git a/geode-core/src/test/java/org/apache/geode/cache/query/internal/CompiledAggregateFunctionJUnitTest.java b/geode-core/src/test/java/org/apache/geode/cache/query/internal/CompiledAggregateFunctionJUnitTest.java
index 1b337bd..0025d89 100644
--- a/geode-core/src/test/java/org/apache/geode/cache/query/internal/CompiledAggregateFunctionJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/cache/query/internal/CompiledAggregateFunctionJUnitTest.java
@@ -14,16 +14,13 @@
*/
package org.apache.geode.cache.query.internal;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
import java.lang.reflect.Field;
-import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Before;
import org.junit.Test;
@@ -46,125 +43,116 @@ import org.apache.geode.cache.query.internal.parse.OQLLexerTokenTypes;
import org.apache.geode.internal.cache.InternalCache;
public class CompiledAggregateFunctionJUnitTest {
-
- private Mockery context;
private InternalCache cache;
- private List bucketList;
+ private List<Integer> bucketList;
@Before
public void setUp() throws Exception {
- context = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
- cache = context.mock(InternalCache.class);
- bucketList = new ArrayList();
- bucketList.add(1);
+ cache = mock(InternalCache.class);
+ bucketList = Collections.singletonList(1);
}
@Test
public void testCount() throws Exception {
CompiledAggregateFunction caf1 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.COUNT);
ExecutionContext context1 = new ExecutionContext(null, cache);
- assertTrue(caf1.evaluate(context1) instanceof Count);
+ assertThat(caf1.evaluate(context1)).isInstanceOf(Count.class);
CompiledAggregateFunction caf2 =
new CompiledAggregateFunction(null, OQLLexerTokenTypes.COUNT, true);
ExecutionContext context2 = new ExecutionContext(null, cache);
- assertTrue(caf2.evaluate(context2) instanceof CountDistinct);
+ assertThat(caf2.evaluate(context2)).isInstanceOf(CountDistinct.class);
CompiledAggregateFunction caf3 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.COUNT);
ExecutionContext context3 = new ExecutionContext(null, cache);
context3.setIsPRQueryNode(true);
- assertTrue(caf3.evaluate(context3) instanceof CountPRQueryNode);
+ assertThat(caf3.evaluate(context3)).isInstanceOf(CountPRQueryNode.class);
CompiledAggregateFunction caf4 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.COUNT);
QueryExecutionContext context4 = new QueryExecutionContext(null, cache);
context4.setBucketList(bucketList);
- assertTrue(caf4.evaluate(context4) instanceof Count);
+ assertThat(caf4.evaluate(context4)).isInstanceOf(Count.class);
CompiledAggregateFunction caf5 =
new CompiledAggregateFunction(null, OQLLexerTokenTypes.COUNT, true);
ExecutionContext context5 = new ExecutionContext(null, cache);
context5.setIsPRQueryNode(true);
- assertTrue(caf5.evaluate(context5) instanceof CountDistinctPRQueryNode);
+ assertThat(caf5.evaluate(context5)).isInstanceOf(CountDistinctPRQueryNode.class);
CompiledAggregateFunction caf6 =
new CompiledAggregateFunction(null, OQLLexerTokenTypes.COUNT, true);
QueryExecutionContext context6 = new QueryExecutionContext(null, cache);
context6.setBucketList(bucketList);
- assertTrue(caf6.evaluate(context6) instanceof DistinctAggregator);
+ assertThat(caf6.evaluate(context6)).isInstanceOf(DistinctAggregator.class);
}
@Test
public void testSum() throws Exception {
CompiledAggregateFunction caf1 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.SUM);
ExecutionContext context1 = new ExecutionContext(null, cache);
- assertTrue(caf1.evaluate(context1) instanceof Sum);
+ assertThat(caf1.evaluate(context1)).isInstanceOf(Sum.class);
CompiledAggregateFunction caf2 =
new CompiledAggregateFunction(null, OQLLexerTokenTypes.SUM, true);
ExecutionContext context2 = new ExecutionContext(null, cache);
- assertTrue(caf2.evaluate(context2) instanceof SumDistinct);
+ assertThat(caf2.evaluate(context2)).isInstanceOf(SumDistinct.class);
CompiledAggregateFunction caf3 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.SUM);
ExecutionContext context3 = new ExecutionContext(null, cache);
context3.setIsPRQueryNode(true);
- assertTrue(caf3.evaluate(context3) instanceof Sum);
+ assertThat(caf3.evaluate(context3)).isInstanceOf(Sum.class);
CompiledAggregateFunction caf4 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.SUM);
QueryExecutionContext context4 = new QueryExecutionContext(null, cache);
context4.setBucketList(bucketList);
- assertTrue(caf4.evaluate(context4) instanceof Sum);
+ assertThat(caf4.evaluate(context4)).isInstanceOf(Sum.class);
CompiledAggregateFunction caf5 =
new CompiledAggregateFunction(null, OQLLexerTokenTypes.SUM, true);
ExecutionContext context5 = new ExecutionContext(null, cache);
context5.setIsPRQueryNode(true);
- assertTrue(caf5.evaluate(context5) instanceof SumDistinctPRQueryNode);
+ assertThat(caf5.evaluate(context5)).isInstanceOf(SumDistinctPRQueryNode.class);
CompiledAggregateFunction caf6 =
new CompiledAggregateFunction(null, OQLLexerTokenTypes.SUM, true);
QueryExecutionContext context6 = new QueryExecutionContext(null, cache);
context6.setBucketList(bucketList);
- assertTrue(caf6.evaluate(context6) instanceof DistinctAggregator);
+ assertThat(caf6.evaluate(context6)).isInstanceOf(DistinctAggregator.class);
}
@Test
public void testAvg() throws Exception {
CompiledAggregateFunction caf1 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.AVG);
ExecutionContext context1 = new ExecutionContext(null, cache);
- assertTrue(caf1.evaluate(context1) instanceof Avg);
+ assertThat(caf1.evaluate(context1)).isInstanceOf(Avg.class);
CompiledAggregateFunction caf2 =
new CompiledAggregateFunction(null, OQLLexerTokenTypes.AVG, true);
ExecutionContext context2 = new ExecutionContext(null, cache);
- assertTrue(caf2.evaluate(context2) instanceof AvgDistinct);
+ assertThat(caf2.evaluate(context2)).isInstanceOf(AvgDistinct.class);
CompiledAggregateFunction caf3 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.AVG);
ExecutionContext context3 = new ExecutionContext(null, cache);
context3.setIsPRQueryNode(true);
- assertTrue(caf3.evaluate(context3) instanceof AvgPRQueryNode);
+ assertThat(caf3.evaluate(context3)).isInstanceOf(AvgPRQueryNode.class);
CompiledAggregateFunction caf4 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.AVG);
QueryExecutionContext context4 = new QueryExecutionContext(null, cache);
context4.setBucketList(this.bucketList);
- assertTrue(caf4.evaluate(context4) instanceof AvgBucketNode);
+ assertThat(caf4.evaluate(context4)).isInstanceOf(AvgBucketNode.class);
CompiledAggregateFunction caf5 =
new CompiledAggregateFunction(null, OQLLexerTokenTypes.AVG, true);
ExecutionContext context5 = new ExecutionContext(null, cache);
context5.setIsPRQueryNode(true);
- assertTrue(caf5.evaluate(context5) instanceof AvgDistinctPRQueryNode);
+ assertThat(caf5.evaluate(context5)).isInstanceOf(AvgDistinctPRQueryNode.class);
CompiledAggregateFunction caf6 =
new CompiledAggregateFunction(null, OQLLexerTokenTypes.AVG, true);
QueryExecutionContext context6 = new QueryExecutionContext(null, cache);
context6.setBucketList(this.bucketList);
- assertTrue(caf6.evaluate(context6) instanceof DistinctAggregator);
+ assertThat(caf6.evaluate(context6)).isInstanceOf(DistinctAggregator.class);
}
@Test
@@ -172,18 +160,17 @@ public class CompiledAggregateFunctionJUnitTest {
CompiledAggregateFunction caf1 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.MAX);
ExecutionContext context1 = new ExecutionContext(null, cache);
Aggregator agg = (Aggregator) caf1.evaluate(context1);
- assertTrue(agg instanceof MaxMin);
+ assertThat(agg).isInstanceOf(MaxMin.class);
MaxMin maxMin = (MaxMin) agg;
Class maxMinClass = MaxMin.class;
Field findMax = maxMinClass.getDeclaredField("findMax");
findMax.setAccessible(true);
- assertTrue((Boolean) findMax.get(maxMin));
+ assertThat(findMax.get(maxMin)).isEqualTo(Boolean.TRUE);
CompiledAggregateFunction caf2 = new CompiledAggregateFunction(null, OQLLexerTokenTypes.MIN);
- ExecutionContext context2 = new ExecutionContext(null, cache);
Aggregator agg1 = (Aggregator) caf2.evaluate(context1);
- assertTrue(agg1 instanceof MaxMin);
+ assertThat(agg1).isInstanceOf(MaxMin.class);
MaxMin maxMin1 = (MaxMin) agg1;
- assertFalse((Boolean) findMax.get(maxMin1));
+ assertThat(findMax.get(maxMin1)).isEqualTo(Boolean.FALSE);
}
}
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/TxCommitMessageTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/TxCommitMessageTest.java
index dab050a..75bd785 100755
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/TxCommitMessageTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/TxCommitMessageTest.java
@@ -15,18 +15,22 @@
package org.apache.geode.internal.cache;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.Sequence;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
-import org.junit.Before;
import org.junit.Test;
+import org.mockito.InOrder;
import org.apache.geode.cache.Scope;
import org.apache.geode.distributed.internal.DistributionManager;
@@ -40,132 +44,64 @@ import org.apache.geode.internal.cache.versions.VersionSource;
*/
public class TxCommitMessageTest {
- private Mockery mockContext;
-
- @Before
- public void setUp() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
+ interface VersionedDataOutput extends DataOutput, VersionedDataStream {
}
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
+ interface VersionedDataInput extends DataInput, VersionedDataStream {
}
- public interface VersionedDataOutput extends DataOutput, VersionedDataStream {
+ private InternalDistributedMember createInternalDistributedMember() {
+ final InternalDistributedMember mockInternalDistributedMember =
+ mock(InternalDistributedMember.class);
+ when(mockInternalDistributedMember.getDSFID()).thenReturn(1);
+ when(mockInternalDistributedMember.getSerializationVersions()).thenReturn(null);
+ return mockInternalDistributedMember;
}
- public interface VersionedDataInput extends DataInput, VersionedDataStream {
+ private EntryEventImpl createMockEntryEvent(InternalRegion mockInternalRegion) {
+ final EntryEventImpl mockEntryEventImpl = mock(EntryEventImpl.class);
+ when(mockEntryEventImpl.isLocalInvalid()).thenReturn(false);
+ when(mockEntryEventImpl.getRegion()).thenReturn(mockInternalRegion);
+ return mockEntryEventImpl;
}
- @Test
- public void toDataWithShadowKeyPre180Server() throws IOException {
- final Sequence toData = mockContext.sequence("toData");
- final VersionedDataOutput mockDataOutput = mockContext.mock(VersionedDataOutput.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockDataOutput).getVersion();
- will(returnValue(Version.GEODE_170));
- // processor id
- oneOf(mockDataOutput).writeInt(with(any(int.class)));
- inSequence(toData);
- // txId.uniqId
- oneOf(mockDataOutput).writeInt(0);
- inSequence(toData);
- // lockId
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // totalMaxSize
- oneOf(mockDataOutput).writeInt(0);
- inSequence(toData);
- // txState.membershipId
- oneOf(mockDataOutput).writeByte(-1);
- inSequence(toData);
- // txState.baseThreadId
- oneOf(mockDataOutput).writeLong(with(any(long.class)));
- inSequence(toData);
- // txState.baseSequenceId
- oneOf(mockDataOutput).writeLong(with(any(long.class)));
- inSequence(toData);
- // txState.needsLargeModCount
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // regionsSize
- oneOf(mockDataOutput).writeInt(1);
- inSequence(toData);
+ private TXEntryState createTxEntryState(InternalRegion mockInternalRegion,
+ EntryEventImpl mockEntryEventImpl) {
+ final TXState txState = new TXState(null, false);
+ final TXRegionState txRegionState = new TXRegionState(mockInternalRegion, txState);
+ final TXEntryState txEntryState =
+ TXEntryState.getFactory().createEntry(null, null, null, null, txRegionState, false);
+ txEntryState.invalidate(mockEntryEventImpl);
+ txEntryState.generateEventOffsets(txState);
+
+ return txEntryState;
+ }
- // regionPath: "/r"
- oneOf(mockDataOutput).writeByte(87);
- inSequence(toData);
- oneOf(mockDataOutput).writeShort(2);
- inSequence(toData);
- oneOf(mockDataOutput).writeBytes("/r");
- inSequence(toData);
- // parentRegionPath: null string
- oneOf(mockDataOutput).writeByte(69);
- inSequence(toData);
- // opKeys size
- oneOf(mockDataOutput).writeInt(1);
- inSequence(toData);
- // needsLargeModCount
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // versionMember
- oneOf(mockDataOutput).writeByte(1);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(1);
- inSequence(toData);
- // opKeys[0]
- oneOf(mockDataOutput).writeByte(87);
- inSequence(toData);
- oneOf(mockDataOutput).writeShort(3);
- inSequence(toData);
- oneOf(mockDataOutput).writeBytes("key");
- inSequence(toData);
- // farSideData[0]
- oneOf(mockDataOutput).writeByte(17);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(0);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- // shadowkey
- oneOf(mockDataOutput).writeLong(-1L);
- inSequence(toData);
- // offset
- oneOf(mockDataOutput).writeInt(with(any(int.class)));
- inSequence(toData);
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
+ private InternalRegion createMockInternalRegion(VersionSource mockVersionSource) {
+ final InternalRegion mockInternalRegion = mock(InternalRegion.class);
+ when(mockInternalRegion.requiresReliabilityCheck()).thenReturn(false);
+ when(mockInternalRegion.getVersionMember()).thenReturn(mockVersionSource);
+ when(mockInternalRegion.getFullPath()).thenReturn("/r");
+ when(mockInternalRegion.getPersistBackup()).thenReturn(false);
+ when(mockInternalRegion.getScope()).thenReturn(Scope.LOCAL);
+ when(mockInternalRegion.isEntryEvictionPossible()).thenReturn(false);
+ when(mockInternalRegion.isEntryExpiryPossible()).thenReturn(false);
+ when(mockInternalRegion.getConcurrencyChecksEnabled()).thenReturn(false);
- // bridgeContext
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- // farSiders
- oneOf(mockDataOutput).writeByte(-1);
- inSequence(toData);
- }
- });
+ return mockInternalRegion;
+ }
+ @Test
+ public void toDataWithShadowKeyPre180Server() throws IOException {
+ final VersionedDataOutput mockDataOutput = mock(VersionedDataOutput.class);
+ when(mockDataOutput.getVersion()).thenReturn(Version.GEODE_170);
final InternalDistributedMember mockInternalDistributedMember =
createInternalDistributedMember();
-
final TXId txId = new TXId(mockInternalDistributedMember, 0);
final TXState txState = new TXState(null, false);
final TXCommitMessage txCommitMessage = new TXCommitMessage(txId, null, txState);
-
final InternalRegion mockInternalRegion =
createMockInternalRegion(mockInternalDistributedMember);
txCommitMessage.startRegion(mockInternalRegion, 0);
@@ -173,109 +109,67 @@ public class TxCommitMessageTest {
final TXEntryState txEntryState = createTxEntryState(mockInternalRegion, mockEntryEventImpl);
txCommitMessage.addOp(null, "key", txEntryState, null);
txCommitMessage.finishRegionComplete();
-
txCommitMessage.toData(mockDataOutput);
+
+ // Asserts
+ InOrder dataOutputInOrder = inOrder(mockDataOutput);
+ // processor id
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(anyInt());
+ // txId.uniqId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(0);
+ // lockId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // totalMaxSize
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(0);
+ // txState.membershipId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(-1);
+ // txState.baseThreadId, txState.baseSequenceId
+ dataOutputInOrder.verify(mockDataOutput, times(2)).writeLong(anyLong());
+ // txState.needsLargeModCount
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // regionsSize
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(1);
+ // regionPath: "/r"
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(87);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeShort(2);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBytes("/r");
+ // parentRegionPath: null string
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(69);
+ // opKeys size
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(1);
+ // needsLargeModCount
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // versionMember
+ dataOutputInOrder.verify(mockDataOutput, times(2)).writeByte(1);
+ // opKeys[0]
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(87);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeShort(3);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBytes("key");
+ // farSideData[0]
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(17);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(0);
+ dataOutputInOrder.verify(mockDataOutput, times(3)).writeByte(41);
+ // shadowkey
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeLong(-1L);
+ // offset
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(anyInt());
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // bridgeContext
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(41);
+ // farSiders
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(-1);
}
@Test
public void toDataWithoutShadowKeyPre180Client() throws IOException {
- final Sequence toData = mockContext.sequence("toData");
- final VersionedDataOutput mockDataOutput = mockContext.mock(VersionedDataOutput.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockDataOutput).getVersion();
- will(returnValue(Version.GEODE_170));
- // processor id
- oneOf(mockDataOutput).writeInt(with(any(int.class)));
- inSequence(toData);
- // txId.uniqId
- oneOf(mockDataOutput).writeInt(0);
- inSequence(toData);
- // lockId
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // totalMaxSize
- oneOf(mockDataOutput).writeInt(0);
- inSequence(toData);
- // txState.membershipId
- oneOf(mockDataOutput).writeByte(-1);
- inSequence(toData);
- // txState.baseThreadId
- oneOf(mockDataOutput).writeLong(with(any(long.class)));
- inSequence(toData);
- // txState.baseSequenceId
- oneOf(mockDataOutput).writeLong(with(any(long.class)));
- inSequence(toData);
- // txState.needsLargeModCount
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // regionsSize
- oneOf(mockDataOutput).writeInt(1);
- inSequence(toData);
-
- // regionPath: "/r"
- oneOf(mockDataOutput).writeByte(87);
- inSequence(toData);
- oneOf(mockDataOutput).writeShort(2);
- inSequence(toData);
- oneOf(mockDataOutput).writeBytes("/r");
- inSequence(toData);
- // parentRegionPath: null string
- oneOf(mockDataOutput).writeByte(69);
- inSequence(toData);
- // opKeys size
- oneOf(mockDataOutput).writeInt(1);
- inSequence(toData);
- // needsLargeModCount
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // versionMember
- oneOf(mockDataOutput).writeByte(1);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(1);
- inSequence(toData);
- // opKeys[0]
- oneOf(mockDataOutput).writeByte(87);
- inSequence(toData);
- oneOf(mockDataOutput).writeShort(3);
- inSequence(toData);
- oneOf(mockDataOutput).writeBytes("key");
- inSequence(toData);
- // farSideData[0]
- oneOf(mockDataOutput).writeByte(17);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(0);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- // no shadowkey
- // offset
- oneOf(mockDataOutput).writeInt(with(any(int.class)));
- inSequence(toData);
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
-
- // bridgeContext
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- // farSiders
- oneOf(mockDataOutput).writeByte(-1);
- inSequence(toData);
- }
- });
-
+ final VersionedDataOutput mockDataOutput = mock(VersionedDataOutput.class);
+ when(mockDataOutput.getVersion()).thenReturn(Version.GEODE_170);
final InternalDistributedMember mockInternalDistributedMember =
createInternalDistributedMember();
-
final TXId txId = new TXId(mockInternalDistributedMember, 0);
final TXState txState = new TXState(null, false);
final TXCommitMessage txCommitMessage = new TXCommitMessage(txId, null, txState);
txCommitMessage.setClientVersion(Version.GEODE_170);
-
final InternalRegion mockInternalRegion =
createMockInternalRegion(mockInternalDistributedMember);
txCommitMessage.startRegion(mockInternalRegion, 0);
@@ -283,113 +177,64 @@ public class TxCommitMessageTest {
final TXEntryState txEntryState = createTxEntryState(mockInternalRegion, mockEntryEventImpl);
txCommitMessage.addOp(null, "key", txEntryState, null);
txCommitMessage.finishRegionComplete();
-
txCommitMessage.toData(mockDataOutput);
+
+ // Asserts
+ InOrder dataOutputInOrder = inOrder(mockDataOutput);
+ // processor id
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(anyInt());
+ // txId.uniqId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(0);
+ // lockId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // totalMaxSize
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(0);
+ // txState.membershipId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(-1);
+ // txState.baseThreadId, txState.baseSequenceId
+ dataOutputInOrder.verify(mockDataOutput, times(2)).writeLong(anyLong());
+ // txState.needsLargeModCount
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // regionsSize
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(1);
+ // regionPath: "/r"
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(87);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeShort(2);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBytes("/r");
+ // parentRegionPath: null string
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(69);
+ // opKeys size
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(1);
+ // needsLargeModCount
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // versionMember
+ dataOutputInOrder.verify(mockDataOutput, times(2)).writeByte(1);
+ // opKeys[0]
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(87);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeShort(3);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBytes("key");
+ // farSideData[0]
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(17);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(0);
+ dataOutputInOrder.verify(mockDataOutput, times(3)).writeByte(41);
+ // no shadowkey offset
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(anyInt());
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // bridgeContext
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(41);
+ // farSiders
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(-1);
}
@Test
public void toDataWithShadowKeyPost180Server() throws IOException {
- final Sequence toData = mockContext.sequence("toData");
- final VersionedDataOutput mockDataOutput = mockContext.mock(VersionedDataOutput.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockDataOutput).getVersion();
- will(returnValue(Version.CURRENT));
- // processor id
- oneOf(mockDataOutput).writeInt(with(any(int.class)));
- inSequence(toData);
- // txId.uniqId
- oneOf(mockDataOutput).writeInt(0);
- inSequence(toData);
- // lockId
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // totalMaxSize
- oneOf(mockDataOutput).writeInt(0);
- inSequence(toData);
- // txState.membershipId
- oneOf(mockDataOutput).writeByte(-1);
- inSequence(toData);
- // txState.baseThreadId
- oneOf(mockDataOutput).writeLong(with(any(long.class)));
- inSequence(toData);
- // txState.baseSequenceId
- oneOf(mockDataOutput).writeLong(with(any(long.class)));
- inSequence(toData);
- // txState.needsLargeModCount
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // hasShadowKeys
- oneOf(mockDataOutput).writeBoolean(true);
- inSequence(toData);
- // regionsSize
- oneOf(mockDataOutput).writeInt(1);
- inSequence(toData);
-
- // regionPath: "/r"
- oneOf(mockDataOutput).writeByte(87);
- inSequence(toData);
- oneOf(mockDataOutput).writeShort(2);
- inSequence(toData);
- oneOf(mockDataOutput).writeBytes("/r");
- inSequence(toData);
- // parentRegionPath: null string
- oneOf(mockDataOutput).writeByte(69);
- inSequence(toData);
- // opKeys size
- oneOf(mockDataOutput).writeInt(1);
- inSequence(toData);
- // needsLargeModCount
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // versionMember
- oneOf(mockDataOutput).writeByte(1);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(1);
- inSequence(toData);
- // opKeys[0]
- oneOf(mockDataOutput).writeByte(87);
- inSequence(toData);
- oneOf(mockDataOutput).writeShort(3);
- inSequence(toData);
- oneOf(mockDataOutput).writeBytes("key");
- inSequence(toData);
- // farSideData[0]
- oneOf(mockDataOutput).writeByte(17);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(0);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- // shadowkey
- oneOf(mockDataOutput).writeLong(-1L);
- inSequence(toData);
- // offset
- oneOf(mockDataOutput).writeInt(with(any(int.class)));
- inSequence(toData);
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
-
- // bridgeContext
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- // farSiders
- oneOf(mockDataOutput).writeByte(-1);
- inSequence(toData);
- }
- });
-
+ final VersionedDataOutput mockDataOutput = mock(VersionedDataOutput.class);
+ when(mockDataOutput.getVersion()).thenReturn(Version.CURRENT);
final InternalDistributedMember mockInternalDistributedMember =
createInternalDistributedMember();
-
final TXId txId = new TXId(mockInternalDistributedMember, 0);
final TXState txState = new TXState(null, false);
final TXCommitMessage txCommitMessage = new TXCommitMessage(txId, null, txState);
-
final InternalRegion mockInternalRegion =
createMockInternalRegion(mockInternalDistributedMember);
txCommitMessage.startRegion(mockInternalRegion, 0);
@@ -397,112 +242,69 @@ public class TxCommitMessageTest {
final TXEntryState txEntryState = createTxEntryState(mockInternalRegion, mockEntryEventImpl);
txCommitMessage.addOp(null, "key", txEntryState, null);
txCommitMessage.finishRegionComplete();
-
txCommitMessage.toData(mockDataOutput);
+
+ // Asserts
+ InOrder dataOutputInOrder = inOrder(mockDataOutput);
+ // processor id
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(anyInt());
+ // txId.uniqId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(0);
+ // lockId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // totalMaxSize
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(0);
+ // txState.membershipId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(-1);
+ // txState.baseThreadId, txState.baseSequenceId
+ dataOutputInOrder.verify(mockDataOutput, times(2)).writeLong(anyLong());
+ // txState.needsLargeModCount
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // hasShadowKeys
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(true);
+ // regionsSize
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(1);
+ // regionPath: "/r"
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(87);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeShort(2);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBytes("/r");
+ // parentRegionPath: null string
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(69);
+ // opKeys size
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(1);
+ // needsLargeModCount
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // versionMember
+ dataOutputInOrder.verify(mockDataOutput, times(2)).writeByte(1);
+ // opKeys[0]
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(87);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeShort(3);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBytes("key");
+ // farSideData[0]
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(17);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(0);
+ dataOutputInOrder.verify(mockDataOutput, times(3)).writeByte(41);
+ // shadowkey
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeLong(-1L);
+ // offset
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(anyInt());
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // bridgeContext
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(41);
+ // farSiders
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(-1);
}
@Test
public void toDataWithoutShadowKeyPost180Client() throws IOException {
- final Sequence toData = mockContext.sequence("toData");
- final VersionedDataOutput mockDataOutput = mockContext.mock(VersionedDataOutput.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockDataOutput).getVersion();
- will(returnValue(Version.CURRENT));
- // processor id
- oneOf(mockDataOutput).writeInt(with(any(int.class)));
- inSequence(toData);
- // txId.uniqId
- oneOf(mockDataOutput).writeInt(0);
- inSequence(toData);
- // lockId
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // totalMaxSize
- oneOf(mockDataOutput).writeInt(0);
- inSequence(toData);
- // txState.membershipId
- oneOf(mockDataOutput).writeByte(-1);
- inSequence(toData);
- // txState.baseThreadId
- oneOf(mockDataOutput).writeLong(with(any(long.class)));
- inSequence(toData);
- // txState.baseSequenceId
- oneOf(mockDataOutput).writeLong(with(any(long.class)));
- inSequence(toData);
- // txState.needsLargeModCount
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // hasShadowKeys
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // regionsSize
- oneOf(mockDataOutput).writeInt(1);
- inSequence(toData);
-
- // regionPath: "/r"
- oneOf(mockDataOutput).writeByte(87);
- inSequence(toData);
- oneOf(mockDataOutput).writeShort(2);
- inSequence(toData);
- oneOf(mockDataOutput).writeBytes("/r");
- inSequence(toData);
- // parentRegionPath: null string
- oneOf(mockDataOutput).writeByte(69);
- inSequence(toData);
- // opKeys size
- oneOf(mockDataOutput).writeInt(1);
- inSequence(toData);
- // needsLargeModCount
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
- // versionMember
- oneOf(mockDataOutput).writeByte(1);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(1);
- inSequence(toData);
- // opKeys[0]
- oneOf(mockDataOutput).writeByte(87);
- inSequence(toData);
- oneOf(mockDataOutput).writeShort(3);
- inSequence(toData);
- oneOf(mockDataOutput).writeBytes("key");
- inSequence(toData);
- // farSideData[0]
- oneOf(mockDataOutput).writeByte(17);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(0);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- // no shadowkey
- // offset
- oneOf(mockDataOutput).writeInt(with(any(int.class)));
- inSequence(toData);
- oneOf(mockDataOutput).writeBoolean(false);
- inSequence(toData);
-
- // bridgeContext
- oneOf(mockDataOutput).writeByte(41);
- inSequence(toData);
- // farSiders
- oneOf(mockDataOutput).writeByte(-1);
- inSequence(toData);
- }
- });
-
+ final VersionedDataOutput mockDataOutput = mock(VersionedDataOutput.class);
+ when(mockDataOutput.getVersion()).thenReturn(Version.CURRENT);
final InternalDistributedMember mockInternalDistributedMember =
createInternalDistributedMember();
-
final TXId txId = new TXId(mockInternalDistributedMember, 0);
final TXState txState = new TXState(null, false);
final TXCommitMessage txCommitMessage = new TXCommitMessage(txId, null, txState);
txCommitMessage.setClientVersion(Version.CURRENT);
-
final InternalRegion mockInternalRegion =
createMockInternalRegion(mockInternalDistributedMember);
txCommitMessage.startRegion(mockInternalRegion, 0);
@@ -510,655 +312,171 @@ public class TxCommitMessageTest {
final TXEntryState txEntryState = createTxEntryState(mockInternalRegion, mockEntryEventImpl);
txCommitMessage.addOp(null, "key", txEntryState, null);
txCommitMessage.finishRegionComplete();
-
txCommitMessage.toData(mockDataOutput);
+
+ // Asserts
+ InOrder dataOutputInOrder = inOrder(mockDataOutput);
+ // processor id
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(anyInt());
+ // txId.uniqId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(0);
+ // lockId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // totalMaxSize
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(0);
+ // txState.membershipId
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(-1);
+ // txState.baseThreadId, txState.baseSequenceId
+ dataOutputInOrder.verify(mockDataOutput, times(2)).writeLong(anyLong());
+ // txState.needsLargeModCount
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // hasShadowKeys
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // regionsSize
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(1);
+ // regionPath: "/r"
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(87);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeShort(2);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBytes("/r");
+ // parentRegionPath: null string
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(69);
+ // opKeys size
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(1);
+ // needsLargeModCount
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // versionMember
+ dataOutputInOrder.verify(mockDataOutput, times(2)).writeByte(1);
+ // opKeys[0]
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(87);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeShort(3);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBytes("key");
+ // farSideData[0]
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(17);
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(0);
+ dataOutputInOrder.verify(mockDataOutput, times(3)).writeByte(41);
+ // no shadowkeyoffset
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeInt(anyInt());
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeBoolean(false);
+ // bridgeContext
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(41);
+ // farSiders
+ dataOutputInOrder.verify(mockDataOutput, times(1)).writeByte(-1);
}
@Test
public void fromDataWithShadowKeyPre180Server() throws Exception {
- final Sequence fromData = mockContext.sequence("fromData");
- final VersionedDataInput mockDataInput = mockContext.mock(VersionedDataInput.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockDataInput).getVersion();
- will(returnValue(Version.GEODE_170));
- // processor id
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- // txId.uniqId
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- // member version
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedByte();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedByte();
- will(returnValue(1));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- // durableId
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 87));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedShort();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput)
- .readFully(with(any(byte[].class)), with(any(int.class)), with(any(int.class)));
- inSequence(fromData);
-
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 0));
- inSequence(fromData);
-
- // lockId
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
- // totalMaxSize
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- // txState.membershipId
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- // txState.baseThreadId
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- // txState.baseSequenceId
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- // txState.needsLargeModCount
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
-
- // regionsSize
- oneOf(mockDataInput).readInt();
- will(returnValue(1));
- inSequence(fromData);
-
- // regionPath: "/r"
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 87));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedShort();
- will(returnValue(2));
- inSequence(fromData);
- oneOf(mockDataInput)
- .readFully(with(any(byte[].class)), with(any(int.class)), with(any(int.class)));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- // opKeys size
- oneOf(mockDataInput).readInt();
- will(returnValue(1));
- inSequence(fromData);
- // needsLargeModCount
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
- // versionMember
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
-
- // opKeys[0]
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 87));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedShort();
- will(returnValue(3));
- inSequence(fromData);
- oneOf(mockDataInput)
- .readFully(with(any(byte[].class)), with(any(int.class)), with(any(int.class)));
- inSequence(fromData);
- // farSideData[0]
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 17));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 0));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- // shadowkey
- oneOf(mockDataInput).readLong();
- will(returnValue(-1L));
- inSequence(fromData);
- // offset
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
-
- // bridgeContext
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- // farSiders
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- }
- });
-
- final DistributionManager mockDistributionManager =
- mockContext.mock(DistributionManager.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockDistributionManager).getCache();
- will(returnValue(null));
- allowing(mockDistributionManager).isLoner();
- will(returnValue(false));
- }
- });
-
+ final VersionedDataInput mockDataInput = mock(VersionedDataInput.class);
+ when(mockDataInput.getVersion()).thenReturn(Version.GEODE_170);
+ when(mockDataInput.readInt()).thenReturn(/* processor id */0, /* txId.uniqId */0,
+ /* member version */0, 0, 0, 0, /* totalMaxSize */0, /* regionsSize */1,
+ /* opKeys size */ 1, /* offset */0);
+ when(mockDataInput.readByte()).thenReturn(/* member version */(byte) -1, (byte) 69, (byte) -1,
+ (byte) 69, (byte) 69, /* durableId */(byte) 87, (byte) 0,
+ /* txState.membershipId */(byte) -1, /* regionPath: "/r" */(byte) 87, (byte) 69,
+ /* versionMember */(byte) 41, /* opKeys[0] */(byte) 87, /* farSideData[0] */(byte) 17,
+ (byte) 0, (byte) 41, (byte) 41, (byte) 41, /* bridgeContext */(byte) 41,
+ /* farSiders */(byte) -1);
+ when(mockDataInput.readUnsignedByte()).thenReturn(/* member version */0, 1);
+ when(mockDataInput.readUnsignedShort()).thenReturn(/* durableId */0, 2, 3);
+ when(mockDataInput.readLong()).thenReturn(/* durableId */0L, 0L, /* txState.baseThreadId */0L,
+ /* txState.baseSequenceId */0L, /* shadowkey */ -1L);
+ when(mockDataInput.readBoolean()).thenReturn(/* lockId */false,
+ /* txState.needsLargeModCount */false, /* needsLargeModCount */false, false);
+
+ final DistributionManager mockDistributionManager = mock(DistributionManager.class);
+ when(mockDistributionManager.getCache()).thenReturn(null);
+ when(mockDistributionManager.isLoner()).thenReturn(false);
final TXCommitMessage txCommitMessage = new TXCommitMessage();
txCommitMessage.setDM(mockDistributionManager);
+ verify(mockDataInput, never()).readInt();
+ verify(mockDataInput, never()).readByte();
+ verify(mockDataInput, never()).readUnsignedByte();
+ verify(mockDataInput, never()).readUnsignedShort();
+ verify(mockDataInput, never()).readLong();
+ verify(mockDataInput, never()).readBoolean();
txCommitMessage.fromData(mockDataInput);
+
+ // Asserts
+ verify(mockDataInput, times(10)).readInt();
+ verify(mockDataInput, times(19)).readByte();
+ verify(mockDataInput, times(2)).readUnsignedByte();
+ verify(mockDataInput, times(3)).readUnsignedShort();
+ verify(mockDataInput, times(5)).readLong();
+ verify(mockDataInput, times(4)).readBoolean();
+ verify(mockDataInput, times(3)).readFully(any(byte[].class), anyInt(), anyInt());
}
@Test
public void fromDataWithShadowKeyPost180Server() throws Exception {
- final Sequence fromData = mockContext.sequence("fromData");
- final DataInput mockDataInput = mockContext.mock(DataInput.class);
- mockContext.checking(new Expectations() {
- {
- // processor id
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- // txId.uniqId
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- // member version
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedByte();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedByte();
- will(returnValue(1));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- // durableId
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 87));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedShort();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput)
- .readFully(with(any(byte[].class)), with(any(int.class)), with(any(int.class)));
- inSequence(fromData);
-
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 0));
- inSequence(fromData);
-
- // lockId
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
- // totalMaxSize
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- // txState.membershipId
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- // txState.baseThreadId
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- // txState.baseSequenceId
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- // txState.needsLargeModCount
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
-
- // hasShadowKeys
- oneOf(mockDataInput).readBoolean();
- will(returnValue(true));
- inSequence(fromData);
-
- // regionsSize
- oneOf(mockDataInput).readInt();
- will(returnValue(1));
- inSequence(fromData);
-
- // regionPath: "/r"
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 87));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedShort();
- will(returnValue(2));
- inSequence(fromData);
- oneOf(mockDataInput)
- .readFully(with(any(byte[].class)), with(any(int.class)), with(any(int.class)));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- // opKeys size
- oneOf(mockDataInput).readInt();
- will(returnValue(1));
- inSequence(fromData);
- // needsLargeModCount
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
- // versionMember
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
-
- // opKeys[0]
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 87));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedShort();
- will(returnValue(3));
- inSequence(fromData);
- oneOf(mockDataInput)
- .readFully(with(any(byte[].class)), with(any(int.class)), with(any(int.class)));
- inSequence(fromData);
- // farSideData[0]
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 17));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 0));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- // shadowkey
- oneOf(mockDataInput).readLong();
- will(returnValue(-1L));
- inSequence(fromData);
- // offset
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
-
- // bridgeContext
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- // farSiders
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- }
- });
-
- final DistributionManager mockDistributionManager =
- mockContext.mock(DistributionManager.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockDistributionManager).getCache();
- will(returnValue(null));
- allowing(mockDistributionManager).isLoner();
- will(returnValue(false));
- }
- });
-
+ final DataInput mockDataInput = mock(DataInput.class);
+ when(mockDataInput.readInt()).thenReturn(/* processor id */0, /* txId.uniqId */0,
+ /* member version */0, 0, 0, 0, /* totalMaxSize */0, /* regionsSize */1,
+ /* opKeys size */ 1, /* offset */0);
+ when(mockDataInput.readByte()).thenReturn(/* member version */(byte) -1, (byte) 69, (byte) -1,
+ (byte) 69, (byte) 69, /* durableId */(byte) 87, (byte) 0,
+ /* txState.membershipId */(byte) -1, /* regionPath: "/r" */(byte) 87, (byte) 69,
+ /* versionMember */(byte) 41, /* opKeys[0] */(byte) 87, /* farSideData[0] */(byte) 17,
+ (byte) 0, (byte) 41, (byte) 41, (byte) 41, /* bridgeContext */(byte) 41,
+ /* farSiders */(byte) -1);
+ when(mockDataInput.readUnsignedByte()).thenReturn(/* member version */0, 1);
+ when(mockDataInput.readUnsignedShort()).thenReturn(/* durableId */0, 2, 3);
+ when(mockDataInput.readLong()).thenReturn(/* durableId */0L, 0L, /* txState.baseThreadId */0L,
+ /* txState.baseSequenceId */0L, /* shadowkey */ -1L);
+ when(mockDataInput.readBoolean()).thenReturn(/* lockId */false,
+ /* txState.needsLargeModCount */false, /* hasShadowKeys */true,
+ /* needsLargeModCount */false, false);
+
+ final DistributionManager mockDistributionManager = mock(DistributionManager.class);
+ when(mockDistributionManager.getCache()).thenReturn(null);
+ when(mockDistributionManager.isLoner()).thenReturn(false);
final TXCommitMessage txCommitMessage = new TXCommitMessage();
txCommitMessage.setDM(mockDistributionManager);
txCommitMessage.fromData(mockDataInput);
+
+ // Asserts
+ verify(mockDataInput, times(10)).readInt();
+ verify(mockDataInput, times(19)).readByte();
+ verify(mockDataInput, times(2)).readUnsignedByte();
+ verify(mockDataInput, times(3)).readUnsignedShort();
+ verify(mockDataInput, times(5)).readLong();
+ verify(mockDataInput, times(5)).readBoolean();
+ verify(mockDataInput, times(3)).readFully(any(byte[].class), anyInt(), anyInt());
}
@Test
public void fromDataWithoutShadowKeyPost180Client() throws Exception {
- final Sequence fromData = mockContext.sequence("fromData");
- final DataInput mockDataInput = mockContext.mock(DataInput.class);
- mockContext.checking(new Expectations() {
- {
- // processor id
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- // txId.uniqId
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- // member version
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedByte();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedByte();
- will(returnValue(1));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- // durableId
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 87));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedShort();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput)
- .readFully(with(any(byte[].class)), with(any(int.class)), with(any(int.class)));
- inSequence(fromData);
-
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 0));
- inSequence(fromData);
-
- // lockId
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
- // totalMaxSize
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- // txState.membershipId
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- // txState.baseThreadId
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- // txState.baseSequenceId
- oneOf(mockDataInput).readLong();
- will(returnValue(0L));
- inSequence(fromData);
- // txState.needsLargeModCount
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
-
- // hasShadowKeys
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
-
- // regionsSize
- oneOf(mockDataInput).readInt();
- will(returnValue(1));
- inSequence(fromData);
-
- // regionPath: "/r"
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 87));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedShort();
- will(returnValue(2));
- inSequence(fromData);
- oneOf(mockDataInput)
- .readFully(with(any(byte[].class)), with(any(int.class)), with(any(int.class)));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 69));
- inSequence(fromData);
- // opKeys size
- oneOf(mockDataInput).readInt();
- will(returnValue(1));
- inSequence(fromData);
- // needsLargeModCount
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
- // versionMember
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
-
- // opKeys[0]
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 87));
- inSequence(fromData);
- oneOf(mockDataInput).readUnsignedShort();
- will(returnValue(3));
- inSequence(fromData);
- oneOf(mockDataInput)
- .readFully(with(any(byte[].class)), with(any(int.class)), with(any(int.class)));
- inSequence(fromData);
- // farSideData[0]
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 17));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 0));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- // no shadowkey
- // offset
- oneOf(mockDataInput).readInt();
- will(returnValue(0));
- inSequence(fromData);
- oneOf(mockDataInput).readBoolean();
- will(returnValue(false));
- inSequence(fromData);
-
- // bridgeContext
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) 41));
- inSequence(fromData);
- // farSiders
- oneOf(mockDataInput).readByte();
- will(returnValue((byte) -1));
- inSequence(fromData);
- }
- });
-
- final DistributionManager mockDistributionManager =
- mockContext.mock(DistributionManager.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockDistributionManager).getCache();
- will(returnValue(null));
- allowing(mockDistributionManager).isLoner();
- will(returnValue(true));
- }
- });
+ final DataInput mockDataInput = mock(DataInput.class);
+ when(mockDataInput.readInt()).thenReturn(/* processor id */0, /* txId.uniqId */0,
+ /* member version */0, 0, 0, 0, /* totalMaxSize */0, /* regionsSize */1,
+ /* opKeys size */ 1, /* offset */0);
+ when(mockDataInput.readByte()).thenReturn(/* member version */(byte) -1, (byte) 69, (byte) -1,
+ (byte) 69, (byte) 69, /* durableId */(byte) 87, (byte) 0,
+ /* txState.membershipId */(byte) -1, /* regionPath: "/r" */(byte) 87, (byte) 69,
+ /* versionMember */(byte) 41, /* opKeys[0] */(byte) 87, /* farSideData[0] */(byte) 17,
+ (byte) 0, (byte) 41, (byte) 41, (byte) 41, /* bridgeContext */(byte) 41,
+ /* farSiders */(byte) -1);
+ when(mockDataInput.readUnsignedByte()).thenReturn(/* member version */0, 1);
+ when(mockDataInput.readUnsignedShort()).thenReturn(/* durableId */0, 2, 3);
+ when(mockDataInput.readLong()).thenReturn(/* durableId */0L, 0L, /* txState.baseThreadId */0L,
+ /* txState.baseSequenceId */0L);
+ when(mockDataInput.readBoolean()).thenReturn(/* lockId */false,
+ /* txState.needsLargeModCount */false, /* hasShadowKeys */false,
+ /* needsLargeModCount */false, false);
+ final DistributionManager mockDistributionManager = mock(DistributionManager.class);
+ when(mockDistributionManager.getCache()).thenReturn(null);
+ when(mockDistributionManager.isLoner()).thenReturn(false);
final TXCommitMessage txCommitMessage = new TXCommitMessage();
txCommitMessage.setDM(mockDistributionManager);
txCommitMessage.fromData(mockDataInput);
- }
-
- private InternalDistributedMember createInternalDistributedMember() throws IOException {
- final InternalDistributedMember mockInternalDistributedMember =
- mockContext.mock(InternalDistributedMember.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockInternalDistributedMember).getDSFID();
- will(returnValue(1));
- allowing(mockInternalDistributedMember).toData(with(any(DataOutput.class)));
- allowing(mockInternalDistributedMember).getSerializationVersions();
- will(returnValue(null));
- }
- });
- return mockInternalDistributedMember;
- }
-
- private EntryEventImpl createMockEntryEvent(InternalRegion mockInternalRegion) {
- final EntryEventImpl mockEntryEventImpl = mockContext.mock(EntryEventImpl.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockEntryEventImpl).isLocalInvalid();
- will(returnValue(false));
- allowing(mockEntryEventImpl).getRegion();
- will(returnValue(mockInternalRegion));
- ignoring(mockEntryEventImpl).putValueTXEntry(with(any(TXEntryState.class)));
- ignoring(mockEntryEventImpl)
- .setTXEntryOldValue(with(any(Object.class)), with(any(boolean.class)));
- }
- });
- return mockEntryEventImpl;
- }
-
- private TXEntryState createTxEntryState(InternalRegion mockInternalRegion,
- EntryEventImpl mockEntryEventImpl) {
- final TXState txState = new TXState(null, false);
- final TXRegionState txRegionState = new TXRegionState(mockInternalRegion, txState);
- final TXEntryState txEntryState =
- TXEntryState.getFactory().createEntry(null, null, null, null, txRegionState, false);
- txEntryState.invalidate(mockEntryEventImpl);
- txEntryState.generateEventOffsets(txState);
- return txEntryState;
- }
- private InternalRegion createMockInternalRegion(VersionSource mockVersionSource) {
- final InternalRegion mockInternalRegion = mockContext.mock(InternalRegion.class);
- mockContext.checking(new Expectations() {
- {
- allowing(mockInternalRegion).requiresReliabilityCheck();
- will(returnValue(false));
- allowing(mockInternalRegion).getVersionMember();
- will(returnValue(mockVersionSource));
- allowing(mockInternalRegion).getFullPath();
- will(returnValue("/r"));
- allowing(mockInternalRegion).getPersistBackup();
- will(returnValue(false));
- allowing(mockInternalRegion).getScope();
- will(returnValue(Scope.LOCAL));
- allowing(mockInternalRegion).isEntryEvictionPossible();
- will(returnValue(false));
- allowing(mockInternalRegion).isEntryExpiryPossible();
- will(returnValue(false));
- ignoring(mockInternalRegion).setInUseByTransaction(true);
- allowing(mockInternalRegion).getConcurrencyChecksEnabled();
- will(returnValue(false));
- }
- });
- return mockInternalRegion;
+ // Asserts
+ verify(mockDataInput, times(10)).readInt();
+ verify(mockDataInput, times(19)).readByte();
+ verify(mockDataInput, times(2)).readUnsignedByte();
+ verify(mockDataInput, times(3)).readUnsignedShort();
+ verify(mockDataInput, times(4)).readLong();
+ verify(mockDataInput, times(5)).readBoolean();
+ verify(mockDataInput, times(3)).readFully(any(byte[].class), anyInt(), anyInt());
}
-
}
diff --git a/geode-core/src/test/java/org/apache/geode/internal/io/CompositeOutputStreamJUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/io/CompositeOutputStreamJUnitTest.java
index d5d73b7..34a438d 100755
--- a/geode-core/src/test/java/org/apache/geode/internal/io/CompositeOutputStreamJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/io/CompositeOutputStreamJUnitTest.java
@@ -14,21 +14,18 @@
*/
package org.apache.geode.internal.io;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
import java.io.IOException;
import java.io.OutputStream;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.Sequence;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
-import org.junit.Before;
import org.junit.Test;
+import org.mockito.InOrder;
/**
@@ -38,29 +35,11 @@ import org.junit.Test;
*/
public class CompositeOutputStreamJUnitTest {
- private Mockery mockContext;
-
- @Before
- public void setUp() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
- }
-
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
- }
-
@Test
public void testNewCompositeOutputStreamWithNoStreams() throws IOException {
final CompositeOutputStream cos = new CompositeOutputStream();
- assertTrue(cos.isEmpty());
- assertEquals(0, cos.size());
+ assertThat(cos.isEmpty()).isTrue();
+ assertThat(cos.size()).isEqualTo(0);
cos.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
cos.write(new byte[] {0, 1});
@@ -71,523 +50,235 @@ public class CompositeOutputStreamJUnitTest {
@Test
public void testMockOutputStream() throws IOException {
- final OutputStream mockOutputStream = mockContext.mock(OutputStream.class, "OutputStream");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockOutputStream).write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
- oneOf(mockOutputStream).write(new byte[] {0, 1});
- oneOf(mockOutputStream).write(9);
- oneOf(mockOutputStream).flush();
- oneOf(mockOutputStream).close();
- }
- });
-
+ final OutputStream mockOutputStream = mock(OutputStream.class, "OutputStream");
mockOutputStream.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
mockOutputStream.write(new byte[] {0, 1});
mockOutputStream.write(9);
mockOutputStream.flush();
mockOutputStream.close();
+
+ verify(mockOutputStream, times(1)).write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
+ verify(mockOutputStream, times(1)).write(new byte[] {0, 1});
+ verify(mockOutputStream, times(1)).write(9);
+ verify(mockOutputStream, times(1)).flush();
+ verify(mockOutputStream, times(1)).close();
}
@Test
public void testNewCompositeOutputStreamWithOneStream() throws IOException {
- final Sequence seqStreamOne = mockContext.sequence("seqStreamOne");
- final OutputStream streamOne = mockContext.mock(OutputStream.class, "streamOne");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamOne).write(2);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(3);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(4);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(0);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(1);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(9);
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).close();
- inSequence(seqStreamOne);
- }
- });
-
- final CompositeOutputStream cos = new CompositeOutputStream(streamOne);
-
- assertFalse(cos.isEmpty());
- assertEquals(1, cos.size());
-
- cos.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
- cos.write(new byte[] {0, 1});
- cos.write(9);
- cos.flush();
- cos.close();
+ final OutputStream mockStreamOne = mock(OutputStream.class, "streamOne");
+ final CompositeOutputStream compositeOutputStream = new CompositeOutputStream(mockStreamOne);
+ assertThat(compositeOutputStream.isEmpty()).isFalse();
+ assertThat(compositeOutputStream.size()).isEqualTo(1);
+ compositeOutputStream.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
+ compositeOutputStream.write(new byte[] {0, 1});
+ compositeOutputStream.write(9);
+ compositeOutputStream.flush();
+ compositeOutputStream.close();
+
+ InOrder inOrder = inOrder(mockStreamOne);
+ inOrder.verify(mockStreamOne, times(1)).write(2);
+ inOrder.verify(mockStreamOne, times(1)).write(3);
+ inOrder.verify(mockStreamOne, times(1)).write(4);
+ inOrder.verify(mockStreamOne, times(1)).write(0);
+ inOrder.verify(mockStreamOne, times(1)).write(1);
+ inOrder.verify(mockStreamOne, times(1)).write(9);
+ inOrder.verify(mockStreamOne, times(2)).flush();
+ inOrder.verify(mockStreamOne, times(1)).close();
}
@Test
public void testNewCompositeOutputStreamWithTwoStreams() throws IOException {
- final Sequence seqStreamOne = mockContext.sequence("seqStreamOne");
- final OutputStream streamOne = mockContext.mock(OutputStream.class, "streamOne");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamOne).write(2);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(3);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(4);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(0);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(1);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(9);
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).close();
- inSequence(seqStreamOne);
- }
- });
-
- final Sequence seqStreamTwo = mockContext.sequence("seqStreamTwo");
- final OutputStream streamTwo = mockContext.mock(OutputStream.class, "streamTwo");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamTwo).write(2);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(3);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(4);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(0);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(1);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(9);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).flush();
- inSequence(seqStreamTwo);
- oneOf(streamTwo).flush();
- inSequence(seqStreamTwo);
- oneOf(streamTwo).close();
- inSequence(seqStreamTwo);
- }
- });
-
+ final OutputStream streamOne = mock(OutputStream.class, "streamOne");
+ final OutputStream streamTwo = mock(OutputStream.class, "streamTwo");
final CompositeOutputStream cos = new CompositeOutputStream(streamOne, streamTwo);
-
- assertFalse(cos.isEmpty());
- assertEquals(2, cos.size());
-
+ assertThat(cos.isEmpty()).isFalse();
+ assertThat(cos.size()).isEqualTo(2);
cos.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
cos.write(new byte[] {0, 1});
cos.write(9);
cos.flush();
cos.close();
+
+ InOrder inOrderStreams = inOrder(streamOne, streamTwo);
+ inOrderStreams.verify(streamOne, times(1)).write(2);
+ inOrderStreams.verify(streamOne, times(1)).write(3);
+ inOrderStreams.verify(streamOne, times(1)).write(4);
+ inOrderStreams.verify(streamOne, times(1)).write(0);
+ inOrderStreams.verify(streamOne, times(1)).write(1);
+ inOrderStreams.verify(streamOne, times(1)).write(9);
+ inOrderStreams.verify(streamOne, times(2)).flush();
+ inOrderStreams.verify(streamOne, times(1)).close();
}
@Test
public void testAddOutputStreamWithTwoStreams() throws IOException {
- final Sequence seqStreamOne = mockContext.sequence("seqStreamOne");
- final OutputStream streamOne = mockContext.mock(OutputStream.class, "streamOne");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamOne).write(2);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(3);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(4);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(0);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(1);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(9);
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).close();
- inSequence(seqStreamOne);
- }
- });
-
- final Sequence seqStreamTwo = mockContext.sequence("seqStreamTwo");
- final OutputStream streamTwo = mockContext.mock(OutputStream.class, "streamTwo");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamTwo).write(2);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(3);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(4);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(0);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(1);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(9);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).flush();
- inSequence(seqStreamTwo);
- oneOf(streamTwo).flush();
- inSequence(seqStreamTwo);
- oneOf(streamTwo).close();
- inSequence(seqStreamTwo);
- }
- });
-
- final Sequence seqStreamThree = mockContext.sequence("seqStreamThree");
- final OutputStream streamThree = mockContext.mock(OutputStream.class, "streamThree");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamThree).write(2);
- inSequence(seqStreamThree);
- oneOf(streamThree).write(3);
- inSequence(seqStreamThree);
- oneOf(streamThree).write(4);
- inSequence(seqStreamThree);
- oneOf(streamThree).write(0);
- inSequence(seqStreamThree);
- oneOf(streamThree).write(1);
- inSequence(seqStreamThree);
- oneOf(streamThree).write(9);
- inSequence(seqStreamThree);
- oneOf(streamThree).flush();
- inSequence(seqStreamThree);
- oneOf(streamThree).flush();
- inSequence(seqStreamThree);
- oneOf(streamThree).close();
- inSequence(seqStreamThree);
- }
- });
-
+ final OutputStream streamOne = mock(OutputStream.class, "streamOne");
+ final OutputStream streamTwo = mock(OutputStream.class, "streamTwo");
+ final OutputStream streamThree = mock(OutputStream.class, "streamThree");
final CompositeOutputStream cos = new CompositeOutputStream(streamOne, streamTwo);
-
- assertFalse(cos.isEmpty());
- assertEquals(2, cos.size());
-
+ assertThat(cos.isEmpty()).isFalse();
+ assertThat(cos.size()).isEqualTo(2);
cos.addOutputStream(streamThree);
- assertEquals(3, cos.size());
-
+ assertThat(cos.size()).isEqualTo(3);
cos.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
cos.write(new byte[] {0, 1});
cos.write(9);
cos.flush();
cos.close();
+
+ InOrder inOrderStreams = inOrder(streamOne, streamTwo, streamThree);
+ inOrderStreams.verify(streamOne, times(1)).write(2);
+ inOrderStreams.verify(streamOne, times(1)).write(3);
+ inOrderStreams.verify(streamOne, times(1)).write(4);
+ inOrderStreams.verify(streamOne, times(1)).write(0);
+ inOrderStreams.verify(streamOne, times(1)).write(1);
+ inOrderStreams.verify(streamOne, times(1)).write(9);
+ inOrderStreams.verify(streamOne, times(2)).flush();
+ inOrderStreams.verify(streamOne, times(1)).close();
}
@Test
public void testAddOutputStreamWithOneStream() throws IOException {
- final Sequence seqStreamOne = mockContext.sequence("seqStreamOne");
- final OutputStream streamOne = mockContext.mock(OutputStream.class, "streamOne");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamOne).write(2);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(3);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(4);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(0);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(1);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(9);
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).close();
- inSequence(seqStreamOne);
- }
- });
-
- final Sequence seqStreamTwo = mockContext.sequence("seqStreamTwo");
- final OutputStream streamTwo = mockContext.mock(OutputStream.class, "streamTwo");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamTwo).write(2);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(3);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(4);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(0);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(1);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(9);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).flush();
- inSequence(seqStreamTwo);
- oneOf(streamTwo).flush();
- inSequence(seqStreamTwo);
- oneOf(streamTwo).close();
- inSequence(seqStreamTwo);
- }
- });
-
+ final OutputStream streamOne = mock(OutputStream.class, "streamOne");
+ final OutputStream streamTwo = mock(OutputStream.class, "streamTwo");
final CompositeOutputStream cos = new CompositeOutputStream(streamOne);
-
- assertFalse(cos.isEmpty());
- assertEquals(1, cos.size());
-
+ assertThat(cos.isEmpty()).isFalse();
+ assertThat(cos.size()).isEqualTo(1);
cos.addOutputStream(streamTwo);
- assertEquals(2, cos.size());
-
+ assertThat(cos.size()).isEqualTo(2);
cos.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
cos.write(new byte[] {0, 1});
cos.write(9);
cos.flush();
cos.close();
+
+ InOrder inOrderStreams = inOrder(streamOne, streamTwo);
+ inOrderStreams.verify(streamOne, times(1)).write(2);
+ inOrderStreams.verify(streamOne, times(1)).write(3);
+ inOrderStreams.verify(streamOne, times(1)).write(4);
+ inOrderStreams.verify(streamOne, times(1)).write(0);
+ inOrderStreams.verify(streamOne, times(1)).write(1);
+ inOrderStreams.verify(streamOne, times(1)).write(9);
+ inOrderStreams.verify(streamOne, times(2)).flush();
+ inOrderStreams.verify(streamOne, times(1)).close();
}
@Test
public void testAddOneOutputStreamWhenEmpty() throws IOException {
- final Sequence seqStreamOne = mockContext.sequence("seqStreamOne");
- final OutputStream streamOne = mockContext.mock(OutputStream.class, "streamOne");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamOne).write(2);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(3);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(4);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(0);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(1);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(9);
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).close();
- inSequence(seqStreamOne);
- }
- });
-
+ final OutputStream streamOne = mock(OutputStream.class, "streamOne");
final CompositeOutputStream cos = new CompositeOutputStream();
-
- assertTrue(cos.isEmpty());
- assertEquals(0, cos.size());
-
+ assertThat(cos.isEmpty()).isTrue();
+ assertThat(cos.size()).isEqualTo(0);
cos.addOutputStream(streamOne);
- assertFalse(cos.isEmpty());
- assertEquals(1, cos.size());
-
+ assertThat(cos.isEmpty()).isFalse();
+ assertThat(cos.size()).isEqualTo(1);
cos.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
cos.write(new byte[] {0, 1});
cos.write(9);
cos.flush();
cos.close();
+
+ InOrder inOrderStreams = inOrder(streamOne);
+ inOrderStreams.verify(streamOne, times(1)).write(2);
+ inOrderStreams.verify(streamOne, times(1)).write(3);
+ inOrderStreams.verify(streamOne, times(1)).write(4);
+ inOrderStreams.verify(streamOne, times(1)).write(0);
+ inOrderStreams.verify(streamOne, times(1)).write(1);
+ inOrderStreams.verify(streamOne, times(1)).write(9);
+ inOrderStreams.verify(streamOne, times(2)).flush();
+ inOrderStreams.verify(streamOne, times(1)).close();
}
@Test
public void testAddTwoOutputStreamsWhenEmpty() throws IOException {
- final Sequence seqStreamOne = mockContext.sequence("seqStreamOne");
- final OutputStream streamOne = mockContext.mock(OutputStream.class, "streamOne");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamOne).write(2);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(3);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(4);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(0);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(1);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(9);
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).close();
- inSequence(seqStreamOne);
- }
- });
-
- final Sequence seqStreamTwo = mockContext.sequence("seqStreamTwo");
- final OutputStream streamTwo = mockContext.mock(OutputStream.class, "streamTwo");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamTwo).write(2);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(3);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(4);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(0);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(1);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).write(9);
- inSequence(seqStreamTwo);
- oneOf(streamTwo).flush();
- inSequence(seqStreamTwo);
- oneOf(streamTwo).flush();
- inSequence(seqStreamTwo);
- oneOf(streamTwo).close();
- inSequence(seqStreamTwo);
- }
- });
-
+ final OutputStream streamOne = mock(OutputStream.class, "streamOne");
+ final OutputStream streamTwo = mock(OutputStream.class, "streamTwo");
final CompositeOutputStream cos = new CompositeOutputStream();
-
- assertTrue(cos.isEmpty());
- assertEquals(0, cos.size());
-
+ assertThat(cos.isEmpty()).isTrue();
+ assertThat(cos.size()).isEqualTo(0);
cos.addOutputStream(streamOne);
cos.addOutputStream(streamTwo);
- assertFalse(cos.isEmpty());
- assertEquals(2, cos.size());
-
+ assertThat(cos.isEmpty()).isFalse();
+ assertThat(cos.size()).isEqualTo(2);
cos.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
cos.write(new byte[] {0, 1});
cos.write(9);
cos.flush();
cos.close();
+
+ InOrder inOrderStreams = inOrder(streamOne, streamTwo);
+ inOrderStreams.verify(streamOne, times(1)).write(2);
+ inOrderStreams.verify(streamOne, times(1)).write(3);
+ inOrderStreams.verify(streamOne, times(1)).write(4);
+ inOrderStreams.verify(streamOne, times(1)).write(0);
+ inOrderStreams.verify(streamOne, times(1)).write(1);
+ inOrderStreams.verify(streamOne, times(1)).write(9);
+ inOrderStreams.verify(streamOne, times(2)).flush();
+ inOrderStreams.verify(streamOne, times(1)).close();
}
@Test
public void testRemoveOutputStreamWithTwoStreams() throws IOException {
- final Sequence seqStreamOne = mockContext.sequence("seqStreamOne");
- final OutputStream streamOne = mockContext.mock(OutputStream.class, "streamOne");
- mockContext.checking(new Expectations() {
- {
- oneOf(streamOne).write(2);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(3);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(4);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(0);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(1);
- inSequence(seqStreamOne);
- oneOf(streamOne).write(9);
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).flush();
- inSequence(seqStreamOne);
- oneOf(streamOne).close();
- inSequence(seqStreamOne);
- }
- });
-
- final OutputStream streamTwo = mockContext.mock(OutputStream.class, "streamTwo");
- mockContext.checking(new Expectations() {
- {
- never(streamTwo).write(2);
- never(streamTwo).write(3);
- never(streamTwo).write(4);
- never(streamTwo).write(0);
- never(streamTwo).write(1);
- never(streamTwo).write(9);
- never(streamTwo).flush();
- never(streamTwo).flush();
- never(streamTwo).close();
- }
- });
-
+ final OutputStream streamOne = mock(OutputStream.class, "streamOne");
+ final OutputStream streamTwo = mock(OutputStream.class, "streamTwo");
final CompositeOutputStream cos = new CompositeOutputStream(streamOne, streamTwo);
-
- assertFalse(cos.isEmpty());
- assertEquals(2, cos.size());
-
+ assertThat(cos.isEmpty()).isFalse();
+ assertThat(cos.size()).isEqualTo(2);
cos.removeOutputStream(streamTwo);
-
- assertFalse(cos.isEmpty());
- assertEquals(1, cos.size());
-
+ assertThat(cos.isEmpty()).isFalse();
+ assertThat(cos.size()).isEqualTo(1);
cos.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
cos.write(new byte[] {0, 1});
cos.write(9);
cos.flush();
cos.close();
+
+ verifyZeroInteractions(streamTwo);
+ InOrder inOrderStreams = inOrder(streamOne);
+ inOrderStreams.verify(streamOne, times(1)).write(2);
+ inOrderStreams.verify(streamOne, times(1)).write(3);
+ inOrderStreams.verify(streamOne, times(1)).write(4);
+ inOrderStreams.verify(streamOne, times(1)).write(0);
+ inOrderStreams.verify(streamOne, times(1)).write(1);
+ inOrderStreams.verify(streamOne, times(1)).write(9);
+ inOrderStreams.verify(streamOne, times(2)).flush();
+ inOrderStreams.verify(streamOne, times(1)).close();
}
@Test
public void testRemoveOutputStreamWithOneStream() throws IOException {
- final OutputStream streamOne = mockContext.mock(OutputStream.class, "streamOne");
- mockContext.checking(new Expectations() {
- {
- never(streamOne).write(2);
- never(streamOne).write(3);
- never(streamOne).write(4);
- never(streamOne).write(0);
- never(streamOne).write(1);
- never(streamOne).write(9);
- never(streamOne).flush();
- never(streamOne).flush();
- never(streamOne).close();
- }
- });
-
+ final OutputStream streamOne = mock(OutputStream.class, "streamOne");
final CompositeOutputStream cos = new CompositeOutputStream(streamOne);
-
- assertFalse(cos.isEmpty());
- assertEquals(1, cos.size());
-
+ assertThat(cos.isEmpty()).isFalse();
+ assertThat(cos.size()).isEqualTo(1);
cos.removeOutputStream(streamOne);
-
- assertTrue(cos.isEmpty());
- assertEquals(0, cos.size());
-
+ assertThat(cos.isEmpty()).isTrue();
+ assertThat(cos.size()).isEqualTo(0);
cos.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
cos.write(new byte[] {0, 1});
cos.write(9);
cos.flush();
cos.close();
+
+ verifyZeroInteractions(streamOne);
}
@Test
public void testRemoveOutputStreamWhenEmpty() throws IOException {
- final OutputStream streamOne = mockContext.mock(OutputStream.class, "streamOne");
- mockContext.checking(new Expectations() {
- {
- never(streamOne).write(2);
- never(streamOne).write(3);
- never(streamOne).write(4);
- never(streamOne).write(0);
- never(streamOne).write(1);
- never(streamOne).write(9);
- never(streamOne).flush();
- never(streamOne).flush();
- never(streamOne).close();
- }
- });
-
+ final OutputStream streamOne = mock(OutputStream.class, "streamOne");
final CompositeOutputStream cos = new CompositeOutputStream();
-
- assertTrue(cos.isEmpty());
- assertEquals(0, cos.size());
-
+ assertThat(cos.isEmpty()).isTrue();
+ assertThat(cos.size()).isEqualTo(0);
cos.removeOutputStream(streamOne);
-
- assertTrue(cos.isEmpty());
- assertEquals(0, cos.size());
-
+ assertThat(cos.isEmpty()).isTrue();
+ assertThat(cos.size()).isEqualTo(0);
cos.write(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 3);
cos.write(new byte[] {0, 1});
cos.write(9);
cos.flush();
cos.close();
+
+ verifyZeroInteractions(streamOne);
}
}
diff --git a/geode-core/src/test/java/org/apache/geode/internal/net/SocketUtilsJUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/net/SocketUtilsJUnitTest.java
index 226eea4..a2fd131 100644
--- a/geode-core/src/test/java/org/apache/geode/internal/net/SocketUtilsJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/net/SocketUtilsJUnitTest.java
@@ -14,20 +14,17 @@
*/
package org.apache.geode.internal.net;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
-import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@@ -39,106 +36,56 @@ import org.apache.geode.test.junit.categories.MembershipTest;
* <p/>
*
* @see org.apache.geode.internal.net.SocketUtils
- * @see org.jmock.Expectations
- * @see org.jmock.Mockery
- * @see org.junit.Assert
* @see org.junit.Test
* @since GemFire 7.0
*/
-@Category({MembershipTest.class})
+@Category(MembershipTest.class)
public class SocketUtilsJUnitTest {
- private Mockery mockContext;
-
- @Before
- public void setup() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
- }
-
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- }
-
@Test
public void testCloseSocket() throws IOException {
- final Socket mockSocket = mockContext.mock(Socket.class, "closeSocketTest");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockSocket).close();
- }
- });
+ final Socket mockSocket = mock(Socket.class, "closeSocketTest");
+ doNothing().when(mockSocket).close();
- assertTrue(SocketUtils.close(mockSocket));
+ assertThat(SocketUtils.close(mockSocket)).isTrue();
+ verify(mockSocket, times(1)).close();
}
@Test
public void testCloseSocketThrowsIOException() throws IOException {
- final Socket mockSocket = mockContext.mock(Socket.class, "closeSocketThrowsIOExceptionTest");
+ final Socket mockSocket = mock(Socket.class, "closeSocketThrowsIOExceptionTest");
+ doThrow(new IOException("Mock Exception")).when(mockSocket).close();
- mockContext.checking(new Expectations() {
- {
- oneOf(mockSocket).close();
- will(throwException(new IOException("test")));
- }
- });
-
- try {
- assertFalse(SocketUtils.close(mockSocket));
- } catch (Throwable t) {
- fail(
- "Calling close on a Socket using SocketUtils threw an unexpected Throwable (" + t + ")!");
- }
+ assertThat(SocketUtils.close(mockSocket)).isFalse();
+ verify(mockSocket, times(1)).close();
}
@Test
public void testCloseSocketWithNull() {
- assertTrue(SocketUtils.close((Socket) null));
+ assertThat(SocketUtils.close((Socket) null)).isTrue();
}
@Test
public void testCloseServerSocket() throws IOException {
- final ServerSocket mockServerSocket =
- mockContext.mock(ServerSocket.class, "closeServerSocketTest");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockServerSocket).close();
- }
- });
+ final ServerSocket mockServerSocket = mock(ServerSocket.class, "closeServerSocketTest");
+ doNothing().when(mockServerSocket).close();
- assertTrue(SocketUtils.close(mockServerSocket));
+ assertThat(SocketUtils.close(mockServerSocket)).isTrue();
+ verify(mockServerSocket, times(1)).close();
}
@Test
public void testCloseServerSocketThrowsIOException() throws IOException {
final ServerSocket mockServerSocket =
- mockContext.mock(ServerSocket.class, "closeServerSocketThrowsIOExceptionTest");
+ mock(ServerSocket.class, "closeServerSocketThrowsIOExceptionTest");
+ doThrow(new IOException("Mock Exception")).when(mockServerSocket).close();
- mockContext.checking(new Expectations() {
- {
- oneOf(mockServerSocket).close();
- will(throwException(new IOException("test")));
- }
- });
-
- try {
- assertFalse(SocketUtils.close(mockServerSocket));
- } catch (Throwable t) {
- fail("Calling close on a ServerSocket using SocketUtils threw an unexpected Throwable (" + t
- + ")!");
- }
+ assertThat(SocketUtils.close(mockServerSocket)).isFalse();
+ verify(mockServerSocket, times(1)).close();
}
@Test
public void testCloseServerSocketWithNull() {
- assertTrue(SocketUtils.close((ServerSocket) null));
+ assertThat(SocketUtils.close((ServerSocket) null)).isTrue();
}
-
}
diff --git a/geode-core/src/test/java/org/apache/geode/internal/util/IOUtilsJUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/util/IOUtilsJUnitTest.java
index a396aa9..62b31c7 100644
--- a/geode-core/src/test/java/org/apache/geode/internal/util/IOUtilsJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/util/IOUtilsJUnitTest.java
@@ -14,12 +14,15 @@
*/
package org.apache.geode.internal.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
@@ -30,13 +33,9 @@ import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Calendar;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
-import org.junit.Before;
import org.junit.Test;
+import org.mockito.InOrder;
+import org.mockito.Mockito;
/**
@@ -44,31 +43,10 @@ import org.junit.Test;
* <p/>
*
* @see org.apache.geode.internal.util.IOUtils
- * @see org.jmock.Expectations
- * @see org.jmock.Mockery
- * @see org.junit.Assert
* @see org.junit.Test
*/
public class IOUtilsJUnitTest {
- private Mockery mockContext;
-
- @Before
- public void setup() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
- }
-
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
- }
-
/**
* Gets a fully-qualified path anchored at root.
* <p/>
@@ -91,239 +69,161 @@ public class IOUtilsJUnitTest {
@Test
public void testAppendToPath() {
- assertEquals(null, IOUtils.appendToPath(null, (String[]) null));
- assertEquals(File.separator, IOUtils.appendToPath(null));
- assertEquals(File.separator, IOUtils.appendToPath(""));
- assertEquals(File.separator, IOUtils.appendToPath(" "));
- assertEquals(File.separator, IOUtils.appendToPath(File.separator));
- assertEquals(toPathname("bin", "a.out"), IOUtils.appendToPath(null, "bin", "a.out"));
- assertEquals(toPathname("bin", "a.out"), IOUtils.appendToPath(File.separator, "bin", "a.out"));
- assertEquals(toPathname("usr", "local", "bin", "a.out"),
- IOUtils.appendToPath(toPathname("usr", "local"), "bin", "a.out"));
+ assertThat(IOUtils.appendToPath(null, (String[]) null)).isNull();
+ assertThat(IOUtils.appendToPath(null)).isEqualTo(File.separator);
+ assertThat(IOUtils.appendToPath("")).isEqualTo(File.separator);
+ assertThat(IOUtils.appendToPath(" ")).isEqualTo(File.separator);
+ assertThat(IOUtils.appendToPath(File.separator)).isEqualTo(File.separator);
+ assertThat(IOUtils.appendToPath(null, "bin", "a.out")).isEqualTo(toPathname("bin", "a.out"));
+ assertThat(IOUtils.appendToPath(File.separator, "bin", "a.out"))
+ .isEqualTo(toPathname("bin", "a.out"));
+ assertThat(IOUtils.appendToPath(toPathname("usr", "local"), "bin", "a.out"))
+ .isEqualTo(toPathname("usr", "local", "bin", "a.out"));
}
@Test
public void testClose() throws IOException {
- final Closeable mockCloseable = mockContext.mock(Closeable.class, "Closeable");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCloseable).close();
- }
- });
-
+ final Closeable mockCloseable = spy(Closeable.class);
IOUtils.close(mockCloseable);
+ verify(mockCloseable, times(1)).close();
}
@Test
public void testCloseIgnoresIOException() throws IOException {
- final Closeable mockCloseable = mockContext.mock(Closeable.class, "Closeable");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCloseable).close();
- will(throwException(new IOException("test")));
- }
- });
-
- try {
- IOUtils.close(mockCloseable);
- } catch (Throwable unexpected) {
- if (unexpected instanceof IOException) {
- fail("Calling close on a Closeable object unexpectedly threw an IOException!");
- }
- }
+ final Closeable mockCloseable = mock(Closeable.class);
+ doThrow(new IOException("Mock Exception")).when(mockCloseable).close();
+ IOUtils.close(mockCloseable);
}
@Test
public void testCreatePath() {
- assertEquals("", IOUtils.createPath());
- assertEquals("/path/to/file.test".replace("/", File.separator),
- IOUtils.createPath("path", "to", "file.test"));
- assertEquals("/path/to/a/directory".replace("/", File.separator),
- IOUtils.createPath("path", "to", "a", "directory"));
+ assertThat(IOUtils.createPath()).isEqualTo("");
+ assertThat(IOUtils.createPath("path", "to", "file.test"))
+ .isEqualTo("/path/to/file.test".replace("/", File.separator));
+ assertThat(IOUtils.createPath("path", "to", "a", "directory"))
+ .isEqualTo("/path/to/a/directory".replace("/", File.separator));
}
@Test
public void testCreatePathWithSeparator() {
- assertEquals("", IOUtils.createPath(new String[0], "-"));
- assertEquals("-path-to-file.ext".replace("/", File.separator),
- IOUtils.createPath(new String[] {"path", "to", "file.ext"}, "-"));
- assertEquals("-path-to-a-directory",
- IOUtils.createPath(new String[] {"path", "to", "a", "directory"}, "-"));
+ assertThat(IOUtils.createPath(new String[0], "-")).isEqualTo("");
+ assertThat(IOUtils.createPath(new String[] {"path", "to", "file.ext"}, "-"))
+ .isEqualTo("-path-to-file.ext".replace("/", File.separator));
+ assertThat(IOUtils.createPath(new String[] {"path", "to", "a", "directory"}, "-"))
+ .isEqualTo("-path-to-a-directory");
}
@Test
public void testGetFilename() {
- assertNull(IOUtils.getFilename(null));
- assertEquals("", IOUtils.getFilename(""));
- assertEquals(" ", IOUtils.getFilename(" "));
- assertEquals("", IOUtils.getFilename(File.separator));
- assertEquals("a.ext", IOUtils.getFilename("a.ext"));
- assertEquals("b.ext", IOUtils.getFilename(toPathname("b.ext")));
- assertEquals("c.ext", IOUtils.getFilename(toPathname("path", "to", "c.ext")));
- assertEquals("filename.ext",
- IOUtils.getFilename(toPathname("export", "path", "to", "some", "filename.ext")));
- assertEquals("",
- IOUtils.getFilename(toPathname("path", "to", "a", "directory") + File.separator));
+ assertThat(IOUtils.getFilename(null)).isNull();
+ assertThat(IOUtils.getFilename("")).isEqualTo("");
+ assertThat(IOUtils.getFilename(" ")).isEqualTo(" ");
+ assertThat(IOUtils.getFilename(File.separator)).isEqualTo("");
+ assertThat(IOUtils.getFilename("a.ext")).isEqualTo("a.ext");
+ assertThat(IOUtils.getFilename(toPathname("b.ext"))).isEqualTo("b.ext");
+ assertThat(IOUtils.getFilename(toPathname("path", "to", "c.ext"))).isEqualTo("c.ext");
+ assertThat(IOUtils.getFilename(toPathname("export", "path", "to", "some", "filename.ext")))
+ .isEqualTo("filename.ext");
+ assertThat(IOUtils.getFilename(toPathname("path", "to", "a", "directory") + File.separator))
+ .isEqualTo("");
}
@Test
public void testIsExistingPathname() {
- assertTrue(IOUtils.isExistingPathname(System.getProperty("java.home")));
- assertTrue(IOUtils.isExistingPathname(System.getProperty("user.home")));
- assertFalse(IOUtils.isExistingPathname("/path/to/non_existing/directory/"));
- assertFalse(IOUtils.isExistingPathname("/path/to/non_existing/file.ext"));
+ assertThat(IOUtils.isExistingPathname(System.getProperty("java.home"))).isTrue();
+ assertThat(IOUtils.isExistingPathname(System.getProperty("user.home"))).isTrue();
+ assertThat(IOUtils.isExistingPathname("/path/to/non_existing/directory/")).isFalse();
+ assertThat(IOUtils.isExistingPathname("/path/to/non_existing/file.ext")).isFalse();
}
@Test
public void testObjectSerialization() throws IOException, ClassNotFoundException {
final Calendar now = Calendar.getInstance();
-
- assertNotNull(now);
+ assertThat(now).isNotNull();
final byte[] nowBytes = IOUtils.serializeObject(now);
-
- assertNotNull(nowBytes);
- assertTrue(nowBytes.length != 0);
+ assertThat(nowBytes).isNotNull();
+ assertThat(nowBytes.length != 0).isTrue();
final Object nowObj = IOUtils.deserializeObject(nowBytes);
-
- assertTrue(nowObj instanceof Calendar);
- assertEquals(now.getTimeInMillis(), ((Calendar) nowObj).getTimeInMillis());
+ assertThat(nowObj).isInstanceOf(Calendar.class);
+ assertThat(((Calendar) nowObj).getTimeInMillis()).isEqualTo(now.getTimeInMillis());
}
@Test
public void testObjectSerializationWithClassLoader() throws IOException, ClassNotFoundException {
final BigDecimal pi = new BigDecimal(Math.PI);
-
final byte[] piBytes = IOUtils.serializeObject(pi);
- assertNotNull(piBytes);
- assertTrue(piBytes.length != 0);
+ assertThat(piBytes).isNotNull();
+ assertThat(piBytes.length != 0).isTrue();
final Object piObj =
IOUtils.deserializeObject(piBytes, IOUtilsJUnitTest.class.getClassLoader());
-
- assertTrue(piObj instanceof BigDecimal);
- assertEquals(pi, piObj);
+ assertThat(piObj).isInstanceOf(BigDecimal.class);
+ assertThat(piObj).isEqualTo(pi);
}
@Test
public void testToByteArray() throws IOException {
final byte[] expected = new byte[] {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE};
-
final byte[] actual = IOUtils.toByteArray(new ByteArrayInputStream(expected));
- assertNotNull(actual);
- assertEquals(expected.length, actual.length);
-
- for (int index = 0; index < actual.length; index++) {
- assertEquals(expected[index], actual[index]);
- }
+ assertThat(actual).isNotNull();
+ assertThat(actual.length).isEqualTo(expected.length);
+ assertThat(actual).isEqualTo(expected);
}
- @Test(expected = IOException.class)
+ @Test
public void testToByteArrayThrowsIOException() throws IOException {
- final InputStream mockIn =
- mockContext.mock(InputStream.class, "testToByteArrayThrowsIOException");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockIn).read(with(aNonNull(byte[].class)));
- will(throwException(new IOException("test")));
- oneOf(mockIn).close();
- }
- });
-
- IOUtils.toByteArray(mockIn);
+ final InputStream mockIn = mock(InputStream.class, "testToByteArrayThrowsIOException");
+ when(mockIn.read(any())).thenThrow(new IOException("Mock IOException"));
+ assertThatThrownBy(() -> IOUtils.toByteArray(mockIn)).isInstanceOf(IOException.class)
+ .hasMessage("Mock IOException");
}
- @Test(expected = AssertionError.class)
- public void testToByteArrayWithNull() throws IOException {
- try {
- IOUtils.toByteArray(null);
- } catch (AssertionError expected) {
- assertEquals("The input stream to read bytes from cannot be null!", expected.getMessage());
- throw expected;
- }
+ @Test
+ public void testToByteArrayWithNull() {
+ assertThatThrownBy(() -> IOUtils.toByteArray(null)).isInstanceOf(AssertionError.class)
+ .hasMessage("The input stream to read bytes from cannot be null!");
}
@Test
- public void testTryGetCanonicalFileElseGetAbsoluteFile() throws Exception {
- final MockFile file = (MockFile) IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(
- new MockFile("/path/to/non_existing/file.test", null));
+ public void testTryGetCanonicalFileElseGetAbsoluteFile() throws IOException {
+ final File mockFile = mock(File.class);
+ when(mockFile.getCanonicalFile()).thenReturn(mock(File.class));
+ final File file = IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(mockFile);
- assertNotNull(file);
- assertFalse(file.exists());
- assertTrue(file.isGetCanonicalFileCalled());
- assertFalse(file.isGetAbsoluteFileCalled());
+ assertThat(file).isNotNull();
+ assertThat(file.exists()).isFalse();
+ verify(mockFile, times(1)).getCanonicalFile();
+ verify(mockFile, times(0)).getAbsoluteFile();
}
@Test
- public void testTryGetCanonicalFileElseGetAbsoluteFileHandlesIOException() throws Exception {
- final MockFile file = (MockFile) IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(
- new MockFile(System.getProperty("user.home"), new IOException("test")));
+ public void testTryGetCanonicalFileElseGetAbsoluteFileHandlesIOException() throws IOException {
+ final File mockFile = mock(File.class);
+ when(mockFile.getAbsoluteFile()).thenReturn(mock(File.class));
+ when(mockFile.getCanonicalFile()).thenThrow(new IOException("Mock Exception"));
+ final File file = IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(mockFile);
- assertNotNull(file);
- assertTrue(file.exists());
- assertTrue(file.isGetCanonicalFileCalled());
- assertTrue(file.isGetAbsoluteFileCalled());
+ assertThat(file).isNotNull();
+ assertThat(file.exists()).isFalse();
+ InOrder inOrder = Mockito.inOrder(mockFile);
+ inOrder.verify(mockFile).getCanonicalFile();
+ inOrder.verify(mockFile).getAbsoluteFile();
}
@Test
public void testVerifyPathnameExists() throws FileNotFoundException {
- assertEquals(System.getProperty("java.io.tmpdir"),
- IOUtils.verifyPathnameExists(System.getProperty("java.io.tmpdir")));
- }
-
- @Test(expected = FileNotFoundException.class)
- public void testVerifyPathnameExistsWithNonExistingPathname() throws FileNotFoundException {
- try {
- IOUtils.verifyPathnameExists("/path/to/non_existing/file.test");
- } catch (FileNotFoundException expected) {
- assertEquals("Pathname (/path/to/non_existing/file.test) could not be found!",
- expected.getMessage());
- throw expected;
- }
+ assertThat(System.getProperty("java.io.tmpdir"))
+ .isEqualTo(IOUtils.verifyPathnameExists(System.getProperty("java.io.tmpdir")));
}
- private static class MockFile extends File {
-
- private boolean isGetAbsoluteFileCalled = false;
- private boolean isGetCanonicalFileCalled = false;
-
- private final IOException e;
-
- public MockFile(final String pathname, IOException e) {
- super(pathname);
- this.e = e;
- }
-
- @Override
- public File getAbsoluteFile() {
- isGetAbsoluteFileCalled = true;
- return this;
- }
-
- protected boolean isGetAbsoluteFileCalled() {
- return isGetAbsoluteFileCalled;
- }
-
- @Override
- public File getCanonicalFile() throws IOException {
- isGetCanonicalFileCalled = true;
-
- if (e != null) {
- throw e;
- }
-
- return this;
- }
-
- protected boolean isGetCanonicalFileCalled() {
- return isGetCanonicalFileCalled;
- }
+ @Test
+ public void testVerifyPathnameExistsWithNonExistingPathname() {
+ assertThatThrownBy(() -> IOUtils.verifyPathnameExists("/path/to/non_existing/file.test"))
+ .isInstanceOf(FileNotFoundException.class)
+ .hasMessage("Pathname (/path/to/non_existing/file.test) could not be found!");
}
-
}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/JettyHelperJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/JettyHelperJUnitTest.java
index 2ea00a7..7ecc227 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/JettyHelperJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/JettyHelperJUnitTest.java
@@ -14,9 +14,7 @@
*/
package org.apache.geode.management.internal;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
import java.util.Properties;
@@ -26,7 +24,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import org.apache.geode.GemFireConfigException;
+import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.distributed.internal.DistributionConfigImpl;
import org.apache.geode.internal.net.SSLConfigurationFactory;
import org.apache.geode.internal.security.SecurableCommunicationChannel;
@@ -36,15 +34,15 @@ import org.apache.geode.internal.security.SecurableCommunicationChannel;
* functionality of the JettyHelper class. Does not start Jetty.
*
* @see org.apache.geode.management.internal.JettyHelper
- * @see org.jmock.Mockery
- * @see org.junit.Assert
* @see org.junit.Test
*/
public class JettyHelperJUnitTest {
+ private DistributionConfig distributionConfig;
@Before
public void setup() {
- SSLConfigurationFactory.setDistributionConfig(new DistributionConfigImpl(new Properties()));
+ distributionConfig = new DistributionConfigImpl(new Properties());
+ SSLConfigurationFactory.setDistributionConfig(distributionConfig);
}
@After
@@ -53,31 +51,20 @@ public class JettyHelperJUnitTest {
}
@Test
- public void testSetPortNoBindAddress() throws Exception {
-
- final Server jetty;
- try {
- jetty = JettyHelper.initJetty(null, 8090,
- SSLConfigurationFactory.getSSLConfigForComponent(SecurableCommunicationChannel.WEB));
- assertNotNull(jetty);
- assertNotNull(jetty.getConnectors()[0]);
- assertEquals(8090, ((ServerConnector) jetty.getConnectors()[0]).getPort());
- } catch (GemFireConfigException e) {
- fail(e.getMessage());
- }
+ public void testSetPortNoBindAddress() {
+ final Server jetty = JettyHelper.initJetty(null, 8090, SSLConfigurationFactory
+ .getSSLConfigForComponent(distributionConfig, SecurableCommunicationChannel.WEB));
+ assertThat(jetty).isNotNull();
+ assertThat(jetty.getConnectors()[0]).isNotNull();
+ assertThat(((ServerConnector) jetty.getConnectors()[0]).getPort()).isEqualTo(8090);
}
@Test
- public void testSetPortWithBindAddress() throws Exception {
- try {
- final Server jetty = JettyHelper.initJetty("10.123.50.1", 10480,
- SSLConfigurationFactory.getSSLConfigForComponent(SecurableCommunicationChannel.WEB));
-
- assertNotNull(jetty);
- assertNotNull(jetty.getConnectors()[0]);
- assertEquals(10480, ((ServerConnector) jetty.getConnectors()[0]).getPort());
- } catch (GemFireConfigException e) {
- fail(e.getMessage());
- }
+ public void testSetPortWithBindAddress() {
+ final Server jetty = JettyHelper.initJetty("10.123.50.1", 10480, SSLConfigurationFactory
+ .getSSLConfigForComponent(distributionConfig, SecurableCommunicationChannel.WEB));
+ assertThat(jetty).isNotNull();
+ assertThat(jetty.getConnectors()[0]).isNotNull();
+ assertThat(((ServerConnector) jetty.getConnectors()[0]).getPort()).isEqualTo(10480);
}
}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
index 7cee1b8..a2cc227 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
@@ -14,10 +14,16 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
@@ -25,17 +31,10 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
-import org.junit.Assert;
+import org.assertj.core.api.AssertionsForClassTypes;
import org.junit.Before;
import org.junit.Test;
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.FunctionInvocationTargetException;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.distributed.DistributedMember;
@@ -54,46 +53,44 @@ import org.apache.geode.management.internal.cli.i18n.CliStrings;
* GemFire shell (gfsh) that access and modify disk stores in GemFire.
*
* @see org.apache.geode.management.internal.cli.commands.DescribeDiskStoreCommand
- * @see ListDiskStoresCommand
+ * @see org.apache.geode.management.internal.cli.commands.ListDiskStoresCommand
* @see org.apache.geode.management.internal.cli.domain.DiskStoreDetails
* @see org.apache.geode.management.internal.cli.functions.DescribeDiskStoreFunction
* @see org.apache.geode.management.internal.cli.functions.ListDiskStoresFunction
- * @see org.jmock.Expectations
- * @see org.jmock.Mockery
- * @see org.jmock.lib.legacy.ClassImposteriser
- * @see org.junit.Assert
* @see org.junit.Test
*
* @since GemFire 7.0
*/
public class DiskStoreCommandsJUnitTest {
-
- private Mockery mockContext;
+ private AbstractExecution mockFunctionExecutor;
+ private ResultCollector mockResultCollector;
+ private DistributedMember mockDistributedMember;
+ private ListDiskStoresCommand listDiskStoresCommand;
+ private DescribeDiskStoreCommand describeDiskStoreCommand;
@Before
+ @SuppressWarnings("unchecked")
public void setUp() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
- }
-
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
- }
-
- private DescribeDiskStoreCommand createDescribeDiskStoreCommand(final InternalCache cache,
- final DistributedMember distributedMember, final Execution functionExecutor) {
- return new TestDescribeDiskStoreCommand(cache, distributedMember, functionExecutor);
- }
-
- private ListDiskStoresCommand createListDiskStoreCommand(final InternalCache cache,
- final DistributedMember distributedMember, final Execution functionExecutor) {
- return new TestListDiskStoresCommand(cache, distributedMember, functionExecutor);
+ listDiskStoresCommand = spy(ListDiskStoresCommand.class);
+ describeDiskStoreCommand = spy(DescribeDiskStoreCommand.class);
+ InternalCache mockCache = mock(InternalCache.class, "InternalCache");
+ mockResultCollector = mock(ResultCollector.class, "ResultCollector");
+ mockFunctionExecutor = mock(AbstractExecution.class, "Function Executor");
+ mockDistributedMember = mock(DistributedMember.class, "DistributedMember");
+
+ when(mockFunctionExecutor.setArguments(any())).thenReturn(mockFunctionExecutor);
+
+ when(listDiskStoresCommand.getCache()).thenReturn(mockCache);
+ doReturn(mockDistributedMember).when(listDiskStoresCommand).getMember(anyString());
+ doReturn(Collections.singleton(mockDistributedMember)).when(listDiskStoresCommand)
+ .getAllMembers();
+ doReturn(mockFunctionExecutor).when(listDiskStoresCommand).getMembersFunctionExecutor(any());
+
+ when(describeDiskStoreCommand.getCache()).thenReturn(mockCache);
+ doReturn(mockDistributedMember).when(describeDiskStoreCommand).getMember(anyString());
+ doReturn(Collections.singleton(mockDistributedMember)).when(describeDiskStoreCommand)
+ .getAllMembers();
+ doReturn(mockFunctionExecutor).when(describeDiskStoreCommand).getMembersFunctionExecutor(any());
}
private DiskStoreDetails createDiskStoreDetails(final String memberId,
@@ -103,339 +100,112 @@ public class DiskStoreCommandsJUnitTest {
@Test
public void testGetDiskStoreDescription() {
- final String diskStoreName = "mockDiskStore";
final String memberId = "mockMember";
-
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final DistributedMember mockMember =
- mockContext.mock(DistributedMember.class, "DistributedMember");
-
- final Execution mockFunctionExecutor = mockContext.mock(Execution.class, "Function Executor");
-
- final ResultCollector mockResultCollector =
- mockContext.mock(ResultCollector.class, "ResultCollector");
-
+ final String diskStoreName = "mockDiskStore";
final DiskStoreDetails expectedDiskStoredDetails =
createDiskStoreDetails(memberId, diskStoreName);
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).setArguments(with(equal(diskStoreName)));
- will(returnValue(mockFunctionExecutor));
- oneOf(mockFunctionExecutor).execute(with(aNonNull(DescribeDiskStoreFunction.class)));
- will(returnValue(mockResultCollector));
- oneOf(mockResultCollector).getResult();
- will(returnValue(Collections.singletonList(expectedDiskStoredDetails)));
- }
- });
-
- final DescribeDiskStoreCommand describeCommand =
- createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
+ when(mockFunctionExecutor.execute(any(DescribeDiskStoreFunction.class)))
+ .thenReturn(mockResultCollector);
+ when(mockResultCollector.getResult())
+ .thenReturn(Collections.singletonList(expectedDiskStoredDetails));
final DiskStoreDetails actualDiskStoreDetails =
- describeCommand.getDiskStoreDescription(memberId, diskStoreName);
-
- assertNotNull(actualDiskStoreDetails);
- assertEquals(expectedDiskStoredDetails, actualDiskStoreDetails);
+ describeDiskStoreCommand.getDiskStoreDescription(memberId, diskStoreName);
+ AssertionsForClassTypes.assertThat(actualDiskStoreDetails).isNotNull();
+ AssertionsForClassTypes.assertThat(actualDiskStoreDetails).isEqualTo(expectedDiskStoredDetails);
}
- @Test(expected = EntityNotFoundException.class)
+ @Test
public void testGetDiskStoreDescriptionThrowsEntityNotFoundException() {
- final String diskStoreName = "mockDiskStore";
final String memberId = "mockMember";
+ final String diskStoreName = "mockDiskStore";
+ when(mockFunctionExecutor.execute(any(DescribeDiskStoreFunction.class)))
+ .thenThrow(new EntityNotFoundException("Mock Exception"));
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final DistributedMember mockMember =
- mockContext.mock(DistributedMember.class, "DistributedMember");
-
- final Execution mockFunctionExecutor = mockContext.mock(Execution.class, "Function Executor");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).setArguments(with(equal(diskStoreName)));
- will(returnValue(mockFunctionExecutor));
- oneOf(mockFunctionExecutor).execute(with(aNonNull(DescribeDiskStoreFunction.class)));
- will(throwException(new EntityNotFoundException("expected")));
- }
- });
-
- final DescribeDiskStoreCommand describeCommand =
- createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
-
- try {
- describeCommand.getDiskStoreDescription(memberId, diskStoreName);
- } catch (EntityNotFoundException expected) {
- assertEquals("expected", expected.getMessage());
- throw expected;
- }
+ assertThatThrownBy(
+ () -> describeDiskStoreCommand.getDiskStoreDescription(memberId, diskStoreName))
+ .isInstanceOf(EntityNotFoundException.class).hasMessage("Mock Exception");
}
- @Test(expected = RuntimeException.class)
+ @Test
public void testGetDiskStoreDescriptionThrowsRuntimeException() {
- final String diskStoreName = "mockDiskStore";
final String memberId = "mockMember";
+ final String diskStoreName = "mockDiskStore";
+ when(mockFunctionExecutor.execute(any(DescribeDiskStoreFunction.class)))
+ .thenThrow(new RuntimeException("Mock Exception"));
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final DistributedMember mockMember =
- mockContext.mock(DistributedMember.class, "DistributedMember");
-
- final Execution mockFunctionExecutor = mockContext.mock(Execution.class, "Function Executor");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).setArguments(with(equal(diskStoreName)));
- will(returnValue(mockFunctionExecutor));
- oneOf(mockFunctionExecutor).execute(with(aNonNull(DescribeDiskStoreFunction.class)));
- will(throwException(new RuntimeException("expected")));
- }
- });
-
- final DescribeDiskStoreCommand describeCommand =
- createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
-
- try {
- describeCommand.getDiskStoreDescription(memberId, diskStoreName);
- } catch (RuntimeException expected) {
- assertEquals("expected", expected.getMessage());
- throw expected;
- }
+ assertThatThrownBy(
+ () -> describeDiskStoreCommand.getDiskStoreDescription(memberId, diskStoreName))
+ .isInstanceOf(RuntimeException.class).hasMessage("Mock Exception");
}
- @Test(expected = RuntimeException.class)
+ @Test
public void testGetDiskStoreDescriptionWithInvalidFunctionResultReturnType() {
- final String diskStoreName = "mockDiskStore";
final String memberId = "mockMember";
-
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final DistributedMember mockMember =
- mockContext.mock(DistributedMember.class, "DistributedMember");
-
- final Execution mockFunctionExecutor = mockContext.mock(Execution.class, "Function Executor");
-
- final ResultCollector mockResultCollector =
- mockContext.mock(ResultCollector.class, "ResultCollector");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).setArguments(with(equal(diskStoreName)));
- will(returnValue(mockFunctionExecutor));
- oneOf(mockFunctionExecutor).execute(with(aNonNull(DescribeDiskStoreFunction.class)));
- will(returnValue(mockResultCollector));
- oneOf(mockResultCollector).getResult();
- will(returnValue(Collections.singletonList(new Object())));
- }
- });
-
- final DescribeDiskStoreCommand describeCommand =
- createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
-
- try {
- describeCommand.getDiskStoreDescription(memberId, diskStoreName);
- } catch (RuntimeException expected) {
- assertEquals(
- CliStrings.format(CliStrings.UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE,
- Object.class.getName(), CliStrings.DESCRIBE_DISK_STORE),
- expected.getMessage());
- assertNull(expected.getCause());
- throw expected;
- }
+ final String diskStoreName = "mockDiskStore";
+ when(mockFunctionExecutor.execute(any(DescribeDiskStoreFunction.class)))
+ .thenReturn(mockResultCollector);
+ when(mockResultCollector.getResult()).thenReturn(Collections.singletonList(new Object()));
+
+ assertThatThrownBy(
+ () -> describeDiskStoreCommand.getDiskStoreDescription(memberId, diskStoreName))
+ .isInstanceOf(RuntimeException.class).hasNoCause().hasMessage(
+ CliStrings.format(CliStrings.UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE,
+ Object.class.getName(), CliStrings.DESCRIBE_DISK_STORE));
}
@Test
public void testGetDiskStoreList() {
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final DistributedMember mockDistributedMember =
- mockContext.mock(DistributedMember.class, "DistributedMember");
-
- final AbstractExecution mockFunctionExecutor =
- mockContext.mock(AbstractExecution.class, "Function Executor");
-
- final ResultCollector mockResultCollector =
- mockContext.mock(ResultCollector.class, "ResultCollector");
-
final DiskStoreDetails diskStoreDetails1 =
- createDiskStoreDetails("memberOne", "cacheServerDiskStore");
+ createDiskStoreDetails("memberOne", "cacheServer1DiskStore1");
final DiskStoreDetails diskStoreDetails2 =
- createDiskStoreDetails("memberOne", "gatewayDiskStore");
- final DiskStoreDetails diskStoreDetails3 = createDiskStoreDetails("memberTwo", "pdxDiskStore");
+ createDiskStoreDetails("memberOne", "cacheServer1DiskStore2");
+ final DiskStoreDetails diskStoreDetails3 =
+ createDiskStoreDetails("memberTwo", "cacheServer2DiskStore1");
final DiskStoreDetails diskStoreDetails4 =
- createDiskStoreDetails("memberTwo", "regionDiskStore");
-
+ createDiskStoreDetails("memberTwo", "cacheServer2DiskStore2");
final List<DiskStoreDetails> expectedDiskStores =
Arrays.asList(diskStoreDetails1, diskStoreDetails2, diskStoreDetails3, diskStoreDetails4);
-
final List<Set<DiskStoreDetails>> results = new ArrayList<>();
-
- results.add(CollectionUtils.asSet(diskStoreDetails4, diskStoreDetails3));
results.add(CollectionUtils.asSet(diskStoreDetails1, diskStoreDetails2));
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
- oneOf(mockFunctionExecutor).execute(with(aNonNull(ListDiskStoresFunction.class)));
- will(returnValue(mockResultCollector));
- oneOf(mockResultCollector).getResult();
- will(returnValue(results));
- }
- });
-
- final ListDiskStoresCommand listCommand =
- createListDiskStoreCommand(mockCache, mockDistributedMember, mockFunctionExecutor);
+ results.add(CollectionUtils.asSet(diskStoreDetails4, diskStoreDetails3));
+ when(mockFunctionExecutor.execute(any(ListDiskStoresFunction.class)))
+ .thenReturn(mockResultCollector);
+ when(mockResultCollector.getResult()).thenReturn(results);
final List<DiskStoreDetails> actualDiskStores =
- listCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
-
- Assert.assertNotNull(actualDiskStores);
- assertEquals(expectedDiskStores, actualDiskStores);
+ listDiskStoresCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
+ assertThat(actualDiskStores).isNotNull();
+ assertThat(actualDiskStores).isEqualTo(expectedDiskStores);
+ verify(mockFunctionExecutor, times(1)).setIgnoreDepartedMembers(true);
}
- @Test(expected = RuntimeException.class)
+ @Test
public void testGetDiskStoreListThrowsRuntimeException() {
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final DistributedMember mockDistributedMember =
- mockContext.mock(DistributedMember.class, "DistributedMember");
-
- final Execution mockFunctionExecutor = mockContext.mock(Execution.class, "Function Executor");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).execute(with(aNonNull(ListDiskStoresFunction.class)));
- will(throwException(new RuntimeException("expected")));
- }
- });
+ when(mockFunctionExecutor.execute(any(ListDiskStoresFunction.class)))
+ .thenThrow(new RuntimeException("Expected Exception"));
- final ListDiskStoresCommand listCommand =
- createListDiskStoreCommand(mockCache, mockDistributedMember, mockFunctionExecutor);
-
- try {
- listCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
- } catch (RuntimeException expected) {
- assertEquals("expected", expected.getMessage());
- throw expected;
- }
+ assertThatThrownBy(() -> listDiskStoresCommand
+ .getDiskStoreListing(Collections.singleton(mockDistributedMember)))
+ .isInstanceOf(RuntimeException.class).hasMessage("Expected Exception");
}
@Test
public void testGetDiskStoreListReturnsFunctionInvocationTargetExceptionInResults() {
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final DistributedMember mockDistributedMember =
- mockContext.mock(DistributedMember.class, "DistributedMember");
-
- final AbstractExecution mockFunctionExecutor =
- mockContext.mock(AbstractExecution.class, "Function Executor");
-
- final ResultCollector mockResultCollector =
- mockContext.mock(ResultCollector.class, "ResultCollector");
-
final DiskStoreDetails diskStoreDetails =
createDiskStoreDetails("memberOne", "cacheServerDiskStore");
-
final List<DiskStoreDetails> expectedDiskStores = Collections.singletonList(diskStoreDetails);
-
final List<Object> results = new ArrayList<>();
-
results.add(CollectionUtils.asSet(diskStoreDetails));
results.add(new FunctionInvocationTargetException("expected"));
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
- oneOf(mockFunctionExecutor).execute(with(aNonNull(ListDiskStoresFunction.class)));
- will(returnValue(mockResultCollector));
- oneOf(mockResultCollector).getResult();
- will(returnValue(results));
- }
- });
-
- final ListDiskStoresCommand listCommand =
- createListDiskStoreCommand(mockCache, mockDistributedMember, mockFunctionExecutor);
+ when(mockFunctionExecutor.execute(any(ListDiskStoresFunction.class)))
+ .thenReturn(mockResultCollector);
+ when(mockResultCollector.getResult()).thenReturn(results);
final List<DiskStoreDetails> actualDiskStores =
- listCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
-
- Assert.assertNotNull(actualDiskStores);
- assertEquals(expectedDiskStores, actualDiskStores);
- }
-
- private static class TestDescribeDiskStoreCommand extends DescribeDiskStoreCommand {
-
- private final InternalCache cache;
- private final DistributedMember distributedMember;
- private final Execution functionExecutor;
-
- TestDescribeDiskStoreCommand(final InternalCache cache,
- final DistributedMember distributedMember, final Execution functionExecutor) {
- assert cache != null : "The Cache cannot be null!";
- this.cache = cache;
- this.distributedMember = distributedMember;
- this.functionExecutor = functionExecutor;
- }
-
- @Override
- public Cache getCache() {
- return this.cache;
- }
-
- @Override
- public Set<DistributedMember> getAllMembers() {
- assertSame(getCache(), cache);
- return Collections.singleton(this.distributedMember);
- }
-
- @Override
- public DistributedMember getMember(String nameOrId) {
- assertSame(getCache(), cache);
- return this.distributedMember;
- }
-
- @Override
- public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
- Assert.assertNotNull(members);
- return this.functionExecutor;
- }
- }
-
- private static class TestListDiskStoresCommand extends ListDiskStoresCommand {
- private final InternalCache cache;
- private final DistributedMember distributedMember;
- private final Execution functionExecutor;
-
- TestListDiskStoresCommand(final InternalCache cache, final DistributedMember distributedMember,
- final Execution functionExecutor) {
- assert cache != null : "The Cache cannot be null!";
- this.cache = cache;
- this.distributedMember = distributedMember;
- this.functionExecutor = functionExecutor;
- }
-
- @Override
- public Cache getCache() {
- return this.cache;
- }
-
- @Override
- public Set<DistributedMember> getAllMembers() {
- assertSame(getCache(), cache);
- return Collections.singleton(this.distributedMember);
- }
-
- @Override
- public DistributedMember getMember(String nameOrId) {
- assertSame(getCache(), cache);
- return this.distributedMember;
- }
-
- @Override
- public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
- Assert.assertNotNull(members);
- return this.functionExecutor;
- }
+ listDiskStoresCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
+ assertThat(actualDiskStores).isNotNull();
+ assertThat(actualDiskStores).isEqualTo(expectedDiskStores);
+ verify(mockFunctionExecutor, times(1)).setIgnoreDepartedMembers(true);
}
}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
index 1cc8098..36c280a 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
@@ -14,9 +14,16 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
@@ -24,21 +31,11 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.FunctionInvocationTargetException;
import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.execute.AbstractExecution;
import org.apache.geode.internal.util.CollectionUtils;
import org.apache.geode.management.internal.cli.domain.IndexDetails;
@@ -57,35 +54,23 @@ import org.apache.geode.management.internal.cli.functions.ListIndexFunction;
* @see org.apache.geode.management.internal.cli.commands.ListIndexCommand
* @see org.apache.geode.management.internal.cli.domain.IndexDetails
* @see org.apache.geode.management.internal.cli.functions.ListIndexFunction
- * @see org.jmock.Expectations
- * @see org.jmock.Mockery
- * @see org.jmock.lib.legacy.ClassImposteriser
- * @see org.junit.Assert
* @see org.junit.Test
* @since GemFire 7.0
*/
public class ListIndexCommandJUnitTest {
- private Mockery mockContext;
+ private ListIndexCommand listIndexCommand;
+ private ResultCollector mockResultCollector;
+ private AbstractExecution mockFunctionExecutor;
@Before
public void setup() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
- }
-
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
- }
-
- private ListIndexCommand createListIndexCommand(final InternalCache cache,
- final Execution functionExecutor) {
- return new TestListIndexCommands(cache, functionExecutor);
+ listIndexCommand = spy(ListIndexCommand.class);
+ mockResultCollector = mock(ResultCollector.class, "ResultCollector");
+ mockFunctionExecutor = mock(AbstractExecution.class, "Function Executor");
+ when(mockFunctionExecutor.execute(any(ListIndexFunction.class)))
+ .thenReturn(mockResultCollector);
+ doReturn(Collections.emptySet()).when(listIndexCommand).getAllMembers();
+ doReturn(mockFunctionExecutor).when(listIndexCommand).getMembersFunctionExecutor(any());
}
private IndexDetails createIndexDetails(final String memberId, final String indexName) {
@@ -93,129 +78,44 @@ public class ListIndexCommandJUnitTest {
}
@Test
- public void testGetIndexListing() {
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final AbstractExecution mockFunctionExecutor =
- mockContext.mock(AbstractExecution.class, "Function Executor");
-
- final ResultCollector mockResultCollector =
- mockContext.mock(ResultCollector.class, "ResultCollector");
+ public void getIndexListingShouldPropagateExceptionsThrownByTheInternalFunctionExecution() {
+ doThrow(new RuntimeException("Mock RuntimeException")).when(mockFunctionExecutor)
+ .execute(any(ListIndexFunction.class));
+ assertThatThrownBy(() -> listIndexCommand.getIndexListing())
+ .isInstanceOf(RuntimeException.class).hasMessageContaining("Mock RuntimeException");
+ }
+ @Test
+ public void getIndexListingShouldReturnTheIndexesOrdered() {
final IndexDetails indexDetails1 = createIndexDetails("memberOne", "empIdIdx");
final IndexDetails indexDetails2 = createIndexDetails("memberOne", "empLastNameIdx");
final IndexDetails indexDetails3 = createIndexDetails("memberTwo", "empDobIdx");
-
+ final List<Set<IndexDetails>> results = new ArrayList<>();
+ results.add(CollectionUtils.asSet(indexDetails2, indexDetails1, indexDetails3));
+ when(mockResultCollector.getResult()).thenReturn(results);
final List<IndexDetails> expectedIndexDetails =
Arrays.asList(indexDetails1, indexDetails2, indexDetails3);
- final List<Set<IndexDetails>> results = new ArrayList<>(2);
-
- results.add(CollectionUtils.asSet(indexDetails2, indexDetails1));
- results.add(CollectionUtils.asSet(indexDetails3));
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
- oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
- will(returnValue(mockResultCollector));
- oneOf(mockResultCollector).getResult();
- will(returnValue(results));
- }
- });
-
- final ListIndexCommand commands = createListIndexCommand(mockCache, mockFunctionExecutor);
- final List<IndexDetails> actualIndexDetails = commands.getIndexListing();
-
- assertNotNull(actualIndexDetails);
- assertEquals(expectedIndexDetails, actualIndexDetails);
- }
-
- @Test(expected = RuntimeException.class)
- public void testGetIndexListingThrowsRuntimeException() {
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
- final Execution mockFunctionExecutor = mockContext.mock(Execution.class, "Function Executor");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
- will(throwException(new RuntimeException("expected")));
- }
- });
-
- final ListIndexCommand commands = createListIndexCommand(mockCache, mockFunctionExecutor);
-
- try {
- commands.getIndexListing();
- } catch (RuntimeException expected) {
- assertEquals("expected", expected.getMessage());
- throw expected;
- }
+ final List<IndexDetails> actualIndexDetails = listIndexCommand.getIndexListing();
+ assertThat(actualIndexDetails).isNotNull();
+ assertThat(actualIndexDetails).isEqualTo(expectedIndexDetails);
+ verify(mockFunctionExecutor, times(1)).setIgnoreDepartedMembers(true);
+ verify(mockFunctionExecutor, times(1)).execute(any(ListIndexFunction.class));
}
@Test
- public void testGetIndexListingReturnsFunctionInvocationTargetExceptionInResults() {
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final AbstractExecution mockFunctionExecutor =
- mockContext.mock(AbstractExecution.class, "Function Executor");
-
- final ResultCollector mockResultCollector =
- mockContext.mock(ResultCollector.class, "ResultCollector");
-
+ public void getIndexListingShouldIgnoreExceptionsReturnedAsResultsFromTheInternalFunctionExecution() {
final IndexDetails indexDetails = createIndexDetails("memberOne", "empIdIdx");
-
- final List<IndexDetails> expectedIndexDetails = Collections.singletonList(indexDetails);
-
final List<Object> results = new ArrayList<>(2);
-
results.add(CollectionUtils.asSet(indexDetails));
- results.add(new FunctionInvocationTargetException("expected"));
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
- oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
- will(returnValue(mockResultCollector));
- oneOf(mockResultCollector).getResult();
- will(returnValue(results));
- }
- });
-
- final ListIndexCommand commands = createListIndexCommand(mockCache, mockFunctionExecutor);
-
- final List<IndexDetails> actualIndexDetails = commands.getIndexListing();
-
- assertNotNull(actualIndexDetails);
- assertEquals(expectedIndexDetails, actualIndexDetails);
- }
-
- private static class TestListIndexCommands extends ListIndexCommand {
- private final InternalCache cache;
- private final Execution functionExecutor;
-
- TestListIndexCommands(final InternalCache cache, final Execution functionExecutor) {
- assert cache != null : "The InternalCache cannot be null!";
- assert functionExecutor != null : "The function executor cannot be null!";
- this.cache = cache;
- this.functionExecutor = functionExecutor;
- }
-
- @Override
- public Cache getCache() {
- return this.cache;
- }
-
- @Override
- public Set<DistributedMember> getAllMembers() {
- assertSame(getCache(), cache);
- return Collections.emptySet();
- }
+ results.add(new FunctionInvocationTargetException("Mock FunctionInvocationTargetException"));
+ when(mockResultCollector.getResult()).thenReturn(results);
+ final List<IndexDetails> expectedIndexDetails = Collections.singletonList(indexDetails);
- @Override
- public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
- Assert.assertNotNull(members);
- return functionExecutor;
- }
+ final List<IndexDetails> actualIndexDetails = listIndexCommand.getIndexListing();
+ assertThat(actualIndexDetails).isNotNull();
+ assertThat(actualIndexDetails).isEqualTo(expectedIndexDetails);
+ verify(mockFunctionExecutor, times(1)).setIgnoreDepartedMembers(true);
+ verify(mockFunctionExecutor, times(1)).execute(any(ListIndexFunction.class));
}
}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunctionJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunctionJUnitTest.java
index 5ea34cb..b98ceae 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunctionJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/DescribeDiskStoreFunctionJUnitTest.java
@@ -14,27 +14,25 @@
*/
package org.apache.geode.management.internal.cli.functions;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
-import org.apache.logging.log4j.Logger;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
+import edu.umd.cs.findbugs.annotations.SuppressWarnings;
+import org.assertj.core.api.AssertionsForClassTypes;
import org.junit.Before;
import org.junit.Test;
@@ -53,9 +51,7 @@ import org.apache.geode.cache.server.ClientSubscriptionConfig;
import org.apache.geode.cache.wan.GatewaySender;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.lang.Filter;
import org.apache.geode.internal.lang.ObjectUtils;
-import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.util.CollectionUtils;
import org.apache.geode.management.internal.cli.domain.DiskStoreDetails;
import org.apache.geode.management.internal.cli.exceptions.EntityNotFoundException;
@@ -67,32 +63,15 @@ import org.apache.geode.management.internal.cli.exceptions.EntityNotFoundExcepti
* @see org.apache.geode.cache.DiskStore
* @see org.apache.geode.management.internal.cli.domain.DiskStoreDetails
* @see org.apache.geode.management.internal.cli.functions.DescribeDiskStoreFunction
- * @see org.jmock.Expectations
- * @see org.jmock.Mockery
- * @see org.junit.Assert
* @see org.junit.Test
* @since GemFire 7.0
*/
-@SuppressWarnings({"null", "unused"})
public class DescribeDiskStoreFunctionJUnitTest {
-
- private static final Logger logger = LogService.getLogger();
-
- private Mockery mockContext;
private InternalCache mockCache;
@Before
public void setup() {
- mockContext = new Mockery();
- mockContext.setImposteriser(ClassImposteriser.INSTANCE);
- mockContext.setThreadingPolicy(new Synchroniser());
- mockCache = mockContext.mock(InternalCache.class, "Cache");
- }
-
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
+ mockCache = mock(InternalCache.class, "Cache");
}
private void assertAsyncEventQueueDetails(
@@ -102,21 +81,15 @@ public class DescribeDiskStoreFunctionJUnitTest {
for (final DiskStoreDetails.AsyncEventQueueDetails actualAsyncEventQueueDetails : diskStoreDetails
.iterateAsyncEventQueues()) {
- final DiskStoreDetails.AsyncEventQueueDetails expectedAsyncEventQueueDetails =
- CollectionUtils.findBy(expectedAsyncEventQueueDetailsSet,
- new Filter<DiskStoreDetails.AsyncEventQueueDetails>() {
- @Override
- public boolean accept(
- final DiskStoreDetails.AsyncEventQueueDetails asyncEventQueueDetails) {
- return ObjectUtils.equals(asyncEventQueueDetails.getId(),
- actualAsyncEventQueueDetails.getId());
- }
- });
-
- assertNotNull(expectedAsyncEventQueueDetails);
+ final DiskStoreDetails.AsyncEventQueueDetails expectedAsyncEventQueueDetails = CollectionUtils
+ .findBy(expectedAsyncEventQueueDetailsSet, asyncEventQueueDetails -> ObjectUtils
+ .equals(asyncEventQueueDetails.getId(), actualAsyncEventQueueDetails.getId()));
+
+ assertThat(expectedAsyncEventQueueDetails).isNotNull();
actualCount++;
}
- assertEquals(expectedAsyncEventQueueDetailsSet.size(), actualCount);
+
+ assertThat(actualCount).isEqualTo(expectedAsyncEventQueueDetailsSet.size());
}
private void assertCacheServerDetails(
@@ -126,23 +99,20 @@ public class DescribeDiskStoreFunctionJUnitTest {
for (final DiskStoreDetails.CacheServerDetails actualCacheServerDetails : diskStoreDetails
.iterateCacheServers()) {
- final DiskStoreDetails.CacheServerDetails expectedCacheServerDetails = CollectionUtils
- .findBy(expectedCacheServerDetailsSet, new Filter<DiskStoreDetails.CacheServerDetails>() {
- public boolean accept(final DiskStoreDetails.CacheServerDetails cacheServerDetails) {
- return ObjectUtils.equals(cacheServerDetails.getBindAddress(),
+ final DiskStoreDetails.CacheServerDetails expectedCacheServerDetails =
+ CollectionUtils.findBy(expectedCacheServerDetailsSet,
+ cacheServerDetails -> ObjectUtils.equals(cacheServerDetails.getBindAddress(),
actualCacheServerDetails.getBindAddress())
&& ObjectUtils.equals(cacheServerDetails.getPort(),
- actualCacheServerDetails.getPort());
- }
- });
+ actualCacheServerDetails.getPort()));
- assertNotNull(expectedCacheServerDetails);
- assertEquals(expectedCacheServerDetails.getHostName(),
- actualCacheServerDetails.getHostName());
+ assertThat(expectedCacheServerDetails).isNotNull();
+ assertThat(actualCacheServerDetails.getHostName())
+ .isEqualTo(expectedCacheServerDetails.getHostName());
actualCount++;
}
- assertEquals(expectedCacheServerDetailsSet.size(), actualCount);
+ assertThat(actualCount).isEqualTo(expectedCacheServerDetailsSet.size());
}
private void assertGatewayDetails(
@@ -152,19 +122,17 @@ public class DescribeDiskStoreFunctionJUnitTest {
for (final DiskStoreDetails.GatewayDetails actualGatewayDetails : diskStoreDetails
.iterateGateways()) {
- DiskStoreDetails.GatewayDetails expectedGatewayDetails = CollectionUtils
- .findBy(expectedGatewayDetailsSet, new Filter<DiskStoreDetails.GatewayDetails>() {
- public boolean accept(final DiskStoreDetails.GatewayDetails gatewayDetails) {
- return ObjectUtils.equals(gatewayDetails.getId(), actualGatewayDetails.getId());
- }
- });
-
- assertNotNull(expectedGatewayDetails);
- assertEquals(expectedGatewayDetails.isPersistent(), actualGatewayDetails.isPersistent());
+ DiskStoreDetails.GatewayDetails expectedGatewayDetails =
+ CollectionUtils.findBy(expectedGatewayDetailsSet, gatewayDetails -> ObjectUtils
+ .equals(gatewayDetails.getId(), actualGatewayDetails.getId()));
+
+ assertThat(expectedGatewayDetails).isNotNull();
+ assertThat(actualGatewayDetails.isPersistent())
+ .isEqualTo(expectedGatewayDetails.isPersistent());
actualCount++;
}
- assertEquals(expectedGatewayDetailsSet.size(), actualCount);
+ assertThat(actualCount).isEqualTo(expectedGatewayDetailsSet.size());
}
private void assertRegionDetails(
@@ -174,23 +142,20 @@ public class DescribeDiskStoreFunctionJUnitTest {
for (final DiskStoreDetails.RegionDetails actualRegionDetails : diskStoreDetails
.iterateRegions()) {
- final DiskStoreDetails.RegionDetails expectedRegionDetails = CollectionUtils
- .findBy(expectedRegionDetailsSet, new Filter<DiskStoreDetails.RegionDetails>() {
- public boolean accept(final DiskStoreDetails.RegionDetails regionDetails) {
- return ObjectUtils.equals(regionDetails.getFullPath(),
- actualRegionDetails.getFullPath());
- }
- });
-
- assertNotNull(expectedRegionDetails);
- assertEquals(expectedRegionDetails.getName(), actualRegionDetails.getName());
- assertEquals(expectedRegionDetails.isOverflowToDisk(),
- actualRegionDetails.isOverflowToDisk());
- assertEquals(expectedRegionDetails.isPersistent(), actualRegionDetails.isPersistent());
+ final DiskStoreDetails.RegionDetails expectedRegionDetails =
+ CollectionUtils.findBy(expectedRegionDetailsSet, regionDetails -> ObjectUtils
+ .equals(regionDetails.getFullPath(), actualRegionDetails.getFullPath()));
+
+ assertThat(expectedRegionDetails).isNotNull();
+ assertThat(actualRegionDetails.getName()).isEqualTo(expectedRegionDetails.getName());
+ assertThat(actualRegionDetails.isPersistent())
+ .isEqualTo(expectedRegionDetails.isPersistent());
+ assertThat(actualRegionDetails.isOverflowToDisk())
+ .isEqualTo(expectedRegionDetails.isOverflowToDisk());
actualCount++;
}
- assertEquals(expectedRegionDetailsSet.size(), actualCount);
+ assertThat(actualCount).isEqualTo(expectedRegionDetailsSet.size());
}
private DiskStoreDetails.AsyncEventQueueDetails createAsyncEventQueueDetails(final String id) {
@@ -202,6 +167,7 @@ public class DescribeDiskStoreFunctionJUnitTest {
final DiskStoreDetails.CacheServerDetails cacheServerDetails =
new DiskStoreDetails.CacheServerDetails(bindAddress, port);
cacheServerDetails.setHostName(hostname);
+
return cacheServerDetails;
}
@@ -235,38 +201,20 @@ public class DescribeDiskStoreFunctionJUnitTest {
final long maxOplogSize, final int queueSize, final long timeInterval,
final int writeBufferSize, final File[] diskDirs, final int[] diskDirSizes,
final float warningPercentage, final float criticalPercentage) {
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, name);
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockDiskStore).getAllowForceCompaction();
- will(returnValue(allowForceCompaction));
- oneOf(mockDiskStore).getAutoCompact();
- will(returnValue(autoCompact));
- oneOf(mockDiskStore).getCompactionThreshold();
- will(returnValue(compactionThreshold));
- atLeast(1).of(mockDiskStore).getDiskStoreUUID();
- will(returnValue(diskStoreId));
- oneOf(mockDiskStore).getMaxOplogSize();
- will(returnValue(maxOplogSize));
- atLeast(1).of(mockDiskStore).getName();
- will(returnValue(name));
- oneOf(mockDiskStore).getQueueSize();
- will(returnValue(queueSize));
- oneOf(mockDiskStore).getTimeInterval();
- will(returnValue(timeInterval));
- oneOf(mockDiskStore).getWriteBufferSize();
- will(returnValue(writeBufferSize));
- allowing(mockDiskStore).getDiskDirs();
- will(returnValue(diskDirs));
- allowing(mockDiskStore).getDiskDirSizes();
- will(returnValue(diskDirSizes));
- allowing(mockDiskStore).getDiskUsageWarningPercentage();
- will(returnValue(warningPercentage));
- allowing(mockDiskStore).getDiskUsageCriticalPercentage();
- will(returnValue(criticalPercentage));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, name);
+ when(mockDiskStore.getAllowForceCompaction()).thenReturn(allowForceCompaction);
+ when(mockDiskStore.getAutoCompact()).thenReturn(autoCompact);
+ when(mockDiskStore.getCompactionThreshold()).thenReturn(compactionThreshold);
+ when(mockDiskStore.getDiskStoreUUID()).thenReturn(diskStoreId);
+ when(mockDiskStore.getMaxOplogSize()).thenReturn(maxOplogSize);
+ when(mockDiskStore.getName()).thenReturn(name);
+ when(mockDiskStore.getQueueSize()).thenReturn(queueSize);
+ when(mockDiskStore.getTimeInterval()).thenReturn(timeInterval);
+ when(mockDiskStore.getWriteBufferSize()).thenReturn(writeBufferSize);
+ when(mockDiskStore.getDiskDirs()).thenReturn(diskDirs);
+ when(mockDiskStore.getDiskDirSizes()).thenReturn(diskDirSizes);
+ when(mockDiskStore.getDiskUsageWarningPercentage()).thenReturn(warningPercentage);
+ when(mockDiskStore.getDiskUsageCriticalPercentage()).thenReturn(criticalPercentage);
return mockDiskStore;
}
@@ -277,110 +225,55 @@ public class DescribeDiskStoreFunctionJUnitTest {
new DiskStoreDetails.RegionDetails(fullPath, name);
regionDetails.setPersistent(persistent);
regionDetails.setOverflowToDisk(overflow);
- return regionDetails;
- }
-
- @Test
- public void testAssertState() {
- DescribeDiskStoreFunction.assertState(true, "null");
- }
- @Test
- public void testAssertStateThrowsIllegalStateException() {
- assertThatThrownBy(
- () -> DescribeDiskStoreFunction.assertState(false, "Expected (%1$s) message!", "test"))
- .isInstanceOf(IllegalStateException.class).hasMessage("Expected (test) message!");
- }
-
- private void setupEmptyRegionsPdxGatewaysCacheServersAndAsyncEventQueues(
- final InternalCache mockCache) {
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).rootRegions();
- will(returnValue(Collections.emptySet()));
- oneOf(mockCache).getCacheServers();
- will(returnValue(Collections.emptyList()));
- oneOf(mockCache).getGatewaySenders();
- will(returnValue(Collections.emptyList()));
- will(returnValue(Collections.emptyList()));
- oneOf(mockCache).getPdxPersistent();
- will(returnValue(false));
- oneOf(mockCache).getAsyncEventQueues();
- will(returnValue(Collections.emptySet()));
- }
- });
+ return regionDetails;
}
+ @SuppressWarnings("unchecked")
private Set<DiskStoreDetails.RegionDetails> setupRegionsForTestExecute(
final InternalCache mockCache, final String diskStoreName) {
- final Region mockUserRegion = mockContext.mock(Region.class, "/UserRegion");
- final Region mockSessionRegion = mockContext.mock(Region.class, "/UserRegion/SessionRegion");
- final Region mockGuestRegion = mockContext.mock(Region.class, "/GuestRegion");
-
+ final Region mockUserRegion = mock(Region.class, "/UserRegion");
+ final Region mockGuestRegion = mock(Region.class, "/GuestRegion");
+ final Region mockSessionRegion = mock(Region.class, "/UserRegion/SessionRegion");
final RegionAttributes mockUserRegionAttributes =
- mockContext.mock(RegionAttributes.class, "UserRegionAttributes");
+ mock(RegionAttributes.class, "UserRegionAttributes");
final RegionAttributes mockSessionRegionAttributes =
- mockContext.mock(RegionAttributes.class, "SessionRegionAttributes");
+ mock(RegionAttributes.class, "SessionRegionAttributes");
final RegionAttributes mockGuestRegionAttributes =
- mockContext.mock(RegionAttributes.class, "GuestRegionAttributes");
-
+ mock(RegionAttributes.class, "GuestRegionAttributes");
final EvictionAttributes mockUserEvictionAttributes =
- mockContext.mock(EvictionAttributes.class, "UserEvictionAttributes");
+ mock(EvictionAttributes.class, "UserEvictionAttributes");
final EvictionAttributes mockSessionEvictionAttributes =
- mockContext.mock(EvictionAttributes.class, "SessionEvictionAttributes");
+ mock(EvictionAttributes.class, "SessionEvictionAttributes");
final EvictionAttributes mockGuestEvictionAttributes =
- mockContext.mock(EvictionAttributes.class, "GuestEvictionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).rootRegions();
- will(returnValue(CollectionUtils.asSet(mockUserRegion, mockGuestRegion)));
- exactly(5).of(mockUserRegion).getAttributes();
- will(returnValue(mockUserRegionAttributes));
- oneOf(mockUserRegion).getFullPath();
- will(returnValue("/UserRegion"));
- oneOf(mockUserRegion).getName();
- will(returnValue("UserRegion"));
- oneOf(mockUserRegion).subregions(false);
- will(returnValue(CollectionUtils.asSet(mockSessionRegion)));
- exactly(2).of(mockUserRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PERSISTENT_PARTITION));
- oneOf(mockUserRegionAttributes).getDiskStoreName();
- will(returnValue(diskStoreName));
- exactly(2).of(mockUserRegionAttributes).getEvictionAttributes();
- will(returnValue(mockUserEvictionAttributes));
- oneOf(mockUserEvictionAttributes).getAction();
- will(returnValue(EvictionAction.LOCAL_DESTROY));
- exactly(7).of(mockSessionRegion).getAttributes();
- will(returnValue(mockSessionRegionAttributes));
- oneOf(mockSessionRegion).getFullPath();
- will(returnValue("/UserRegion/SessionRegion"));
- oneOf(mockSessionRegion).getName();
- will(returnValue("SessionRegion"));
- oneOf(mockSessionRegion).subregions(false);
- will(returnValue(Collections.emptySet()));
- exactly(2).of(mockSessionRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.REPLICATE));
- oneOf(mockSessionRegionAttributes).getDiskStoreName();
- will(returnValue(diskStoreName));
- exactly(4).of(mockSessionRegionAttributes).getEvictionAttributes();
- will(returnValue(mockSessionEvictionAttributes));
- exactly(2).of(mockSessionEvictionAttributes).getAction();
- will(returnValue(EvictionAction.OVERFLOW_TO_DISK));
- exactly(4).of(mockGuestRegion).getAttributes();
- will(returnValue(mockGuestRegionAttributes));
- oneOf(mockGuestRegion).subregions(false);
- will(returnValue(Collections.emptySet()));
- oneOf(mockGuestRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.REPLICATE));
- oneOf(mockGuestRegionAttributes).getDiskStoreName();
- will(returnValue(DiskStoreDetails.DEFAULT_DISK_STORE_NAME));
- exactly(2).of(mockGuestRegionAttributes).getEvictionAttributes();
- will(returnValue(mockGuestEvictionAttributes));
- oneOf(mockGuestEvictionAttributes).getAction();
- will(returnValue(EvictionAction.OVERFLOW_TO_DISK));
- }
- });
+ mock(EvictionAttributes.class, "GuestEvictionAttributes");
+
+ when(mockCache.rootRegions())
+ .thenReturn(CollectionUtils.asSet(mockUserRegion, mockGuestRegion));
+ when(mockUserRegion.getAttributes()).thenReturn(mockUserRegionAttributes);
+ when(mockUserRegion.getFullPath()).thenReturn("/UserRegion");
+ when(mockUserRegion.getName()).thenReturn("UserRegion");
+ when(mockUserRegion.subregions(false)).thenReturn(CollectionUtils.asSet(mockSessionRegion));
+ when(mockUserRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PERSISTENT_PARTITION);
+ when(mockUserRegionAttributes.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockUserRegionAttributes.getEvictionAttributes()).thenReturn(mockUserEvictionAttributes);
+ when(mockUserEvictionAttributes.getAction()).thenReturn(EvictionAction.LOCAL_DESTROY);
+ when(mockSessionRegion.getAttributes()).thenReturn(mockSessionRegionAttributes);
+ when(mockSessionRegion.getFullPath()).thenReturn("/UserRegion/SessionRegion");
+ when(mockSessionRegion.getName()).thenReturn("SessionRegion");
+ when(mockSessionRegion.subregions(false)).thenReturn(Collections.emptySet());
+ when(mockSessionRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.REPLICATE);
+ when(mockSessionRegionAttributes.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockSessionRegionAttributes.getEvictionAttributes())
+ .thenReturn(mockSessionEvictionAttributes);
+ when(mockSessionEvictionAttributes.getAction()).thenReturn(EvictionAction.OVERFLOW_TO_DISK);
+ when(mockGuestRegion.getAttributes()).thenReturn(mockGuestRegionAttributes);
+ when(mockGuestRegion.subregions(false)).thenReturn(Collections.emptySet());
+ when(mockGuestRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.REPLICATE);
+ when(mockGuestRegionAttributes.getDiskStoreName())
+ .thenReturn(DiskStoreDetails.DEFAULT_DISK_STORE_NAME);
+ when(mockGuestRegionAttributes.getEvictionAttributes()).thenReturn(mockGuestEvictionAttributes);
+ when(mockGuestEvictionAttributes.getAction()).thenReturn(EvictionAction.OVERFLOW_TO_DISK);
return CollectionUtils.asSet(createRegionDetails("/UserRegion", "UserRegion", true, false),
createRegionDetails("/UserRegion/SessionRegion", "SessionRegion", false, true));
@@ -388,193 +281,149 @@ public class DescribeDiskStoreFunctionJUnitTest {
private Set<DiskStoreDetails.GatewayDetails> setupGatewaysForTestExecute(
final InternalCache mockCache, final String diskStoreName) {
- final GatewaySender mockGatewaySender = mockContext.mock(GatewaySender.class, "GatewaySender");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getGatewaySenders();
- will(returnValue(CollectionUtils.asSet(mockGatewaySender)));
- oneOf(mockGatewaySender).getDiskStoreName();
- will(returnValue(diskStoreName));
- oneOf(mockGatewaySender).getId();
- will(returnValue("0123456789"));
- oneOf(mockGatewaySender).isPersistenceEnabled();
- will(returnValue(true));
- }
- });
+ final GatewaySender mockGatewaySender = mock(GatewaySender.class, "GatewaySender");
+ when(mockCache.getGatewaySenders()).thenReturn(CollectionUtils.asSet(mockGatewaySender));
+ when(mockGatewaySender.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockGatewaySender.getId()).thenReturn("0123456789");
+ when(mockGatewaySender.isPersistenceEnabled()).thenReturn(true);
return CollectionUtils.asSet(createGatewayDetails("0123456789", true));
}
private Set<DiskStoreDetails.CacheServerDetails> setupCacheServersForTestExecute(
final InternalCache mockCache, final String diskStoreName) {
- final CacheServer mockCacheServer1 = mockContext.mock(CacheServer.class, "CacheServer1");
- final CacheServer mockCacheServer2 = mockContext.mock(CacheServer.class, "CacheServer2");
- final CacheServer mockCacheServer3 = mockContext.mock(CacheServer.class, "CacheServer3");
-
+ final CacheServer mockCacheServer1 = mock(CacheServer.class, "CacheServer1");
+ final CacheServer mockCacheServer2 = mock(CacheServer.class, "CacheServer2");
+ final CacheServer mockCacheServer3 = mock(CacheServer.class, "CacheServer3");
final ClientSubscriptionConfig cacheServer1ClientSubscriptionConfig =
- mockContext.mock(ClientSubscriptionConfig.class, "cacheServer1ClientSubscriptionConfig");
+ mock(ClientSubscriptionConfig.class, "cacheServer1ClientSubscriptionConfig");
final ClientSubscriptionConfig cacheServer3ClientSubscriptionConfig =
- mockContext.mock(ClientSubscriptionConfig.class, "cacheServer3ClientSubscriptionConfig");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getCacheServers();
- will(returnValue(Arrays.asList(mockCacheServer1, mockCacheServer2, mockCacheServer3)));
- exactly(2).of(mockCacheServer1).getClientSubscriptionConfig();
- will(returnValue(cacheServer1ClientSubscriptionConfig));
- oneOf(cacheServer1ClientSubscriptionConfig).getDiskStoreName();
- will(returnValue(diskStoreName));
- oneOf(mockCacheServer2).getClientSubscriptionConfig();
- will(returnValue(null));
- exactly(2).of(mockCacheServer3).getClientSubscriptionConfig();
- will(returnValue(cacheServer3ClientSubscriptionConfig));
- oneOf(cacheServer3ClientSubscriptionConfig).getDiskStoreName();
- will(returnValue(""));
- oneOf(mockCacheServer1).getBindAddress();
- will(returnValue("10.127.0.1"));
- oneOf(mockCacheServer1).getPort();
- will(returnValue(10123));
- oneOf(mockCacheServer1).getHostnameForClients();
- will(returnValue("rodan"));
- }
- });
+ mock(ClientSubscriptionConfig.class, "cacheServer3ClientSubscriptionConfig");
+
+ when(mockCache.getCacheServers())
+ .thenReturn(Arrays.asList(mockCacheServer1, mockCacheServer2, mockCacheServer3));
+ when(mockCacheServer1.getClientSubscriptionConfig())
+ .thenReturn(cacheServer1ClientSubscriptionConfig);
+ when(cacheServer1ClientSubscriptionConfig.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockCacheServer2.getClientSubscriptionConfig()).thenReturn(null);
+ when(mockCacheServer3.getClientSubscriptionConfig())
+ .thenReturn(cacheServer3ClientSubscriptionConfig);
+ when(cacheServer3ClientSubscriptionConfig.getDiskStoreName()).thenReturn("");
+ when(mockCacheServer1.getBindAddress()).thenReturn("10.127.0.1");
+ when(mockCacheServer1.getPort()).thenReturn(10123);
+ when(mockCacheServer1.getHostnameForClients()).thenReturn("rodan");
return CollectionUtils.asSet(createCacheServerDetails("10.127.0.1", 10123, "rodan"));
}
private Set<DiskStoreDetails.AsyncEventQueueDetails> setupAsyncEventQueuesForTestExecute(
final InternalCache mockCache, final String diskStoreName) {
- final AsyncEventQueue mockAsyncEventQueue1 =
- mockContext.mock(AsyncEventQueue.class, "AsyncEventQueue1");
- final AsyncEventQueue mockAsyncEventQueue2 =
- mockContext.mock(AsyncEventQueue.class, "AsyncEventQueue2");
- final AsyncEventQueue mockAsyncEventQueue3 =
- mockContext.mock(AsyncEventQueue.class, "AsyncEventQueue3");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getAsyncEventQueues();
- will(returnValue(CollectionUtils.asSet(mockAsyncEventQueue1, mockAsyncEventQueue2,
- mockAsyncEventQueue3)));
- oneOf(mockAsyncEventQueue1).isPersistent();
- will(returnValue(true));
- oneOf(mockAsyncEventQueue1).getDiskStoreName();
- will(returnValue(diskStoreName));
- oneOf(mockAsyncEventQueue1).getId();
- will(returnValue("9876543210"));
- oneOf(mockAsyncEventQueue2).isPersistent();
- will(returnValue(false));
- oneOf(mockAsyncEventQueue3).isPersistent();
- will(returnValue(true));
- oneOf(mockAsyncEventQueue3).getDiskStoreName();
- will(returnValue("memSto"));
- }
- });
+ final AsyncEventQueue mockAsyncEventQueue1 = mock(AsyncEventQueue.class, "AsyncEventQueue1");
+ final AsyncEventQueue mockAsyncEventQueue2 = mock(AsyncEventQueue.class, "AsyncEventQueue2");
+ final AsyncEventQueue mockAsyncEventQueue3 = mock(AsyncEventQueue.class, "AsyncEventQueue3");
+
+ when(mockCache.getAsyncEventQueues()).thenReturn(
+ CollectionUtils.asSet(mockAsyncEventQueue1, mockAsyncEventQueue2, mockAsyncEventQueue3));
+ when(mockAsyncEventQueue1.isPersistent()).thenReturn(true);
+ when(mockAsyncEventQueue1.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockAsyncEventQueue1.getId()).thenReturn("9876543210");
+ when(mockAsyncEventQueue2.isPersistent()).thenReturn(false);
+ when(mockAsyncEventQueue3.isPersistent()).thenReturn(true);
+ when(mockAsyncEventQueue3.getDiskStoreName()).thenReturn("memSto");
return CollectionUtils.asSet(createAsyncEventQueueDetails("9876543210"));
}
@Test
+ public void testAssertState() {
+ DescribeDiskStoreFunction.assertState(true, "null");
+ }
+
+ @Test
+ public void testAssertStateThrowsIllegalStateException() {
+ assertThatThrownBy(
+ () -> DescribeDiskStoreFunction.assertState(false, "Expected (%1$s) message!", "test"))
+ .isInstanceOf(IllegalStateException.class).hasMessage("Expected (test) message!");
+ }
+
+ @Test
public void testExecute() throws Throwable {
+ // Prepare Mocks
final UUID diskStoreId = UUID.randomUUID();
-
final String diskStoreName = "mockDiskStore";
final String memberId = "mockMemberId";
final String memberName = "mockMemberName";
-
final InternalDistributedMember mockMember =
- mockContext.mock(InternalDistributedMember.class, "DistributedMember");
-
+ mock(InternalDistributedMember.class, "DistributedMember");
final FunctionContext mockFunctionContext =
- mockContext.mock(FunctionContext.class, "testExecute$FunctionContext");
-
+ mock(FunctionContext.class, "testExecute$FunctionContext");
final DiskStore mockDiskStore =
createMockDiskStore(diskStoreId, diskStoreName, true, false,
- 75, 8192l, 500, 120l, 10240, createFileArray("/export/disk/backup",
+ 75, 8192L, 500, 120L, 10240, createFileArray("/export/disk/backup",
"/export/disk/overflow", "/export/disk/persistence"),
createIntArray(10240, 204800, 4096000), 50, 75);
-
final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getMyId();
- will(returnValue(mockMember));
- oneOf(mockCache).findDiskStore(diskStoreName);
- will(returnValue(mockDiskStore));
- oneOf(mockCache).getPdxPersistent();
- will(returnValue(true));
- oneOf(mockCache).getPdxDiskStore();
- will(returnValue("memoryStore"));
- oneOf(mockMember).getId();
- will(returnValue(memberId));
- oneOf(mockMember).getName();
- will(returnValue(memberName));
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockCache));
- oneOf(mockFunctionContext).getArguments();
- will(returnValue(diskStoreName));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
-
+ when(mockCache.getMyId()).thenReturn(mockMember);
+ when(mockCache.findDiskStore(diskStoreName)).thenReturn(mockDiskStore);
+ when(mockCache.getPdxPersistent()).thenReturn(true);
+ when(mockCache.getPdxDiskStore()).thenReturn("memoryStore");
+ when(mockMember.getId()).thenReturn(memberId);
+ when(mockMember.getName()).thenReturn(memberName);
+ when(mockFunctionContext.getCache()).thenReturn(mockCache);
+ when(mockFunctionContext.getArguments()).thenReturn(diskStoreName);
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
+
+ // Expected Results
final Set<DiskStoreDetails.RegionDetails> expectedRegionDetails =
setupRegionsForTestExecute(mockCache, diskStoreName);
-
final Set<DiskStoreDetails.GatewayDetails> expectedGatewayDetails =
setupGatewaysForTestExecute(mockCache, diskStoreName);
-
final Set<DiskStoreDetails.CacheServerDetails> expectedCacheServerDetails =
setupCacheServersForTestExecute(mockCache, diskStoreName);
-
final Set<DiskStoreDetails.AsyncEventQueueDetails> expectedAsyncEventQueueDetails =
setupAsyncEventQueuesForTestExecute(mockCache, diskStoreName);
+ // Execute Function and assert results
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.execute(mockFunctionContext);
final List<?> results = testResultSender.getResults();
-
- assertNotNull(results);
- assertEquals(1, results.size());
+ assertThat(results).isNotNull();
+ assertThat(results.size()).isEqualTo(1);
final DiskStoreDetails diskStoreDetails = (DiskStoreDetails) results.get(0);
-
- assertNotNull(diskStoreDetails);
- assertEquals(diskStoreId, diskStoreDetails.getId());
- assertEquals(diskStoreName, diskStoreDetails.getName());
- assertEquals(memberId, diskStoreDetails.getMemberId());
- assertEquals(memberName, diskStoreDetails.getMemberName());
- assertTrue(diskStoreDetails.getAllowForceCompaction());
- assertFalse(diskStoreDetails.getAutoCompact());
- assertEquals(75, diskStoreDetails.getCompactionThreshold().intValue());
- assertEquals(8192l, diskStoreDetails.getMaxOplogSize().longValue());
- assertFalse(diskStoreDetails.isPdxSerializationMetaDataStored());
- assertEquals(500, diskStoreDetails.getQueueSize().intValue());
- assertEquals(120l, diskStoreDetails.getTimeInterval().longValue());
- assertEquals(10240, diskStoreDetails.getWriteBufferSize().intValue());
- assertEquals(50.0f, diskStoreDetails.getDiskUsageWarningPercentage().floatValue(), 0.0f);
- assertEquals(75.0f, diskStoreDetails.getDiskUsageCriticalPercentage().floatValue(), 0.0f);
-
+ AssertionsForClassTypes.assertThat(diskStoreDetails).isNotNull();
+ assertThat(diskStoreDetails.getId()).isEqualTo(diskStoreId);
+ assertThat(diskStoreDetails.getName()).isEqualTo(diskStoreName);
+ assertThat(diskStoreDetails.getMemberId()).isEqualTo(memberId);
+ assertThat(diskStoreDetails.getMemberName()).isEqualTo(memberName);
+ assertThat(diskStoreDetails.getAllowForceCompaction()).isTrue();
+ assertThat(diskStoreDetails.getAutoCompact()).isFalse();
+ assertThat(diskStoreDetails.getCompactionThreshold().intValue()).isEqualTo(75);
+ assertThat(diskStoreDetails.getMaxOplogSize().longValue()).isEqualTo(8192L);
+ assertThat(diskStoreDetails.isPdxSerializationMetaDataStored()).isFalse();
+ assertThat(diskStoreDetails.getQueueSize().intValue()).isEqualTo(500);
+ assertThat(diskStoreDetails.getTimeInterval().longValue()).isEqualTo(120L);
+ assertThat(diskStoreDetails.getWriteBufferSize().intValue()).isEqualTo(10240);
+ assertThat(diskStoreDetails.getDiskUsageWarningPercentage()).isEqualTo(50.0f);
+ assertThat(diskStoreDetails.getDiskUsageCriticalPercentage()).isEqualTo(75.0f);
+
+ final List<Integer> expectedDiskDirSizes = Arrays.asList(10240, 204800, 4096000);
final List<String> expectedDiskDirs =
Arrays.asList(new File("/export/disk/backup").getAbsolutePath(),
new File("/export/disk/overflow").getAbsolutePath(),
new File("/export/disk/persistence").getAbsolutePath());
-
- final List<Integer> expectdDiskDirSizes = Arrays.asList(10240, 204800, 4096000);
-
int count = 0;
for (final DiskStoreDetails.DiskDirDetails diskDirDetails : diskStoreDetails) {
- assertTrue(expectedDiskDirs.contains(diskDirDetails.getAbsolutePath()));
- assertTrue(expectdDiskDirSizes.contains(diskDirDetails.getSize()));
+ assertThat(expectedDiskDirSizes.contains(diskDirDetails.getSize())).isTrue();
+ assertThat(expectedDiskDirs.contains(diskDirDetails.getAbsolutePath())).isTrue();
count++;
}
- assertEquals(expectedDiskDirs.size(), count);
+ verify(mockDiskStore, atLeastOnce()).getName();
+ verify(mockDiskStore, atLeastOnce()).getDiskStoreUUID();
+ assertThat(count).isEqualTo(expectedDiskDirs.size());
assertRegionDetails(expectedRegionDetails, diskStoreDetails);
assertCacheServerDetails(expectedCacheServerDetails, diskStoreDetails);
assertGatewayDetails(expectedGatewayDetails, diskStoreDetails);
@@ -583,1210 +432,753 @@ public class DescribeDiskStoreFunctionJUnitTest {
@Test
public void testExecuteOnMemberHavingANonGemFireCache() throws Throwable {
- final Cache mockNonGemCache = mockContext.mock(Cache.class, "NonGemCache");
-
- final FunctionContext mockFunctionContext =
- mockContext.mock(FunctionContext.class, "FunctionContext");
-
+ final Cache mockNonGemCache = mock(Cache.class, "NonGemCache");
+ final FunctionContext mockFunctionContext = mock(FunctionContext.class, "FunctionContext");
final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockNonGemCache));
- exactly(0).of(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
+ when(mockFunctionContext.getCache()).thenReturn(mockNonGemCache);
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.execute(mockFunctionContext);
final List<?> results = testResultSender.getResults();
-
- assertNotNull(results);
- assertTrue(results.isEmpty());
+ assertThat(results).isNotNull();
+ assertThat(results.isEmpty()).isTrue();
}
@Test
- public void testExecuteThrowingEntityNotFoundException() throws Exception {
- final String diskStoreName = "testDiskStore";
+ public void testExecuteThrowingEntityNotFoundException() {
final String memberId = "mockMemberId";
final String memberName = "mockMemberName";
-
+ final String diskStoreName = "testDiskStore";
final InternalDistributedMember mockMember =
- mockContext.mock(InternalDistributedMember.class, "DistributedMember");
-
- final FunctionContext mockFunctionContext =
- mockContext.mock(FunctionContext.class, "FunctionContext");
-
+ mock(InternalDistributedMember.class, "DistributedMember");
+ final FunctionContext mockFunctionContext = mock(FunctionContext.class, "FunctionContext");
final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getMyId();
- will(returnValue(mockMember));
- oneOf(mockCache).findDiskStore(diskStoreName);
- will(returnValue(null));
- oneOf(mockMember).getId();
- will(returnValue(memberId));
- oneOf(mockMember).getName();
- will(returnValue(memberName));
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockCache));
- oneOf(mockFunctionContext).getArguments();
- will(returnValue(diskStoreName));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
+ when(mockCache.getMyId()).thenReturn(mockMember);
+ when(mockCache.findDiskStore(diskStoreName)).thenReturn(null);
+ when(mockMember.getId()).thenReturn(memberId);
+ when(mockMember.getName()).thenReturn(memberName);
+ when(mockFunctionContext.getCache()).thenReturn(mockCache);
+ when(mockFunctionContext.getArguments()).thenReturn(diskStoreName);
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.execute(mockFunctionContext);
-
String expected = String.format("A disk store with name (%1$s) was not found on member (%2$s).",
diskStoreName, memberName);
- assertThatThrownBy(() -> testResultSender.getResults())
- .isInstanceOf(EntityNotFoundException.class).hasMessage(expected);
+ assertThatThrownBy(testResultSender::getResults).isInstanceOf(EntityNotFoundException.class)
+ .hasMessage(expected);
}
@Test
- public void testExecuteThrowingRuntimeException() throws Exception {
+ public void testExecuteThrowingRuntimeException() {
final String diskStoreName = "testDiskStore";
final String memberId = "mockMemberId";
final String memberName = "mockMemberName";
-
+ final FunctionContext mockFunctionContext = mock(FunctionContext.class, "FunctionContext");
final InternalDistributedMember mockMember =
- mockContext.mock(InternalDistributedMember.class, "DistributedMember");
-
- final FunctionContext mockFunctionContext =
- mockContext.mock(FunctionContext.class, "FunctionContext");
-
+ mock(InternalDistributedMember.class, "DistributedMember");
final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getMyId();
- will(returnValue(mockMember));
- oneOf(mockCache).findDiskStore(diskStoreName);
- will(throwException(new RuntimeException("ExpectedStrings")));
- oneOf(mockMember).getId();
- will(returnValue(memberId));
- oneOf(mockMember).getName();
- will(returnValue(memberName));
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockCache));
- oneOf(mockFunctionContext).getArguments();
- will(returnValue(diskStoreName));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
+ when(mockCache.getMyId()).thenReturn(mockMember);
+ when(mockCache.findDiskStore(diskStoreName)).thenThrow(new RuntimeException("ExpectedStrings"));
+ when(mockMember.getId()).thenReturn(memberId);
+ when(mockMember.getName()).thenReturn(memberName);
+ when(mockFunctionContext.getCache()).thenReturn(mockCache);
+ when(mockFunctionContext.getArguments()).thenReturn(diskStoreName);
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.execute(mockFunctionContext);
-
- assertThatThrownBy(() -> testResultSender.getResults()).isInstanceOf(RuntimeException.class)
+ assertThatThrownBy(testResultSender::getResults).isInstanceOf(RuntimeException.class)
.hasMessage("ExpectedStrings");
}
@Test
- public void testExecuteWithDiskDirsAndDiskSizesMismatch() throws Exception {
+ public void testExecuteWithDiskDirsAndDiskSizesMismatch() {
final String diskStoreName = "mockDiskStore";
final String memberId = "mockMemberId";
final String memberName = "mockMemberName";
-
final UUID diskStoreId = UUID.randomUUID();
-
+ final FunctionContext mockFunctionContext = mock(FunctionContext.class, "FunctionContext");
final InternalDistributedMember mockMember =
- mockContext.mock(InternalDistributedMember.class, "DistributedMember");
-
+ mock(InternalDistributedMember.class, "DistributedMember");
final DiskStore mockDiskStore =
- createMockDiskStore(diskStoreId, diskStoreName, false, true, 70, 8192000l, 1000, 300l, 8192,
+ createMockDiskStore(diskStoreId, diskStoreName, false, true, 70, 8192000L, 1000, 300L, 8192,
createFileArray("/export/disk0/gemfire/backup"), new int[0], 50, 75);
-
- final FunctionContext mockFunctionContext =
- mockContext.mock(FunctionContext.class, "FunctionContext");
-
final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getMyId();
- will(returnValue(mockMember));
- oneOf(mockCache).findDiskStore(diskStoreName);
- will(returnValue(mockDiskStore));
- oneOf(mockMember).getId();
- will(returnValue(memberId));
- oneOf(mockMember).getName();
- will(returnValue(memberName));
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockCache));
- oneOf(mockFunctionContext).getArguments();
- will(returnValue(diskStoreName));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
+ when(mockCache.getMyId()).thenReturn(mockMember);
+ when(mockCache.findDiskStore(diskStoreName)).thenReturn(mockDiskStore);
+ when(mockMember.getId()).thenReturn(memberId);
+ when(mockMember.getName()).thenReturn(memberName);
+ when(mockFunctionContext.getCache()).thenReturn(mockCache);
+ when(mockFunctionContext.getArguments()).thenReturn(diskStoreName);
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.execute(mockFunctionContext);
-
String expected =
"The number of disk directories with a specified size (0) does not match the number of disk directories (1)!";
- assertThatThrownBy(() -> testResultSender.getResults()).hasMessage(expected);
+ assertThatThrownBy(testResultSender::getResults).hasMessage(expected);
+ verify(mockDiskStore, atLeastOnce()).getName();
+ verify(mockDiskStore, atLeastOnce()).getDiskStoreUUID();
}
@Test
public void testGetRegionDiskStoreName() {
final String expectedDiskStoreName = "testDiskStore";
-
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDiskStoreName();
- will(returnValue(expectedDiskStoreName));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDiskStoreName()).thenReturn(expectedDiskStoreName);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertEquals(expectedDiskStoreName, function.getDiskStoreName(mockRegion));
+ assertThat(function.getDiskStoreName(mockRegion)).isEqualTo(expectedDiskStoreName);
}
@Test
public void testGetRegionDiskStoreNameWhenUnspecified() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDiskStoreName();
- will(returnValue(null));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDiskStoreName()).thenReturn(null);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertEquals(DiskStoreDetails.DEFAULT_DISK_STORE_NAME, function.getDiskStoreName(mockRegion));
+ assertThat(function.getDiskStoreName(mockRegion))
+ .isEqualTo(DiskStoreDetails.DEFAULT_DISK_STORE_NAME);
}
@Test
public void testIsRegionOverflowToDiskWhenEvictionActionIsLocalDestroy() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
final EvictionAttributes mockEvictionAttributes =
- mockContext.mock(EvictionAttributes.class, "EvictionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- exactly(2).of(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- exactly(2).of(mockRegionAttributes).getEvictionAttributes();
- will(returnValue(mockEvictionAttributes));
- oneOf(mockEvictionAttributes).getAction();
- will(returnValue(EvictionAction.LOCAL_DESTROY));
- }
- });
+ mock(EvictionAttributes.class, "EvictionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getEvictionAttributes()).thenReturn(mockEvictionAttributes);
+ when(mockEvictionAttributes.getAction()).thenReturn(EvictionAction.LOCAL_DESTROY);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isOverflowToDisk(mockRegion));
+ assertThat(function.isOverflowToDisk(mockRegion)).isFalse();
+ verify(mockRegion, times(2)).getAttributes();
+ verify(mockRegionAttributes, times(2)).getEvictionAttributes();
}
@Test
public void testIsRegionOverflowToDiskWhenEvictionActionIsOverflowToDisk() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
final EvictionAttributes mockEvictionAttributes =
- mockContext.mock(EvictionAttributes.class, "EvictionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- exactly(2).of(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- exactly(2).of(mockRegionAttributes).getEvictionAttributes();
- will(returnValue(mockEvictionAttributes));
- oneOf(mockEvictionAttributes).getAction();
- will(returnValue(EvictionAction.OVERFLOW_TO_DISK));
- }
- });
+ mock(EvictionAttributes.class, "EvictionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getEvictionAttributes()).thenReturn(mockEvictionAttributes);
+ when(mockEvictionAttributes.getAction()).thenReturn(EvictionAction.OVERFLOW_TO_DISK);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isOverflowToDisk(mockRegion));
+ assertThat(function.isOverflowToDisk(mockRegion)).isTrue();
+ verify(mockRegion, times(2)).getAttributes();
+ verify(mockRegionAttributes, times(2)).getEvictionAttributes();
}
@Test
public void testIsRegionOverflowToDiskWithNullEvictionAttributes() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getEvictionAttributes();
- will(returnValue(null));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getEvictionAttributes()).thenReturn(null);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isOverflowToDisk(mockRegion));
+ assertThat(function.isOverflowToDisk(mockRegion)).isFalse();
}
@Test
public void testIsRegionPersistentWhenDataPolicyIsPersistentPartition() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PERSISTENT_PARTITION));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PERSISTENT_PARTITION);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isPersistent(mockRegion));
+ assertThat(function.isPersistent(mockRegion)).isTrue();
}
@Test
public void testIsRegionPersistentWhenDataPolicyIsPersistentReplicate() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PERSISTENT_REPLICATE));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PERSISTENT_REPLICATE);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isPersistent(mockRegion));
+ assertThat(function.isPersistent(mockRegion)).isTrue();
}
@Test
public void testIsRegionPersistentWhenDataPolicyIsNormal() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.NORMAL));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.NORMAL);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isPersistent(mockRegion));
+ assertThat(function.isPersistent(mockRegion)).isFalse();
}
@Test
public void testIsRegionPersistentWhenDataPolicyIsPartition() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PARTITION));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PARTITION);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isPersistent(mockRegion));
+ assertThat(function.isPersistent(mockRegion)).isFalse();
}
@Test
public void testIsRegionPersistentWhenDataPolicyIsPreloaded() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PRELOADED));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PRELOADED);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isPersistent(mockRegion));
+ assertThat(function.isPersistent(mockRegion)).isFalse();
}
@Test
public void testIsRegionPersistentWhenDataPolicyIsReplicate() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.REPLICATE));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.REPLICATE);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isPersistent(mockRegion));
+ assertThat(function.isPersistent(mockRegion)).isFalse();
}
@Test
public void testIsRegionUsingDiskStoreWhenUsingDefaultDiskStore() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- atLeast(1).of(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PERSISTENT_REPLICATE));
- oneOf(mockRegionAttributes).getDiskStoreName();
- will(returnValue(null));
- oneOf(mockDiskStore).getName();
- will(returnValue(DiskStoreDetails.DEFAULT_DISK_STORE_NAME));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PERSISTENT_REPLICATE);
+ when(mockRegionAttributes.getDiskStoreName()).thenReturn(null);
+ when(mockDiskStore.getName()).thenReturn(DiskStoreDetails.DEFAULT_DISK_STORE_NAME);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isUsingDiskStore(mockRegion, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockRegion, mockDiskStore)).isTrue();
+ verify(mockRegion, atLeastOnce()).getAttributes();
}
@Test
public void testIsRegionUsingDiskStoreWhenPersistent() {
final String diskStoreName = "testDiskStore";
-
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- atLeast(1).of(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PERSISTENT_PARTITION));
- oneOf(mockRegionAttributes).getDiskStoreName();
- will(returnValue(diskStoreName));
- oneOf(mockDiskStore).getName();
- will(returnValue(diskStoreName));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PERSISTENT_PARTITION);
+ when(mockRegionAttributes.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockDiskStore.getName()).thenReturn(diskStoreName);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isUsingDiskStore(mockRegion, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockRegion, mockDiskStore)).isTrue();
+ verify(mockRegion, atLeastOnce()).getAttributes();
}
@Test
public void testIsRegionUsingDiskStoreWhenOverflowing() {
final String diskStoreName = "testDiskStore";
-
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
+ final Region mockRegion = mock(Region.class, "Region");
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
final EvictionAttributes mockEvictionAttributes =
- mockContext.mock(EvictionAttributes.class, "EvictionAttributes");
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- exactly(4).of(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PARTITION));
- oneOf(mockRegionAttributes).getDiskStoreName();
- will(returnValue(diskStoreName));
- exactly(2).of(mockRegionAttributes).getEvictionAttributes();
- will(returnValue(mockEvictionAttributes));
- oneOf(mockEvictionAttributes).getAction();
- will(returnValue(EvictionAction.OVERFLOW_TO_DISK));
- oneOf(mockDiskStore).getName();
- will(returnValue(diskStoreName));
- }
- });
+ mock(EvictionAttributes.class, "EvictionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PARTITION);
+ when(mockRegionAttributes.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockRegionAttributes.getEvictionAttributes()).thenReturn(mockEvictionAttributes);
+ when(mockEvictionAttributes.getAction()).thenReturn(EvictionAction.OVERFLOW_TO_DISK);
+ when(mockDiskStore.getName()).thenReturn(diskStoreName);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isUsingDiskStore(mockRegion, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockRegion, mockDiskStore)).isTrue();
+ verify(mockRegion, times(4)).getAttributes();
+ verify(mockRegionAttributes, times(2)).getEvictionAttributes();
}
@Test
public void testIsRegionUsingDiskStoreWhenDiskStoresMismatch() {
- final Region mockRegion = mockContext.mock(Region.class, "Region");
- final RegionAttributes mockRegionAttributes =
- mockContext.mock(RegionAttributes.class, "RegionAttributes");
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- atLeast(1).of(mockRegion).getAttributes();
- will(returnValue(mockRegionAttributes));
- oneOf(mockRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PERSISTENT_PARTITION));
- oneOf(mockRegionAttributes).getDiskStoreName();
- will(returnValue("mockDiskStore"));
- oneOf(mockDiskStore).getName();
- will(returnValue("testDiskStore"));
- }
- });
+ final Region mockRegion = mock(Region.class, "Region");
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final RegionAttributes mockRegionAttributes = mock(RegionAttributes.class, "RegionAttributes");
+ when(mockRegion.getAttributes()).thenReturn(mockRegionAttributes);
+ when(mockRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PERSISTENT_PARTITION);
+ when(mockRegionAttributes.getDiskStoreName()).thenReturn("mockDiskStore");
+ when(mockDiskStore.getName()).thenReturn("testDiskStore");
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isUsingDiskStore(mockRegion, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockRegion, mockDiskStore)).isFalse();
}
@Test
public void testSetRegionDetails() {
+ // Prepare Mocks
final String diskStoreName = "companyDiskStore";
- final Region mockCompanyRegion = mockContext.mock(Region.class, "/CompanyRegion");
- final Region mockContractorsRegion =
- mockContext.mock(Region.class, "/CompanyRegion/ContractorsRegion");
- final Region mockEmployeeRegion =
- mockContext.mock(Region.class, "/CompanyRegion/EmployeeRegion");
- final Region mockRolesRegion =
- mockContext.mock(Region.class, "/CompanyRegion/EmployeeRegion/RolesRegion");
- final Region mockProductsRegion =
- mockContext.mock(Region.class, "/CompanyRegion/ProductsRegion");
- final Region mockServicesRegion =
- mockContext.mock(Region.class, "/CompanyRegion/ServicesRegion");
- final Region mockPartnersRegion = mockContext.mock(Region.class, "/PartnersRegion");
- final Region mockCustomersRegion = mockContext.mock(Region.class, "/CustomersRegion");
-
+ final Region mockCompanyRegion = mock(Region.class, "/CompanyRegion");
final RegionAttributes mockCompanyRegionAttributes =
- mockContext.mock(RegionAttributes.class, "CompanyRegionAttributes");
- final RegionAttributes mockContractorsRegionAttributes =
- mockContext.mock(RegionAttributes.class, "ContractorsRegionAttributes");
+ mock(RegionAttributes.class, "CompanyRegionAttributes");
+ final EvictionAttributes mockCompanyEvictionAttributes =
+ mock(EvictionAttributes.class, "CompanyEvictionAttributes");
+ when(mockCompanyRegion.getAttributes()).thenReturn(mockCompanyRegionAttributes);
+ when(mockCompanyRegion.getFullPath()).thenReturn("/CompanyRegion");
+ when(mockCompanyRegion.getName()).thenReturn("CompanyRegion");
+ when(mockCompanyRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PERSISTENT_PARTITION);
+ when(mockCompanyRegionAttributes.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockCompanyRegionAttributes.getEvictionAttributes())
+ .thenReturn(mockCompanyEvictionAttributes);
+ when(mockCompanyEvictionAttributes.getAction()).thenReturn(EvictionAction.LOCAL_DESTROY);
+
+ final Region mockEmployeeRegion = mock(Region.class, "/CompanyRegion/EmployeeRegion");
+ when(mockEmployeeRegion.getAttributes()).thenReturn(mockCompanyRegionAttributes);
+ when(mockEmployeeRegion.getFullPath()).thenReturn("/CompanyRegion/EmployeeRegion");
+ when(mockEmployeeRegion.getName()).thenReturn("EmployeeRegion");
+
+ final Region mockProductsRegion = mock(Region.class, "/CompanyRegion/ProductsRegion");
final RegionAttributes mockProductsServicesRegionAttributes =
- mockContext.mock(RegionAttributes.class, "ProductsServicesRegionAttributes");
+ mock(RegionAttributes.class, "ProductsServicesRegionAttributes");
+ when(mockProductsRegion.getAttributes()).thenReturn(mockProductsServicesRegionAttributes);
+ when(mockProductsRegion.subregions(false)).thenReturn(Collections.emptySet());
+ when(mockProductsServicesRegionAttributes.getDataPolicy())
+ .thenReturn(DataPolicy.PERSISTENT_REPLICATE);
+ when(mockProductsServicesRegionAttributes.getDiskStoreName())
+ .thenReturn("productsServicesDiskStore");
+
+ final Region mockServicesRegion = mock(Region.class, "/CompanyRegion/ServicesRegion");
+ when(mockServicesRegion.getAttributes()).thenReturn(mockProductsServicesRegionAttributes);
+ when(mockServicesRegion.subregions(false)).thenReturn(Collections.emptySet());
+
+ final Region mockContractorsRegion = mock(Region.class, "/CompanyRegion/ContractorsRegion");
+ final RegionAttributes mockContractorsRegionAttributes =
+ mock(RegionAttributes.class, "ContractorsRegionAttributes");
+ final EvictionAttributes mockContractorsEvictionAttributes =
+ mock(EvictionAttributes.class, "ContractorsEvictionAttributes");
+ when(mockContractorsRegion.getAttributes()).thenReturn(mockContractorsRegionAttributes);
+ when(mockContractorsRegion.getFullPath()).thenReturn("/CompanyRegion/ContractorsRegion");
+ when(mockContractorsRegion.getName()).thenReturn("ContractorsRegion");
+ when(mockContractorsRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.REPLICATE);
+ when(mockContractorsRegionAttributes.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockContractorsRegionAttributes.getEvictionAttributes())
+ .thenReturn(mockContractorsEvictionAttributes);
+ when(mockContractorsEvictionAttributes.getAction()).thenReturn(EvictionAction.OVERFLOW_TO_DISK);
+
+ final Region mockRolesRegion = mock(Region.class, "/CompanyRegion/EmployeeRegion/RolesRegion");
+ when(mockRolesRegion.getAttributes()).thenReturn(mockCompanyRegionAttributes);
+ when(mockRolesRegion.getFullPath()).thenReturn("/CompanyRegion/EmployeeRegion/RolesRegion");
+ when(mockRolesRegion.getName()).thenReturn("RolesRegion");
+ when(mockRolesRegion.subregions(false)).thenReturn(Collections.emptySet());
+
+ final Region mockPartnersRegion = mock(Region.class, "/PartnersRegion");
final RegionAttributes mockPartnersRegionAttributes =
- mockContext.mock(RegionAttributes.class, "PartnersRegionAttributes");
- final RegionAttributes mockCustomersRegionAttributes =
- mockContext.mock(RegionAttributes.class, "CustomersRegionAttributes");
+ mock(RegionAttributes.class, "PartnersRegionAttributes");
+ when(mockPartnersRegion.getAttributes()).thenReturn(mockPartnersRegionAttributes);
+ when(mockPartnersRegion.subregions(false)).thenReturn(Collections.emptySet());
+ when(mockPartnersRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.PERSISTENT_PARTITION);
+ when(mockPartnersRegionAttributes.getDiskStoreName()).thenReturn("");
- final EvictionAttributes mockCompanyEvictionAttributes =
- mockContext.mock(EvictionAttributes.class, "CompanyEvictionAttributes");
- final EvictionAttributes mockContractorsEvictionAttributes =
- mockContext.mock(EvictionAttributes.class, "ContractorsEvictionAttributes");
+ final Region mockCustomersRegion = mock(Region.class, "/CustomersRegion");
+ final RegionAttributes mockCustomersRegionAttributes =
+ mock(RegionAttributes.class, "CustomersRegionAttributes");
final EvictionAttributes mockCustomersEvictionAttributes =
- mockContext.mock(EvictionAttributes.class, "CustomersEvictionAttributes");
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).rootRegions();
- will(returnValue(
- CollectionUtils.asSet(mockCompanyRegion, mockPartnersRegion, mockCustomersRegion)));
- exactly(5).of(mockCompanyRegion).getAttributes();
- will(returnValue(mockCompanyRegionAttributes));
- oneOf(mockCompanyRegion).getFullPath();
- will(returnValue("/CompanyRegion"));
- oneOf(mockCompanyRegion).getName();
- will(returnValue("CompanyRegion"));
- oneOf(mockCompanyRegion).subregions(false);
- will(returnValue(CollectionUtils.asSet(mockContractorsRegion, mockEmployeeRegion,
- mockProductsRegion, mockServicesRegion)));
- exactly(5).of(mockEmployeeRegion).getAttributes();
- will(returnValue(mockCompanyRegionAttributes));
- oneOf(mockEmployeeRegion).getFullPath();
- will(returnValue("/CompanyRegion/EmployeeRegion"));
- oneOf(mockEmployeeRegion).getName();
- will(returnValue("EmployeeRegion"));
- oneOf(mockEmployeeRegion).subregions(false);
- will(returnValue(CollectionUtils.asSet(mockRolesRegion)));
- exactly(5).of(mockRolesRegion).getAttributes();
- will(returnValue(mockCompanyRegionAttributes));
- oneOf(mockRolesRegion).getFullPath();
- will(returnValue("/CompanyRegion/EmployeeRegion/RolesRegion"));
- oneOf(mockRolesRegion).getName();
- will(returnValue("RolesRegion"));
- oneOf(mockRolesRegion).subregions(false);
- will(returnValue(Collections.emptySet()));
- exactly(6).of(mockCompanyRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PERSISTENT_PARTITION));
- exactly(3).of(mockCompanyRegionAttributes).getDiskStoreName();
- will(returnValue(diskStoreName));
- exactly(6).of(mockCompanyRegionAttributes).getEvictionAttributes();
- will(returnValue(mockCompanyEvictionAttributes));
- exactly(3).of(mockCompanyEvictionAttributes).getAction();
- will(returnValue(EvictionAction.LOCAL_DESTROY));
-
- exactly(7).of(mockContractorsRegion).getAttributes();
- will(returnValue(mockContractorsRegionAttributes));
- oneOf(mockContractorsRegion).getFullPath();
- will(returnValue("/CompanyRegion/ContractorsRegion"));
- oneOf(mockContractorsRegion).getName();
- will(returnValue("ContractorsRegion"));
- oneOf(mockContractorsRegion).subregions(false);
- will(returnValue(Collections.emptySet()));
- exactly(2).of(mockContractorsRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.REPLICATE));
- oneOf(mockContractorsRegionAttributes).getDiskStoreName();
- will(returnValue(diskStoreName));
- exactly(4).of(mockContractorsRegionAttributes).getEvictionAttributes();
- will(returnValue(mockContractorsEvictionAttributes));
- exactly(2).of(mockContractorsEvictionAttributes).getAction();
- will(returnValue(EvictionAction.OVERFLOW_TO_DISK));
-
- exactly(2).of(mockProductsRegion).getAttributes();
- will(returnValue(mockProductsServicesRegionAttributes));
- oneOf(mockProductsRegion).subregions(false);
- will(returnValue(Collections.emptySet()));
- exactly(2).of(mockServicesRegion).getAttributes();
- will(returnValue(mockProductsServicesRegionAttributes));
- oneOf(mockServicesRegion).subregions(false);
- will(returnValue(Collections.emptySet()));
- exactly(2).of(mockProductsServicesRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PERSISTENT_REPLICATE));
- exactly(2).of(mockProductsServicesRegionAttributes).getDiskStoreName();
- will(returnValue("productsServicesDiskStore"));
-
- exactly(2).of(mockPartnersRegion).getAttributes();
- will(returnValue(mockPartnersRegionAttributes));
- oneOf(mockPartnersRegion).subregions(false);
- will(returnValue(Collections.emptySet()));
- oneOf(mockPartnersRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.PERSISTENT_PARTITION));
- oneOf(mockPartnersRegionAttributes).getDiskStoreName();
- will(returnValue(""));
-
- exactly(4).of(mockCustomersRegion).getAttributes();
- will(returnValue(mockCustomersRegionAttributes));
- oneOf(mockCustomersRegion).subregions(false);
- will(returnValue(Collections.emptySet()));
- oneOf(mockCustomersRegionAttributes).getDataPolicy();
- will(returnValue(DataPolicy.REPLICATE));
- oneOf(mockCustomersRegionAttributes).getDiskStoreName();
- will(returnValue(null));
- exactly(2).of(mockCustomersRegionAttributes).getEvictionAttributes();
- will(returnValue(mockCustomersEvictionAttributes));
- oneOf(mockCustomersEvictionAttributes).getAction();
- will(returnValue(EvictionAction.OVERFLOW_TO_DISK));
-
- atLeast(1).of(mockDiskStore).getName();
- will(returnValue(diskStoreName));
- }
- });
-
+ mock(EvictionAttributes.class, "CustomersEvictionAttributes");
+ when(mockCustomersRegion.getAttributes()).thenReturn(mockCustomersRegionAttributes);
+ when(mockCustomersRegion.subregions(false)).thenReturn(Collections.emptySet());
+ when(mockCustomersRegionAttributes.getDataPolicy()).thenReturn(DataPolicy.REPLICATE);
+ when(mockCustomersRegionAttributes.getDiskStoreName()).thenReturn(null);
+ when(mockCustomersRegionAttributes.getEvictionAttributes())
+ .thenReturn(mockCustomersEvictionAttributes);
+ when(mockCustomersEvictionAttributes.getAction()).thenReturn(EvictionAction.OVERFLOW_TO_DISK);
+
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ when(mockDiskStore.getName()).thenReturn(diskStoreName);
+
+ Set<Region<?, ?>> mockRootRegions = new HashSet<>();
+ mockRootRegions.add(mockCompanyRegion);
+ mockRootRegions.add(mockPartnersRegion);
+ mockRootRegions.add(mockCustomersRegion);
+ when(mockCache.rootRegions()).thenReturn(mockRootRegions);
+ when(mockCompanyRegion.subregions(false)).thenReturn(CollectionUtils
+ .asSet(mockContractorsRegion, mockEmployeeRegion, mockProductsRegion, mockServicesRegion));
+ when(mockEmployeeRegion.subregions(false)).thenReturn(CollectionUtils.asSet(mockRolesRegion));
+ when(mockContractorsRegion.subregions(false)).thenReturn(Collections.emptySet());
+
+ // Execute Region and assert results
final Set<DiskStoreDetails.RegionDetails> expectedRegionDetails = CollectionUtils.asSet(
createRegionDetails("/CompanyRegion", "CompanyRegion", true, false),
createRegionDetails("/CompanyRegion/EmployeeRegion", "EmployeeRegion", true, false),
createRegionDetails("/CompanyRegion/EmployeeRegion/RolesRegion", "RolesRegion", true,
false),
createRegionDetails("/CompanyRegion/ContractorsRegion", "ContractorsRegion", false, true));
-
final DiskStoreDetails diskStoreDetails = new DiskStoreDetails(diskStoreName, "memberOne");
-
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.setRegionDetails(mockCache, mockDiskStore, diskStoreDetails);
-
assertRegionDetails(expectedRegionDetails, diskStoreDetails);
+ verify(mockCompanyRegion, times(5)).getAttributes();
+ verify(mockEmployeeRegion, times(5)).getAttributes();
+ verify(mockRolesRegion, times(5)).getAttributes();
+ verify(mockCompanyRegionAttributes, times(6)).getDataPolicy();
+ verify(mockCompanyRegionAttributes, times(3)).getDiskStoreName();
+ verify(mockCompanyRegionAttributes, times(6)).getEvictionAttributes();
+ verify(mockCompanyEvictionAttributes, times(3)).getAction();
+ verify(mockContractorsRegion, times(7)).getAttributes();
+ verify(mockContractorsRegionAttributes, times(2)).getDataPolicy();
+ verify(mockContractorsRegionAttributes, times(4)).getEvictionAttributes();
+ verify(mockContractorsEvictionAttributes, times(2)).getAction();
+ verify(mockProductsRegion, times(2)).getAttributes();
+ verify(mockServicesRegion, times(2)).getAttributes();
+ verify(mockProductsServicesRegionAttributes, times(2)).getDataPolicy();
+ verify(mockProductsServicesRegionAttributes, times(2)).getDiskStoreName();
+ verify(mockPartnersRegion, times(2)).getAttributes();
+ verify(mockCustomersRegion, times(4)).getAttributes();
+ verify(mockCustomersRegionAttributes, times(2)).getEvictionAttributes();
+ verify(mockDiskStore, atLeastOnce()).getName();
}
@Test
public void testGetCacheServerDiskStoreName() {
final String expectedDiskStoreName = "testDiskStore";
-
- final CacheServer mockCacheServer = mockContext.mock(CacheServer.class, "CacheServer");
+ final CacheServer mockCacheServer = mock(CacheServer.class, "CacheServer");
final ClientSubscriptionConfig mockClientSubscriptionConfig =
- mockContext.mock(ClientSubscriptionConfig.class, "ClientSubscriptionConfig");
-
- mockContext.checking(new Expectations() {
- {
- exactly(2).of(mockCacheServer).getClientSubscriptionConfig();
- will(returnValue(mockClientSubscriptionConfig));
- oneOf(mockClientSubscriptionConfig).getDiskStoreName();
- will(returnValue(expectedDiskStoreName));
- }
- });
+ mock(ClientSubscriptionConfig.class, "ClientSubscriptionConfig");
+ when(mockCacheServer.getClientSubscriptionConfig()).thenReturn(mockClientSubscriptionConfig);
+ when(mockClientSubscriptionConfig.getDiskStoreName()).thenReturn(expectedDiskStoreName);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertEquals(expectedDiskStoreName, function.getDiskStoreName(mockCacheServer));
+ assertThat(function.getDiskStoreName(mockCacheServer)).isEqualTo(expectedDiskStoreName);
+ verify(mockCacheServer, times(2)).getClientSubscriptionConfig();
}
@Test
public void testGetCacheServerDiskStoreNameWhenUnspecified() {
- final CacheServer mockCacheServer = mockContext.mock(CacheServer.class, "CacheServer");
+ final CacheServer mockCacheServer = mock(CacheServer.class, "CacheServer");
final ClientSubscriptionConfig mockClientSubscriptionConfig =
- mockContext.mock(ClientSubscriptionConfig.class, "ClientSubscriptionConfig");
-
- mockContext.checking(new Expectations() {
- {
- exactly(2).of(mockCacheServer).getClientSubscriptionConfig();
- will(returnValue(mockClientSubscriptionConfig));
- oneOf(mockClientSubscriptionConfig).getDiskStoreName();
- will(returnValue(null));
- }
- });
+ mock(ClientSubscriptionConfig.class, "ClientSubscriptionConfig");
+ when(mockCacheServer.getClientSubscriptionConfig()).thenReturn(mockClientSubscriptionConfig);
+ when(mockClientSubscriptionConfig.getDiskStoreName()).thenReturn(null);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertEquals(DiskStoreDetails.DEFAULT_DISK_STORE_NAME,
- function.getDiskStoreName(mockCacheServer));
+ assertThat(function.getDiskStoreName(mockCacheServer))
+ .isEqualTo(DiskStoreDetails.DEFAULT_DISK_STORE_NAME);
+ verify(mockCacheServer, times(2)).getClientSubscriptionConfig();
}
@Test
public void testGetCacheServerDiskStoreNameWithNullClientSubscriptionConfig() {
- final CacheServer mockCacheServer = mockContext.mock(CacheServer.class, "CacheServer");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCacheServer).getClientSubscriptionConfig();
- will(returnValue(null));
- }
- });
+ final CacheServer mockCacheServer = mock(CacheServer.class, "CacheServer");
+ when(mockCacheServer.getClientSubscriptionConfig()).thenReturn(null);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertNull(function.getDiskStoreName(mockCacheServer));
+ assertThat(function.getDiskStoreName(mockCacheServer)).isNull();
}
@Test
public void testIsCacheServerUsingDiskStore() {
final String diskStoreName = "testDiskStore";
-
- final CacheServer mockCacheServer = mockContext.mock(CacheServer.class, "CacheServer");
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final CacheServer mockCacheServer = mock(CacheServer.class, "CacheServer");
final ClientSubscriptionConfig mockClientSubscriptionConfig =
- mockContext.mock(ClientSubscriptionConfig.class, "ClientSubscriptionConfig");
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- exactly(2).of(mockCacheServer).getClientSubscriptionConfig();
- will(returnValue(mockClientSubscriptionConfig));
- oneOf(mockClientSubscriptionConfig).getDiskStoreName();
- will(returnValue(diskStoreName));
- oneOf(mockDiskStore).getName();
- will(returnValue(diskStoreName));
- }
- });
+ mock(ClientSubscriptionConfig.class, "ClientSubscriptionConfig");
+ when(mockCacheServer.getClientSubscriptionConfig()).thenReturn(mockClientSubscriptionConfig);
+ when(mockClientSubscriptionConfig.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockDiskStore.getName()).thenReturn(diskStoreName);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
+ assertThat(function.isUsingDiskStore(mockCacheServer, mockDiskStore)).isTrue();
+ verify(mockCacheServer, times(2)).getClientSubscriptionConfig();
- assertTrue(function.isUsingDiskStore(mockCacheServer, mockDiskStore));
}
@Test
public void testIsCacheServerUsingDiskStoreWhenDiskStoresMismatch() {
- final CacheServer mockCacheServer = mockContext.mock(CacheServer.class, "CacheServer");
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final CacheServer mockCacheServer = mock(CacheServer.class, "CacheServer");
final ClientSubscriptionConfig mockClientSubscriptionConfig =
- mockContext.mock(ClientSubscriptionConfig.class, "ClientSubscriptionConfig");
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- exactly(2).of(mockCacheServer).getClientSubscriptionConfig();
- will(returnValue(mockClientSubscriptionConfig));
- oneOf(mockClientSubscriptionConfig).getDiskStoreName();
- will(returnValue(" "));
- oneOf(mockDiskStore).getName();
- will(returnValue("otherDiskStore"));
- }
- });
+ mock(ClientSubscriptionConfig.class, "ClientSubscriptionConfig");
+ when(mockCacheServer.getClientSubscriptionConfig()).thenReturn(mockClientSubscriptionConfig);
+ when(mockClientSubscriptionConfig.getDiskStoreName()).thenReturn(" ");
+ when(mockDiskStore.getName()).thenReturn("otherDiskStore");
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isUsingDiskStore(mockCacheServer, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockCacheServer, mockDiskStore)).isFalse();
+ verify(mockCacheServer, times(2)).getClientSubscriptionConfig();
}
@Test
public void testIsCacheServerUsingDiskStoreWhenUsingDefaultDiskStore() {
- final CacheServer mockCacheServer = mockContext.mock(CacheServer.class, "CacheServer");
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final CacheServer mockCacheServer = mock(CacheServer.class, "CacheServer");
final ClientSubscriptionConfig mockClientSubscriptionConfig =
- mockContext.mock(ClientSubscriptionConfig.class, "ClientSubscriptionConfig");
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- exactly(2).of(mockCacheServer).getClientSubscriptionConfig();
- will(returnValue(mockClientSubscriptionConfig));
- oneOf(mockClientSubscriptionConfig).getDiskStoreName();
- will(returnValue(""));
- oneOf(mockDiskStore).getName();
- will(returnValue(DiskStoreDetails.DEFAULT_DISK_STORE_NAME));
- }
- });
+ mock(ClientSubscriptionConfig.class, "ClientSubscriptionConfig");
+ when(mockCacheServer.getClientSubscriptionConfig()).thenReturn(mockClientSubscriptionConfig);
+ when(mockClientSubscriptionConfig.getDiskStoreName()).thenReturn("");
+ when(mockDiskStore.getName()).thenReturn(DiskStoreDetails.DEFAULT_DISK_STORE_NAME);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isUsingDiskStore(mockCacheServer, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockCacheServer, mockDiskStore)).isTrue();
+ verify(mockCacheServer, times(2)).getClientSubscriptionConfig();
}
@Test
public void testSetCacheServerDetails() {
final String diskStoreName = "testDiskStore";
-
- final CacheServer mockCacheServer1 = mockContext.mock(CacheServer.class, "CacheServer1");
- final CacheServer mockCacheServer2 = mockContext.mock(CacheServer.class, "CacheServer2");
- final CacheServer mockCacheServer3 = mockContext.mock(CacheServer.class, "CacheServer3");
-
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final CacheServer mockCacheServer1 = mock(CacheServer.class, "CacheServer1");
+ final CacheServer mockCacheServer2 = mock(CacheServer.class, "CacheServer2");
+ final CacheServer mockCacheServer3 = mock(CacheServer.class, "CacheServer3");
final ClientSubscriptionConfig mockCacheServer1ClientSubscriptionConfig =
- mockContext.mock(ClientSubscriptionConfig.class, "cacheServer1ClientSubscriptionConfig");
+ mock(ClientSubscriptionConfig.class, "cacheServer1ClientSubscriptionConfig");
final ClientSubscriptionConfig mockCacheServer2ClientSubscriptionConfig =
- mockContext.mock(ClientSubscriptionConfig.class, "cacheServer2ClientSubscriptionConfig");
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getCacheServers();
- will(returnValue(Arrays.asList(mockCacheServer1, mockCacheServer2, mockCacheServer3)));
- exactly(2).of(mockCacheServer1).getClientSubscriptionConfig();
- will(returnValue(mockCacheServer1ClientSubscriptionConfig));
- oneOf(mockCacheServer1ClientSubscriptionConfig).getDiskStoreName();
- will(returnValue(diskStoreName));
- oneOf(mockCacheServer1).getBindAddress();
- will(returnValue("10.127.255.1"));
- oneOf(mockCacheServer1).getPort();
- will(returnValue(65536));
- oneOf(mockCacheServer1).getHostnameForClients();
- will(returnValue("gemini"));
- exactly(2).of(mockCacheServer2).getClientSubscriptionConfig();
- will(returnValue(mockCacheServer2ClientSubscriptionConfig));
- oneOf(mockCacheServer2ClientSubscriptionConfig).getDiskStoreName();
- will(returnValue(" "));
- oneOf(mockCacheServer3).getClientSubscriptionConfig();
- will(returnValue(null));
- exactly(3).of(mockDiskStore).getName();
- will(returnValue(diskStoreName));
- }
- });
+ mock(ClientSubscriptionConfig.class, "cacheServer2ClientSubscriptionConfig");
+ when(mockCache.getCacheServers())
+ .thenReturn(Arrays.asList(mockCacheServer1, mockCacheServer2, mockCacheServer3));
+ when(mockCacheServer1.getClientSubscriptionConfig())
+ .thenReturn(mockCacheServer1ClientSubscriptionConfig);
+ when(mockCacheServer1ClientSubscriptionConfig.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockCacheServer1.getBindAddress()).thenReturn("10.127.255.1");
+ when(mockCacheServer1.getPort()).thenReturn(65536);
+ when(mockCacheServer1.getHostnameForClients()).thenReturn("gemini");
+ when(mockCacheServer2.getClientSubscriptionConfig())
+ .thenReturn(mockCacheServer2ClientSubscriptionConfig);
+ when(mockCacheServer2ClientSubscriptionConfig.getDiskStoreName()).thenReturn(" ");
+ when(mockCacheServer3.getClientSubscriptionConfig()).thenReturn(null);
+ when(mockDiskStore.getName()).thenReturn(diskStoreName);
final Set<DiskStoreDetails.CacheServerDetails> expectedCacheServerDetails =
CollectionUtils.asSet(createCacheServerDetails("10.127.255.1", 65536, "gemini"));
-
final DiskStoreDetails diskStoreDetails = new DiskStoreDetails(diskStoreName, "memberOne");
-
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.setCacheServerDetails(mockCache, mockDiskStore, diskStoreDetails);
-
assertCacheServerDetails(expectedCacheServerDetails, diskStoreDetails);
+ verify(mockCacheServer1, times(2)).getClientSubscriptionConfig();
+ verify(mockCacheServer2, times(2)).getClientSubscriptionConfig();
+ verify(mockDiskStore, times(3)).getName();
}
@Test
public void testGetGatewaySenderDiskStoreName() {
final String expectedDiskStoreName = "testDiskStore";
-
- final GatewaySender mockGatewaySender = mockContext.mock(GatewaySender.class, "GatewaySender");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockGatewaySender).getDiskStoreName();
- will(returnValue(expectedDiskStoreName));
- }
- });
+ final GatewaySender mockGatewaySender = mock(GatewaySender.class, "GatewaySender");
+ when(mockGatewaySender.getDiskStoreName()).thenReturn(expectedDiskStoreName);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertEquals(expectedDiskStoreName, function.getDiskStoreName(mockGatewaySender));
+ assertThat(function.getDiskStoreName(mockGatewaySender)).isEqualTo(expectedDiskStoreName);
}
@Test
public void testGetGatewaySenderDiskStoreNameWhenUnspecified() {
- final GatewaySender mockGatewaySender = mockContext.mock(GatewaySender.class, "GatewaySender");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockGatewaySender).getDiskStoreName();
- will(returnValue(" "));
- }
- });
+ final GatewaySender mockGatewaySender = mock(GatewaySender.class, "GatewaySender");
+ when(mockGatewaySender.getDiskStoreName()).thenReturn(" ");
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertEquals(DiskStoreDetails.DEFAULT_DISK_STORE_NAME,
- function.getDiskStoreName(mockGatewaySender));
+ assertThat(function.getDiskStoreName(mockGatewaySender))
+ .isEqualTo(DiskStoreDetails.DEFAULT_DISK_STORE_NAME);
}
@Test
public void testIsGatewaySenderPersistent() {
- final GatewaySender mockGatewaySender = mockContext.mock(GatewaySender.class, "GatewaySender");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockGatewaySender).isPersistenceEnabled();
- will(returnValue(true));
- }
- });
+ final GatewaySender mockGatewaySender = mock(GatewaySender.class, "GatewaySender");
+ when(mockGatewaySender.isPersistenceEnabled()).thenReturn(true);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isPersistent(mockGatewaySender));
+ assertThat(function.isPersistent(mockGatewaySender)).isTrue();
}
@Test
public void testIsGatewaySenderPersistentWhenPersistenceIsNotEnabled() {
- final GatewaySender mockGatewaySender = mockContext.mock(GatewaySender.class, "GatewaySender");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockGatewaySender).isPersistenceEnabled();
- will(returnValue(true));
- }
- });
+ final GatewaySender mockGatewaySender = mock(GatewaySender.class, "GatewaySender");
+ when(mockGatewaySender.isPersistenceEnabled()).thenReturn(true);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isPersistent(mockGatewaySender));
+ assertThat(function.isPersistent(mockGatewaySender)).isTrue();
}
@Test
public void testIsGatewaySenderUsingDiskStore() {
final String diskStoreName = "testDiskStore";
-
- final GatewaySender mockGatewaySender = mockContext.mock(GatewaySender.class, "GatewaySender");
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockGatewaySender).getDiskStoreName();
- will(returnValue(diskStoreName));
- oneOf(mockDiskStore).getName();
- will(returnValue(diskStoreName));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final GatewaySender mockGatewaySender = mock(GatewaySender.class, "GatewaySender");
+ when(mockGatewaySender.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockDiskStore.getName()).thenReturn(diskStoreName);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isUsingDiskStore(mockGatewaySender, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockGatewaySender, mockDiskStore)).isTrue();
}
@Test
public void testIsGatewaySenderUsingDiskStoreWhenDiskStoresMismatch() {
- final GatewaySender mockGatewaySender = mockContext.mock(GatewaySender.class, "GatewaySender");
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockGatewaySender).getDiskStoreName();
- will(returnValue("mockDiskStore"));
- oneOf(mockDiskStore).getName();
- will(returnValue("testDiskStore"));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final GatewaySender mockGatewaySender = mock(GatewaySender.class, "GatewaySender");
+ when(mockGatewaySender.getDiskStoreName()).thenReturn("mockDiskStore");
+ when(mockDiskStore.getName()).thenReturn("testDiskStore");
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isUsingDiskStore(mockGatewaySender, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockGatewaySender, mockDiskStore)).isFalse();
}
@Test
public void testIsGatewaySenderUsingDiskStoreWhenUsingDefaultDiskStores() {
- final GatewaySender mockGatewaySender = mockContext.mock(GatewaySender.class, "GatewaySender");
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockGatewaySender).getDiskStoreName();
- will(returnValue(" "));
- oneOf(mockDiskStore).getName();
- will(returnValue(DiskStoreDetails.DEFAULT_DISK_STORE_NAME));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final GatewaySender mockGatewaySender = mock(GatewaySender.class, "GatewaySender");
+ when(mockGatewaySender.getDiskStoreName()).thenReturn(" ");
+ when(mockDiskStore.getName()).thenReturn(DiskStoreDetails.DEFAULT_DISK_STORE_NAME);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isUsingDiskStore(mockGatewaySender, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockGatewaySender, mockDiskStore)).isTrue();
}
@Test
public void testSetPdxSerializationDetails() {
final String diskStoreName = "testDiskStore";
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getPdxPersistent();
- will(returnValue(true));
- oneOf(mockCache).getPdxDiskStore();
- will(returnValue(diskStoreName));
- oneOf(mockDiskStore).getName();
- will(returnValue(diskStoreName));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ when(mockCache.getPdxPersistent()).thenReturn(true);
+ when(mockCache.getPdxDiskStore()).thenReturn(diskStoreName);
+ when(mockDiskStore.getName()).thenReturn(diskStoreName);
final DiskStoreDetails diskStoreDetails = new DiskStoreDetails(diskStoreName, "memberOne");
-
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.setPdxSerializationDetails(mockCache, mockDiskStore, diskStoreDetails);
-
- assertTrue(diskStoreDetails.isPdxSerializationMetaDataStored());
+ assertThat(diskStoreDetails.isPdxSerializationMetaDataStored()).isTrue();
}
@Test
public void testSetPdxSerializationDetailsWhenDiskStoreMismatch() {
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getPdxPersistent();
- will(returnValue(true));
- oneOf(mockCache).getPdxDiskStore();
- will(returnValue("mockDiskStore"));
- oneOf(mockDiskStore).getName();
- will(returnValue("testDiskStore"));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ when(mockCache.getPdxPersistent()).thenReturn(true);
+ when(mockCache.getPdxDiskStore()).thenReturn("mockDiskStore");
+ when(mockDiskStore.getName()).thenReturn("testDiskStore");
final DiskStoreDetails diskStoreDetails = new DiskStoreDetails("testDiskStore", "memberOne");
-
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.setPdxSerializationDetails(mockCache, mockDiskStore, diskStoreDetails);
-
- assertFalse(diskStoreDetails.isPdxSerializationMetaDataStored());
+ assertThat(diskStoreDetails.isPdxSerializationMetaDataStored()).isFalse();
}
@Test
public void testSetPdxSerializationDetailsWhenPdxIsNotPersistent() {
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getPdxPersistent();
- will(returnValue(false));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ when(mockCache.getPdxPersistent()).thenReturn(false);
final DiskStoreDetails diskStoreDetails = new DiskStoreDetails("testDiskStore", "memberOne");
-
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.setPdxSerializationDetails(mockCache, mockDiskStore, diskStoreDetails);
-
- assertFalse(diskStoreDetails.isPdxSerializationMetaDataStored());
+ assertThat(diskStoreDetails.isPdxSerializationMetaDataStored()).isFalse();
}
@Test
public void testGetAsyncEventQueueDiskStoreName() {
final String expectedDiskStoreName = "testDiskStore";
-
- final AsyncEventQueue mockQueue = mockContext.mock(AsyncEventQueue.class, "AsyncEventQueue");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockQueue).getDiskStoreName();
- will(returnValue(expectedDiskStoreName));
- }
- });
+ final AsyncEventQueue mockQueue = mock(AsyncEventQueue.class, "AsyncEventQueue");
+ when(mockQueue.getDiskStoreName()).thenReturn(expectedDiskStoreName);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertEquals(expectedDiskStoreName, function.getDiskStoreName(mockQueue));
+ assertThat(function.getDiskStoreName(mockQueue)).isEqualTo(expectedDiskStoreName);
}
@Test
public void testGetAsyncEventQueueDiskStoreNameUsingDefaultDiskStore() {
- final AsyncEventQueue mockQueue = mockContext.mock(AsyncEventQueue.class, "AsyncEventQueue");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockQueue).getDiskStoreName();
- will(returnValue(null));
- }
- });
+ final AsyncEventQueue mockQueue = mock(AsyncEventQueue.class, "AsyncEventQueue");
+ when(mockQueue.getDiskStoreName()).thenReturn(null);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertEquals(DiskStoreDetails.DEFAULT_DISK_STORE_NAME, function.getDiskStoreName(mockQueue));
+ assertThat(function.getDiskStoreName(mockQueue))
+ .isEqualTo(DiskStoreDetails.DEFAULT_DISK_STORE_NAME);
}
@Test
public void testIsAsyncEventQueueUsingDiskStore() {
final String diskStoreName = "testDiskStore";
-
- final AsyncEventQueue mockQueue = mockContext.mock(AsyncEventQueue.class, "AsyncEventQueue");
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockQueue).getDiskStoreName();
- will(returnValue(diskStoreName));
- oneOf(mockQueue).isPersistent();
- will(returnValue(true));
- oneOf(mockDiskStore).getName();
- will(returnValue(diskStoreName));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final AsyncEventQueue mockQueue = mock(AsyncEventQueue.class, "AsyncEventQueue");
+ when(mockQueue.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockQueue.isPersistent()).thenReturn(true);
+ when(mockDiskStore.getName()).thenReturn(diskStoreName);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isUsingDiskStore(mockQueue, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockQueue, mockDiskStore)).isTrue();
}
@Test
public void testIsAsyncEventQueueUsingDiskStoreWhenDiskStoresMismatch() {
- final AsyncEventQueue mockQueue = mockContext.mock(AsyncEventQueue.class, "AsyncEventQueue");
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockQueue).getDiskStoreName();
- will(returnValue("mockDiskStore"));
- oneOf(mockQueue).isPersistent();
- will(returnValue(true));
- oneOf(mockDiskStore).getName();
- will(returnValue(DiskStoreDetails.DEFAULT_DISK_STORE_NAME));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final AsyncEventQueue mockQueue = mock(AsyncEventQueue.class, "AsyncEventQueue");
+ when(mockQueue.getDiskStoreName()).thenReturn("mockDiskStore");
+ when(mockQueue.isPersistent()).thenReturn(true);
+ when(mockDiskStore.getName()).thenReturn(DiskStoreDetails.DEFAULT_DISK_STORE_NAME);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isUsingDiskStore(mockQueue, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockQueue, mockDiskStore)).isFalse();
}
@Test
public void testIsAsyncEventQueueUsingDiskStoreWhenQueueIsNotPersistent() {
- final String diskStoreName = "testDiskStore";
-
- final AsyncEventQueue mockQueue = mockContext.mock(AsyncEventQueue.class, "AsyncEventQueue");
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockQueue).isPersistent();
- will(returnValue(false));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final AsyncEventQueue mockQueue = mock(AsyncEventQueue.class, "AsyncEventQueue");
+ when(mockQueue.isPersistent()).thenReturn(false);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertFalse(function.isUsingDiskStore(mockQueue, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockQueue, mockDiskStore)).isFalse();
}
@Test
public void testIsAsyncEventQueueUsingDiskStoreWhenUsingDefaultDiskStore() {
- final AsyncEventQueue mockQueue = mockContext.mock(AsyncEventQueue.class, "AsyncEventQueue");
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockQueue).getDiskStoreName();
- will(returnValue(" "));
- oneOf(mockQueue).isPersistent();
- will(returnValue(true));
- oneOf(mockDiskStore).getName();
- will(returnValue(DiskStoreDetails.DEFAULT_DISK_STORE_NAME));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final AsyncEventQueue mockQueue = mock(AsyncEventQueue.class, "AsyncEventQueue");
+ when(mockQueue.getDiskStoreName()).thenReturn(" ");
+ when(mockQueue.isPersistent()).thenReturn(true);
+ when(mockDiskStore.getName()).thenReturn(DiskStoreDetails.DEFAULT_DISK_STORE_NAME);
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
- assertTrue(function.isUsingDiskStore(mockQueue, mockDiskStore));
+ assertThat(function.isUsingDiskStore(mockQueue, mockDiskStore)).isTrue();
}
@Test
public void testSetAsyncEventQueueDetails() {
final String diskStoreName = "testDiskStore";
-
- final AsyncEventQueue mockQueue1 = mockContext.mock(AsyncEventQueue.class, "AsyncEvenQueue1");
- final AsyncEventQueue mockQueue2 = mockContext.mock(AsyncEventQueue.class, "AsyncEvenQueue2");
- final AsyncEventQueue mockQueue3 = mockContext.mock(AsyncEventQueue.class, "AsyncEvenQueue3");
-
- final DiskStore mockDiskStore = mockContext.mock(DiskStore.class, "DiskStore");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getAsyncEventQueues();
- will(returnValue(CollectionUtils.asSet(mockQueue1, mockQueue2, mockQueue3)));
- oneOf(mockQueue1).isPersistent();
- will(returnValue(true));
- oneOf(mockQueue1).getDiskStoreName();
- will(returnValue(diskStoreName));
- oneOf(mockQueue1).getId();
- will(returnValue("q1"));
- oneOf(mockQueue2).isPersistent();
- will(returnValue(true));
- oneOf(mockQueue2).getDiskStoreName();
- will(returnValue(null));
- oneOf(mockQueue3).isPersistent();
- will(returnValue(false));
- atLeast(1).of(mockDiskStore).getName();
- will(returnValue(diskStoreName));
- }
- });
+ final DiskStore mockDiskStore = mock(DiskStore.class, "DiskStore");
+ final AsyncEventQueue mockQueue1 = mock(AsyncEventQueue.class, "AsyncEvenQueue1");
+ final AsyncEventQueue mockQueue2 = mock(AsyncEventQueue.class, "AsyncEvenQueue2");
+ final AsyncEventQueue mockQueue3 = mock(AsyncEventQueue.class, "AsyncEvenQueue3");
+ when(mockCache.getAsyncEventQueues())
+ .thenReturn(CollectionUtils.asSet(mockQueue1, mockQueue2, mockQueue3));
+ when(mockQueue1.isPersistent()).thenReturn(true);
+ when(mockQueue1.getDiskStoreName()).thenReturn(diskStoreName);
+ when(mockQueue1.getId()).thenReturn("q1");
+ when(mockQueue2.isPersistent()).thenReturn(true);
+ when(mockQueue2.getDiskStoreName()).thenReturn(null);
+ when(mockQueue3.isPersistent()).thenReturn(false);
+ when(mockDiskStore.getName()).thenReturn(diskStoreName);
final Set<DiskStoreDetails.AsyncEventQueueDetails> expectedAsyncEventQueueDetails =
CollectionUtils.asSet(createAsyncEventQueueDetails("q1"));
-
final DiskStoreDetails diskStoreDetails = new DiskStoreDetails(diskStoreName, "memberOne");
-
final DescribeDiskStoreFunction function = new DescribeDiskStoreFunction();
-
function.setAsyncEventQueueDetails(mockCache, mockDiskStore, diskStoreDetails);
-
assertAsyncEventQueueDetails(expectedAsyncEventQueueDetails, diskStoreDetails);
+ verify(mockDiskStore, atLeastOnce()).getName();
}
private static class TestResultSender implements ResultSender {
-
- private final List<Object> results = new LinkedList<>();
-
private Throwable t;
+ private final List<Object> results = new LinkedList<>();
protected List<Object> getResults() throws Throwable {
if (t != null) {
throw t;
}
+
return Collections.unmodifiableList(results);
}
@@ -1805,5 +1197,4 @@ public class DescribeDiskStoreFunctionJUnitTest {
this.t = t;
}
}
-
}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/ListDiskStoresFunctionJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/ListDiskStoresFunctionJUnitTest.java
index bcd3444..e9f2a63 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/ListDiskStoresFunctionJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/ListDiskStoresFunctionJUnitTest.java
@@ -14,11 +14,13 @@
*/
package org.apache.geode.management.internal.cli.functions;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@@ -27,16 +29,12 @@ import java.util.List;
import java.util.Set;
import java.util.UUID;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheClosedException;
+import org.apache.geode.cache.DiskStore;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.execute.ResultSender;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
@@ -52,251 +50,143 @@ import org.apache.geode.management.internal.cli.domain.DiskStoreDetails;
* @see org.apache.geode.internal.cache.DiskStoreImpl
* @see org.apache.geode.management.internal.cli.domain.DiskStoreDetails
* @see org.apache.geode.management.internal.cli.functions.ListDiskStoresFunction
- * @see org.jmock.Expectations
- * @see org.jmock.Mockery
- * @see org.junit.Assert
* @see org.junit.Test
* @since GemFire 7.0
*/
public class ListDiskStoresFunctionJUnitTest {
-
- private Mockery mockContext;
private InternalCache mockCache;
private FunctionContext mockFunctionContext;
-
-
@Before
public void setup() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
-
- mockCache = mockContext.mock(InternalCache.class, "Cache");
- mockFunctionContext = mockContext.mock(FunctionContext.class, "FunctionContext");
- }
-
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
- }
-
- private DiskStoreDetails createDiskStoreDetails(final UUID id, final String name,
- final String memberName, final String memberId) {
- return new DiskStoreDetails(id, name, memberId, memberName);
+ mockCache = mock(InternalCache.class, "Cache");
+ mockFunctionContext = mock(FunctionContext.class, "FunctionContext");
}
@Test
@SuppressWarnings("unchecked")
public void testExecute() throws Throwable {
+ final String memberId = "mockMemberId";
+ final String memberName = "mockMemberName";
final UUID mockDiskStoreOneId = UUID.randomUUID();
final UUID mockDiskStoreTwoId = UUID.randomUUID();
final UUID mockDiskStoreThreeId = UUID.randomUUID();
-
- final String memberId = "mockMemberId";
- final String memberName = "mockMemberName";
-
+ final DiskStoreImpl mockDiskStoreOne = mock(DiskStoreImpl.class, "DiskStoreOne");
+ final DiskStoreImpl mockDiskStoreTwo = mock(DiskStoreImpl.class, "DiskStoreTwo");
+ final DiskStoreImpl mockDiskStoreThree = mock(DiskStoreImpl.class, "DiskStoreThree");
final InternalDistributedMember mockMember =
- mockContext.mock(InternalDistributedMember.class, "DistributedMember");
-
- final DiskStoreImpl mockDiskStoreOne = mockContext.mock(DiskStoreImpl.class, "DiskStoreOne");
- final DiskStoreImpl mockDiskStoreTwo = mockContext.mock(DiskStoreImpl.class, "DiskStoreTwo");
- final DiskStoreImpl mockDiskStoreThree =
- mockContext.mock(DiskStoreImpl.class, "DiskStoreThree");
-
- final Collection<DiskStoreImpl> mockDiskStores = new ArrayList<DiskStoreImpl>();
-
- mockDiskStores.add(mockDiskStoreOne);
- mockDiskStores.add(mockDiskStoreTwo);
- mockDiskStores.add(mockDiskStoreThree);
-
+ mock(InternalDistributedMember.class, "DistributedMember");
+ final Collection<DiskStore> mockDiskStores =
+ Arrays.asList(mockDiskStoreOne, mockDiskStoreTwo, mockDiskStoreThree);
final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getMyId();
- will(returnValue(mockMember));
- oneOf(mockCache).listDiskStoresIncludingRegionOwned();
- will(returnValue(mockDiskStores));
- exactly(3).of(mockMember).getId();
- will(returnValue(memberId));
- exactly(3).of(mockMember).getName();
- will(returnValue(memberName));
- oneOf(mockDiskStoreOne).getDiskStoreUUID();
- will(returnValue(mockDiskStoreOneId));
- oneOf(mockDiskStoreOne).getName();
- will(returnValue("ds-backup"));
- oneOf(mockDiskStoreTwo).getDiskStoreUUID();
- will(returnValue(mockDiskStoreTwoId));
- oneOf(mockDiskStoreTwo).getName();
- will(returnValue("ds-overflow"));
- oneOf(mockDiskStoreThree).getDiskStoreUUID();
- will(returnValue(mockDiskStoreThreeId));
- oneOf(mockDiskStoreThree).getName();
- will(returnValue("ds-persistence"));
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockCache));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
+ when(mockCache.getMyId()).thenReturn(mockMember);
+ when(mockCache.listDiskStoresIncludingRegionOwned()).thenReturn(mockDiskStores);
+ when(mockMember.getId()).thenReturn(memberId);
+ when(mockMember.getName()).thenReturn(memberName);
+ when(mockDiskStoreOne.getDiskStoreUUID()).thenReturn(mockDiskStoreOneId);
+ when(mockDiskStoreOne.getName()).thenReturn("ds-backup");
+ when(mockDiskStoreTwo.getDiskStoreUUID()).thenReturn(mockDiskStoreTwoId);
+ when(mockDiskStoreTwo.getName()).thenReturn("ds-overflow");
+ when(mockDiskStoreThree.getDiskStoreUUID()).thenReturn(mockDiskStoreThreeId);
+ when(mockDiskStoreThree.getName()).thenReturn("ds-persistence");
+ when(mockFunctionContext.getCache()).thenReturn(mockCache);
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
final ListDiskStoresFunction function = new ListDiskStoresFunction();
-
function.execute(mockFunctionContext);
final List<?> results = testResultSender.getResults();
-
- assertNotNull(results);
- assertEquals(1, results.size());
+ assertThat(results).isNotNull();
+ assertThat(results.size()).isEqualTo(1);
final Set<DiskStoreDetails> diskStoreDetails = (Set<DiskStoreDetails>) results.get(0);
-
- assertNotNull(diskStoreDetails);
- assertEquals(3, diskStoreDetails.size());
+ assertThat(diskStoreDetails).isNotNull();
+ assertThat(diskStoreDetails.size()).isEqualTo(3);
+ verify(mockMember, times(3)).getId();
+ verify(mockMember, times(3)).getName();
diskStoreDetails.containsAll(
- Arrays.asList(createDiskStoreDetails(mockDiskStoreOneId, "ds-backup", memberId, memberName),
- createDiskStoreDetails(mockDiskStoreTwoId, "ds-overflow", memberId, memberName),
- createDiskStoreDetails(mockDiskStoreThreeId, "ds-persistence", memberId, memberName)));
+ Arrays.asList(new DiskStoreDetails(mockDiskStoreOneId, "ds-backup", memberId, memberName),
+ new DiskStoreDetails(mockDiskStoreTwoId, "ds-overflow", memberId, memberName),
+ new DiskStoreDetails(mockDiskStoreThreeId, "ds-persistence", memberId, memberName)));
}
- @Test(expected = CacheClosedException.class)
- public void testExecuteOnMemberWithNoCache() throws Throwable {
- final FunctionContext mockFunctionContext =
- mockContext.mock(FunctionContext.class, "MockFunctionContext");
-
+ @Test
+ public void testExecuteOnMemberWithNoCache() {
final ListDiskStoresFunction testListDiskStoresFunction = new ListDiskStoresFunction();
-
final TestResultSender testResultSender = new TestResultSender();
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionContext).getCache();
- will(throwException(new CacheClosedException("Expected")));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
-
+ when(mockFunctionContext.getCache())
+ .thenThrow(new CacheClosedException("Mocked CacheClosedException"));
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
testListDiskStoresFunction.execute(mockFunctionContext);
-
- try {
- testResultSender.getResults();
- } catch (CacheClosedException expected) {
- assertEquals("Expected", expected.getMessage());
- throw expected;
- }
+ assertThatThrownBy(testResultSender::getResults).isInstanceOf(CacheClosedException.class)
+ .hasMessage("Mocked CacheClosedException");
}
@Test
@SuppressWarnings("unchecked")
public void testExecuteOnMemberHavingNoDiskStores() throws Throwable {
final InternalDistributedMember mockMember =
- mockContext.mock(InternalDistributedMember.class, "DistributedMember");
-
+ mock(InternalDistributedMember.class, "DistributedMember");
final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getMyId();
- will(returnValue(mockMember));
- oneOf(mockCache).listDiskStoresIncludingRegionOwned();
- will(returnValue(Collections.emptyList()));
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockCache));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
+ when(mockCache.getMyId()).thenReturn(mockMember);
+ when(mockCache.listDiskStoresIncludingRegionOwned()).thenReturn(Collections.emptyList());
+ when(mockFunctionContext.getCache()).thenReturn(mockCache);
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
final ListDiskStoresFunction function = new ListDiskStoresFunction();
-
function.execute(mockFunctionContext);
final List<?> results = testResultSender.getResults();
-
- assertNotNull(results);
- assertEquals(1, results.size());
+ assertThat(results).isNotNull();
+ assertThat(results.size()).isEqualTo(1);
final Set<DiskStoreDetails> diskStoreDetails = (Set<DiskStoreDetails>) results.get(0);
-
- assertNotNull(diskStoreDetails);
- assertTrue(diskStoreDetails.isEmpty());
+ assertThat(diskStoreDetails).isNotNull();
+ assertThat(diskStoreDetails.isEmpty()).isTrue();
}
@Test
@SuppressWarnings("unchecked")
public void testExecuteOnMemberWithANonGemFireCache() throws Throwable {
final TestResultSender testResultSender = new TestResultSender();
-
- final Cache mockNonGemCache = mockContext.mock(Cache.class, "NonGemCache");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockNonGemCache));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
+ final Cache mockNonGemCache = mock(Cache.class, "NonGemCache");
+ when(mockFunctionContext.getCache()).thenReturn(mockNonGemCache);
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
final ListDiskStoresFunction function = new ListDiskStoresFunction();
-
function.execute(mockFunctionContext);
final List<?> results = testResultSender.getResults();
-
- assertNotNull(results);
- assertEquals(1, results.size());
+ assertThat(results).isNotNull();
+ assertThat(results.size()).isEqualTo(1);
final Set<DiskStoreDetails> diskStoreDetails = (Set<DiskStoreDetails>) results.get(0);
-
- assertNotNull(diskStoreDetails);
- assertTrue(diskStoreDetails.isEmpty());
+ assertThat(diskStoreDetails).isNotNull();
+ assertThat(diskStoreDetails.isEmpty()).isTrue();
}
- @Test(expected = RuntimeException.class)
- public void testExecuteThrowsRuntimeException() throws Throwable {
+ @Test
+ public void testExecuteThrowsRuntimeException() {
final InternalDistributedMember mockMember =
- mockContext.mock(InternalDistributedMember.class, "DistributedMember");
-
+ mock(InternalDistributedMember.class, "DistributedMember");
final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getMyId();
- will(returnValue(mockMember));
- oneOf(mockCache).listDiskStoresIncludingRegionOwned();
- will(throwException(new RuntimeException("expected")));
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockCache));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
+ when(mockCache.getMyId()).thenReturn(mockMember);
+ when(mockCache.listDiskStoresIncludingRegionOwned())
+ .thenThrow(new RuntimeException("Mock RuntimeException"));
+ when(mockFunctionContext.getCache()).thenReturn(mockCache);
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
final ListDiskStoresFunction function = new ListDiskStoresFunction();
-
function.execute(mockFunctionContext);
-
- try {
- testResultSender.getResults();
- } catch (Throwable throwable) {
- assertTrue(throwable instanceof RuntimeException);
- assertEquals("expected", throwable.getMessage());
- throw throwable;
- }
+ assertThatThrownBy(testResultSender::getResults).isInstanceOf(RuntimeException.class)
+ .hasMessage("Mock RuntimeException");
}
private static class TestResultSender implements ResultSender {
-
- private final List<Object> results = new LinkedList<Object>();
-
private Throwable t;
+ private final List<Object> results = new LinkedList<>();
+
protected List<Object> getResults() throws Throwable {
if (t != null) {
@@ -320,5 +210,4 @@ public class ListDiskStoresFunctionJUnitTest {
this.t = t;
}
}
-
}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/ListIndexFunctionJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/ListIndexFunctionJUnitTest.java
index ecbaf27..04fad64 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/ListIndexFunctionJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/functions/ListIndexFunctionJUnitTest.java
@@ -14,10 +14,10 @@
*/
package org.apache.geode.management.internal.cli.functions;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
@@ -27,11 +27,6 @@ import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -45,7 +40,6 @@ import org.apache.geode.cache.query.IndexType;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.DistributedSystem;
-import org.apache.geode.internal.lang.Filter;
import org.apache.geode.internal.lang.ObjectUtils;
import org.apache.geode.internal.util.CollectionUtils;
import org.apache.geode.management.internal.cli.domain.IndexDetails;
@@ -58,83 +52,84 @@ import org.apache.geode.management.internal.cli.domain.IndexDetails.IndexStatist
* </p>
*
* @see org.apache.geode.management.internal.cli.functions.ListIndexFunction
- * @see org.jmock.Expectations
- * @see org.jmock.Mockery
- * @see org.jmock.lib.legacy.ClassImposteriser
- * @see org.junit.Assert
* @see org.junit.Test
* @since GemFire 7.0
*/
public class ListIndexFunctionJUnitTest {
-
- private Mockery mockContext;
- private AtomicLong mockCounter;
+ private AtomicLong counter;
+ private QueryService mockQueryService;
+ private TestResultSender testResultSender;
+ private FunctionContext mockFunctionContext;
+ private final String mockMemberId = "mockMemberId";
+ private final String mockMemberName = "mockMemberName";
@Before
public void setup() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
- mockCounter = new AtomicLong(0l);
- }
+ counter = new AtomicLong(0L);
+ testResultSender = new TestResultSender();
+ mockQueryService = mock(QueryService.class, "QueryService");
+ mockFunctionContext = mock(FunctionContext.class, "FunctionContext");
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
- }
-
- private void assertIndexDetailsEquals(final IndexDetails expectedIndexDetails,
- final IndexDetails actualIndexDetails) {
- assertEquals(expectedIndexDetails.getFromClause(), actualIndexDetails.getFromClause());
- assertEquals(expectedIndexDetails.getIndexedExpression(),
- actualIndexDetails.getIndexedExpression());
- assertEquals(expectedIndexDetails.getIndexName(), actualIndexDetails.getIndexName());
- assertIndexStatisticsDetailsEquals(expectedIndexDetails.getIndexStatisticsDetails(),
- actualIndexDetails.getIndexStatisticsDetails());
- assertEquals(expectedIndexDetails.getIndexType(), actualIndexDetails.getIndexType());
- assertEquals(expectedIndexDetails.getMemberId(), actualIndexDetails.getMemberId());
- assertEquals(expectedIndexDetails.getMemberName(), actualIndexDetails.getMemberName());
- assertEquals(expectedIndexDetails.getProjectionAttributes(),
- actualIndexDetails.getProjectionAttributes());
- assertEquals(expectedIndexDetails.getRegionName(), actualIndexDetails.getRegionName());
- assertEquals(expectedIndexDetails.getRegionPath(), actualIndexDetails.getRegionPath());
+ final Cache mockCache = mock(Cache.class, "Cache");
+ final DistributedSystem mockDistributedSystem =
+ mock(DistributedSystem.class, "DistributedSystem");
+ final DistributedMember mockDistributedMember =
+ mock(DistributedMember.class, "DistributedMember");
+ when(mockCache.getQueryService()).thenReturn(mockQueryService);
+ when(mockCache.getDistributedSystem()).thenReturn(mockDistributedSystem);
+ when(mockDistributedSystem.getDistributedMember()).thenReturn(mockDistributedMember);
+ when(mockDistributedMember.getId()).thenReturn(mockMemberId);
+ when(mockDistributedMember.getName()).thenReturn(mockMemberName);
+ when(mockFunctionContext.getCache()).thenReturn(mockCache);
+ when(mockFunctionContext.getResultSender()).thenReturn(testResultSender);
}
private void assertIndexStatisticsDetailsEquals(
- final IndexStatisticsDetails expectedIndexStatisticsDetails,
- final IndexStatisticsDetails actualIndexStatisticsDetails) {
+ final IndexStatisticsDetails actualIndexStatisticsDetails,
+ final IndexStatisticsDetails expectedIndexStatisticsDetails) {
if (expectedIndexStatisticsDetails != null) {
- assertNotNull(actualIndexStatisticsDetails);
- assertEquals(expectedIndexStatisticsDetails.getNumberOfKeys(),
- actualIndexStatisticsDetails.getNumberOfKeys());
- assertEquals(expectedIndexStatisticsDetails.getNumberOfUpdates(),
- actualIndexStatisticsDetails.getNumberOfUpdates());
- assertEquals(expectedIndexStatisticsDetails.getNumberOfValues(),
- actualIndexStatisticsDetails.getNumberOfValues());
- assertEquals(expectedIndexStatisticsDetails.getTotalUpdateTime(),
- actualIndexStatisticsDetails.getTotalUpdateTime());
- assertEquals(expectedIndexStatisticsDetails.getTotalUses(),
- actualIndexStatisticsDetails.getTotalUses());
-
+ assertThat(actualIndexStatisticsDetails).isNotNull();
+ assertThat(actualIndexStatisticsDetails.getNumberOfKeys())
+ .isEqualTo(expectedIndexStatisticsDetails.getNumberOfKeys());
+ assertThat(actualIndexStatisticsDetails.getNumberOfUpdates())
+ .isEqualTo(expectedIndexStatisticsDetails.getNumberOfUpdates());
+ assertThat(actualIndexStatisticsDetails.getNumberOfValues())
+ .isEqualTo(expectedIndexStatisticsDetails.getNumberOfValues());
+ assertThat(actualIndexStatisticsDetails.getTotalUpdateTime())
+ .isEqualTo(expectedIndexStatisticsDetails.getTotalUpdateTime());
+ assertThat(actualIndexStatisticsDetails.getTotalUses())
+ .isEqualTo(expectedIndexStatisticsDetails.getTotalUses());
} else {
- assertNull(actualIndexStatisticsDetails);
+ assertThat(actualIndexStatisticsDetails).isNull();
}
}
- private IndexDetails createIndexDetails(final String memberId, final String regionPath,
- final String indexName, final IndexType indexType, final String fromClause,
- final String indexedExpression, final String memberName, final String projectionAttributes,
- final String regionName) {
- final IndexDetails indexDetails = new IndexDetails(memberId, regionPath, indexName);
+ private void assertIndexDetailsEquals(final IndexDetails actualIndexDetails,
+ final IndexDetails expectedIndexDetails) {
+ assertThat(actualIndexDetails).isNotNull();
+ assertThat(actualIndexDetails.getFromClause()).isEqualTo(expectedIndexDetails.getFromClause());
+ assertThat(actualIndexDetails.getIndexedExpression())
+ .isEqualTo(expectedIndexDetails.getIndexedExpression());
+ assertThat(actualIndexDetails.getIndexName()).isEqualTo(expectedIndexDetails.getIndexName());
+ assertThat(actualIndexDetails.getIndexType()).isEqualTo(expectedIndexDetails.getIndexType());
+ assertThat(actualIndexDetails.getMemberId()).isEqualTo(expectedIndexDetails.getMemberId());
+ assertThat(actualIndexDetails.getMemberName()).isEqualTo(expectedIndexDetails.getMemberName());
+ assertThat(actualIndexDetails.getProjectionAttributes())
+ .isEqualTo(expectedIndexDetails.getProjectionAttributes());
+ assertThat(actualIndexDetails.getRegionName()).isEqualTo(expectedIndexDetails.getRegionName());
+ assertThat(actualIndexDetails.getRegionPath()).isEqualTo(expectedIndexDetails.getRegionPath());
+ assertIndexStatisticsDetailsEquals(actualIndexDetails.getIndexStatisticsDetails(),
+ expectedIndexDetails.getIndexStatisticsDetails());
+ }
+ private IndexDetails createIndexDetails(final String regionPath, final String indexName,
+ final IndexType indexType, final String fromClause, final String indexedExpression,
+ final String projectionAttributes, final String regionName) {
+ final IndexDetails indexDetails = new IndexDetails(mockMemberId, regionPath, indexName);
indexDetails.setFromClause(fromClause);
indexDetails.setIndexedExpression(indexedExpression);
indexDetails.setIndexType(indexType);
- indexDetails.setMemberName(memberName);
+ indexDetails.setMemberName(mockMemberName);
indexDetails.setProjectionAttributes(projectionAttributes);
indexDetails.setRegionName(regionName);
@@ -145,7 +140,6 @@ public class ListIndexFunctionJUnitTest {
final Long numberOfUpdates, final Long numberOfValues, final Long totalUpdateTime,
final Long totalUses) {
final IndexStatisticsDetails indexStatisticsDetails = new IndexStatisticsDetails();
-
indexStatisticsDetails.setNumberOfKeys(numberOfKeys);
indexStatisticsDetails.setNumberOfUpdates(numberOfUpdates);
indexStatisticsDetails.setNumberOfValues(numberOfValues);
@@ -155,62 +149,40 @@ public class ListIndexFunctionJUnitTest {
return indexStatisticsDetails;
}
+ @SuppressWarnings("unchecked")
private Index createMockIndex(final IndexDetails indexDetails) {
- final Index mockIndex = mockContext.mock(Index.class,
- "Index " + indexDetails.getIndexName() + " " + mockCounter.getAndIncrement());
-
- final Region mockRegion = mockContext.mock(Region.class,
- "Region " + indexDetails.getRegionPath() + " " + mockCounter.getAndIncrement());
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockIndex).getFromClause();
- will(returnValue(indexDetails.getFromClause()));
- oneOf(mockIndex).getIndexedExpression();
- will(returnValue(indexDetails.getIndexedExpression()));
- oneOf(mockIndex).getName();
- will(returnValue(indexDetails.getIndexName()));
- oneOf(mockIndex).getProjectionAttributes();
- will(returnValue(indexDetails.getProjectionAttributes()));
- exactly(2).of(mockIndex).getRegion();
- will(returnValue(mockRegion));
- oneOf(mockIndex).getType();
- will(returnValue(indexDetails.getIndexType()));
- oneOf(mockRegion).getName();
- will(returnValue(indexDetails.getRegionName()));
- oneOf(mockRegion).getFullPath();
- will(returnValue(indexDetails.getRegionPath()));
- }
- });
+ final Region mockRegion =
+ mock(Region.class, "Region " + indexDetails.getRegionPath() + " " + counter
+ .getAndIncrement());
+ when(mockRegion.getName()).thenReturn(indexDetails.getRegionName());
+ when(mockRegion.getFullPath()).thenReturn(indexDetails.getRegionPath());
+
+ final Index mockIndex = mock(Index.class, "Index " + indexDetails.getIndexName() + " " + counter
+ .getAndIncrement());
+ when(mockIndex.getRegion()).thenReturn(mockRegion);
+ when(mockIndex.getType()).thenReturn(indexDetails.getIndexType());
+ when(mockIndex.getName()).thenReturn(indexDetails.getIndexName());
+ when(mockIndex.getFromClause()).thenReturn(indexDetails.getFromClause());
+ when(mockIndex.getIndexedExpression()).thenReturn(indexDetails.getIndexedExpression());
+ when(mockIndex.getProjectionAttributes()).thenReturn(indexDetails.getProjectionAttributes());
if (indexDetails.getIndexStatisticsDetails() != null) {
- final IndexStatistics mockIndexStatistics = mockContext.mock(IndexStatistics.class,
- "IndexStatistics " + indexDetails.getIndexName() + " " + mockCounter.getAndIncrement());
-
- mockContext.checking(new Expectations() {
- {
- exactly(2).of(mockIndex).getStatistics();
- will(returnValue(mockIndexStatistics));
- oneOf(mockIndexStatistics).getNumUpdates();
- will(returnValue(indexDetails.getIndexStatisticsDetails().getNumberOfUpdates()));
- oneOf(mockIndexStatistics).getNumberOfKeys();
- will(returnValue(indexDetails.getIndexStatisticsDetails().getNumberOfKeys()));
- oneOf(mockIndexStatistics).getNumberOfValues();
- will(returnValue(indexDetails.getIndexStatisticsDetails().getNumberOfValues()));
- oneOf(mockIndexStatistics).getTotalUpdateTime();
- will(returnValue(indexDetails.getIndexStatisticsDetails().getTotalUpdateTime()));
- oneOf(mockIndexStatistics).getTotalUses();
- will(returnValue(indexDetails.getIndexStatisticsDetails().getTotalUses()));
- }
- });
-
+ final IndexStatistics mockIndexStatistics = mock(IndexStatistics.class,
+ "IndexStatistics " + indexDetails.getIndexName() + " " + counter
+ .getAndIncrement());
+ when(mockIndex.getStatistics()).thenReturn(mockIndexStatistics);
+ when(mockIndexStatistics.getNumUpdates())
+ .thenReturn(indexDetails.getIndexStatisticsDetails().getNumberOfUpdates());
+ when(mockIndexStatistics.getNumberOfKeys())
+ .thenReturn(indexDetails.getIndexStatisticsDetails().getNumberOfKeys());
+ when(mockIndexStatistics.getNumberOfValues())
+ .thenReturn(indexDetails.getIndexStatisticsDetails().getNumberOfValues());
+ when(mockIndexStatistics.getTotalUpdateTime())
+ .thenReturn(indexDetails.getIndexStatisticsDetails().getTotalUpdateTime());
+ when(mockIndexStatistics.getTotalUses())
+ .thenReturn(indexDetails.getIndexStatisticsDetails().getTotalUses());
} else {
- mockContext.checking(new Expectations() {
- {
- oneOf(mockIndex).getStatistics();
- will(returnValue(null));
- }
- });
+ when(mockIndex.getStatistics()).thenReturn(null);
}
return mockIndex;
@@ -219,207 +191,87 @@ public class ListIndexFunctionJUnitTest {
@Test
@SuppressWarnings("unchecked")
public void testExecute() throws Throwable {
- final String memberId = "mockMemberId";
- final String memberName = "mockMemberName";
-
- final Cache mockCache = mockContext.mock(Cache.class, "Cache");
-
- final DistributedSystem mockDistributedSystem =
- mockContext.mock(DistributedSystem.class, "DistributedSystem");
- final DistributedMember mockDistributedMember =
- mockContext.mock(DistributedMember.class, "DistributedMember");
-
- final IndexDetails indexDetailsOne =
- createIndexDetails(memberId, "/Employees", "empIdIdx", IndexType.PRIMARY_KEY, "/Employees",
- "id", memberName, "id, firstName, lastName", "Employees");
-
+ // Expected Results
+ final IndexDetails indexDetailsOne = createIndexDetails("/Employees", "empIdIdx",
+ IndexType.PRIMARY_KEY, "/Employees", "id", "id, firstName, lastName", "Employees");
indexDetailsOne.setIndexStatisticsDetails(
- createIndexStatisticsDetails(10124l, 4096l, 10124l, 1284100l, 280120l));
-
- final IndexDetails indexDetailsTwo =
- createIndexDetails(memberId, "/Employees", "empGivenNameIdx", IndexType.FUNCTIONAL,
- "/Employees", "lastName", memberName, "id, firstName, lastName", "Employees");
-
- final IndexDetails indexDetailsThree =
- createIndexDetails(memberId, "/Contractors", "empIdIdx", IndexType.PRIMARY_KEY,
- "/Contrators", "id", memberName, "id, firstName, lastName", "Contractors");
-
+ createIndexStatisticsDetails(10124L, 4096L, 10124L, 1284100L, 280120L));
+ final IndexDetails indexDetailsTwo = createIndexDetails("/Employees", "empGivenNameIdx",
+ IndexType.FUNCTIONAL, "/Employees", "lastName", "id, firstName, lastName", "Employees");
+ final IndexDetails indexDetailsThree = createIndexDetails("/Contractors", "empIdIdx",
+ IndexType.PRIMARY_KEY, "/Contrators", "id", "id, firstName, lastName", "Contractors");
indexDetailsThree.setIndexStatisticsDetails(
- createIndexStatisticsDetails(1024l, 256l, 20248l, 768001l, 24480l));
-
- final IndexDetails indexDetailsFour =
- createIndexDetails(memberId, "/Employees", "empIdIdx", IndexType.FUNCTIONAL, "/Employees",
- "emp_id", memberName, "id, surname, givenname", "Employees");
-
- final Set<IndexDetails> expectedIndexDetailsSet = new HashSet<IndexDetails>(3);
-
- expectedIndexDetailsSet.add(indexDetailsOne);
- expectedIndexDetailsSet.add(indexDetailsTwo);
- expectedIndexDetailsSet.add(indexDetailsThree);
-
- final QueryService mockQueryService = mockContext.mock(QueryService.class, "QueryService");
-
- final FunctionContext mockFunctionContext =
- mockContext.mock(FunctionContext.class, "FunctionContext");
-
- final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getDistributedSystem();
- will(returnValue(mockDistributedSystem));
- oneOf(mockCache).getQueryService();
- will(returnValue(mockQueryService));
- oneOf(mockDistributedSystem).getDistributedMember();
- will(returnValue(mockDistributedMember));
- exactly(4).of(mockDistributedMember).getId();
- will(returnValue(memberId));
- exactly(4).of(mockDistributedMember).getName();
- will(returnValue(memberName));
- oneOf(mockQueryService).getIndexes();
- will(returnValue(
- Arrays.asList(createMockIndex(indexDetailsOne), createMockIndex(indexDetailsTwo),
- createMockIndex(indexDetailsThree), createMockIndex(indexDetailsFour))));
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockCache));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
-
+ createIndexStatisticsDetails(1024L, 256L, 20248L, 768001L, 24480L));
+ final IndexDetails indexDetailsFour = createIndexDetails("/Employees", "empIdIdx",
+ IndexType.FUNCTIONAL, "/Employees", "emp_id", "id, surname, givenname", "Employees");
+ final Set<IndexDetails> expectedIndexDetailsSet =
+ new HashSet<>(Arrays.asList(indexDetailsOne, indexDetailsTwo, indexDetailsThree));
+
+ // Prepare Mocks
+ List<Index> indexes =
+ Arrays.asList(createMockIndex(indexDetailsOne), createMockIndex(indexDetailsTwo),
+ createMockIndex(indexDetailsThree), createMockIndex(indexDetailsFour));
+ when(mockQueryService.getIndexes()).thenReturn(indexes);
+
+ // Execute Function and Assert Results
final ListIndexFunction function = new ListIndexFunction();
-
function.execute(mockFunctionContext);
final List<?> results = testResultSender.getResults();
-
- assertNotNull(results);
- assertEquals(1, results.size());
+ assertThat(results).isNotNull();
+ assertThat(results.size()).isEqualTo(1);
final Set<IndexDetails> actualIndexDetailsSet = (Set<IndexDetails>) results.get(0);
-
- assertNotNull(actualIndexDetailsSet);
- assertEquals(expectedIndexDetailsSet.size(), actualIndexDetailsSet.size());
+ assertThat(actualIndexDetailsSet).isNotNull();
+ assertThat(actualIndexDetailsSet.size()).isEqualTo(expectedIndexDetailsSet.size());
for (final IndexDetails expectedIndexDetails : expectedIndexDetailsSet) {
- final IndexDetails actualIndexDetails =
- CollectionUtils.findBy(actualIndexDetailsSet, new Filter<IndexDetails>() {
- @Override
- public boolean accept(final IndexDetails indexDetails) {
- return ObjectUtils.equals(expectedIndexDetails, indexDetails);
- }
- });
-
- assertNotNull(actualIndexDetails);
- assertIndexDetailsEquals(expectedIndexDetails, actualIndexDetails);
+ final IndexDetails actualIndexDetails = CollectionUtils.findBy(actualIndexDetailsSet,
+ indexDetails -> ObjectUtils.equals(expectedIndexDetails, indexDetails));
+ assertIndexDetailsEquals(actualIndexDetails, expectedIndexDetails);
}
}
@Test
@SuppressWarnings("unchecked")
public void testExecuteWithNoIndexes() throws Throwable {
- final Cache mockCache = mockContext.mock(Cache.class, "Cache");
-
- final DistributedSystem mockDistributedSystem =
- mockContext.mock(DistributedSystem.class, "DistributedSystem");
- final DistributedMember mockDistributedMember =
- mockContext.mock(DistributedMember.class, "DistributedMember");
-
- final QueryService mockQueryService = mockContext.mock(QueryService.class, "QueryService");
-
- final FunctionContext mockFunctionContext =
- mockContext.mock(FunctionContext.class, "FunctionContext");
-
- final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getDistributedSystem();
- will(returnValue(mockDistributedSystem));
- oneOf(mockCache).getQueryService();
- will(returnValue(mockQueryService));
- oneOf(mockDistributedSystem).getDistributedMember();
- will(returnValue(mockDistributedMember));
- oneOf(mockQueryService).getIndexes();
- will(returnValue(Collections.emptyList()));
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockCache));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
+ // Prepare Mocks
+ when(mockQueryService.getIndexes()).thenReturn(Collections.emptyList());
+ // Execute Function and assert results
final ListIndexFunction function = new ListIndexFunction();
-
function.execute(mockFunctionContext);
final List<?> results = testResultSender.getResults();
-
- assertNotNull(results);
- assertEquals(1, results.size());
+ assertThat(results).isNotNull();
+ assertThat(results.size()).isEqualTo(1);
final Set<IndexDetails> actualIndexDetailsSet = (Set<IndexDetails>) results.get(0);
-
- assertNotNull(actualIndexDetailsSet);
- assertTrue(actualIndexDetailsSet.isEmpty());
+ assertThat(actualIndexDetailsSet).isNotNull();
+ assertThat(actualIndexDetailsSet.isEmpty()).isTrue();
}
- @Test(expected = RuntimeException.class)
- public void testExecuteThrowsException() throws Throwable {
- final Cache mockCache = mockContext.mock(Cache.class, "Cache");
-
- final DistributedSystem mockDistributedSystem =
- mockContext.mock(DistributedSystem.class, "DistributedSystem");
- final DistributedMember mockDistributedMember =
- mockContext.mock(DistributedMember.class, "DistributedMember");
-
- final QueryService mockQueryService = mockContext.mock(QueryService.class, "QueryService");
-
- final FunctionContext mockFunctionContext =
- mockContext.mock(FunctionContext.class, "FunctionContext");
-
- final TestResultSender testResultSender = new TestResultSender();
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).getDistributedSystem();
- will(returnValue(mockDistributedSystem));
- oneOf(mockCache).getQueryService();
- will(returnValue(mockQueryService));
- oneOf(mockDistributedSystem).getDistributedMember();
- will(returnValue(mockDistributedMember));
- oneOf(mockQueryService).getIndexes();
- will(throwException(new RuntimeException("expected")));
- oneOf(mockFunctionContext).getCache();
- will(returnValue(mockCache));
- oneOf(mockFunctionContext).getResultSender();
- will(returnValue(testResultSender));
- }
- });
+ @Test
+ public void testExecuteThrowsException() {
+ // Prepare Mocks
+ when(mockQueryService.getIndexes()).thenThrow(new RuntimeException("Mocked Exception"));
+ // Execute Function and assert results
final ListIndexFunction function = new ListIndexFunction();
-
function.execute(mockFunctionContext);
-
- try {
- testResultSender.getResults();
- } catch (Throwable t) {
- assertTrue(t instanceof RuntimeException);
- assertEquals("expected", t.getMessage());
- throw t;
- }
+ assertThatThrownBy(() -> testResultSender.getResults()).isInstanceOf(RuntimeException.class)
+ .hasMessage("Mocked Exception");
}
private static class TestResultSender implements ResultSender {
-
- private final List<Object> results = new LinkedList<Object>();
-
private Throwable t;
+ private final List<Object> results = new LinkedList<>();
protected List<Object> getResults() throws Throwable {
if (t != null) {
throw t;
}
+
return Collections.unmodifiableList(results);
}
@@ -438,5 +290,4 @@ public class ListIndexFunctionJUnitTest {
this.t = t;
}
}
-
}
diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommandsJUnitTest.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommandsJUnitTest.java
index e9129f5..86bc2d3 100644
--- a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommandsJUnitTest.java
+++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommandsJUnitTest.java
@@ -16,8 +16,8 @@ package org.apache.geode.cache.lucene.internal.cli;
import static org.apache.commons.lang.SystemUtils.LINE_SEPARATOR;
import static org.apache.geode.management.internal.cli.result.ResultData.TYPE_TABULAR;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.isA;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
@@ -42,7 +42,6 @@ import junitparams.Parameters;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -82,27 +81,23 @@ import org.apache.geode.test.junit.categories.LuceneTest;
* @see LuceneIndexCommands
* @see LuceneIndexDetails
* @see LuceneListIndexFunction
- * @see org.jmock.Expectations
- * @see org.jmock.Mockery
- * @see org.jmock.lib.legacy.ClassImposteriser
- * @see org.junit.Assert
* @see org.junit.Test
* @since GemFire 7.0
*/
-@Category({LuceneTest.class})
+@Category(LuceneTest.class)
@RunWith(JUnitParamsRunner.class)
public class LuceneIndexCommandsJUnitTest {
private InternalCache mockCache;
@Before
- public void before() throws Exception {
+ public void before() {
this.mockCache = mock(InternalCache.class, "InternalCache");
when(this.mockCache.getSecurityService()).thenReturn(mock(SecurityService.class));
}
@Test
- public void testListIndexWithoutStats() throws Exception {
+ public void testListIndexWithoutStats() {
final String serverName = "mockServer";
final AbstractExecution mockFunctionExecutor =
mock(AbstractExecution.class, "Function Executor");
@@ -126,7 +121,7 @@ public class LuceneIndexCommandsJUnitTest {
results.add(CollectionUtils.asSet(indexDetails2, indexDetails1, indexDetails3));
- when(mockFunctionExecutor.execute(isA(LuceneListIndexFunction.class)))
+ when(mockFunctionExecutor.execute(any(LuceneListIndexFunction.class)))
.thenReturn(mockResultCollector);
when(mockResultCollector.getResult()).thenReturn(results);
@@ -134,23 +129,22 @@ public class LuceneIndexCommandsJUnitTest {
CommandResult result = (CommandResult) commands.listIndex(false);
TabularResultData data = (TabularResultData) result.getResultData();
- assertEquals(Arrays.asList("memberFive", "memberSix", "memberTen"),
- data.retrieveAllValues("Index Name"));
- assertEquals(Arrays.asList("/Employees", "/Employees", "/Employees"),
- data.retrieveAllValues("Region Path"));
- assertEquals(Arrays.asList("[field1, field2, field3]", "[field1, field2, field3]",
- "[field1, field2, field3]"), data.retrieveAllValues("Indexed Fields"));
- assertEquals(
- Arrays.asList("{field1=StandardAnalyzer, field2=KeywordAnalyzer}",
+ assertThat(data.retrieveAllValues("Index Name"))
+ .isEqualTo(Arrays.asList("memberFive", "memberSix", "memberTen"));
+ assertThat(data.retrieveAllValues("Region Path"))
+ .isEqualTo(Arrays.asList("/Employees", "/Employees", "/Employees"));
+ assertThat(data.retrieveAllValues("Indexed Fields")).isEqualTo(Arrays.asList(
+ "[field1, field2, field3]", "[field1, field2, field3]", "[field1, field2, field3]"));
+ assertThat(data.retrieveAllValues("Field Analyzer"))
+ .isEqualTo(Arrays.asList("{field1=StandardAnalyzer, field2=KeywordAnalyzer}",
"{field1=StandardAnalyzer, field2=KeywordAnalyzer}",
- "{field1=StandardAnalyzer, field2=KeywordAnalyzer}"),
- data.retrieveAllValues("Field Analyzer"));
- assertEquals(Arrays.asList("INITIALIZED", "NOT_INITIALIZED", "INITIALIZED"),
- data.retrieveAllValues("Status"));
+ "{field1=StandardAnalyzer, field2=KeywordAnalyzer}"));
+ assertThat(data.retrieveAllValues("Status"))
+ .isEqualTo(Arrays.asList("INITIALIZED", "NOT_INITIALIZED", "INITIALIZED"));
}
@Test
- public void testListIndexWithStats() throws Exception {
+ public void testListIndexWithStats() {
final String serverName = "mockServer";
final AbstractExecution mockFunctionExecutor =
mock(AbstractExecution.class, "Function Executor");
@@ -178,7 +172,7 @@ public class LuceneIndexCommandsJUnitTest {
results.add(CollectionUtils.asSet(indexDetails2, indexDetails1, indexDetails3));
- when(mockFunctionExecutor.execute(isA(LuceneListIndexFunction.class)))
+ when(mockFunctionExecutor.execute(any(LuceneListIndexFunction.class)))
.thenReturn(mockResultCollector);
when(mockResultCollector.getResult()).thenReturn(results);
@@ -186,26 +180,24 @@ public class LuceneIndexCommandsJUnitTest {
CommandResult result = (CommandResult) commands.listIndex(true);
TabularResultData data = (TabularResultData) result.getResultData();
- assertEquals(Arrays.asList("memberFive", "memberSix", "memberTen"),
- data.retrieveAllValues("Index Name"));
- assertEquals(Arrays.asList("/Employees", "/Employees", "/Employees"),
- data.retrieveAllValues("Region Path"));
- assertEquals(Arrays.asList("[field1, field2, field3]", "[field1, field2, field3]",
- "[field1, field2, field3]"), data.retrieveAllValues("Indexed Fields"));
- assertEquals(
- Arrays.asList("{field1=StandardAnalyzer, field2=KeywordAnalyzer}",
+ assertThat(data.retrieveAllValues("Index Name"))
+ .isEqualTo(Arrays.asList("memberFive", "memberSix", "memberTen"));
+ assertThat(data.retrieveAllValues("Region Path"))
+ .isEqualTo(Arrays.asList("/Employees", "/Employees", "/Employees"));
+ assertThat(data.retrieveAllValues("Indexed Fields")).isEqualTo(Arrays.asList(
+ "[field1, field2, field3]", "[field1, field2, field3]", "[field1, field2, field3]"));
+ assertThat(data.retrieveAllValues("Field Analyzer"))
+ .isEqualTo(Arrays.asList("{field1=StandardAnalyzer, field2=KeywordAnalyzer}",
"{field1=StandardAnalyzer, field2=KeywordAnalyzer}",
- "{field1=StandardAnalyzer, field2=KeywordAnalyzer}"),
- data.retrieveAllValues("Field Analyzer"));
- assertEquals(Arrays.asList("1", "2", "3"), data.retrieveAllValues("Query Executions"));
- assertEquals(Arrays.asList("10", "20", "30"), data.retrieveAllValues("Commits"));
- assertEquals(Arrays.asList("5", "10", "15"), data.retrieveAllValues("Updates"));
- assertEquals(Arrays.asList("1", "2", "3"), data.retrieveAllValues("Documents"));
- assertEquals(
- Arrays.asList(HeterogeneousLuceneSerializer.class.getSimpleName(),
+ "{field1=StandardAnalyzer, field2=KeywordAnalyzer}"));
+ assertThat(data.retrieveAllValues("Query Executions")).isEqualTo(Arrays.asList("1", "2", "3"));
+ assertThat(data.retrieveAllValues("Commits")).isEqualTo(Arrays.asList("10", "20", "30"));
+ assertThat(data.retrieveAllValues("Updates")).isEqualTo(Arrays.asList("5", "10", "15"));
+ assertThat(data.retrieveAllValues("Documents")).isEqualTo(Arrays.asList("1", "2", "3"));
+ assertThat(data.retrieveAllValues("Serializer"))
+ .isEqualTo(Arrays.asList(HeterogeneousLuceneSerializer.class.getSimpleName(),
HeterogeneousLuceneSerializer.class.getSimpleName(),
- HeterogeneousLuceneSerializer.class.getSimpleName()),
- data.retrieveAllValues("Serializer"));
+ HeterogeneousLuceneSerializer.class.getSimpleName()));
}
@Test
@@ -214,12 +206,15 @@ public class LuceneIndexCommandsJUnitTest {
final LuceneIndexCommands commands = spy(createIndexCommands(this.mockCache, null));
final List<CliFunctionResult> cliFunctionResults = new ArrayList<>();
- cliFunctionResults.add(new CliFunctionResult("member1", true, "Index Created"));
- cliFunctionResults.add(new CliFunctionResult("member2", false, "Index creation failed"));
- cliFunctionResults.add(new CliFunctionResult("member3", true, "Index Created"));
+ cliFunctionResults
+ .add(new CliFunctionResult("member1", CliFunctionResult.StatusState.OK, "Index Created"));
+ cliFunctionResults.add(new CliFunctionResult("member2", CliFunctionResult.StatusState.ERROR,
+ "Index creation failed"));
+ cliFunctionResults
+ .add(new CliFunctionResult("member3", CliFunctionResult.StatusState.OK, "Index Created"));
doReturn(mockResultCollector).when(commands).executeFunctionOnAllMembers(
- isA(LuceneCreateIndexFunction.class), any(LuceneIndexInfo.class));
+ any(LuceneCreateIndexFunction.class), any(LuceneIndexInfo.class));
doReturn(cliFunctionResults).when(mockResultCollector).getResult();
String indexName = "index";
@@ -232,11 +227,13 @@ public class LuceneIndexCommandsJUnitTest {
CommandResult result = (CommandResult) commands.createIndex(indexName, regionPath,
searchableFields, fieldAnalyzers, serializer);
- assertEquals(Status.OK, result.getStatus());
+ assertThat(result.getStatus()).isEqualTo(Status.OK);
TabularResultData data = (TabularResultData) result.getResultData();
- assertEquals(Arrays.asList("member1", "member2", "member3"), data.retrieveAllValues("Member"));
- assertEquals(Arrays.asList("Successfully created lucene index", "Failed: Index creation failed",
- "Successfully created lucene index"), data.retrieveAllValues("Status"));
+ assertThat(data.retrieveAllValues("Member"))
+ .isEqualTo(Arrays.asList("member1", "member2", "member3"));
+ assertThat(data.retrieveAllValues("Status"))
+ .isEqualTo(Arrays.asList("Successfully created lucene index",
+ "Failed: Index creation failed", "Successfully created lucene index"));
}
@Test
@@ -257,23 +254,27 @@ public class LuceneIndexCommandsJUnitTest {
fieldAnalyzers, mockIndexStats, LuceneIndexStatus.INITIALIZED, serverName, serializer));
doReturn(mockResultCollector).when(commands).executeFunctionOnRegion(
- isA(LuceneDescribeIndexFunction.class), any(LuceneIndexInfo.class), eq(true));
+ any(LuceneDescribeIndexFunction.class), any(LuceneIndexInfo.class), eq(true));
doReturn(indexDetails).when(mockResultCollector).getResult();
CommandResult result = (CommandResult) commands.describeIndex("memberFive", "/Employees");
TabularResultData data = (TabularResultData) result.getResultData();
- assertEquals(Collections.singletonList("memberFive"), data.retrieveAllValues("Index Name"));
- assertEquals(Collections.singletonList("/Employees"), data.retrieveAllValues("Region Path"));
- assertEquals(Collections.singletonList("[field1, field2, field3]"),
- data.retrieveAllValues("Indexed Fields"));
- assertEquals(Collections.singletonList("{field1=StandardAnalyzer, field2=KeywordAnalyzer}"),
- data.retrieveAllValues("Field Analyzer"));
- assertEquals(Collections.singletonList("INITIALIZED"), data.retrieveAllValues("Status"));
- assertEquals(Collections.singletonList("1"), data.retrieveAllValues("Query Executions"));
- assertEquals(Collections.singletonList("10"), data.retrieveAllValues("Commits"));
- assertEquals(Collections.singletonList("5"), data.retrieveAllValues("Updates"));
- assertEquals(Collections.singletonList("1"), data.retrieveAllValues("Documents"));
+ assertThat(data.retrieveAllValues("Index Name"))
+ .isEqualTo(Collections.singletonList("memberFive"));
+ assertThat(data.retrieveAllValues("Region Path"))
+ .isEqualTo(Collections.singletonList("/Employees"));
+ assertThat(data.retrieveAllValues("Indexed Fields"))
+ .isEqualTo(Collections.singletonList("[field1, field2, field3]"));
+ assertThat(data.retrieveAllValues("Field Analyzer"))
+ .isEqualTo(Collections.singletonList("{field1=StandardAnalyzer, field2=KeywordAnalyzer}"));
+ assertThat(data.retrieveAllValues("Status"))
+ .isEqualTo(Collections.singletonList("INITIALIZED"));
+ assertThat(data.retrieveAllValues("Query Executions"))
+ .isEqualTo(Collections.singletonList("1"));
+ assertThat(data.retrieveAllValues("Commits")).isEqualTo(Collections.singletonList("10"));
+ assertThat(data.retrieveAllValues("Updates")).isEqualTo(Collections.singletonList("5"));
+ assertThat(data.retrieveAllValues("Documents")).isEqualTo(Collections.singletonList("1"));
}
@Test
@@ -287,17 +288,16 @@ public class LuceneIndexCommandsJUnitTest {
queryResults.add(createQueryResults("B", "Result1", Float.valueOf("1.2")));
queryResults.add(createQueryResults("C", "Result1", Float.valueOf("1.1")));
queryResultsList.add(queryResults);
- doReturn(mockResultCollector).when(commands).executeSearch(isA(LuceneQueryInfo.class));
+ doReturn(mockResultCollector).when(commands).executeSearch(any(LuceneQueryInfo.class));
doReturn(queryResultsList).when(mockResultCollector).getResult();
CommandResult result =
(CommandResult) commands.searchIndex("index", "region", "Result1", "field1", -1, false);
-
TabularResultData data = (TabularResultData) result.getResultData();
-
- assertEquals(Arrays.asList("A", "B", "C"), data.retrieveAllValues("key"));
- assertEquals(Arrays.asList("Result1", "Result1", "Result1"), data.retrieveAllValues("value"));
- assertEquals(Arrays.asList("1.3", "1.2", "1.1"), data.retrieveAllValues("score"));
+ assertThat(data.retrieveAllValues("key")).isEqualTo(Arrays.asList("A", "B", "C"));
+ assertThat(data.retrieveAllValues("value"))
+ .isEqualTo(Arrays.asList("Result1", "Result1", "Result1"));
+ assertThat(data.retrieveAllValues("score")).isEqualTo(Arrays.asList("1.3", "1.2", "1.1"));
}
@Ignore
@@ -335,36 +335,36 @@ public class LuceneIndexCommandsJUnitTest {
verify(mockGfsh, times(20)).printAsInfo(resultCaptor.capture());
List<String> actualPageResults = resultCaptor.getAllValues();
- assertEquals(expectedPage1, actualPageResults.get(0));
- assertEquals("\t\tPage 1 of 4", actualPageResults.get(1));
+ assertThat(actualPageResults.get(0)).isEqualTo(expectedPage1);
+ assertThat(actualPageResults.get(1)).isEqualTo("\t\tPage 1 of 4");
- assertEquals(expectedPage2, actualPageResults.get(2));
- assertEquals("\t\tPage 2 of 4", actualPageResults.get(3));
+ assertThat(actualPageResults.get(2)).isEqualTo(expectedPage2);
+ assertThat(actualPageResults.get(3)).isEqualTo("\t\tPage 2 of 4");
- assertEquals(expectedPage3, actualPageResults.get(4));
- assertEquals("\t\tPage 3 of 4", actualPageResults.get(5));
+ assertThat(actualPageResults.get(4)).isEqualTo(expectedPage3);
+ assertThat(actualPageResults.get(5)).isEqualTo("\t\tPage 3 of 4");
- assertEquals(expectedPage4, actualPageResults.get(6));
- assertEquals("\t\tPage 4 of 4", actualPageResults.get(7));
+ assertThat(actualPageResults.get(6)).isEqualTo(expectedPage4);
+ assertThat(actualPageResults.get(7)).isEqualTo("\t\tPage 4 of 4");
- assertEquals("No more results to display.", actualPageResults.get(8));
+ assertThat(actualPageResults.get(8)).isEqualTo("No more results to display.");
- assertEquals(expectedPage4, actualPageResults.get(9));
- assertEquals("\t\tPage 4 of 4", actualPageResults.get(10));
+ assertThat(actualPageResults.get(9)).isEqualTo(expectedPage4);
+ assertThat(actualPageResults.get(10)).isEqualTo("\t\tPage 4 of 4");
- assertEquals(expectedPage3, actualPageResults.get(11));
- assertEquals("\t\tPage 3 of 4", actualPageResults.get(12));
+ assertThat(actualPageResults.get(11)).isEqualTo(expectedPage3);
+ assertThat(actualPageResults.get(12)).isEqualTo("\t\tPage 3 of 4");
- assertEquals(expectedPage2, actualPageResults.get(13));
- assertEquals("\t\tPage 2 of 4", actualPageResults.get(14));
+ assertThat(actualPageResults.get(13)).isEqualTo(expectedPage2);
+ assertThat(actualPageResults.get(14)).isEqualTo("\t\tPage 2 of 4");
- assertEquals(expectedPage1, actualPageResults.get(15));
- assertEquals("\t\tPage 1 of 4", actualPageResults.get(16));
+ assertThat(actualPageResults.get(15)).isEqualTo(expectedPage1);
+ assertThat(actualPageResults.get(16)).isEqualTo("\t\tPage 1 of 4");
- assertEquals("At the top of the search results.", actualPageResults.get(17));
+ assertThat(actualPageResults.get(17)).isEqualTo("At the top of the search results.");
- assertEquals(expectedPage1, actualPageResults.get(18));
- assertEquals("\t\tPage 1 of 4", actualPageResults.get(19));
+ assertThat(actualPageResults.get(18)).isEqualTo(expectedPage1);
+ assertThat(actualPageResults.get(19)).isEqualTo("\t\tPage 1 of 4");
}
@Test
@@ -378,15 +378,13 @@ public class LuceneIndexCommandsJUnitTest {
queryResults.add(createQueryResults("B", "Result1", Float.valueOf("1.2")));
queryResults.add(createQueryResults("C", "Result1", Float.valueOf("1.1")));
queryResultsList.add(queryResults);
- doReturn(mockResultCollector).when(commands).executeSearch(isA(LuceneQueryInfo.class));
+ doReturn(mockResultCollector).when(commands).executeSearch(any(LuceneQueryInfo.class));
doReturn(queryResultsList).when(mockResultCollector).getResult();
CommandResult result =
(CommandResult) commands.searchIndex("index", "region", "Result1", "field1", -1, true);
-
TabularResultData data = (TabularResultData) result.getResultData();
-
- assertEquals(Arrays.asList("A", "B", "C"), data.retrieveAllValues("key"));
+ assertThat(data.retrieveAllValues("key")).isEqualTo(Arrays.asList("A", "B", "C"));
}
@Test
@@ -417,25 +415,23 @@ public class LuceneIndexCommandsJUnitTest {
queryResults.add(createQueryResults("T", "Result1", 1));
queryResultsList.add(queryResults);
- doReturn(mockResultCollector).when(commands).executeSearch(isA(LuceneQueryInfo.class));
+ doReturn(mockResultCollector).when(commands).executeSearch(any(LuceneQueryInfo.class));
doReturn(queryResultsList).when(mockResultCollector).getResult();
CommandResult result =
(CommandResult) commands.searchIndex("index", "region", "Result1", "field1", -1, true);
-
TabularResultData data = (TabularResultData) result.getResultData();
-
- assertEquals(queryResults.size(), data.retrieveAllValues("key").size());
+ assertThat(data.retrieveAllValues("key").size()).isEqualTo(queryResults.size());
}
@Test
- public void testDestroySingleIndexNoRegionMembers() throws Exception {
+ public void testDestroySingleIndexNoRegionMembers() {
LuceneIndexCommands commands = createTestLuceneIndexCommandsForDestroyIndex();
final List<CliFunctionResult> cliFunctionResults = new ArrayList<>();
String expectedStatus = CliStrings.format(
LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__COULD_NOT_FIND__MEMBERS_GREATER_THAN_VERSION_0,
new Object[] {Version.GEODE_180}) + LINE_SEPARATOR;
- cliFunctionResults.add(new CliFunctionResult("member0"));
+ cliFunctionResults.add(new CliFunctionResult("member0", CliFunctionResult.StatusState.OK));
doReturn(Collections.emptySet()).when(commands).getNormalMembersWithSameOrNewerVersion(any());
CommandResult result = (CommandResult) commands.destroyIndex("index", "regionPath");
verifyDestroyIndexCommandResult(result, cliFunctionResults, expectedStatus);
@@ -443,7 +439,7 @@ public class LuceneIndexCommandsJUnitTest {
@Test
@Parameters({"true", "false"})
- public void testDestroySingleIndexWithRegionMembers(boolean expectedToSucceed) throws Exception {
+ public void testDestroySingleIndexWithRegionMembers(boolean expectedToSucceed) {
LuceneIndexCommands commands = createTestLuceneIndexCommandsForDestroyIndex();
String indexName = "index";
String regionPath = "regionPath";
@@ -459,8 +455,9 @@ public class LuceneIndexCommandsJUnitTest {
if (expectedToSucceed) {
expectedStatus = CliStrings.format(
LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__SUCCESSFULLY_DESTROYED_INDEX_0_FROM_REGION_1,
- new Object[] {indexName, regionPath});
- cliFunctionResults.add(new CliFunctionResult(mockMember.getId()));
+ indexName, regionPath);
+ cliFunctionResults
+ .add(new CliFunctionResult(mockMember.getId(), CliFunctionResult.StatusState.OK));
} else {
Exception e = new IllegalStateException("failed");
expectedStatus = e.getMessage();
@@ -468,7 +465,7 @@ public class LuceneIndexCommandsJUnitTest {
}
doReturn(mockResultCollector).when(commands).executeFunction(
- isA(LuceneDestroyIndexFunction.class), any(LuceneDestroyIndexInfo.class), any(Set.class));
+ any(LuceneDestroyIndexFunction.class), any(LuceneDestroyIndexInfo.class), anySet());
doReturn(cliFunctionResults).when(mockResultCollector).getResult();
doReturn(members).when(commands).getNormalMembersWithSameOrNewerVersion(any());
@@ -478,21 +475,21 @@ public class LuceneIndexCommandsJUnitTest {
}
@Test
- public void testDestroyAllIndexesNoRegionMembers() throws Exception {
+ public void testDestroyAllIndexesNoRegionMembers() {
LuceneIndexCommands commands = createTestLuceneIndexCommandsForDestroyIndex();
doReturn(Collections.emptySet()).when(commands).getNormalMembersWithSameOrNewerVersion(any());
final List<CliFunctionResult> cliFunctionResults = new ArrayList<>();
String expectedStatus = CliStrings.format(
LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__COULD_NOT_FIND__MEMBERS_GREATER_THAN_VERSION_0,
new Object[] {Version.GEODE_180}) + LINE_SEPARATOR;
- cliFunctionResults.add(new CliFunctionResult("member0"));
+ cliFunctionResults.add(new CliFunctionResult("member0", CliFunctionResult.StatusState.OK));
CommandResult result = (CommandResult) commands.destroyIndex(null, "regionPath");
verifyDestroyIndexCommandResult(result, cliFunctionResults, expectedStatus);
}
@Test
@Parameters({"true", "false"})
- public void testDestroyAllIndexesWithRegionMembers(boolean expectedToSucceed) throws Exception {
+ public void testDestroyAllIndexesWithRegionMembers(boolean expectedToSucceed) {
LuceneIndexCommands commands = createTestLuceneIndexCommandsForDestroyIndex();
String indexName = null;
String regionPath = "regionPath";
@@ -509,7 +506,8 @@ public class LuceneIndexCommandsJUnitTest {
expectedStatus = CliStrings.format(
LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__SUCCESSFULLY_DESTROYED_INDEXES_FROM_REGION_0,
new Object[] {regionPath});
- cliFunctionResults.add(new CliFunctionResult(mockMember.getId()));
+ cliFunctionResults
+ .add(new CliFunctionResult(mockMember.getId(), CliFunctionResult.StatusState.OK));
} else {
Exception e = new IllegalStateException("failed");
expectedStatus = e.getMessage();
@@ -517,7 +515,7 @@ public class LuceneIndexCommandsJUnitTest {
}
doReturn(mockResultCollector).when(commands).executeFunction(
- isA(LuceneDestroyIndexFunction.class), any(LuceneDestroyIndexInfo.class), any(Set.class));
+ any(LuceneDestroyIndexFunction.class), any(LuceneDestroyIndexInfo.class), anySet());
doReturn(cliFunctionResults).when(mockResultCollector).getResult();
doReturn(members).when(commands).getNormalMembersWithSameOrNewerVersion(any());
@@ -531,33 +529,34 @@ public class LuceneIndexCommandsJUnitTest {
final LuceneIndexCommands commands = spy(createIndexCommands(this.mockCache, null));
final List<CliFunctionResult> cliFunctionResults = new ArrayList<>();
- cliFunctionResults.add(new CliFunctionResult("member", true, "Index Destroyed"));
+ cliFunctionResults
+ .add(new CliFunctionResult("member", CliFunctionResult.StatusState.OK, "Index Destroyed"));
doReturn(mockResultCollector).when(commands).executeFunctionOnRegion(
- isA(LuceneDestroyIndexFunction.class), any(LuceneIndexInfo.class), eq(false));
+ any(LuceneDestroyIndexFunction.class), any(LuceneIndexInfo.class), eq(false));
doReturn(cliFunctionResults).when(mockResultCollector).getResult();
return commands;
}
private void verifyDestroyIndexCommandResult(CommandResult result,
List<CliFunctionResult> cliFunctionResults, String expectedStatus) {
- assertEquals(Status.OK, result.getStatus());
+ assertThat(result.getStatus()).isEqualTo(Status.OK);
if (result.getType().equals(TYPE_TABULAR)) {
TabularResultData data = (TabularResultData) result.getResultData();
List<String> members = data.retrieveAllValues("Member");
- assertEquals(cliFunctionResults.size(), members.size());
+ assertThat(cliFunctionResults.size()).isEqualTo(members.size());
// Verify each member
for (int i = 0; i < members.size(); i++) {
- assertEquals("member" + i, members.get(i));
+ assertThat(members.get(i)).isEqualTo("member" + i);
}
// Verify each status
List<String> status = data.retrieveAllValues("Status");
for (String statu : status) {
- assertEquals(expectedStatus, statu);
+ assertThat(statu).isEqualTo(expectedStatus);
}
} else {
// Info result. Verify next lines are equal.
- assertEquals(result.nextLine(), expectedStatus);
+ assertThat(result.nextLine()).isEqualTo(expectedStatus);
}
}
@@ -568,7 +567,7 @@ public class LuceneIndexCommandsJUnitTest {
data.accumulate("value", expectedResults[i].getValue());
data.accumulate("score", expectedResults[i].getScore());
}
- CommandResult commandResult = (CommandResult) ResultBuilder.buildResult(data);
+ CommandResult commandResult = ResultBuilder.buildResult(data);
StringBuilder buffer = new StringBuilder();
while (commandResult.hasNextLine()) {
buffer.append(commandResult.nextLine());
@@ -622,7 +621,7 @@ public class LuceneIndexCommandsJUnitTest {
private final Execution functionExecutor;
- protected LuceneTestIndexCommands(final InternalCache cache, final Execution functionExecutor) {
+ LuceneTestIndexCommands(final InternalCache cache, final Execution functionExecutor) {
assert cache != null : "The InternalCache cannot be null!";
setCache(cache);
this.functionExecutor = functionExecutor;
@@ -635,7 +634,7 @@ public class LuceneIndexCommandsJUnitTest {
@Override
public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
- Assert.assertNotNull(members);
+ assertThat(members).isNotNull();
return this.functionExecutor;
}
}
diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesJUnitTest.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesJUnitTest.java
index 0a95924..498a6ff 100644
--- a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesJUnitTest.java
+++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/distributed/TopEntriesJUnitTest.java
@@ -14,13 +14,8 @@
*/
package org.apache.geode.cache.lucene.internal.distributed;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
-import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@@ -30,17 +25,15 @@ import org.apache.geode.cache.lucene.internal.LuceneServiceImpl;
import org.apache.geode.cache.lucene.test.LuceneTestUtilities;
import org.apache.geode.test.junit.categories.LuceneTest;
-@Category({LuceneTest.class})
+@Category(LuceneTest.class)
public class TopEntriesJUnitTest {
-
- private Mockery mockContext;
-
- private EntryScore<String> r1_1 = new EntryScore("3", .9f);
- private EntryScore<String> r1_2 = new EntryScore("1", .8f);
- private EntryScore<String> r2_1 = new EntryScore("2", 0.85f);
- private EntryScore<String> r2_2 = new EntryScore("4", 0.1f);
+ private EntryScore<String> r1_1 = new EntryScore<>("3", .9f);
+ private EntryScore<String> r1_2 = new EntryScore<>("1", .8f);
+ private EntryScore<String> r2_1 = new EntryScore<>("2", 0.85f);
+ private EntryScore<String> r2_2 = new EntryScore<>("4", 0.1f);
@Test
+ @SuppressWarnings("unchecked")
public void testPopulateTopEntries() {
TopEntries<String> hits = new TopEntries<>();
hits.addHit(r1_1);
@@ -48,11 +41,12 @@ public class TopEntriesJUnitTest {
hits.addHit(r1_2);
hits.addHit(r2_2);
- assertEquals(4, hits.size());
+ assertThat(hits.size()).isEqualTo(4);
LuceneTestUtilities.verifyResultOrder(hits.getHits(), r1_1, r2_1, r1_2, r2_2);
}
@Test
+ @SuppressWarnings("unchecked")
public void putSameScoreEntries() {
TopEntries<String> hits = new TopEntries<>();
EntryScore<String> r1 = new EntryScore<>("1", .8f);
@@ -60,17 +54,17 @@ public class TopEntriesJUnitTest {
hits.addHit(r1);
hits.addHit(r2);
- assertEquals(2, hits.size());
+ assertThat(hits.size()).isEqualTo(2);
LuceneTestUtilities.verifyResultOrder(hits.getHits(), r1, r2);
}
@Test
public void testInitialization() {
TopEntries<String> hits = new TopEntries<>();
- assertEquals(LuceneQueryFactory.DEFAULT_LIMIT, hits.getLimit());
+ assertThat(hits.getLimit()).isEqualTo(LuceneQueryFactory.DEFAULT_LIMIT);
hits = new TopEntries<>(123);
- assertEquals(123, hits.getLimit());
+ assertThat(hits.getLimit()).isEqualTo(123);
}
@Test(expected = IllegalArgumentException.class)
@@ -79,25 +73,28 @@ public class TopEntriesJUnitTest {
}
@Test
- public void enforceLimit() throws Exception {
+ @SuppressWarnings("unchecked")
+ public void enforceLimit() {
TopEntries<String> hits = new TopEntries<>(3);
hits.addHit(r1_1);
hits.addHit(r2_1);
hits.addHit(r1_2);
hits.addHit(r2_2);
- assertEquals(3, hits.size());
+ assertThat(hits.size()).isEqualTo(3);
LuceneTestUtilities.verifyResultOrder(hits.getHits(), r1_1, r2_1, r1_2);
}
@Test
+ @SuppressWarnings("unchecked")
public void testSerialization() {
LuceneServiceImpl.registerDataSerializables();
TopEntries<String> hits = new TopEntries<>(3);
TopEntries<String> copy = CopyHelper.deepCopy(hits);
- assertEquals(3, copy.getLimit());
- assertEquals(0, copy.getHits().size());
+ assertThat(copy).isNotNull();
+ assertThat(copy.getLimit()).isEqualTo(3);
+ assertThat(copy.getHits().size()).isEqualTo(0);
hits = new TopEntries<>(3);
hits.addHit(r1_1);
@@ -105,23 +102,8 @@ public class TopEntriesJUnitTest {
hits.addHit(r1_2);
copy = CopyHelper.deepCopy(hits);
- assertEquals(3, copy.size());
+ assertThat(copy).isNotNull();
+ assertThat(copy.size()).isEqualTo(3);
LuceneTestUtilities.verifyResultOrder(copy.getHits(), r1_1, r2_1, r1_2);
}
-
- @Before
- public void setupMock() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
- }
-
- @After
- public void validateMock() {
- mockContext.assertIsSatisfied();
- mockContext = null;
- }
}
diff --git a/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerJUnitTest.java b/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerJUnitTest.java
index 8f164a0..ebaebcb 100644
--- a/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerJUnitTest.java
+++ b/geode-rebalancer/src/test/java/org/apache/geode/cache/util/AutoBalancerJUnitTest.java
@@ -14,12 +14,19 @@
*/
package org.apache.geode.cache.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -27,17 +34,10 @@ import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.Sequence;
-import org.jmock.api.Invocation;
-import org.jmock.lib.action.CustomAction;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
+import org.mockito.InOrder;
+import org.mockito.Mockito;
import org.apache.geode.GemFireConfigException;
import org.apache.geode.cache.control.RebalanceFactory;
@@ -61,261 +61,217 @@ import org.apache.geode.internal.cache.partitioned.LoadProbe;
* UnitTests for AutoBalancer. All collaborators should be mocked.
*/
public class AutoBalancerJUnitTest {
- Mockery mockContext;
-
- CacheOperationFacade mockCacheFacade;
- OOBAuditor mockAuditor;
- AuditScheduler mockScheduler;
- TimeProvider mockClock;
+ private TimeProvider mockClock;
+ private OOBAuditor mockAuditor;
+ private AuditScheduler mockScheduler;
+ private CacheOperationFacade mockCacheFacade;
@Before
public void setupMock() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
+ mockClock = mock(TimeProvider.class);
+ mockAuditor = mock(OOBAuditor.class);
+ mockScheduler = mock(AuditScheduler.class);
+ mockCacheFacade = mock(CacheOperationFacade.class);
+ }
- mockCacheFacade = mockContext.mock(CacheOperationFacade.class);
- mockAuditor = mockContext.mock(OOBAuditor.class);
- mockScheduler = mockContext.mock(AuditScheduler.class);
- mockClock = mockContext.mock(TimeProvider.class);
+ private static Properties getBasicConfig() {
+ Properties props = new Properties();
+ // every second schedule
+ props.put(AutoBalancer.SCHEDULE, "* 0/30 * * * ?");
+ return props;
}
- @After
- public void validateMock() {
- mockContext.assertIsSatisfied();
- mockContext = null;
+ private GeodeCacheFacade getFacadeForResourceManagerOps(final boolean simulate) throws Exception {
+ final GemFireCacheImpl mockCache = mock(GemFireCacheImpl.class);
+ final InternalResourceManager mockRM = mock(InternalResourceManager.class);
+ final RebalanceFactory mockRebalanceFactory = mock(RebalanceFactory.class);
+ final RebalanceOperation mockRebalanceOperation = mock(RebalanceOperation.class);
+ final RebalanceResults mockRebalanceResults = mock(RebalanceResults.class);
+
+ when(mockCache.isClosed()).thenReturn(false);
+ when(mockCache.getResourceManager()).thenReturn(mockRM);
+ when(mockRM.createRebalanceFactory()).thenReturn(mockRebalanceFactory);
+ when(mockRebalanceFactory.start()).thenReturn(mockRebalanceOperation);
+ when(mockRebalanceFactory.simulate()).thenReturn(mockRebalanceOperation);
+ when(mockRebalanceOperation.getResults()).thenReturn(mockRebalanceResults);
+ if (simulate)
+ when(mockRebalanceResults.getTotalBucketTransferBytes()).thenReturn(12345L);
+
+ return new GeodeCacheFacade(mockCache);
}
@Test
- public void testLockStatExecuteInSequence() throws InterruptedException {
- final Sequence sequence = mockContext.sequence("sequence");
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCacheFacade).acquireAutoBalanceLock();
- inSequence(sequence);
- will(returnValue(true));
- oneOf(mockCacheFacade).incrementAttemptCounter();
- inSequence(sequence);
- oneOf(mockCacheFacade).getTotalTransferSize();
- inSequence(sequence);
- will(returnValue(0L));
- }
- });
+ public void testLockStatExecuteInSequence() {
+ when(mockCacheFacade.acquireAutoBalanceLock()).thenReturn(true);
+ when(mockCacheFacade.getTotalTransferSize()).thenReturn(0L);
AutoBalancer balancer = new AutoBalancer(null, null, null, mockCacheFacade);
balancer.getOOBAuditor().execute();
+ InOrder inOrder = Mockito.inOrder(mockCacheFacade);
+ inOrder.verify(mockCacheFacade, times(1)).acquireAutoBalanceLock();
+ inOrder.verify(mockCacheFacade, times(1)).incrementAttemptCounter();
+ inOrder.verify(mockCacheFacade, times(1)).getTotalTransferSize();
}
@Test
- public void testAcquireLockAfterReleasedRemotely() throws InterruptedException {
- final Sequence sequence = mockContext.sequence("sequence");
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCacheFacade).acquireAutoBalanceLock();
- inSequence(sequence);
- will(returnValue(false));
- oneOf(mockCacheFacade).acquireAutoBalanceLock();
- inSequence(sequence);
- will(returnValue(true));
- oneOf(mockCacheFacade).incrementAttemptCounter();
- oneOf(mockCacheFacade).getTotalTransferSize();
- will(returnValue(0L));
- }
- });
+ public void testAcquireLockAfterReleasedRemotely() {
+ when(mockCacheFacade.getTotalTransferSize()).thenReturn(0L);
+ when(mockCacheFacade.acquireAutoBalanceLock()).thenReturn(false, true);
AutoBalancer balancer = new AutoBalancer(null, null, null, mockCacheFacade);
balancer.getOOBAuditor().execute();
balancer.getOOBAuditor().execute();
+ InOrder inOrder = Mockito.inOrder(mockCacheFacade);
+ inOrder.verify(mockCacheFacade, times(2)).acquireAutoBalanceLock();
+ inOrder.verify(mockCacheFacade, times(1)).incrementAttemptCounter();
+ inOrder.verify(mockCacheFacade, times(1)).getTotalTransferSize();
}
@Test
- public void testFailExecuteIfLockedElsewhere() throws InterruptedException {
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCacheFacade).acquireAutoBalanceLock();
- will(returnValue(false));
- // no other methods, rebalance, will be called
- }
- });
+ public void testFailExecuteIfLockedElsewhere() {
+ when(mockCacheFacade.acquireAutoBalanceLock()).thenReturn(false);
AutoBalancer balancer = new AutoBalancer(null, null, null, mockCacheFacade);
balancer.getOOBAuditor().execute();
+ verify(mockCacheFacade, times(1)).acquireAutoBalanceLock();
}
- @Test(expected = IllegalStateException.class)
+ @Test
public void testNoCacheError() {
AutoBalancer balancer = new AutoBalancer();
OOBAuditor auditor = balancer.getOOBAuditor();
- auditor.execute();
+ assertThatThrownBy(auditor::execute).isInstanceOf(IllegalStateException.class);
}
@Test
public void testOOBWhenBelowSizeThreshold() {
final long totalSize = 1000L;
-
final Map<PartitionedRegion, InternalPRInfo> details = new HashMap<>();
- mockContext.checking(new Expectations() {
- {
- allowing(mockCacheFacade).getRegionMemberDetails();
- will(returnValue(details));
- // first run
- oneOf(mockCacheFacade).getTotalDataSize(details);
- will(returnValue(totalSize));
- oneOf(mockCacheFacade).getTotalTransferSize();
- // half of threshold limit
- will(returnValue((AutoBalancer.DEFAULT_SIZE_THRESHOLD_PERCENT * totalSize / 100) / 2));
-
- // second run
- oneOf(mockCacheFacade).getTotalTransferSize();
- // nothing to transfer
- will(returnValue(0L));
- }
- });
+ when(mockCacheFacade.getRegionMemberDetails()).thenReturn(details);
+ when(mockCacheFacade.getTotalDataSize(details)).thenReturn(totalSize);
+ // First Run: half of threshold limit. Second Run: nothing to transfer.
+ when(mockCacheFacade.getTotalTransferSize())
+ .thenReturn((AutoBalancer.DEFAULT_SIZE_THRESHOLD_PERCENT * totalSize / 100) / 2, 0L);
AutoBalancer balancer = new AutoBalancer(null, null, null, mockCacheFacade);
Properties config = getBasicConfig();
config.put(AutoBalancer.MINIMUM_SIZE, "10");
- balancer.init(config);
+ balancer.initialize(null, config);
SizeBasedOOBAuditor auditor = (SizeBasedOOBAuditor) balancer.getOOBAuditor();
- // first run
- assertFalse(auditor.needsRebalancing());
+ // First run
+ assertThat(auditor.needsRebalancing()).isFalse();
- // second run
- assertFalse(auditor.needsRebalancing());
+ // Second run
+ assertThat(auditor.needsRebalancing()).isFalse();
}
@Test
public void testOOBWhenAboveThresholdButBelowMin() {
final long totalSize = 1000L;
-
- mockContext.checking(new Expectations() {
- {
- // first run
- oneOf(mockCacheFacade).getTotalTransferSize();
- // twice threshold
- will(returnValue((AutoBalancer.DEFAULT_SIZE_THRESHOLD_PERCENT * totalSize / 100) * 2));
-
- // second run
- oneOf(mockCacheFacade).getTotalTransferSize();
- // more than total size
- will(returnValue(2 * totalSize));
- }
- });
+ // First Run: twice threshold. Second Run: more than total size.
+ when(mockCacheFacade.getTotalTransferSize()).thenReturn(
+ (AutoBalancer.DEFAULT_SIZE_THRESHOLD_PERCENT * totalSize / 100) / 2, 2 * totalSize);
AutoBalancer balancer = new AutoBalancer(null, null, null, mockCacheFacade);
Properties config = getBasicConfig();
config.put(AutoBalancer.MINIMUM_SIZE, "" + (totalSize * 5));
- balancer.init(config);
+ balancer.initialize(null, config);
SizeBasedOOBAuditor auditor = (SizeBasedOOBAuditor) balancer.getOOBAuditor();
- // first run
- assertFalse(auditor.needsRebalancing());
+ // First run
+ assertThat(auditor.needsRebalancing()).isFalse();
- // second run
- assertFalse(auditor.needsRebalancing());
+ // Second run
+ assertThat(auditor.needsRebalancing()).isFalse();
}
@Test
public void testOOBWhenAboveThresholdAndMin() {
final long totalSize = 1000L;
-
final Map<PartitionedRegion, InternalPRInfo> details = new HashMap<>();
- mockContext.checking(new Expectations() {
- {
- allowing(mockCacheFacade).getRegionMemberDetails();
- will(returnValue(details));
-
- // first run
- oneOf(mockCacheFacade).getTotalDataSize(details);
- will(returnValue(totalSize));
- oneOf(mockCacheFacade).getTotalTransferSize();
- // twice threshold
- will(returnValue((AutoBalancer.DEFAULT_SIZE_THRESHOLD_PERCENT * totalSize / 100) * 2));
-
- // second run
- oneOf(mockCacheFacade).getTotalDataSize(details);
- will(returnValue(totalSize));
- oneOf(mockCacheFacade).getTotalTransferSize();
- // more than total size
- will(returnValue(2 * totalSize));
- }
- });
+ when(mockCacheFacade.getRegionMemberDetails()).thenReturn(details);
+ when(mockCacheFacade.getTotalDataSize(details)).thenReturn(totalSize);
+ // First Run: twice threshold. Second Run: more than total size.
+ when(mockCacheFacade.getTotalTransferSize()).thenReturn(
+ (AutoBalancer.DEFAULT_SIZE_THRESHOLD_PERCENT * totalSize / 100) * 2, 2 * totalSize);
AutoBalancer balancer = new AutoBalancer(null, null, null, mockCacheFacade);
Properties config = getBasicConfig();
config.put(AutoBalancer.MINIMUM_SIZE, "10");
- balancer.init(config);
+ balancer.initialize(null, config);
SizeBasedOOBAuditor auditor = (SizeBasedOOBAuditor) balancer.getOOBAuditor();
- // first run
- assertTrue(auditor.needsRebalancing());
+ // First run
+ assertThat(auditor.needsRebalancing()).isTrue();
- // second run
- assertTrue(auditor.needsRebalancing());
+ // Second run
+ assertThat(auditor.needsRebalancing()).isTrue();
}
- @Test(expected = GemFireConfigException.class)
+ @Test
public void testInvalidSchedule() {
String someSchedule = "X Y * * * *";
Properties props = new Properties();
props.put(AutoBalancer.SCHEDULE, someSchedule);
AutoBalancer autoR = new AutoBalancer();
- autoR.init(props);
+ assertThatThrownBy(() -> autoR.initialize(null, props))
+ .isInstanceOf(GemFireConfigException.class);
}
@Test
public void testOOBAuditorInit() {
AutoBalancer balancer = new AutoBalancer();
- balancer.init(getBasicConfig());
+ balancer.initialize(null, getBasicConfig());
SizeBasedOOBAuditor auditor = (SizeBasedOOBAuditor) balancer.getOOBAuditor();
- assertEquals(AutoBalancer.DEFAULT_SIZE_THRESHOLD_PERCENT, auditor.getSizeThreshold());
- assertEquals(AutoBalancer.DEFAULT_MINIMUM_SIZE, auditor.getSizeMinimum());
+ assertThat(auditor.getSizeThreshold()).isEqualTo(AutoBalancer.DEFAULT_SIZE_THRESHOLD_PERCENT);
+ assertThat(auditor.getSizeMinimum()).isEqualTo(AutoBalancer.DEFAULT_MINIMUM_SIZE);
Properties props = getBasicConfig();
props.put(AutoBalancer.SIZE_THRESHOLD_PERCENT, "17");
props.put(AutoBalancer.MINIMUM_SIZE, "10");
balancer = new AutoBalancer();
- balancer.init(props);
+ balancer.initialize(null, props);
auditor = (SizeBasedOOBAuditor) balancer.getOOBAuditor();
- assertEquals(17, auditor.getSizeThreshold());
- assertEquals(10, auditor.getSizeMinimum());
+ assertThat(auditor.getSizeThreshold()).isEqualTo(17);
+ assertThat(auditor.getSizeMinimum()).isEqualTo(10);
}
- @Test(expected = GemFireConfigException.class)
+ @Test
public void testConfigTransferThresholdNegative() {
AutoBalancer balancer = new AutoBalancer();
Properties props = getBasicConfig();
props.put(AutoBalancer.SIZE_THRESHOLD_PERCENT, "-1");
- balancer.initialize(null, props);
+ assertThatThrownBy(() -> balancer.initialize(null, props))
+ .isInstanceOf(GemFireConfigException.class);
}
- @Test(expected = GemFireConfigException.class)
+ @Test
public void testConfigSizeMinNegative() {
AutoBalancer balancer = new AutoBalancer();
Properties props = getBasicConfig();
props.put(AutoBalancer.MINIMUM_SIZE, "-1");
- balancer.initialize(null, props);
+ assertThatThrownBy(() -> balancer.initialize(null, props))
+ .isInstanceOf(GemFireConfigException.class);
}
- @Test(expected = GemFireConfigException.class)
+ @Test
public void testConfigTransferThresholdZero() {
AutoBalancer balancer = new AutoBalancer();
Properties props = getBasicConfig();
props.put(AutoBalancer.SIZE_THRESHOLD_PERCENT, "0");
- balancer.initialize(null, props);
+ assertThatThrownBy(() -> balancer.initialize(null, props))
+ .isInstanceOf(GemFireConfigException.class);
}
- @Test(expected = GemFireConfigException.class)
+ @Test
public void testConfigTransferThresholdTooHigh() {
AutoBalancer balancer = new AutoBalancer();
Properties props = getBasicConfig();
props.put(AutoBalancer.SIZE_THRESHOLD_PERCENT, "100");
- balancer.initialize(null, props);
+ assertThatThrownBy(() -> balancer.initialize(null, props))
+ .isInstanceOf(GemFireConfigException.class);
}
@Test
@@ -325,205 +281,112 @@ public class AutoBalancerJUnitTest {
props.put(AutoBalancer.SCHEDULE, someSchedule);
props.put(AutoBalancer.SIZE_THRESHOLD_PERCENT, 17);
- mockContext.checking(new Expectations() {
- {
- oneOf(mockScheduler).init(someSchedule);
- oneOf(mockAuditor).init(props);
- }
- });
-
AutoBalancer autoR = new AutoBalancer(mockScheduler, mockAuditor, null, null);
autoR.initialize(null, props);
+ verify(mockAuditor, times(1)).init(props);
+ verify(mockScheduler, times(1)).init(someSchedule);
}
@Test
public void testMinimalConfiguration() {
AutoBalancer autoR = new AutoBalancer();
- try {
- autoR.init(null);
- fail();
- } catch (GemFireConfigException e) {
- // expected
- }
+ assertThatThrownBy(() -> autoR.initialize(null, null))
+ .isInstanceOf(GemFireConfigException.class);
Properties props = getBasicConfig();
- autoR.init(props);
+ assertThatCode(() -> autoR.initialize(null, props)).doesNotThrowAnyException();
}
@Test
- @Ignore("GEODE-2789: need to rewrite this test")
public void testFacadeTotalTransferSize() throws Exception {
- assertEquals(12345, getFacadeForResourceManagerOps(true).getTotalTransferSize());
+ assertThat(getFacadeForResourceManagerOps(true).getTotalTransferSize()).isEqualTo(12345);
}
@Test
- @Ignore("GEODE-2789: need to rewrite this test")
- public void testFacadeRebalance() throws Exception {
- getFacadeForResourceManagerOps(false).rebalance();
- }
-
- private GeodeCacheFacade getFacadeForResourceManagerOps(final boolean simulate) throws Exception {
- final GemFireCacheImpl mockCache = mockContext.mock(GemFireCacheImpl.class);
- final InternalResourceManager mockRM = mockContext.mock(InternalResourceManager.class);
- final RebalanceFactory mockRebalanceFactory = mockContext.mock(RebalanceFactory.class);
- final RebalanceOperation mockRebalanceOperation = mockContext.mock(RebalanceOperation.class);
- final RebalanceResults mockRebalanceResults = mockContext.mock(RebalanceResults.class);
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).isClosed();
- will(returnValue(false));
- oneOf(mockCache).getResourceManager();
- will(returnValue(mockRM));
- oneOf(mockRM).createRebalanceFactory();
- will(returnValue(mockRebalanceFactory));
- if (simulate) {
- oneOf(mockRebalanceFactory).simulate();
- } else {
- oneOf(mockRebalanceFactory).start();
- }
- will(returnValue(mockRebalanceOperation));
- oneOf(mockRebalanceOperation).getResults();
- will(returnValue(mockRebalanceResults));
- if (simulate) {
- atLeast(1).of(mockRebalanceResults).getTotalBucketTransferBytes();
- will(returnValue(12345L));
- }
- allowing(mockRebalanceResults);
- }
- });
-
- GeodeCacheFacade facade = new GeodeCacheFacade(mockCache);
-
- return facade;
+ public void testFacadeRebalance() {
+ assertThatCode(() -> getFacadeForResourceManagerOps(false).rebalance())
+ .doesNotThrowAnyException();
}
@Test
public void testFacadeTotalBytesNoRegion() {
CacheOperationFacade facade = new AutoBalancer().getCacheOperationFacade();
- assertEquals(0, facade.getTotalDataSize(new HashMap<PartitionedRegion, InternalPRInfo>()));
+ assertThat(facade.getTotalDataSize(new HashMap<>())).isEqualTo(0);
}
@Test
- @Ignore("GEODE-2789: need to rewrite this test")
public void testFacadeCollectMemberDetailsNoRegion() {
- final GemFireCacheImpl mockCache = mockContext.mock(GemFireCacheImpl.class);
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).isClosed();
- will(returnValue(false));
- oneOf(mockCache).getPartitionedRegions();
- will(returnValue(new HashSet<PartitionedRegion>()));
- }
- });
-
+ final GemFireCacheImpl mockCache = mock(GemFireCacheImpl.class);
+ when(mockCache.isClosed()).thenReturn(false);
+ when(mockCache.getPartitionedRegions()).thenReturn(Collections.emptySet());
GeodeCacheFacade facade = new GeodeCacheFacade(mockCache);
- assertEquals(0, facade.getRegionMemberDetails().size());
+ assertThat(facade.getRegionMemberDetails().size()).isEqualTo(0);
}
@Test
- @Ignore("GEODE-2789: need to rewrite this test")
public void testFacadeCollectMemberDetails2Regions() {
- final GemFireCacheImpl mockCache = mockContext.mock(GemFireCacheImpl.class);
- final InternalResourceManager mockRM = mockContext.mock(InternalResourceManager.class);
- final LoadProbe mockProbe = mockContext.mock(LoadProbe.class);
-
- final PartitionedRegion mockR1 = mockContext.mock(PartitionedRegion.class, "r1");
- final PartitionedRegion mockR2 = mockContext.mock(PartitionedRegion.class, "r2");
+ final LoadProbe mockProbe = mock(LoadProbe.class);
+ final GemFireCacheImpl mockCache = mock(GemFireCacheImpl.class);
+ final InternalResourceManager mockRM = mock(InternalResourceManager.class);
+ final PartitionedRegion mockR1 = mock(PartitionedRegion.class, "r1");
+ final PartitionedRegion mockR2 = mock(PartitionedRegion.class, "r2");
+ final PRHARedundancyProvider mockRedundancyProviderR1 =
+ mock(PRHARedundancyProvider.class, "prhaR1");
+ final InternalPRInfo mockR1PRInfo = mock(InternalPRInfo.class, "prInforR1");
+ final PRHARedundancyProvider mockRedundancyProviderR2 =
+ mock(PRHARedundancyProvider.class, "prhaR2");
+ final InternalPRInfo mockR2PRInfo = mock(InternalPRInfo.class, "prInforR2");
final HashSet<PartitionedRegion> regions = new HashSet<>();
regions.add(mockR1);
regions.add(mockR2);
- final PRHARedundancyProvider mockRedundancyProviderR1 =
- mockContext.mock(PRHARedundancyProvider.class, "prhaR1");
- final InternalPRInfo mockR1PRInfo = mockContext.mock(InternalPRInfo.class, "prInforR1");
-
- final PRHARedundancyProvider mockRedundancyProviderR2 =
- mockContext.mock(PRHARedundancyProvider.class, "prhaR2");
- final InternalPRInfo mockR2PRInfo = mockContext.mock(InternalPRInfo.class, "prInforR2");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockCache).isClosed();
- will(returnValue(false));
- oneOf(mockCache).getPartitionedRegions();
- will(returnValue(regions));
- exactly(2).of(mockCache).getResourceManager();
- will(returnValue(mockRM));
- exactly(2).of(mockRM).getLoadProbe();
- will(returnValue(mockProbe));
- allowing(mockR1).getFullPath();
- oneOf(mockR1).getRedundancyProvider();
- will(returnValue(mockRedundancyProviderR1));
- allowing(mockR2).getFullPath();
- oneOf(mockR2).getRedundancyProvider();
- will(returnValue(mockRedundancyProviderR2));
-
- oneOf(mockRedundancyProviderR1).buildPartitionedRegionInfo(with(true),
- with(any(LoadProbe.class)));
- will(returnValue(mockR1PRInfo));
-
- oneOf(mockRedundancyProviderR2).buildPartitionedRegionInfo(with(true),
- with(any(LoadProbe.class)));
- will(returnValue(mockR2PRInfo));
- }
- });
+ when(mockCache.isClosed()).thenReturn(false);
+ when(mockCache.getPartitionedRegions()).thenReturn(regions);
+ when(mockCache.getResourceManager()).thenReturn(mockRM);
+ when(mockCache.getInternalResourceManager()).thenReturn(mockRM);
+ when(mockRM.getLoadProbe()).thenReturn(mockProbe);
+ when(mockR1.getRedundancyProvider()).thenReturn(mockRedundancyProviderR1);
+ when(mockR2.getRedundancyProvider()).thenReturn(mockRedundancyProviderR2);
+ when(mockRedundancyProviderR1.buildPartitionedRegionInfo(eq(true), any(LoadProbe.class)))
+ .thenReturn(mockR1PRInfo);
+ when(mockRedundancyProviderR2.buildPartitionedRegionInfo(eq(true), any(LoadProbe.class)))
+ .thenReturn(mockR2PRInfo);
GeodeCacheFacade facade = new GeodeCacheFacade(mockCache);
-
Map<PartitionedRegion, InternalPRInfo> map = facade.getRegionMemberDetails();
- assertNotNull(map);
- assertEquals(2, map.size());
- assertEquals(map.get(mockR1), mockR1PRInfo);
- assertEquals(map.get(mockR2), mockR2PRInfo);
+ assertThat(map).isNotNull();
+ assertThat(map.size()).isEqualTo(2);
+ assertThat(map.get(mockR1)).isEqualTo(mockR1PRInfo);
+ assertThat(map.get(mockR2)).isEqualTo(mockR2PRInfo);
}
@Test
- @Ignore("GEODE-2789: need to rewrite this test")
public void testFacadeTotalBytes2Regions() {
- final PartitionedRegion mockR1 = mockContext.mock(PartitionedRegion.class, "r1");
- final PartitionedRegion mockR2 = mockContext.mock(PartitionedRegion.class, "r2");
- final HashSet<PartitionedRegion> regions = new HashSet<>();
- regions.add(mockR1);
- regions.add(mockR2);
-
- final InternalPRInfo mockR1PRInfo = mockContext.mock(InternalPRInfo.class, "prInforR1");
- final PartitionMemberInfo mockR1M1Info = mockContext.mock(PartitionMemberInfo.class, "r1M1");
- final PartitionMemberInfo mockR1M2Info = mockContext.mock(PartitionMemberInfo.class, "r1M2");
+ final PartitionedRegion mockR1 = mock(PartitionedRegion.class, "r1");
+ final InternalPRInfo mockR1PRInfo = mock(InternalPRInfo.class, "prInforR1");
+ final PartitionMemberInfo mockR1M1Info = mock(PartitionMemberInfo.class, "r1M1");
+ final PartitionMemberInfo mockR1M2Info = mock(PartitionMemberInfo.class, "r1M2");
final HashSet<PartitionMemberInfo> r1Members = new HashSet<>();
r1Members.add(mockR1M1Info);
r1Members.add(mockR1M2Info);
+ when(mockR1PRInfo.getPartitionMemberInfo()).thenReturn(r1Members);
+ when(mockR1M1Info.getSize()).thenReturn(123L);
+ when(mockR1M2Info.getSize()).thenReturn(74L);
- final InternalPRInfo mockR2PRInfo = mockContext.mock(InternalPRInfo.class, "prInforR2");
- final PartitionMemberInfo mockR2M1Info = mockContext.mock(PartitionMemberInfo.class, "r2M1");
+ final PartitionedRegion mockR2 = mock(PartitionedRegion.class, "r2");
+ final InternalPRInfo mockR2PRInfo = mock(InternalPRInfo.class, "prInforR2");
+ final PartitionMemberInfo mockR2M1Info = mock(PartitionMemberInfo.class, "r2M1");
final HashSet<PartitionMemberInfo> r2Members = new HashSet<>();
r2Members.add(mockR2M1Info);
+ when(mockR2PRInfo.getPartitionMemberInfo()).thenReturn(r2Members);
+ when(mockR2M1Info.getSize()).thenReturn(3475L);
final Map<PartitionedRegion, InternalPRInfo> details = new HashMap<>();
details.put(mockR1, mockR1PRInfo);
details.put(mockR2, mockR2PRInfo);
- mockContext.checking(new Expectations() {
- {
- allowing(mockR1).getFullPath();
- allowing(mockR2).getFullPath();
-
- oneOf(mockR1PRInfo).getPartitionMemberInfo();
- will(returnValue(r1Members));
- atLeast(1).of(mockR1M1Info).getSize();
- will(returnValue(123L));
- atLeast(1).of(mockR1M2Info).getSize();
- will(returnValue(74L));
-
- oneOf(mockR2PRInfo).getPartitionMemberInfo();
- will(returnValue(r2Members));
- atLeast(1).of(mockR2M1Info).getSize();
- will(returnValue(3475L));
- }
- });
-
GeodeCacheFacade facade = new GeodeCacheFacade() {
@Override
public Map<PartitionedRegion, InternalPRInfo> getRegionMemberDetails() {
@@ -531,79 +394,57 @@ public class AutoBalancerJUnitTest {
}
};
- assertEquals(123 + 74 + 3475, facade.getTotalDataSize(details));
+ assertThat(facade.getTotalDataSize(details)).isEqualTo(123 + 74 + 3475);
+ verify(mockR1M1Info, atLeastOnce()).getSize();
+ verify(mockR1M2Info, atLeastOnce()).getSize();
+ verify(mockR2M1Info, atLeastOnce()).getSize();
}
@Test
public void testAuditorInvocation() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(3);
- mockContext.checking(new Expectations() {
- {
- oneOf(mockAuditor).init(with(any(Properties.class)));
- atLeast(2).of(mockAuditor).execute();
- allowing(mockClock).currentTimeMillis();
- will(new CustomAction("returnTime") {
- @Override
- public Object invoke(Invocation invocation) throws Throwable {
- latch.countDown();
- return 990L;
- }
- });
- }
+ when(mockClock.currentTimeMillis()).then((invocation) -> {
+ latch.countDown();
+ return 990L;
});
Properties props = AutoBalancerJUnitTest.getBasicConfig();
-
- assertEquals(3, latch.getCount());
+ assertThat(latch.getCount()).isEqualTo(3);
AutoBalancer autoR = new AutoBalancer(null, mockAuditor, mockClock, null);
autoR.initialize(null, props);
- assertTrue(latch.await(1, TimeUnit.MINUTES));
+
+ assertThat(latch.await(1, TimeUnit.MINUTES)).isTrue();
+ verify(mockAuditor, atLeast(2)).execute();
+ verify(mockAuditor, times(1)).init(any(Properties.class));
}
@Test
public void destroyAutoBalancer() throws InterruptedException {
+ final int timer = 20; // simulate 20 milliseconds
final CountDownLatch latch = new CountDownLatch(2);
final CountDownLatch timerLatch = new CountDownLatch(1);
- final int timer = 20; // simulate 20 milliseconds
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockAuditor).init(with(any(Properties.class)));
- allowing(mockAuditor).execute();
- allowing(mockClock).currentTimeMillis();
- will(new CustomAction("returnTime") {
- @Override
- public Object invoke(Invocation invocation) throws Throwable {
- latch.countDown();
- if (latch.getCount() == 0) {
- assertTrue(timerLatch.await(1, TimeUnit.SECONDS));
- // scheduler is destroyed before wait is over
- fail();
- }
- return 1000L - timer;
- }
- });
+ when(mockClock.currentTimeMillis()).then((invocation) -> {
+ latch.countDown();
+ if (latch.getCount() == 0) {
+ assertThat(timerLatch.await(1, TimeUnit.SECONDS)).isTrue();
+ // scheduler is destroyed before wait is over
+ // fail();
+ throw new AssertionError();
}
+ return 1000L - timer;
});
Properties props = AutoBalancerJUnitTest.getBasicConfig();
-
- assertEquals(2, latch.getCount());
+ assertThat(latch.getCount()).isEqualTo(2);
AutoBalancer autoR = new AutoBalancer(null, mockAuditor, mockClock, null);
autoR.initialize(null, props);
- assertTrue(latch.await(1, TimeUnit.MINUTES));
+ assertThat(latch.await(1, TimeUnit.MINUTES)).isTrue();
+ verify(mockAuditor, times(1)).init(any(Properties.class));
// after destroy no more execute will be called.
autoR.destroy();
timerLatch.countDown();
TimeUnit.MILLISECONDS.sleep(2 * timer);
}
-
- static Properties getBasicConfig() {
- Properties props = new Properties();
- // every second schedule
- props.put(AutoBalancer.SCHEDULE, "* 0/30 * * * ?");
- return props;
- }
}
diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/support/LoginHandlerInterceptorJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/support/LoginHandlerInterceptorJUnitTest.java
index e6d2537..0c71f0a 100644
--- a/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/support/LoginHandlerInterceptorJUnitTest.java
+++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/controllers/support/LoginHandlerInterceptorJUnitTest.java
@@ -14,10 +14,14 @@
*/
package org.apache.geode.management.internal.web.controllers.support;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.apache.geode.management.internal.security.ResourceConstants.PASSWORD;
+import static org.apache.geode.management.internal.security.ResourceConstants.USER_NAME;
+import static org.apache.geode.management.internal.web.controllers.support.LoginHandlerInterceptor.ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import java.util.Enumeration;
import java.util.HashMap;
@@ -29,13 +33,11 @@ import javax.servlet.http.HttpServletRequest;
import edu.umd.cs.mtc.MultithreadedTestCase;
import edu.umd.cs.mtc.TestFramework;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TestName;
import org.apache.geode.internal.security.SecurityService;
import org.apache.geode.management.internal.security.ResourceConstants;
@@ -44,38 +46,26 @@ import org.apache.geode.management.internal.security.ResourceConstants;
* The LoginHandlerInterceptorJUnitTest class is a test suite of test cases to test the contract and
* functionality of the Spring HandlerInterceptor, LoginHandlerInterceptor class.
*
- * @see org.jmock.Mockery
- * @see org.junit.Assert
* @see org.junit.Test
* @since GemFire 8.0
*/
public class LoginHandlerInterceptorJUnitTest {
-
- private Mockery mockContext;
-
private SecurityService securityService;
+ @Rule
+ public TestName name = new TestName();
+
@Before
public void setUp() {
- mockContext = new Mockery();
- mockContext.setImposteriser(ClassImposteriser.INSTANCE);
- mockContext.setThreadingPolicy(new Synchroniser());
LoginHandlerInterceptor.getEnvironment().clear();
-
- securityService = mockContext.mock(SecurityService.class);
+ securityService = mock(SecurityService.class);
}
@After
public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
LoginHandlerInterceptor.getEnvironment().clear();
}
- private String createEnvironmentVariable(final String name) {
- return (LoginHandlerInterceptor.ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + name);
- }
-
private <T> Enumeration<T> enumeration(final Iterator<T> iterator) {
return new Enumeration<T>() {
public boolean hasMoreElements() {
@@ -89,52 +79,66 @@ public class LoginHandlerInterceptorJUnitTest {
}
@Test
- public void testPreHandleAfterCompletion() throws Exception {
+ public void preHandleShouldSetEnvironmentVariablesFromSpecificRequestParameters()
+ throws Exception {
final Map<String, String> requestParameters = new HashMap<>(2);
-
requestParameters.put("parameter", "one");
- requestParameters.put(createEnvironmentVariable("variable"), "two");
-
- final HttpServletRequest mockHttpRequest = mockContext.mock(HttpServletRequest.class,
- "testPreHandleAfterCompletion.HttpServletRequest");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockHttpRequest).getParameterNames();
- will(returnValue(enumeration(requestParameters.keySet().iterator())));
- oneOf(mockHttpRequest).getHeader(ResourceConstants.USER_NAME);
- will(returnValue("admin"));
- oneOf(mockHttpRequest).getHeader(ResourceConstants.PASSWORD);
- will(returnValue("password"));
- oneOf(mockHttpRequest).getParameter(with(equal(createEnvironmentVariable("variable"))));
- will(returnValue(requestParameters.get(createEnvironmentVariable("variable"))));
- oneOf(securityService).login(with(aNonNull(Properties.class)));
- oneOf(securityService).logout();
- }
- });
+ requestParameters.put(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "variable", "two");
+ final HttpServletRequest mockHttpRequest = mock(HttpServletRequest.class, name.getMethodName());
+ when(mockHttpRequest.getParameterNames())
+ .thenReturn(enumeration(requestParameters.keySet().iterator()));
+ when(mockHttpRequest.getHeader(USER_NAME)).thenReturn("admin");
+ when(mockHttpRequest.getHeader(PASSWORD)).thenReturn("password");
+ when(mockHttpRequest.getParameter(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "variable"))
+ .thenReturn("two");
LoginHandlerInterceptor handlerInterceptor = new LoginHandlerInterceptor(securityService);
+ Map<String, String> environmentBeforePreHandle = LoginHandlerInterceptor.getEnvironment();
+ assertThat(environmentBeforePreHandle).isNotNull();
+ assertThat(environmentBeforePreHandle.isEmpty()).isTrue();
+
+ assertThat(handlerInterceptor.preHandle(mockHttpRequest, null, null)).isTrue();
+ Map<String, String> environmentAfterPreHandle = LoginHandlerInterceptor.getEnvironment();
+ assertThat(environmentAfterPreHandle).isNotNull();
+ assertThat(environmentAfterPreHandle).isNotSameAs(environmentBeforePreHandle);
+ assertThat(environmentAfterPreHandle.size()).isEqualTo(1);
+ assertThat(environmentAfterPreHandle.containsKey("variable")).isTrue();
+ assertThat(environmentAfterPreHandle.get("variable")).isEqualTo("two");
+ Properties expectedLoginProperties = new Properties();
+ expectedLoginProperties.put(USER_NAME, "admin");
+ expectedLoginProperties.put(PASSWORD, "password");
+ verify(securityService, times(1)).login(expectedLoginProperties);
+ }
- Map<String, String> envBefore = LoginHandlerInterceptor.getEnvironment();
-
- assertNotNull(envBefore);
- assertTrue(envBefore.isEmpty());
- assertTrue(handlerInterceptor.preHandle(mockHttpRequest, null, null));
-
- Map<String, String> envSet = LoginHandlerInterceptor.getEnvironment();
+ @Test
+ public void afterCompletionShouldCleanTheEnvironment() throws Exception {
+ final Map<String, String> requestParameters = new HashMap<>(2);
+ requestParameters.put(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "variable", "two");
+ final HttpServletRequest mockHttpRequest = mock(HttpServletRequest.class, name.getMethodName());
+ when(mockHttpRequest.getParameterNames())
+ .thenReturn(enumeration(requestParameters.keySet().iterator()));
+ when(mockHttpRequest.getHeader(USER_NAME)).thenReturn("admin");
+ when(mockHttpRequest.getHeader(PASSWORD)).thenReturn("password");
+ when(mockHttpRequest.getParameter(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "variable"))
+ .thenReturn("two");
- assertNotNull(envSet);
- assertNotSame(envBefore, envSet);
- assertEquals(1, envSet.size());
- assertTrue(envSet.containsKey("variable"));
- assertEquals("two", envSet.get("variable"));
+ LoginHandlerInterceptor handlerInterceptor = new LoginHandlerInterceptor(securityService);
+ assertThat(handlerInterceptor.preHandle(mockHttpRequest, null, null)).isTrue();
+ Map<String, String> environmentAfterPreHandle = LoginHandlerInterceptor.getEnvironment();
+ assertThat(environmentAfterPreHandle).isNotNull();
+ assertThat(environmentAfterPreHandle.size()).isEqualTo(1);
+ assertThat(environmentAfterPreHandle.containsKey("variable")).isTrue();
+ assertThat(environmentAfterPreHandle.get("variable")).isEqualTo("two");
+ Properties expectedLoginProperties = new Properties();
+ expectedLoginProperties.put(USER_NAME, "admin");
+ expectedLoginProperties.put(PASSWORD, "password");
+ verify(securityService, times(1)).login(expectedLoginProperties);
handlerInterceptor.afterCompletion(mockHttpRequest, null, null, null);
-
- Map<String, String> envAfter = LoginHandlerInterceptor.getEnvironment();
-
- assertNotNull(envAfter);
- assertTrue(envAfter.isEmpty());
+ Map<String, String> environmentAfterCompletion = LoginHandlerInterceptor.getEnvironment();
+ assertThat(environmentAfterCompletion).isNotNull();
+ assertThat(environmentAfterCompletion.isEmpty()).isTrue();
+ verify(securityService, times(1)).logout();
}
@Test
@@ -143,162 +147,130 @@ public class LoginHandlerInterceptorJUnitTest {
}
private class HandlerInterceptorThreadSafetyMultiThreadedTestCase extends MultithreadedTestCase {
-
- private LoginHandlerInterceptor handlerInterceptor;
-
private HttpServletRequest mockHttpRequestOne;
private HttpServletRequest mockHttpRequestTwo;
+ private LoginHandlerInterceptor handlerInterceptor;
@Override
public void initialize() {
super.initialize();
final Map<String, String> requestParametersOne = new HashMap<>(3);
-
requestParametersOne.put("param", "one");
- requestParametersOne.put(createEnvironmentVariable("STAGE"), "test");
- requestParametersOne.put(createEnvironmentVariable("GEODE_HOME"), "/path/to/gemfire/700");
-
- mockHttpRequestOne = mockContext.mock(HttpServletRequest.class,
- "testHandlerInterceptorThreadSafety.HttpServletRequest.1");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockHttpRequestOne).getParameterNames();
- will(returnValue(enumeration(requestParametersOne.keySet().iterator())));
- oneOf(mockHttpRequestOne).getHeader(ResourceConstants.USER_NAME);
- will(returnValue("admin"));
- oneOf(mockHttpRequestOne).getHeader(ResourceConstants.PASSWORD);
- will(returnValue("password"));
- oneOf(mockHttpRequestOne).getParameter(with(equal(createEnvironmentVariable("STAGE"))));
- will(returnValue(requestParametersOne.get(createEnvironmentVariable("STAGE"))));
- oneOf(mockHttpRequestOne)
- .getParameter(with(equal(createEnvironmentVariable("GEODE_HOME"))));
- will(returnValue(requestParametersOne.get(createEnvironmentVariable("GEODE_HOME"))));
- oneOf(securityService).login(with(aNonNull(Properties.class)));
- oneOf(securityService).logout();
- }
- });
-
- mockHttpRequestTwo = mockContext.mock(HttpServletRequest.class,
- "testHandlerInterceptorThreadSafety.HttpServletRequest.2");
-
+ requestParametersOne.put(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "STAGE", "test");
+ requestParametersOne.put(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "GEODE_HOME",
+ "/path/to/geode");
+
+ mockHttpRequestOne =
+ mock(HttpServletRequest.class, "testHandlerInterceptorThreadSafety.HttpServletRequest.1");
+ when(mockHttpRequestOne.getParameterNames())
+ .thenReturn(enumeration(requestParametersOne.keySet().iterator()));
+ when(mockHttpRequestOne.getHeader(ResourceConstants.USER_NAME)).thenReturn("admin");
+ when(mockHttpRequestOne.getHeader(ResourceConstants.PASSWORD)).thenReturn("password");
+ when(mockHttpRequestOne.getParameter(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "STAGE"))
+ .thenReturn("test");
+ when(mockHttpRequestOne
+ .getParameter(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "GEODE_HOME"))
+ .thenReturn("/path/to/geode");
+
+ mockHttpRequestTwo =
+ mock(HttpServletRequest.class, "testHandlerInterceptorThreadSafety.HttpServletRequest.2");
final Map<String, String> requestParametersTwo = new HashMap<>(3);
-
requestParametersTwo.put("parameter", "two");
- requestParametersTwo.put(createEnvironmentVariable("HOST"), "localhost");
- requestParametersTwo.put(createEnvironmentVariable("GEODE_HOME"), "/path/to/gemfire/75");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockHttpRequestTwo).getParameterNames();
- will(returnValue(enumeration(requestParametersTwo.keySet().iterator())));
- oneOf(mockHttpRequestTwo).getHeader(ResourceConstants.USER_NAME);
- will(returnValue("admin"));
- oneOf(mockHttpRequestTwo).getHeader(ResourceConstants.PASSWORD);
- will(returnValue("password"));
- oneOf(mockHttpRequestTwo).getParameter(with(equal(createEnvironmentVariable("HOST"))));
- will(returnValue(requestParametersTwo.get(createEnvironmentVariable("HOST"))));
- oneOf(mockHttpRequestTwo)
- .getParameter(with(equal(createEnvironmentVariable("GEODE_HOME"))));
- will(returnValue(requestParametersTwo.get(createEnvironmentVariable("GEODE_HOME"))));
- oneOf(securityService).login(with(aNonNull(Properties.class)));
- oneOf(securityService).logout();
- }
- });
+ requestParametersTwo.put(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "HOST", "localhost");
+ requestParametersTwo.put(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "GEODE_HOME",
+ "/path/to/geode/180");
+ when(mockHttpRequestTwo.getParameterNames())
+ .thenReturn(enumeration(requestParametersTwo.keySet().iterator()));
+ when(mockHttpRequestTwo.getHeader(ResourceConstants.USER_NAME)).thenReturn("admin");
+ when(mockHttpRequestTwo.getHeader(ResourceConstants.PASSWORD)).thenReturn("password");
+ when(mockHttpRequestTwo.getParameter(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "HOST"))
+ .thenReturn("localhost");
+ when(mockHttpRequestTwo
+ .getParameter(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX + "GEODE_HOME"))
+ .thenReturn("/path/to/geode/180");
handlerInterceptor = new LoginHandlerInterceptor(securityService);
}
+ @SuppressWarnings("unused")
public void thread1() throws Exception {
assertTick(0);
Thread.currentThread().setName("HTTP Request Processing Thread 1");
Map<String, String> env = LoginHandlerInterceptor.getEnvironment();
-
- assertNotNull(env);
- assertTrue(env.isEmpty());
- assertTrue(handlerInterceptor.preHandle(mockHttpRequestOne, null, null));
+ assertThat(env).isNotNull();
+ assertThat(env.isEmpty()).isTrue();
+ assertThat(handlerInterceptor.preHandle(mockHttpRequestOne, null, null)).isTrue();
env = LoginHandlerInterceptor.getEnvironment();
-
- assertNotNull(env);
- assertEquals(2, env.size());
- assertFalse(env.containsKey("param"));
- assertFalse(env.containsKey("parameter"));
- assertFalse(env.containsKey("HOST"));
- assertFalse(env.containsKey("security-username"));
- assertFalse(env.containsKey("security-password"));
- assertEquals("test", env.get("STAGE"));
- assertEquals("/path/to/gemfire/700", env.get("GEODE_HOME"));
+ assertThat(env).isNotNull();
+ assertThat(env.size()).isEqualTo(2);
+ assertThat(env.containsKey("param")).isFalse();
+ assertThat(env.containsKey("parameter")).isFalse();
+ assertThat(env.containsKey("HOST")).isFalse();
+ assertThat(env.containsKey("security-username")).isFalse();
+ assertThat(env.containsKey("security-password")).isFalse();
+ assertThat(env.get("STAGE")).isEqualTo("test");
+ assertThat(env.get("GEODE_HOME")).isEqualTo("/path/to/geode");
waitForTick(2);
-
env = LoginHandlerInterceptor.getEnvironment();
-
- assertNotNull(env);
- assertEquals(2, env.size());
- assertFalse(env.containsKey("param"));
- assertFalse(env.containsKey("parameter"));
- assertFalse(env.containsKey("HOST"));
- assertFalse(env.containsKey("security-username"));
- assertFalse(env.containsKey("security-password"));
- assertEquals("test", env.get("STAGE"));
- assertEquals("/path/to/gemfire/700", env.get("GEODE_HOME"));
+ assertThat(env).isNotNull();
+ assertThat(env.size()).isEqualTo(2);
+ assertThat(env.containsKey("param")).isFalse();
+ assertThat(env.containsKey("parameter")).isFalse();
+ assertThat(env.containsKey("HOST")).isFalse();
+ assertThat(env.containsKey("security-username")).isFalse();
+ assertThat(env.containsKey("security-password")).isFalse();
+ assertThat(env.get("STAGE")).isEqualTo("test");
+ assertThat(env.get("GEODE_HOME")).isEqualTo("/path/to/geode");
waitForTick(4);
-
env = LoginHandlerInterceptor.getEnvironment();
-
- assertNotNull(env);
- assertEquals(2, env.size());
- assertFalse(env.containsKey("param"));
- assertFalse(env.containsKey("parameter"));
- assertFalse(env.containsKey("HOST"));
- assertFalse(env.containsKey("security-username"));
- assertFalse(env.containsKey("security-password"));
- assertEquals("test", env.get("STAGE"));
- assertEquals("/path/to/gemfire/700", env.get("GEODE_HOME"));
+ assertThat(env).isNotNull();
+ assertThat(env.size()).isEqualTo(2);
+ assertThat(env.containsKey("param")).isFalse();
+ assertThat(env.containsKey("parameter")).isFalse();
+ assertThat(env.containsKey("HOST")).isFalse();
+ assertThat(env.containsKey("security-username")).isFalse();
+ assertThat(env.containsKey("security-password")).isFalse();
+ assertThat(env.get("STAGE")).isEqualTo("test");
+ assertThat(env.get("GEODE_HOME")).isEqualTo("/path/to/geode");
handlerInterceptor.afterCompletion(mockHttpRequestOne, null, null, null);
-
env = LoginHandlerInterceptor.getEnvironment();
-
assertNotNull(env);
assertTrue(env.isEmpty());
}
+ @SuppressWarnings("unused")
public void thread2() throws Exception {
assertTick(0);
Thread.currentThread().setName("HTTP Request Processing Thread 2");
- waitForTick(1);
+ waitForTick(1);
Map<String, String> env = LoginHandlerInterceptor.getEnvironment();
-
- assertNotNull(env);
- assertTrue(env.isEmpty());
- assertTrue(handlerInterceptor.preHandle(mockHttpRequestTwo, null, null));
+ assertThat(env).isNotNull();
+ assertThat(env.isEmpty()).isTrue();
+ assertThat(handlerInterceptor.preHandle(mockHttpRequestTwo, null, null)).isTrue();
env = LoginHandlerInterceptor.getEnvironment();
-
- assertNotNull(env);
- assertEquals(2, env.size());
- assertFalse(env.containsKey("parameter"));
- assertFalse(env.containsKey("param"));
- assertFalse(env.containsKey("STAGE"));
- assertFalse(env.containsKey("security-username"));
- assertFalse(env.containsKey("security-password"));
- assertEquals("localhost", env.get("HOST"));
- assertEquals("/path/to/gemfire/75", env.get("GEODE_HOME"));
+ assertThat(env).isNotNull();
+ assertThat(env.size()).isEqualTo(2);
+ assertThat(env.containsKey("parameter")).isFalse();
+ assertThat(env.containsKey("param")).isFalse();
+ assertThat(env.containsKey("STAGE")).isFalse();
+ assertThat(env.containsKey("security-username")).isFalse();
+ assertThat(env.containsKey("security-password")).isFalse();
+ assertThat(env.get("HOST")).isEqualTo("localhost");
+ assertThat(env.get("GEODE_HOME")).isEqualTo("/path/to/geode/180");
waitForTick(3);
-
handlerInterceptor.afterCompletion(mockHttpRequestTwo, null, null, null);
-
env = LoginHandlerInterceptor.getEnvironment();
-
- assertNotNull(env);
- assertTrue(env.isEmpty());
+ assertThat(env).isNotNull();
+ assertThat(env.isEmpty()).isTrue();
}
@Override
@@ -307,5 +279,4 @@ public class LoginHandlerInterceptorJUnitTest {
handlerInterceptor = null;
}
}
-
}
diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java
index 6db583a..e6dd20b 100644
--- a/geode-web/src/test/java/org/apache/geode/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java
+++ b/geode-web/src/test/java/org/apache/geode/management/internal/web/http/converter/SerializableObjectHttpMessageConverterJUnitTest.java
@@ -14,10 +14,9 @@
*/
package org.apache.geode.management.internal.web.http.converter;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -25,11 +24,6 @@ import java.io.IOException;
import java.io.Serializable;
import java.util.Calendar;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
@@ -45,139 +39,78 @@ import org.apache.geode.internal.util.IOUtils;
* <p/>
*
* @see org.apache.geode.management.internal.web.http.converter.SerializableObjectHttpMessageConverter
- * @see org.jmock.Mockery
- * @see org.junit.Assert
* @see org.junit.Test
* @since GemFire 8.0
*/
public class SerializableObjectHttpMessageConverterJUnitTest {
-
- private Mockery mockContext;
+ private SerializableObjectHttpMessageConverter converter;
@Before
public void setUp() {
- mockContext = new Mockery();
- mockContext.setImposteriser(ClassImposteriser.INSTANCE);
- mockContext.setThreadingPolicy(new Synchroniser());
- }
-
... 186 lines suppressed ...