You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by kl...@apache.org on 2018/04/23 05:46:38 UTC

[geode] branch develop updated (47ae5e7 -> d66fd4f)

This is an automated email from the ASF dual-hosted git repository.

klund pushed a change to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git.


    from 47ae5e7  GEODE-5102: Lucene rolling test with REINDEX (#1818)
     new af5d6ee  GEODE-1279: Rename HARegionQueueSizeRegressionTest
     new 7cc9e8f  GEODE-5020: Move HARegionQueue system properties to SystemPropertyHelper
     new 83dd8fc  GEODE-5058: Delete redundant DUnit tests with JUnit4 prefix
     new 3849147  GEODE-5033: Improve TearDown of DistributedTestRule
     new 34acd5c  GEODE-4876: Remove additional uses of DUnit Host and cleanup
     new f144fb4  GEODE-5060: Delete DistributedDisconnectRule
     new 46b8dde  GEODE-5033: Use DistributedTestRule as non-static Rule
     new 0ac5587  GEODE-1279: Rename BucketCreationCrash RegressionTests
     new b5fc48c  GEODE-1279: Delete useless test Bug51400DUnitTest
     new fcc9436  GEODE-1279: Rename RegisterInterestKeysValuesDistributedTest
     new 2e22ab1  GEODE-1279: Rename DeltaPropagationFailureRegressionTest
     new 130a13d  GEODE-1279: Rename QueueRemovalMessageProcessingDistributedTest
     new d66fd4f  GEODE-5033: Fixup OverridingGetPropertiesDisconnectsAllDistributedTest

The 13 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../geode/internal/cache/InternalRegion.java       |   2 +
 .../geode/internal/cache/ha/HARegionQueue.java     |  67 ++--
 .../geode/internal/lang/SystemPropertyHelper.java  |   4 +
 ...java => BucketCreationCrashRegressionTest.java} |  46 +--
 .../geode/internal/cache/ha/Bug48571DUnitTest.java | 290 ---------------
 .../geode/internal/cache/ha/Bug48879DUnitTest.java | 227 ------------
 ...java => HARegionQueueExpiryRegressionTest.java} |   6 +-
 .../internal/cache/ha/HARegionQueueJUnitTest.java  |   4 +-
 .../cache/ha/HARegionQueueSizeRegressionTest.java  | 245 +++++++++++++
 .../HARegionQueueThreadIdExpiryRegressionTest.java | 198 +++++++++++
 ...BucketCreationCrashCompletesRegressionTest.java | 248 +++++++++++++
 .../cache/partitioned/Bug39356DUnitTest.java       | 233 ------------
 .../cache/partitioned/Bug43684DUnitTest.java       | 359 -------------------
 .../cache/partitioned/Bug47388DUnitTest.java       | 265 --------------
 .../cache/partitioned/Bug51400DUnitTest.java       | 181 ----------
 ...eueRemovalMessageProcessingDistributedTest.java | 269 ++++++++++++++
 .../RegisterInterestKeysValuesDistributedTest.java | 394 +++++++++++++++++++++
 .../internal/cache/tier/Bug40396DUnitTest.java     | 217 ------------
 .../DeltaPropagationFailureRegressionTest.java     | 155 ++++++++
 .../geode/test/dunit/DistributedTestUtils.java     |   3 +-
 .../dunit/cache/internal/JUnit4CacheTestCase.java  |   5 +
 .../CatchingUnexpectedExceptionExampleTest.java    |  14 +-
 .../examples/LocatorPortClusterExampleTest.java    |   8 +-
 .../dunit/internal/JUnit4DistributedTestCase.java  |  62 +---
 .../dunit/rules/AbstractDistributedTestRule.java   |  94 +++++
 .../apache/geode/test/dunit/rules/CacheRule.java   | 105 +++++-
 .../test/dunit/rules/CleanupDUnitVMsRule.java      |  12 +-
 .../geode/test/dunit/rules/ClientCacheRule.java    |   6 +-
 .../dunit/rules/DistributedDisconnectRule.java     | 138 --------
 .../test/dunit/rules/DistributedDiskDirRule.java   |   2 +
 .../dunit/rules/DistributedExternalResource.java   |   2 +-
 .../rules/DistributedRestoreSystemProperties.java  |  37 +-
 .../test/dunit/rules/DistributedTestRule.java      | 172 ++++++++-
 .../DistributedUseJacksonForJsonPathRule.java      |  20 +-
 .../geode/test/dunit/rules/SharedCountersRule.java |  13 +-
 .../test/dunit/rules/SharedErrorCollector.java     |  46 +--
 .../tests/CacheRuleBuilderDistributedTest.java     |   5 +-
 .../rules/tests/CacheRuleDistributedTest.java      |   5 +-
 ...edDisconnectRuleAsClassRuleDistributedTest.java | 172 ---------
 .../DistributedDisconnectRuleDistributedTest.java  | 187 ----------
 ...utedRestoreSystemPropertiesDistributedTest.java |  39 +-
 .../DistributedRestoreSystemPropertiesTest.java    |  56 ---
 .../tests/DistributedTestRuleDistributedTest.java  |   9 +-
 .../tests/SharedCountersRuleDistributedTest.java   |   5 +-
 .../tests/SharedErrorCollectorDistributedTest.java |  12 +-
 ...sicDUnitTest.java => BasicDistributedTest.java} |  76 ++--
 .../tests/GetCurrentVmNumDistributedTest.java      |   6 +-
 ...=> GetDefaultDiskStoreNameDistributedTest.java} |  13 +-
 .../GetPidAndIdAfterBounceDistributedTest.java     |   6 +-
 .../dunit/tests/GetPidAndIdDistributedTest.java    |   6 +-
 ....java => GetTestMethodNameDistributedTest.java} |  12 +-
 .../test/dunit/tests/JUnit4BasicDUnitTest.java     | 243 -------------
 .../JUnit4GetDefaultDiskStoreNameDUnitTest.java    |  67 ----
 .../tests/JUnit4GetTestMethodNameDUnitTest.java    |  53 ---
 ...ridingGetPropertiesDisconnectsAllDUnitTest.java |  60 ----
 .../geode/test/dunit/tests/JUnit4VMDUnitTest.java  | 205 -----------
 ...etPropertiesDisconnectsAllDistributedTest.java} |  30 +-
 .../{VMDUnitTest.java => VMDistributedTest.java}   |  24 +-
 58 files changed, 2135 insertions(+), 3305 deletions(-)
 rename geode-core/src/test/java/org/apache/geode/internal/cache/{BucketCreationRequesterCrashHARegressionTest.java => BucketCreationCrashRegressionTest.java} (88%)
 delete mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48571DUnitTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48879DUnitTest.java
 rename geode-core/src/test/java/org/apache/geode/internal/cache/ha/{ClientSubscriptionExpiryDataLossRegressionTest.java => HARegionQueueExpiryRegressionTest.java} (95%)
 create mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueSizeRegressionTest.java
 create mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueThreadIdExpiryRegressionTest.java
 create mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/BucketCreationCrashCompletesRegressionTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug39356DUnitTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug43684DUnitTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug47388DUnitTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug51400DUnitTest.java
 create mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/QueueRemovalMessageProcessingDistributedTest.java
 create mode 100644 geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/RegisterInterestKeysValuesDistributedTest.java
 delete mode 100755 geode-core/src/test/java/org/apache/geode/internal/cache/tier/Bug40396DUnitTest.java
 create mode 100755 geode-core/src/test/java/org/apache/geode/internal/cache/tier/DeltaPropagationFailureRegressionTest.java
 create mode 100644 geode-core/src/test/java/org/apache/geode/test/dunit/rules/AbstractDistributedTestRule.java
 delete mode 100755 geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedDisconnectRuleAsClassRuleDistributedTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedDisconnectRuleDistributedTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedRestoreSystemPropertiesTest.java
 rename geode-core/src/test/java/org/apache/geode/test/dunit/tests/{BasicDUnitTest.java => BasicDistributedTest.java} (70%)
 rename geode-core/src/test/java/org/apache/geode/test/dunit/tests/{GetDefaultDiskStoreNameDUnitTest.java => GetDefaultDiskStoreNameDistributedTest.java} (83%)
 rename geode-core/src/test/java/org/apache/geode/test/dunit/tests/{GetTestMethodNameDUnitTest.java => GetTestMethodNameDistributedTest.java} (79%)
 delete mode 100644 geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4BasicDUnitTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4GetDefaultDiskStoreNameDUnitTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4GetTestMethodNameDUnitTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4OverridingGetPropertiesDisconnectsAllDUnitTest.java
 delete mode 100644 geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4VMDUnitTest.java
 rename geode-core/src/test/java/org/apache/geode/test/dunit/tests/{OverridingGetPropertiesDisconnectsAllDUnitTest.java => OverridingGetPropertiesDisconnectsAllDistributedTest.java} (69%)
 rename geode-core/src/test/java/org/apache/geode/test/dunit/tests/{VMDUnitTest.java => VMDistributedTest.java} (92%)

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 11/13: GEODE-1279: Rename DeltaPropagationFailureRegressionTest

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit 2e22ab16b409aa70dcca4f09faf908fe33858c2b
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Fri Apr 20 16:13:07 2018 -0700

    GEODE-1279: Rename DeltaPropagationFailureRegressionTest
    
    * Bug40396DUnitTest -> DeltaPropagationFailureRegressionTest
---
 .../internal/cache/tier/Bug40396DUnitTest.java     | 217 ---------------------
 .../DeltaPropagationFailureRegressionTest.java     | 155 +++++++++++++++
 2 files changed, 155 insertions(+), 217 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/tier/Bug40396DUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/Bug40396DUnitTest.java
deleted file mode 100755
index aa01b89..0000000
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/tier/Bug40396DUnitTest.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.internal.cache.tier;
-
-import static org.junit.Assert.*;
-
-import java.util.Properties;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.AttributesFactory;
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.DataPolicy;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionAttributes;
-import org.apache.geode.cache.Scope;
-import org.apache.geode.cache.server.CacheServer;
-import org.apache.geode.distributed.DistributedSystem;
-import org.apache.geode.internal.AvailablePort;
-import org.apache.geode.internal.cache.tier.sockets.DeltaEOFException;
-import org.apache.geode.internal.cache.tier.sockets.FaultyDelta;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.Invoke;
-import org.apache.geode.test.dunit.SerializableRunnable;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.ClientServerTest;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-/**
- * Test delta propagation for faulty delta implementation
- *
- * @since GemFire 6.1
- */
-@Category({DistributedTest.class, ClientServerTest.class})
-public class Bug40396DUnitTest extends JUnit4DistributedTestCase {
-
-  private static Cache cache;
-  private static final String REGION_NAME = "Bug40396DUnitTest_region";
-
-  private static final String END_OF_FILE_EX = "eofe";
-  private static final String ARRAY_INDEX_OUT_BOUND_EX = "aiob";
-
-  private static int counter;
-
-  private VM server;
-  private VM server2;
-
-  private static final int PUT_COUNT = 10;
-
-  public Bug40396DUnitTest() {
-    super();
-  }
-
-  @Override
-  public final void postSetUp() throws Exception {
-    disconnectAllFromDS();
-    final Host host = Host.getHost(0);
-    server = host.getVM(0);
-    server2 = host.getVM(2);
-  }
-
-  /*
-   * create server cache
-   */
-  public static Integer createServerCache() throws Exception {
-    new Bug40396DUnitTest().createCache(new Properties());
-    AttributesFactory factory = new AttributesFactory();
-    factory.setScope(Scope.DISTRIBUTED_ACK);
-    factory.setDataPolicy(DataPolicy.REPLICATE);
-    RegionAttributes attrs = factory.create();
-    Region region = cache.createRegion(REGION_NAME, attrs);
-    region.getAttributesMutator().setCloningEnabled(false);
-    CacheServer server = cache.addCacheServer();
-    addExceptions();
-    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
-    server.setPort(port);
-    // ensures updates to be sent instead of invalidations
-    server.setNotifyBySubscription(true);
-    server.start();
-    return new Integer(server.getPort());
-
-  }
-
-  public static void addExceptions() throws Exception {
-    if (cache != null && !cache.isClosed()) {
-      cache.getLogger()
-          .info("<ExpectedException action=add>" + "java.io.EOFException" + "</ExpectedException>");
-      cache.getLogger().info("<ExpectedException action=add>"
-          + "java.lang.ArrayIndexOutOfBoundsException" + "</ExpectedException>");
-    }
-  }
-
-  public static void removeExceptions() {
-    if (cache != null && !cache.isClosed()) {
-      cache.getLogger().info(
-          "<ExpectedException action=remove>" + "java.io.EOFException" + "</ExpectedException>");
-      cache.getLogger().info("<ExpectedException action=remove>"
-          + "java.lang.ArrayIndexOutOfBoundsException" + "</ExpectedException>");
-    }
-  }
-
-  /*
-   * create cache with properties
-   */
-  private void createCache(Properties props) throws Exception {
-    DistributedSystem ds = getSystem(props);
-    cache = CacheFactory.create(ds);
-    assertNotNull(cache);
-  }
-
-  public static void closeCache() {
-    if (cache != null && !cache.isClosed()) {
-      cache.close();
-      cache.getDistributedSystem().disconnect();
-    }
-  }
-
-  public static Exception putDelta(String regName, String type) {
-    Region reg = cache.getRegion(Region.SEPARATOR + regName);
-    try {
-      if (type.equals(END_OF_FILE_EX)) {
-        DeltaEOFException obj = new DeltaEOFException();
-        for (int i = 0; i < PUT_COUNT; i++) {
-          obj.setIntVal(i);
-          obj.setBigObj(new byte[] {(byte) (i + 3), (byte) (i + 3)});
-          reg.put("key", obj);
-        }
-      } else if (type.equals(ARRAY_INDEX_OUT_BOUND_EX)) {
-        FaultyDelta obj = new FaultyDelta();
-        for (int i = 0; i < PUT_COUNT; i++) {
-          obj.setIntVal(i);
-          obj.setBigObj(new byte[] {(byte) (i + 3), (byte) (i + 3)});
-          reg.put("key", obj);
-        }
-      }
-    } catch (Exception ex) {
-      return ex;
-    }
-    // this make tests fail
-    return new Exception();
-  }
-
-  /**
-   * This test does the following 1)send faulty implementation (Reading more in fromDelta then what
-   * sent by toDelta) of delta raises EOF exception<br>
-   */
-  @Test
-  public void testForFaultyDeltaImplementationForEOFEX() {
-    boolean matched = false;
-    ((Integer) server.invoke(() -> Bug40396DUnitTest.createServerCache())).intValue();
-    ((Integer) server2.invoke(() -> Bug40396DUnitTest.createServerCache())).intValue();
-    Exception xp =
-        (Exception) server.invoke(() -> Bug40396DUnitTest.putDelta(REGION_NAME, END_OF_FILE_EX));
-    StackTraceElement[] st = xp.getCause().getStackTrace();
-    matched = getMatched(st);
-
-    assertTrue("pattern not found", matched);
-  }
-
-  private boolean getMatched(StackTraceElement[] ste) {
-    boolean mched = false;
-    for (int i = 0; i < ste.length; i++) {
-      if (mched)
-        break;
-      if (ste[i].toString().indexOf("fromDelta") != -1)
-        mched = true;
-    }
-    return mched;
-  }
-
-  /**
-   * This test does the following 1)send faulty implementation when reading incorrect order from
-   * toDelta, raises delta raises array index out of bound exception<br>
-   */
-  @Test
-  public void testForFaultyDeltaImplementationForAIOBEX() {
-    boolean matched = false;
-    ((Integer) server.invoke(() -> Bug40396DUnitTest.createServerCache())).intValue();
-    ((Integer) server2.invoke(() -> Bug40396DUnitTest.createServerCache())).intValue();
-    Exception xp = (Exception) server
-        .invoke(() -> Bug40396DUnitTest.putDelta(REGION_NAME, ARRAY_INDEX_OUT_BOUND_EX));
-
-    StackTraceElement[] st = xp.getStackTrace();
-    matched = getMatched(st);
-
-    assertTrue("pattern not found", matched);
-  }
-
-  @Override
-  public final void preTearDown() throws Exception {
-    // then close the servers
-    server.invoke(() -> Bug40396DUnitTest.removeExceptions());
-    server.invoke(() -> Bug40396DUnitTest.closeCache());
-    server2.invoke(() -> Bug40396DUnitTest.closeCache());
-    cache = null;
-    Invoke.invokeInEveryVM(new SerializableRunnable() {
-      public void run() {
-        cache = null;
-      }
-    });
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/tier/DeltaPropagationFailureRegressionTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/DeltaPropagationFailureRegressionTest.java
new file mode 100755
index 0000000..50e2cab
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/tier/DeltaPropagationFailureRegressionTest.java
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.internal.cache.tier;
+
+import static org.apache.geode.internal.cache.tier.DeltaPropagationFailureRegressionTest.DeltaFailure.FROM_DELTA;
+import static org.apache.geode.internal.cache.tier.DeltaPropagationFailureRegressionTest.DeltaFailure.TO_DELTA;
+import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
+import static org.apache.geode.test.dunit.VM.getVM;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowable;
+
+import java.io.EOFException;
+import java.io.Serializable;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.DeltaSerializationException;
+import org.apache.geode.cache.AttributesFactory;
+import org.apache.geode.cache.DataPolicy;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.Scope;
+import org.apache.geode.cache.server.CacheServer;
+import org.apache.geode.internal.cache.tier.sockets.DeltaEOFException;
+import org.apache.geode.internal.cache.tier.sockets.FaultyDelta;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.rules.CacheRule;
+import org.apache.geode.test.dunit.rules.DistributedTestRule;
+import org.apache.geode.test.junit.categories.ClientServerTest;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
+
+/**
+ * Test delta propagation for faulty delta implementation
+ *
+ * <p>
+ * TRAC #40396: Need better error messages (and unit tests) when users code delta propagation
+ * methods incorrectly
+ *
+ * @since GemFire 6.1
+ */
+@Category({DistributedTest.class, ClientServerTest.class})
+@SuppressWarnings("serial")
+public class DeltaPropagationFailureRegressionTest implements Serializable {
+
+  private static final int PUT_COUNT = 10;
+
+  private String regionName;
+
+  private VM server1;
+  private VM server2;
+
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
+
+  @Rule
+  public CacheRule cacheRule = new CacheRule();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @Before
+  public void setUp() throws Exception {
+    server1 = getVM(0);
+    server2 = getVM(2);
+
+    regionName = getClass().getSimpleName() + "_" + testName.getMethodName();
+
+    server1.invoke(() -> createServerCache());
+    server2.invoke(() -> createServerCache());
+  }
+
+  /**
+   * Verifies error handling when trying to read more in fromDelta then what sent by toDelta which
+   * throws EOFException
+   */
+  @Test
+  public void fromDeltaThrowsDeltaSerializationExceptionWithCauseEofException() {
+    addIgnoredException(EOFException.class);
+
+    Throwable thrown = server1.invoke(() -> catchThrowable(() -> putDelta(FROM_DELTA)));
+
+    assertThat(thrown).isInstanceOf(DeltaSerializationException.class)
+        .hasMessageContaining("deserializing delta bytes").hasCauseInstanceOf(EOFException.class);
+  }
+
+  /**
+   * Verifies error handling when reading incorrect order from toDelta which throws
+   * ArrayIndexOutOfBoundsException
+   */
+  @Test
+  public void toDeltaThrowsArrayIndexOutOfBoundsException() {
+    addIgnoredException(ArrayIndexOutOfBoundsException.class);
+
+    Throwable thrown = server1.invoke(() -> catchThrowable(() -> putDelta(TO_DELTA)));
+
+    assertThat(thrown).isInstanceOf(ArrayIndexOutOfBoundsException.class);
+  }
+
+  private int createServerCache() throws Exception {
+    cacheRule.createCache();
+
+    AttributesFactory af = new AttributesFactory();
+    af.setCloningEnabled(false);
+    af.setDataPolicy(DataPolicy.REPLICATE);
+    af.setScope(Scope.DISTRIBUTED_ACK);
+
+    cacheRule.getCache().createRegion(regionName, af.create());
+
+    CacheServer server = cacheRule.getCache().addCacheServer();
+    server.setPort(0);
+    // ensures updates to be sent instead of invalidates
+    server.setNotifyBySubscription(true);
+    server.start();
+    return server.getPort();
+  }
+
+  private void putDelta(DeltaFailure deltaFailure) {
+    Region region = cacheRule.getCache().getRegion(regionName);
+    deltaFailure.putInRegion(region);
+  }
+
+  enum DeltaFailure {
+    FROM_DELTA(new DeltaEOFException()), TO_DELTA(new FaultyDelta());
+
+    private final FaultyDelta value;
+
+    DeltaFailure(FaultyDelta value) {
+      this.value = value;
+    }
+
+    void putInRegion(Region region) {
+      for (int i = 0; i < PUT_COUNT; i++) {
+        value.setIntVal(i);
+        value.setBigObj(new byte[] {(byte) (i + 3), (byte) (i + 3)});
+        region.put("key", value);
+      }
+    }
+
+  }
+}

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 08/13: GEODE-1279: Rename BucketCreationCrash RegressionTests

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit 0ac55878e52a3abe83617550950debb2b2485742
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Thu Apr 12 12:59:21 2018 -0700

    GEODE-1279: Rename BucketCreationCrash RegressionTests
    
    * BucketCreationRequesterCrashHARegressionTest ->
      BucketCreationCrashNoHangRegressionTest
    * Bug39356DUnitTest -> BucketCreationCrashCompletesRegressionTest
---
 ...java => BucketCreationCrashRegressionTest.java} |  46 ++--
 ...BucketCreationCrashCompletesRegressionTest.java | 248 +++++++++++++++++++++
 .../cache/partitioned/Bug39356DUnitTest.java       | 233 -------------------
 3 files changed, 273 insertions(+), 254 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/BucketCreationRequesterCrashHARegressionTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/BucketCreationCrashRegressionTest.java
similarity index 88%
rename from geode-core/src/test/java/org/apache/geode/internal/cache/BucketCreationRequesterCrashHARegressionTest.java
rename to geode-core/src/test/java/org/apache/geode/internal/cache/BucketCreationCrashRegressionTest.java
index c0e124f..41c5617 100644
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/BucketCreationRequesterCrashHARegressionTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/BucketCreationCrashRegressionTest.java
@@ -19,14 +19,16 @@ import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_NETWOR
 import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
 import static org.apache.geode.distributed.ConfigurationProperties.USE_CLUSTER_CONFIGURATION;
 import static org.apache.geode.test.dunit.DistributedTestUtils.crashDistributedSystem;
-import static org.apache.geode.test.dunit.Host.getHost;
 import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
 import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.apache.geode.test.dunit.VM.getHostName;
+import static org.apache.geode.test.dunit.VM.getVM;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
 import java.io.File;
 import java.io.IOException;
+import java.io.Serializable;
 import java.net.InetAddress;
 import java.util.Properties;
 import java.util.Set;
@@ -50,26 +52,25 @@ import org.apache.geode.distributed.internal.DistributionMessage;
 import org.apache.geode.distributed.internal.DistributionMessageObserver;
 import org.apache.geode.internal.cache.partitioned.ManageBucketMessage;
 import org.apache.geode.internal.cache.partitioned.ManageBucketMessage.ManageBucketReplyMessage;
-import org.apache.geode.test.dunit.NetworkUtils;
 import org.apache.geode.test.dunit.RMIException;
 import org.apache.geode.test.dunit.SerializableRunnableIF;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.cache.CacheTestCase;
+import org.apache.geode.test.dunit.rules.CacheRule;
+import org.apache.geode.test.dunit.rules.DistributedTestRule;
 import org.apache.geode.test.dunit.rules.SharedErrorCollector;
 import org.apache.geode.test.junit.categories.DistributedTest;
 import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
 import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
 
 /**
- * Test to make sure that we can handle a crash of the member directing bucket creation.
- *
- * BucketCreationRequesterCrashHARegressionTest
+ * Verifies that new bucket does not hang after requester crashes.
  *
  * <p>
  * TRAC #41733: Hang in BucketAdvisor.waitForPrimaryMember
  */
 @Category(DistributedTest.class)
-public class BucketCreationRequesterCrashHARegressionTest extends CacheTestCase {
+@SuppressWarnings("serial")
+public class BucketCreationCrashRegressionTest implements Serializable {
 
   private String uniqueName;
   private String hostName;
@@ -81,6 +82,12 @@ public class BucketCreationRequesterCrashHARegressionTest extends CacheTestCase
   private VM locator;
 
   @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
+
+  @Rule
+  public CacheRule cacheRule = new CacheRule();
+
+  @Rule
   public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
 
   @Rule
@@ -91,12 +98,12 @@ public class BucketCreationRequesterCrashHARegressionTest extends CacheTestCase
 
   @Before
   public void setUp() throws Exception {
-    server1 = getHost(0).getVM(0);
-    server2 = getHost(0).getVM(1);
-    locator = getHost(0).getVM(2);
+    server1 = getVM(0);
+    server2 = getVM(1);
+    locator = getVM(2);
 
     uniqueName = getClass().getSimpleName() + "_" + testName.getMethodName();
-    hostName = NetworkUtils.getServerHostName(server1.getHost());
+    hostName = getHostName();
     locatorLog = new File(temporaryFolder.newFolder(uniqueName), "locator.log");
 
     locatorPort = locator.invoke(() -> startLocator());
@@ -106,9 +113,8 @@ public class BucketCreationRequesterCrashHARegressionTest extends CacheTestCase
     server2.invoke(() -> createServerCache());
 
     // cluster should ONLY have 3 members (our 2 servers and 1 locator)
-    assertThat(server1.invoke(
-        () -> getCache().getDistributionManager().getDistributionManagerIdsIncludingAdmin()))
-            .hasSize(3);
+    assertThat(server1.invoke(() -> cacheRule.getCache().getDistributionManager()
+        .getDistributionManagerIdsIncludingAdmin())).hasSize(3);
 
     addIgnoredException(ForcedDisconnectException.class);
   }
@@ -119,8 +125,6 @@ public class BucketCreationRequesterCrashHARegressionTest extends CacheTestCase
     invokeInEveryVM(() -> {
       DistributionMessageObserver.setInstance(null);
     });
-
-    disconnectAllFromDS();
   }
 
   /**
@@ -199,7 +203,7 @@ public class BucketCreationRequesterCrashHARegressionTest extends CacheTestCase
   }
 
   private void createServerCache() {
-    getCache(createServerConfig());
+    cacheRule.createCache(createServerConfig());
   }
 
   private void createPartitionedRegion() {
@@ -210,11 +214,11 @@ public class BucketCreationRequesterCrashHARegressionTest extends CacheTestCase
     af.setDataPolicy(DataPolicy.PARTITION);
     af.setPartitionAttributes(paf.create());
 
-    getCache().createRegion(uniqueName, af.create());
+    cacheRule.getCache().createRegion(uniqueName, af.create());
   }
 
   private void putData(final int startKey, final int endKey, final String value) {
-    Region<Integer, String> region = getCache().getRegion(uniqueName);
+    Region<Integer, String> region = cacheRule.getCache().getRegion(uniqueName);
 
     for (int i = startKey; i < endKey; i++) {
       region.put(i, value);
@@ -222,7 +226,7 @@ public class BucketCreationRequesterCrashHARegressionTest extends CacheTestCase
   }
 
   private Set<Integer> getBucketList() {
-    PartitionedRegion region = (PartitionedRegion) getCache().getRegion(uniqueName);
+    PartitionedRegion region = (PartitionedRegion) cacheRule.getCache().getRegion(uniqueName);
     return new TreeSet<>(region.getDataStore().getAllLocalBucketIds());
   }
 
@@ -233,7 +237,7 @@ public class BucketCreationRequesterCrashHARegressionTest extends CacheTestCase
   }
 
   private void crashServer() {
-    crashDistributedSystem(getSystem());
+    crashDistributedSystem(cacheRule.getSystem());
   }
 
   private class RunnableBeforeProcessMessageObserver extends DistributionMessageObserver {
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/BucketCreationCrashCompletesRegressionTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/BucketCreationCrashCompletesRegressionTest.java
new file mode 100644
index 0000000..8415408
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/BucketCreationCrashCompletesRegressionTest.java
@@ -0,0 +1,248 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.internal.cache.partitioned;
+
+import static java.util.concurrent.TimeUnit.MINUTES;
+import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_NETWORK_PARTITION_DETECTION;
+import static org.apache.geode.test.dunit.DistributedTestUtils.crashDistributedSystem;
+import static org.apache.geode.test.dunit.DistributedTestUtils.getAllDistributedSystemProperties;
+import static org.apache.geode.test.dunit.VM.getVM;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.awaitility.Awaitility.await;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.CancelException;
+import org.apache.geode.cache.AttributesFactory;
+import org.apache.geode.cache.DataPolicy;
+import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.distributed.internal.ClusterDistributionManager;
+import org.apache.geode.distributed.internal.DistributionMessage;
+import org.apache.geode.distributed.internal.DistributionMessageObserver;
+import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
+import org.apache.geode.internal.cache.ForceReattemptException;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.cache.PartitionedRegion;
+import org.apache.geode.internal.cache.PartitionedRegionDataStore;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.rules.CacheRule;
+import org.apache.geode.test.dunit.rules.DistributedTestRule;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
+
+/**
+ * Verifies that bucket creation completes even after requester crashes.
+ *
+ * <p>
+ * TRAC #39356: Missing PR buckets with HA
+ */
+@Category(DistributedTest.class)
+@SuppressWarnings("serial")
+public class BucketCreationCrashCompletesRegressionTest implements Serializable {
+
+  private String regionName;
+
+  private VM vm0;
+  private VM vm1;
+  private VM vm2;
+
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
+
+  @Rule
+  public CacheRule cacheRule = new CacheRule();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @Before
+  public void setUp() {
+    vm0 = getVM(0);
+    vm1 = getVM(1);
+    vm2 = getVM(2);
+
+    regionName = getClass().getSimpleName() + "_" + testName.getMethodName();
+
+    vm0.invoke(() -> createCache(getDistributedSystemProperties()));
+    vm1.invoke(() -> createCache(getDistributedSystemProperties()));
+    vm2.invoke(() -> createCache(getDistributedSystemProperties()));
+  }
+
+  /**
+   * This tests the case where the VM forcing other VMs to create a bucket crashes while creating
+   * the bucket.
+   */
+  @Test
+  public void testCrashWhileCreatingABucket() {
+    vm1.invoke(() -> createPartitionedRegionWithObserver());
+    vm2.invoke(() -> createPartitionedRegionWithObserver());
+
+    vm0.invoke(() -> createAccessorAndCrash());
+
+    vm1.invoke(() -> verifyBucketsAfterAccessorCrashes());
+    vm2.invoke(() -> verifyBucketsAfterAccessorCrashes());
+  }
+
+  /**
+   * A test to make sure that we cannot move a bucket to a member which already hosts the bucket,
+   * thereby reducing our redundancy.
+   */
+  @Test
+  public void testMoveBucketToHostThatHasTheBucketAlready() {
+    vm0.invoke(() -> createPartitionedRegion());
+    vm1.invoke(() -> createPartitionedRegion());
+
+    // Create a bucket
+    vm0.invoke(() -> {
+      createBucket();
+    });
+
+    InternalDistributedMember member1 = vm1.invoke(() -> getCache().getMyId());
+
+    // Move the bucket
+    vm0.invoke(() -> {
+      verifyCannotMoveBucketToExistingHost(member1);
+    });
+  }
+
+  private void createPartitionedRegionWithObserver() {
+    DistributionMessageObserver.setInstance(new MyRegionObserver());
+
+    PartitionAttributesFactory paf = new PartitionAttributesFactory();
+    paf.setRedundantCopies(1);
+    paf.setRecoveryDelay(0);
+
+    AttributesFactory af = new AttributesFactory();
+    af.setDataPolicy(DataPolicy.PARTITION);
+    af.setPartitionAttributes(paf.create());
+
+    getCache().createRegion(regionName, af.create());
+  }
+
+  private void createAccessorAndCrash() {
+    PartitionAttributesFactory<String, String> paf = new PartitionAttributesFactory<>();
+    paf.setRedundantCopies(1);
+    paf.setLocalMaxMemory(0);
+
+    AttributesFactory<String, String> af = new AttributesFactory<>();
+    af.setDataPolicy(DataPolicy.PARTITION);
+    af.setPartitionAttributes(paf.create());
+
+    Region<String, String> region = getCache().createRegion(regionName, af.create());
+
+    // trigger the creation of a bucket, which should trigger the destruction of this VM.
+    assertThatThrownBy(() -> region.put("ping", "pong")).isInstanceOf(CancelException.class);
+  }
+
+  private boolean hasBucketOwners(PartitionedRegion partitionedRegion, int bucketId) {
+    try {
+      return partitionedRegion.getBucketOwnersForValidation(bucketId) != null;
+    } catch (ForceReattemptException e) {
+      return false;
+    }
+  }
+
+  private void verifyBucketsAfterAccessorCrashes() throws ForceReattemptException {
+    PartitionedRegion partitionedRegion = (PartitionedRegion) getCache().getRegion(regionName);
+    for (int i = 0; i < partitionedRegion.getAttributes().getPartitionAttributes()
+        .getTotalNumBuckets(); i++) {
+      int bucketId = i;
+
+      await().atMost(2, MINUTES).until(() -> {
+        hasBucketOwners(partitionedRegion, bucketId);
+      });
+
+      List owners = partitionedRegion.getBucketOwnersForValidation(bucketId);
+      assertThat(owners).isNotNull();
+      if (owners.isEmpty()) {
+        continue;
+      }
+      assertThat(owners).hasSize(2);
+    }
+  }
+
+  private void createPartitionedRegion() {
+    PartitionAttributesFactory paf = new PartitionAttributesFactory();
+    paf.setRedundantCopies(1);
+    paf.setRecoveryDelay(-1);
+    paf.setStartupRecoveryDelay(-1);
+
+    AttributesFactory af = new AttributesFactory();
+    af.setPartitionAttributes(paf.create());
+
+    getCache().createRegion(regionName, af.create());
+  }
+
+  private void createBucket() {
+    Region<Integer, String> region = getCache().getRegion(regionName);
+    region.put(0, "A");
+  }
+
+  private void verifyCannotMoveBucketToExistingHost(InternalDistributedMember member1) {
+    PartitionedRegion partitionedRegion = (PartitionedRegion) getCache().getRegion(regionName);
+    Set<InternalDistributedMember> bucketOwners =
+        partitionedRegion.getRegionAdvisor().getBucketOwners(0);
+
+    assertThat(bucketOwners).hasSize(2);
+
+    PartitionedRegionDataStore dataStore = partitionedRegion.getDataStore();
+
+    assertThat(dataStore.isManagingBucket(0)).isTrue();
+    // try to move the bucket from the other member to this one. This should
+    // fail because we already have the bucket
+    assertThat(dataStore.moveBucket(0, member1, true)).isFalse();
+    assertThat(partitionedRegion.getRegionAdvisor().getBucketOwners(0)).isEqualTo(bucketOwners);
+  }
+
+  private void crashServer() {
+    crashDistributedSystem(cacheRule.getSystem());
+  }
+
+  private InternalCache getCache() {
+    return cacheRule.getCache();
+  }
+
+  private void createCache(Properties config) {
+    cacheRule.createCache(config);
+  }
+
+  public Properties getDistributedSystemProperties() {
+    Properties config = new Properties();
+    config.put(ENABLE_NETWORK_PARTITION_DETECTION, "false");
+    return getAllDistributedSystemProperties(config);
+  }
+
+  private class MyRegionObserver extends DistributionMessageObserver implements Serializable {
+
+    @Override
+    public void beforeProcessMessage(ClusterDistributionManager dm, DistributionMessage message) {
+      if (message instanceof ManageBucketMessage) {
+        vm0.invoke(() -> {
+          crashServer();
+        });
+      }
+    }
+  }
+}
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug39356DUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug39356DUnitTest.java
deleted file mode 100644
index d6b9ee8..0000000
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug39356DUnitTest.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.internal.cache.partitioned;
-
-import static org.junit.Assert.*;
-
-import java.io.Serializable;
-import java.util.*;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.CancelException;
-import org.apache.geode.LogWriter;
-import org.apache.geode.cache.AttributesFactory;
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.DataPolicy;
-import org.apache.geode.cache.PartitionAttributes;
-import org.apache.geode.cache.PartitionAttributesFactory;
-import org.apache.geode.cache.Region;
-import org.apache.geode.distributed.*;
-import org.apache.geode.distributed.internal.ClusterDistributionManager;
-import org.apache.geode.distributed.internal.DistributionMessage;
-import org.apache.geode.distributed.internal.DistributionMessageObserver;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
-import org.apache.geode.internal.cache.ForceReattemptException;
-import org.apache.geode.internal.cache.PartitionedRegion;
-import org.apache.geode.internal.cache.PartitionedRegionDataStore;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.SerializableRunnable;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-@Category(DistributedTest.class)
-public class Bug39356DUnitTest extends JUnit4CacheTestCase {
-
-  protected static final String REGION_NAME = "myregion";
-
-  @Override
-  public Properties getDistributedSystemProperties() {
-    Properties result = super.getDistributedSystemProperties();
-    result.put(ConfigurationProperties.ENABLE_NETWORK_PARTITION_DETECTION, "false");
-    return result;
-  }
-
-  /**
-   * This tests the case where the VM forcing other VMs to create a bucket crashes while creating
-   * the bucket.
-   */
-  @Test
-  public void testCrashWhileCreatingABucket() {
-    Host host = Host.getHost(0);
-    final VM vm0 = host.getVM(0);
-    final VM vm1 = host.getVM(1);
-    final VM vm2 = host.getVM(2);
-
-    SerializableRunnable createParReg = new SerializableRunnable("Create parReg") {
-      public void run() {
-        DistributionMessageObserver.setInstance(new MyRegionObserver(vm0));
-        Cache cache = getCache();
-        AttributesFactory af = new AttributesFactory();
-        PartitionAttributesFactory pf = new PartitionAttributesFactory();
-        pf.setRedundantCopies(1);
-        pf.setRecoveryDelay(0);
-        af.setDataPolicy(DataPolicy.PARTITION);
-        af.setPartitionAttributes(pf.create());
-        cache.createRegion(REGION_NAME, af.create());
-      }
-    };
-    vm1.invoke(createParReg);
-    vm2.invoke(createParReg);
-
-    SerializableRunnable createParRegAccessor = new SerializableRunnable("Create parReg") {
-      public void run() {
-        Cache cache = getCache();
-        AttributesFactory af = new AttributesFactory();
-        PartitionAttributesFactory pf = new PartitionAttributesFactory();
-        pf.setRedundantCopies(1);
-        pf.setLocalMaxMemory(0);
-        af.setDataPolicy(DataPolicy.PARTITION);
-        af.setPartitionAttributes(pf.create());
-        Region r = cache.createRegion(REGION_NAME, af.create());
-
-        // trigger the creation of a bucket, which should trigger the destruction of this VM.
-        try {
-          r.put("ping", "pong");
-          fail("Should have gotten a CancelException");
-        } catch (CancelException e) {
-          // this is ok, we expect our observer to close this cache.
-        }
-      }
-    };
-
-    vm0.invoke(createParRegAccessor);
-
-    SerializableRunnable verifyBuckets = new SerializableRunnable("Verify buckets") {
-
-      public void run() {
-        LogWriter log = org.apache.geode.test.dunit.LogWriterUtils.getLogWriter();
-        Cache cache = getCache();
-        PartitionedRegion r = (PartitionedRegion) cache.getRegion(REGION_NAME);
-        for (int i = 0; i < r.getAttributes().getPartitionAttributes().getTotalNumBuckets(); i++) {
-          List owners = null;
-          while (owners == null) {
-            try {
-              owners = r.getBucketOwnersForValidation(i);
-            } catch (ForceReattemptException e) {
-              log.info(
-                  Bug39356DUnitTest.class + " verify buckets Caught a ForceReattemptException");
-              Wait.pause(1000);
-            }
-          }
-          if (owners.isEmpty()) {
-            log.info("skipping bucket " + i + " because it has no data");
-            continue;
-          }
-          assertEquals("Expecting bucket " + i + " to have two copies", 2, owners.size());
-          log.info("bucket " + i + " had two copies");
-        }
-      }
-    };
-    vm1.invoke(verifyBuckets);
-    vm2.invoke(verifyBuckets);
-  }
-
-  protected class MyRegionObserver extends DistributionMessageObserver implements Serializable {
-    private final VM vm0;
-
-    MyRegionObserver(VM vm0) {
-      this.vm0 = vm0;
-    }
-
-
-    public void afterProcessMessage(ClusterDistributionManager dm, DistributionMessage message) {}
-
-
-    public void beforeProcessMessage(ClusterDistributionManager dm, DistributionMessage message) {
-      if (message instanceof ManageBucketMessage) {
-        vm0.invoke(new SerializableRunnable("Disconnect VM 0") {
-          public void run() {
-            disconnectFromDS();
-            try {
-              Thread.sleep(10000);
-            } catch (InterruptedException e) {
-              fail("interrupted");
-            }
-          }
-        });
-      }
-    }
-
-  }
-
-  /**
-   * A test to make sure that we cannot move a bucket to a member which already hosts the bucket,
-   * thereby reducing our redundancy.
-   */
-  @Test
-  public void testMoveBucketToHostThatHasTheBucketAlready() {
-    Host host = Host.getHost(0);
-    VM vm0 = host.getVM(0);
-    VM vm1 = host.getVM(1);
-
-    SerializableRunnable createPrRegion = new SerializableRunnable("createRegion") {
-      public void run() {
-        Cache cache = getCache();
-        AttributesFactory attr = new AttributesFactory();
-        PartitionAttributesFactory paf = new PartitionAttributesFactory();
-        paf.setRedundantCopies(1);
-        paf.setRecoveryDelay(-1);
-        paf.setStartupRecoveryDelay(-1);
-        PartitionAttributes prAttr = paf.create();
-        attr.setPartitionAttributes(prAttr);
-        cache.createRegion("region1", attr.create());
-      }
-    };
-
-    vm0.invoke(createPrRegion);
-    vm1.invoke(createPrRegion);
-
-    // Create a bucket
-    vm0.invoke(new SerializableRunnable("createSomeBuckets") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion("region1");
-        region.put(Integer.valueOf(0), "A");
-      }
-    });
-
-    final InternalDistributedMember vm1MemberId =
-        (InternalDistributedMember) vm1.invoke(new SerializableCallable() {
-
-          public Object call() throws Exception {
-            return InternalDistributedSystem.getAnyInstance().getDistributedMember();
-          }
-        });
-
-
-    // Move the bucket
-    vm0.invoke(new SerializableRunnable("moveBucket") {
-
-      public void run() {
-        Cache cache = getCache();
-        PartitionedRegion region = (PartitionedRegion) cache.getRegion("region1");
-        Set<InternalDistributedMember> owners = region.getRegionAdvisor().getBucketOwners(0);
-        assertEquals(2, owners.size());
-        PartitionedRegionDataStore ds = region.getDataStore();
-        assertTrue(ds.isManagingBucket(0));
-        // try to move the bucket from the other member to this one. This should
-        // fail because we already have the bucket
-        assertFalse(ds.moveBucket(0, vm1MemberId, true));
-        assertEquals(owners, region.getRegionAdvisor().getBucketOwners(0));
-      }
-    });
-  }
-}

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 06/13: GEODE-5060: Delete DistributedDisconnectRule

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit f144fb40c1b0aa62f2b6f884fba4bd140f595f68
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Thu Apr 12 12:54:33 2018 -0700

    GEODE-5060: Delete DistributedDisconnectRule
    
    DistributedTestRule.TearDown makes DistributedDisconnectRule redundant.
---
 .../CatchingUnexpectedExceptionExampleTest.java    |  14 +-
 .../examples/LocatorPortClusterExampleTest.java    |   8 +-
 .../dunit/rules/DistributedDisconnectRule.java     | 138 ---------------
 ...edDisconnectRuleAsClassRuleDistributedTest.java | 172 -------------------
 .../DistributedDisconnectRuleDistributedTest.java  | 187 ---------------------
 5 files changed, 5 insertions(+), 514 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/examples/CatchingUnexpectedExceptionExampleTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/examples/CatchingUnexpectedExceptionExampleTest.java
index e170dab..fbcab50 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/examples/CatchingUnexpectedExceptionExampleTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/examples/CatchingUnexpectedExceptionExampleTest.java
@@ -20,7 +20,6 @@ import static org.assertj.core.api.Assertions.assertThat;
 
 import java.io.Serializable;
 
-import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -32,7 +31,6 @@ import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.RegionFactory;
 import org.apache.geode.internal.cache.LocalRegion;
 import org.apache.geode.test.dunit.SerializableRunnable;
-import org.apache.geode.test.dunit.rules.DistributedDisconnectRule;
 import org.apache.geode.test.dunit.rules.DistributedTestRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
@@ -40,18 +38,14 @@ import org.apache.geode.test.junit.categories.DistributedTest;
 @SuppressWarnings("serial")
 public class CatchingUnexpectedExceptionExampleTest implements Serializable {
 
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
-
   @Rule
-  public DistributedDisconnectRule disconnectRule =
-      new DistributedDisconnectRule.Builder().disconnectAfter(true).build();
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
 
   /**
    * Don't do this! Catch Exception and invoke fail => anti-pattern
    */
   @Test
-  public void createRegion_withTryCatch_dontDoThis() throws Exception {
+  public void createRegion_withTryCatch_DO_NOT_DO_THIS() throws Exception {
     getVM(0).invoke(new SerializableRunnable("Create Region") {
       @Override
       public void run() {
@@ -71,7 +65,7 @@ public class CatchingUnexpectedExceptionExampleTest implements Serializable {
    * Use "throws Exception" is better!
    */
   @Test
-  public void createRegion_withThrowsException_thisIsBetter() throws Exception {
+  public void createRegion_withThrowsException_THIS_IS_BETTER() throws Exception {
     getVM(0).invoke(new SerializableRunnable("Create Region") {
       @Override
       public void run() throws Exception {
@@ -87,7 +81,7 @@ public class CatchingUnexpectedExceptionExampleTest implements Serializable {
    * Use lambda without having to specify run() with throws Exception -- best!
    */
   @Test
-  public void createRegion_withLambda_thisIsBest() throws Exception {
+  public void createRegion_withLambda_THIS_IS_BEST() throws Exception {
     getVM(0).invoke("Create Region", () -> {
       Cache cache = new CacheFactory().create();
       RegionFactory regionFactory = cache.createRegionFactory(new AttributesFactory().create());
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/examples/LocatorPortClusterExampleTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/examples/LocatorPortClusterExampleTest.java
index e391357..a448bf1 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/examples/LocatorPortClusterExampleTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/examples/LocatorPortClusterExampleTest.java
@@ -26,7 +26,6 @@ import java.util.Properties;
 
 import org.junit.After;
 import org.junit.Before;
-import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -34,7 +33,6 @@ import org.junit.experimental.categories.Category;
 import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.internal.cache.InternalCache;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.rules.DistributedDisconnectRule;
 import org.apache.geode.test.dunit.rules.DistributedTestRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
@@ -42,12 +40,8 @@ import org.apache.geode.test.junit.categories.DistributedTest;
 @SuppressWarnings("serial")
 public class LocatorPortClusterExampleTest implements Serializable {
 
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
-
   @Rule
-  public DistributedDisconnectRule disconnectRule =
-      new DistributedDisconnectRule.Builder().disconnectAfter(true).build();
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
 
   private static InternalCache cache;
 
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
deleted file mode 100755
index 41f7fc9..0000000
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.test.dunit.rules;
-
-import static java.util.concurrent.TimeUnit.MINUTES;
-
-import com.google.common.base.Stopwatch;
-
-import org.apache.geode.admin.internal.AdminDistributedSystemImpl;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.test.dunit.SerializableRunnable;
-
-/**
- * JUnit Rule that disconnects DistributedSystem in all VMs.
- *
- * <p>
- * DistributedDisconnectRule can be used in DistributedTests to disconnect all VMs before or after
- * each test:
- *
- * <pre>
- * {@literal @}Rule
- * public DistributedDisconnectRule distributedDisconnectRule = new DistributedDisconnectRule();
- *
- * {@literal @}Test
- * public void createCacheInEveryDUnitVM() throws Exception {
- *   cache = (InternalCache) new CacheFactory().create();
- *   assertThat(cache.isClosed()).isFalse();
- *   assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
- *
- *   for (VM vm: Host.getHost(0).getAllVMs()) {
- *     vm.invoke(() -> {
- *       cache = (InternalCache) new CacheFactory().create();
- *       assertThat(cache.isClosed()).isFalse();
- *       assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
- *     });
- *   }
- * }
- * </pre>
- */
-public class DistributedDisconnectRule extends DistributedExternalResource {
-
-  private final boolean disconnectBefore;
-  private final boolean disconnectAfter;
-
-  public static Builder builder() {
-    return new Builder();
-  }
-
-  public DistributedDisconnectRule(final Builder builder) {
-    this(new RemoteInvoker(), builder);
-  }
-
-  public DistributedDisconnectRule(final RemoteInvoker invoker, final Builder builder) {
-    super(invoker);
-    this.disconnectBefore = builder.disconnectBefore;
-    this.disconnectAfter = builder.disconnectAfter;
-  }
-
-  @Override
-  protected void before() throws Throwable {
-    if (this.disconnectBefore) {
-      invoker().invokeInEveryVMAndController(serializableRunnable());
-    }
-  }
-
-  @Override
-  protected void after() {
-    if (this.disconnectAfter) {
-      invoker().invokeInEveryVMAndController(serializableRunnable());
-    }
-  }
-
-  private static SerializableRunnable serializableRunnable() {
-    return new SerializableRunnable() {
-      @Override
-      public void run() {
-        disconnect();
-      }
-    };
-  }
-
-  public static void disconnect() {
-    Stopwatch stopwatch = Stopwatch.createStarted();
-    InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance();
-
-    while (system != null && stopwatch.elapsed(MINUTES) < 10) {
-      system = InternalDistributedSystem.getConnectedInstance();
-      try {
-        system.disconnect();
-      } catch (Exception ignore) {
-        // ignored
-      }
-    }
-
-    AdminDistributedSystemImpl adminSystem = AdminDistributedSystemImpl.getConnectedInstance();
-    if (adminSystem != null) {
-      adminSystem.disconnect();
-    }
-  }
-
-  /**
-   * Builds an instance of DistributedDisconnectRule
-   */
-  public static class Builder {
-    private boolean disconnectBefore;
-    private boolean disconnectAfter;
-
-    public Builder() {
-      // nothing
-    }
-
-    public Builder disconnectBefore(final boolean disconnectBefore) {
-      this.disconnectBefore = disconnectBefore;
-      return this;
-    }
-
-    public Builder disconnectAfter(final boolean disconnectAfter) {
-      this.disconnectAfter = disconnectAfter;
-      return this;
-    }
-
-    public DistributedDisconnectRule build() {
-      return new DistributedDisconnectRule(this);
-    }
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedDisconnectRuleAsClassRuleDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedDisconnectRuleAsClassRuleDistributedTest.java
deleted file mode 100644
index 5a52574..0000000
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedDisconnectRuleAsClassRuleDistributedTest.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.test.dunit.rules.tests;
-
-import static org.apache.geode.test.dunit.VM.getAllVMs;
-import static org.apache.geode.test.dunit.rules.DistributedDisconnectRule.disconnect;
-import static org.assertj.core.api.Assertions.assertThat;
-
-import org.junit.After;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.runner.Result;
-import org.junit.runners.MethodSorters;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.rules.DistributedDisconnectRule;
-import org.apache.geode.test.dunit.rules.DistributedTestRule;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.rules.RuleList;
-import org.apache.geode.test.junit.runners.TestRunner;
-
-@Category(DistributedTest.class)
-public class DistributedDisconnectRuleAsClassRuleDistributedTest {
-
-  @After
-  public void tearDown() throws Exception {
-    disconnect();
-    DisconnectBefore.cache = null;
-    DisconnectAfter.cache = null;
-
-    for (VM vm : Host.getHost(0).getAllVMs()) {
-      vm.invoke(() -> {
-        disconnect();
-        DisconnectBefore.cache = null;
-        DisconnectAfter.cache = null;
-      });
-    }
-  }
-
-  @Test
-  public void disconnectBeforeShouldDisconnectAllBeforeTests() throws Exception {
-    Result result = TestRunner.runTest(DisconnectBefore.class);
-
-    assertThat(result.wasSuccessful()).isTrue();
-
-    assertThat(DisconnectBefore.cache.getInternalDistributedSystem().isConnected()).isTrue();
-    assertThat(DisconnectBefore.cache.isClosed()).isFalse();
-
-    for (VM vm : Host.getHost(0).getAllVMs()) {
-      vm.invoke(() -> {
-        assertThat(DisconnectBefore.cache.getInternalDistributedSystem().isConnected()).isTrue();
-        assertThat(DisconnectBefore.cache.isClosed()).isFalse();
-      });
-    }
-  }
-
-  @Test
-  public void disconnectAfterShouldDisconnectAllAfterTests() throws Exception {
-    Result result = TestRunner.runTest(DisconnectAfter.class);
-
-    assertThat(result.wasSuccessful()).isTrue();
-
-    assertThat(DisconnectAfter.cache.getInternalDistributedSystem().isConnected()).isFalse();
-    assertThat(DisconnectAfter.cache.isClosed()).isTrue();
-
-    for (VM vm : Host.getHost(0).getAllVMs()) {
-      vm.invoke(() -> {
-        assertThat(DisconnectAfter.cache.getInternalDistributedSystem().isConnected()).isFalse();
-        assertThat(DisconnectAfter.cache.isClosed()).isTrue();
-      });
-    }
-  }
-
-  /**
-   * Used by test {@link #disconnectBeforeShouldDisconnectAllBeforeTests()}
-   */
-  public static class DisconnectBefore {
-
-    @ClassRule
-    public static RuleList rules = new RuleList().add(new DistributedTestRule())
-        .add(new DistributedDisconnectRule.Builder().disconnectBefore(true).build());
-
-    static InternalCache cache;
-
-    @BeforeClass
-    public static void setUpClass() throws Exception {
-      cache = (InternalCache) new CacheFactory().create();
-      assertThat(cache.isClosed()).isFalse();
-      assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-
-      for (VM vm : getAllVMs()) {
-        vm.invoke(() -> {
-          cache = (InternalCache) new CacheFactory().create();
-          assertThat(cache.isClosed()).isFalse();
-          assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-        });
-      }
-    }
-
-    @Test
-    public void everyDUnitVMShouldStillBeConnected() throws Exception {
-      assertThat(cache.isClosed()).isFalse();
-      assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-
-      for (VM vm : getAllVMs()) {
-        vm.invoke(() -> {
-          assertThat(cache.isClosed()).isFalse();
-          assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-        });
-      }
-    }
-  }
-
-  /**
-   * Used by test {@link #disconnectAfterShouldDisconnectAllAfterTests()}
-   */
-  @FixMethodOrder(MethodSorters.NAME_ASCENDING)
-  public static class DisconnectAfter {
-
-    @ClassRule
-    public static RuleList rules = new RuleList().add(new DistributedTestRule())
-        .add(new DistributedDisconnectRule.Builder().disconnectAfter(true).build());
-
-    static InternalCache cache;
-
-    @Test
-    public void createCacheInEveryVM() throws Exception {
-      cache = (InternalCache) new CacheFactory().create();
-      assertThat(cache.isClosed()).isFalse();
-      assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-
-      for (VM vm : getAllVMs()) {
-        vm.invoke(() -> {
-          cache = (InternalCache) new CacheFactory().create();
-          assertThat(cache.isClosed()).isFalse();
-          assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-        });
-      }
-    }
-
-    @Test
-    public void everyVMShouldStillBeConnected() throws Exception {
-      assertThat(cache.isClosed()).isFalse();
-      assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-
-      for (VM vm : getAllVMs()) {
-        vm.invoke(() -> {
-          assertThat(cache.isClosed()).isFalse();
-          assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-        });
-      }
-    }
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedDisconnectRuleDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedDisconnectRuleDistributedTest.java
deleted file mode 100644
index 01bbcee..0000000
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedDisconnectRuleDistributedTest.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.test.dunit.rules.tests;
-
-import static org.apache.geode.test.dunit.VM.getAllVMs;
-import static org.apache.geode.test.dunit.rules.DistributedDisconnectRule.disconnect;
-import static org.assertj.core.api.Assertions.assertThat;
-
-import org.junit.After;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.runner.Result;
-import org.junit.runners.MethodSorters;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.rules.DistributedDisconnectRule;
-import org.apache.geode.test.dunit.rules.DistributedTestRule;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.runners.TestRunner;
-
-@Category(DistributedTest.class)
-public class DistributedDisconnectRuleDistributedTest {
-
-  private static InternalCache cache;
-
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
-
-  @After
-  public void tearDown() throws Exception {
-    disconnect();
-    cache = null;
-
-    for (VM vm : getAllVMs()) {
-      vm.invoke(() -> {
-        disconnect();
-        cache = null;
-      });
-    }
-  }
-
-  @Test
-  public void disconnectShouldDisconnect() throws Exception {
-    cache = (InternalCache) new CacheFactory().create();
-    assertThat(cache.isClosed()).isFalse();
-    assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-
-    disconnect();
-
-    assertThat(cache.isClosed()).isTrue();
-    assertThat(cache.getInternalDistributedSystem().isConnected()).isFalse();
-  }
-
-  @Test
-  public void disconnectBeforeShouldDisconnectBeforeEachTest() throws Exception {
-    createCacheInEveryVM();
-    assertThatConnectedInEveryVM();
-
-    Result result = TestRunner.runTest(DisconnectBefore.class);
-
-    assertThat(result.wasSuccessful()).isTrue();
-    assertThatConnectedInEveryVM();
-  }
-
-  @Test
-  public void disconnectAfterShouldDisconnectAfterEachTest() throws Exception {
-    createCacheInEveryVM();
-    assertThatConnectedInEveryVM();
-
-    Result result = TestRunner.runTest(DisconnectAfter.class);
-
-    assertThat(result.wasSuccessful()).isTrue();
-    assertThatDisconnectedInEveryVM();
-  }
-
-  static void createCacheInEveryVM() throws Exception {
-    cache = (InternalCache) new CacheFactory().create();
-
-    for (VM vm : getAllVMs()) {
-      vm.invoke(() -> {
-        cache = (InternalCache) new CacheFactory().create();
-      });
-    }
-  }
-
-  static void assertThatConnectedInEveryVM() throws Exception {
-    assertThat(cache.isClosed()).isFalse();
-    assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-
-    for (VM vm : getAllVMs()) {
-      vm.invoke(() -> {
-        assertThat(cache.isClosed()).isFalse();
-        assertThat(cache.getInternalDistributedSystem().isConnected()).isTrue();
-      });
-    }
-  }
-
-  static void assertThatDisconnectedInEveryVM() throws Exception {
-    assertThat(cache.getInternalDistributedSystem().isConnected()).isFalse();
-    assertThat(cache.isClosed()).isTrue();
-
-    for (VM vm : getAllVMs()) {
-      vm.invoke(() -> {
-        assertThat(cache.getInternalDistributedSystem().isConnected()).isFalse();
-        assertThat(cache.isClosed()).isTrue();
-      });
-    }
-  }
-
-  /**
-   * Used by test {@link #disconnectBeforeShouldDisconnectBeforeEachTest()}
-   */
-  @FixMethodOrder(MethodSorters.NAME_ASCENDING)
-  public static class DisconnectBefore {
-
-    @ClassRule
-    public static DistributedTestRule distributedTestRule = new DistributedTestRule();
-
-    @Rule
-    public DistributedDisconnectRule distributedDisconnectRule =
-        new DistributedDisconnectRule.Builder().disconnectBefore(true).build();
-
-    @Test
-    public void test001CreateCacheInEveryVM() throws Exception {
-      assertThatDisconnectedInEveryVM();
-      createCacheInEveryVM();
-      assertThatConnectedInEveryVM();
-    }
-
-    @Test
-    public void test002EveryVMShouldHaveDisconnected() throws Exception {
-      assertThatDisconnectedInEveryVM();
-      createCacheInEveryVM();
-      assertThatConnectedInEveryVM();
-    }
-  }
-
-  /**
-   * Used by test {@link #disconnectAfterShouldDisconnectAfterEachTest()}
-   */
-  @FixMethodOrder(MethodSorters.NAME_ASCENDING)
-  public static class DisconnectAfter {
-
-    @ClassRule
-    public static DistributedTestRule distributedTestRule = new DistributedTestRule();
-
-    @Rule
-    public DistributedDisconnectRule distributedDisconnectRule =
-        new DistributedDisconnectRule.Builder().disconnectAfter(true).build();
-
-    @Test
-    public void test001AlreadyHasCacheInEveryVM() throws Exception {
-      assertThatConnectedInEveryVM();
-    }
-
-    @Test
-    public void test002CreateCacheInEveryVM() throws Exception {
-      assertThatDisconnectedInEveryVM();
-      createCacheInEveryVM();
-      assertThatConnectedInEveryVM();
-    }
-
-    @Test
-    public void test003EveryVMShouldHaveDisconnected() throws Exception {
-      assertThatDisconnectedInEveryVM();
-      createCacheInEveryVM();
-      assertThatConnectedInEveryVM();
-    }
-  }
-}

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 05/13: GEODE-4876: Remove additional uses of DUnit Host and cleanup

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit 34acd5cc82a7506bd6d310a7e9ef18463ec738fa
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Thu Apr 12 12:45:40 2018 -0700

    GEODE-4876: Remove additional uses of DUnit Host and cleanup
---
 .../java/org/apache/geode/test/dunit/DistributedTestUtils.java     | 3 ++-
 .../org/apache/geode/test/dunit/rules/CleanupDUnitVMsRule.java     | 7 ++++---
 .../apache/geode/test/dunit/rules/DistributedExternalResource.java | 2 +-
 3 files changed, 7 insertions(+), 5 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/DistributedTestUtils.java b/geode-core/src/test/java/org/apache/geode/test/dunit/DistributedTestUtils.java
index 0eb3a94..2892783 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/DistributedTestUtils.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/DistributedTestUtils.java
@@ -15,6 +15,7 @@
 package org.apache.geode.test.dunit;
 
 import static org.apache.geode.distributed.ConfigurationProperties.DISABLE_AUTO_RECONNECT;
+import static org.apache.geode.test.dunit.VM.getHostName;
 import static org.junit.Assert.assertEquals;
 
 import java.io.File;
@@ -164,7 +165,7 @@ public class DistributedTestUtils {
    * Returns a {@link ConfigurationProperties#LOCATORS} string for the standard dunit locator.
    */
   public static String getLocators() {
-    return Host.getHost(0).getHostName() + "[" + getLocatorPort() + "]";
+    return getHostName() + "[" + getLocatorPort() + "]";
   }
 
   public static void unregisterAllDataSerializersFromAllVms() {
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CleanupDUnitVMsRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CleanupDUnitVMsRule.java
index 73ccad7..145f5b8 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CleanupDUnitVMsRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CleanupDUnitVMsRule.java
@@ -15,20 +15,21 @@
 package org.apache.geode.test.dunit.rules;
 
 import static org.apache.geode.test.dunit.Host.getHostCount;
+import static org.apache.geode.test.dunit.VM.getAllVMs;
 
 import org.apache.geode.test.dunit.VM;
 
-public class CleanupDUnitVMsRule extends ExternalResource implements Serializable {
+public class CleanupDUnitVMsRule extends AbstractDistributedTestRule {
 
   @Override
   public void before() {
     if (getHostCount() > 0) {
-      getHost(0).getAllVMs().forEach(VM::bounce);
+      getAllVMs().forEach(VM::bounce);
     }
   }
 
   @Override
   public void after() {
-    getHost(0).getAllVMs().forEach(VM::bounce);
+    getAllVMs().forEach(VM::bounce);
   }
 }
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedExternalResource.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedExternalResource.java
index 529643a..0a47a3c 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedExternalResource.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedExternalResource.java
@@ -34,6 +34,6 @@ public abstract class DistributedExternalResource extends SerializableExternalRe
   }
 
   protected RemoteInvoker invoker() {
-    return this.invoker;
+    return invoker;
   }
 }

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 09/13: GEODE-1279: Delete useless test Bug51400DUnitTest

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit b5fc48c629d791177439a16b22ab9d8624131e94
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Fri Apr 13 10:18:24 2018 -0700

    GEODE-1279: Delete useless test Bug51400DUnitTest
---
 .../cache/partitioned/Bug51400DUnitTest.java       | 181 ---------------------
 1 file changed, 181 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug51400DUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug51400DUnitTest.java
deleted file mode 100644
index 907b28c..0000000
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug51400DUnitTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.internal.cache.partitioned;
-
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.junit.Assert.*;
-
-import java.util.Properties;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionFactory;
-import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.client.ClientCacheFactory;
-import org.apache.geode.cache.client.ClientRegionFactory;
-import org.apache.geode.cache.client.ClientRegionShortcut;
-import org.apache.geode.cache.server.CacheServer;
-import org.apache.geode.distributed.DistributedSystem;
-import org.apache.geode.internal.AvailablePort;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientProxyStats;
-import org.apache.geode.test.dunit.AsyncInvocation;
-import org.apache.geode.test.dunit.DistributedTestUtils;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.NetworkUtils;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-@Category(DistributedTest.class)
-public class Bug51400DUnitTest extends JUnit4DistributedTestCase {
-
-  private static VM server0 = null;
-  private static VM server1 = null;
-  private static VM client0 = null;
-  private static VM client1 = null;
-
-  private static GemFireCacheImpl cache;
-
-  public static final String REGION_NAME = "Bug51400DUnitTest_region";
-
-  @Override
-  public final void postSetUp() throws Exception {
-    Host host = Host.getHost(0);
-    server0 = host.getVM(0);
-    server1 = host.getVM(1);
-    client0 = host.getVM(2);
-    client1 = host.getVM(3);
-  }
-
-  @Override
-  public final void preTearDown() throws Exception {
-    closeCache();
-
-    client0.invoke(() -> Bug51400DUnitTest.closeCache());
-    client1.invoke(() -> Bug51400DUnitTest.closeCache());
-
-    server0.invoke(() -> Bug51400DUnitTest.closeCache());
-    server1.invoke(() -> Bug51400DUnitTest.closeCache());
-  }
-
-  public static void closeCache() throws Exception {
-    if (cache != null) {
-      cache.close();
-    }
-  }
-
-  public static Integer createServerCache(Integer mcastPort, Integer maxMessageCount)
-      throws Exception {
-    Properties props = new Properties();
-    props.setProperty(LOCATORS, "localhost[" + DistributedTestUtils.getDUnitLocatorPort() + "]");
-
-    Bug51400DUnitTest test = new Bug51400DUnitTest();
-    DistributedSystem ds = test.getSystem(props);
-    ds.disconnect();
-    cache = (GemFireCacheImpl) CacheFactory.create(test.getSystem());
-    // cache = (GemFireCacheImpl) new CacheFactory(props).create();
-
-    RegionFactory<String, String> rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-
-    rf.setConcurrencyChecksEnabled(false);
-
-    Region<String, String> region = rf.create(REGION_NAME);
-
-    CacheServer server = cache.addCacheServer();
-    server.setMaximumMessageCount(maxMessageCount);
-    server.setPort(AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET));
-    server.start();
-    return server.getPort();
-  }
-
-  public static void createClientCache(String hostName, Integer[] ports, Integer interval)
-      throws Exception {
-    Properties props = new Properties();
-
-    DistributedSystem ds = new Bug51400DUnitTest().getSystem(props);
-    ds.disconnect();
-    ClientCacheFactory ccf = new ClientCacheFactory(props);
-    ccf.setPoolSubscriptionEnabled(true);
-    ccf.setPoolSubscriptionAckInterval(interval);
-    for (int port : ports) {
-      ccf.addPoolServer(hostName, port);
-    }
-    cache = (GemFireCacheImpl) ccf.create();
-
-    ClientRegionFactory<String, String> crf =
-        cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
-
-    Region<String, String> region = crf.create(REGION_NAME);
-
-    region.registerInterest("ALL_KEYS");
-  }
-
-  public static void verifyQueueSize(Boolean isPrimary, Integer numOfEvents) throws Exception {
-    CacheClientProxyStats stats =
-        ((CacheClientProxy) CacheClientNotifier.getInstance().getClientProxies().toArray()[0])
-            .getStatistics();
-
-    if (isPrimary) {
-      numOfEvents = numOfEvents + 1; // marker
-    }
-    long qSize = stats.getMessageQueueSize();
-    assertEquals("Expected queue size: " + numOfEvents + " but actual size: " + qSize + " at "
-        + (isPrimary ? "primary." : "secondary."), numOfEvents.intValue(), qSize);
-  }
-
-
-  @Ignore("ticket51932")
-  @Test
-  public void testDeadlock() throws Throwable {
-    int maxQSize = 5;
-    // Set infinite ack interval so that the queue will not be drained.
-    int ackInterval = Integer.MAX_VALUE;
-
-    fail("Invoking bad method");
-    int port1 = 0;
-    // int port1 = (Integer) server0.invoke(() -> Bug51400DUnitTest.createServerCache( maxQSize));
-
-    client1.invoke(Bug51400DUnitTest.class, "createClientCache", new Object[] {
-        NetworkUtils.getServerHostName(Host.getHost(0)), new Integer[] {port1}, ackInterval});
-
-    // Do puts from server as well as from client on the same key.
-    AsyncInvocation ai1 = server0.invokeAsync(() -> Bug51400DUnitTest.updateKey(2 * maxQSize));
-    AsyncInvocation ai2 = client1.invokeAsync(() -> Bug51400DUnitTest.updateKey(2 * maxQSize));
-    ai1.getResult();
-    ai2.getResult();
-    // Verify that the queue has crossed its limit of maxQSize
-    server0.invoke(() -> Bug51400DUnitTest.verifyQueueSize(true, 2 * maxQSize));
-  }
-
-  public static void updateKey(Integer num) {
-    try {
-      String k = "51400_KEY";
-      Region r = cache.getRegion(REGION_NAME);
-      for (int i = 0; i < num; ++i) {
-        r.put(k, "VALUE_" + i);
-      }
-    } catch (Exception e) {
-      fail("Failed in updateKey()" + e);
-    }
-  }
-
-}

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 02/13: GEODE-5020: Move HARegionQueue system properties to SystemPropertyHelper

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit 7cc9e8fbc09a4f553b5d6b94a0615820fdd3c9af
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Thu Apr 5 15:11:38 2018 -0700

    GEODE-5020: Move HARegionQueue system properties to SystemPropertyHelper
    
    Rename ClientSubscriptionExpiryDataLossRegressionTest as
    HARegionQueueExpiryRegressionTest.
    
    Rename Bug48879DUnitTest as HARegionQueueThreadIdExpiryRegressionTest.
    
    Overhaul HARegionQueueThreadIdExpiryRegressionTest:
    * remove Thread sleeps
    * use Rules and Awaitility
    * use System properties instead of public static variables
---
 .../geode/internal/cache/ha/HARegionQueue.java     |  67 ++++--
 .../geode/internal/lang/SystemPropertyHelper.java  |   4 +
 .../geode/internal/cache/ha/Bug48879DUnitTest.java | 227 ---------------------
 ...java => HARegionQueueExpiryRegressionTest.java} |   6 +-
 .../internal/cache/ha/HARegionQueueJUnitTest.java  |   4 +-
 .../HARegionQueueThreadIdExpiryRegressionTest.java | 198 ++++++++++++++++++
 6 files changed, 255 insertions(+), 251 deletions(-)

diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/ha/HARegionQueue.java b/geode-core/src/main/java/org/apache/geode/internal/cache/ha/HARegionQueue.java
index 630bdea..8a5ccbb 100755
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/ha/HARegionQueue.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/ha/HARegionQueue.java
@@ -14,6 +14,10 @@
  */
 package org.apache.geode.internal.cache.ha;
 
+import static org.apache.geode.internal.lang.SystemPropertyHelper.HA_REGION_QUEUE_EXPIRY_TIME_PROPERTY;
+import static org.apache.geode.internal.lang.SystemPropertyHelper.THREAD_ID_EXPIRY_TIME_PROPERTY;
+import static org.apache.geode.internal.lang.SystemPropertyHelper.getProductIntegerProperty;
+
 import java.io.DataInput;
 import java.io.DataOutput;
 import java.io.IOException;
@@ -30,6 +34,7 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.NoSuchElementException;
+import java.util.Optional;
 import java.util.Queue;
 import java.util.Set;
 import java.util.TreeMap;
@@ -67,7 +72,6 @@ import org.apache.geode.cache.query.internal.cq.InternalCqQuery;
 import org.apache.geode.cache.server.CacheServer;
 import org.apache.geode.cache.util.CacheListenerAdapter;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.DistributionConfig;
 import org.apache.geode.distributed.internal.DistributionManager;
 import org.apache.geode.distributed.internal.InternalDistributedSystem;
 import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
@@ -239,12 +243,6 @@ public class HARegionQueue implements RegionQueue {
   public static final long INIT_OF_SEQUENCEID = -1L;
 
   /**
-   * Constant used to set region entry expiry time using system property.
-   */
-  public static final String REGION_ENTRY_EXPIRY_TIME =
-      DistributionConfig.GEMFIRE_PREFIX + "MessageTimeToLive";
-
-  /**
    * The default frequency (in seconds) at which a message will be sent by the primary to all the
    * secondary nodes to remove the events which have already been dispatched from the queue.
    */
@@ -298,12 +296,6 @@ public class HARegionQueue implements RegionQueue {
   static boolean testMarkerMessageRecieved = false;
   static boolean isUsedByTest = false;
 
-  static final int DEFAULT_THREAD_ID_EXPIRY_TIME = 300;
-  /**
-   * For testing purposes, allows resetting expiry time for ThreadIdentifiers. In seconds.
-   */
-  public static int threadIdExpiryTime = DEFAULT_THREAD_ID_EXPIRY_TIME;
-
   /**
    * Used by durable queues to maintain acked events by client
    */
@@ -604,6 +596,7 @@ public class HARegionQueue implements RegionQueue {
    *
    * @param object object to put onto the queue
    */
+  @Override
   public boolean put(Object object) throws CacheException, InterruptedException {
     this.giiLock.readLock().lock(); // fix for bug #41681 - durable client misses event
     try {
@@ -1125,6 +1118,7 @@ public class HARegionQueue implements RegionQueue {
   /**
    * Returns the underlying region that backs this queue.
    */
+  @Override
   public HARegion getRegion() {
     return this.region;
   }
@@ -1190,6 +1184,7 @@ public class HARegionQueue implements RegionQueue {
    * @throws CacheException The exception can be thrown by BlockingQueue if it encounters
    *         InterruptedException while waiting for data
    */
+  @Override
   public Object take() throws CacheException, InterruptedException {
     Conflatable object = null;
     Long next = null;
@@ -1227,6 +1222,7 @@ public class HARegionQueue implements RegionQueue {
     return object;
   }
 
+  @Override
   public List take(int batchSize) throws CacheException, InterruptedException {
     List batch = new ArrayList(batchSize * 2);
     for (int i = 0; i < batchSize; i++) {
@@ -1260,6 +1256,7 @@ public class HARegionQueue implements RegionQueue {
    * Removes the events that were peeked by this thread. The events are destroyed from the queue and
    * conflation map and DispatchedAndCurrentEvents are updated accordingly.
    */
+  @Override
   public void remove() throws InterruptedException {
     List peekedIds = (List) HARegionQueue.peekedEventsContext.get();
 
@@ -1352,6 +1349,7 @@ public class HARegionQueue implements RegionQueue {
     // ARB: Implemented in DurableHARegionQueue.
   }
 
+  @Override
   public Object peek() throws InterruptedException {
     if (Thread.interrupted())
       throw new InterruptedException();
@@ -1393,6 +1391,7 @@ public class HARegionQueue implements RegionQueue {
     return object;
   }
 
+  @Override
   public List peek(int batchSize) throws InterruptedException {
     return peek(batchSize, -1);
   }
@@ -1436,6 +1435,7 @@ public class HARegionQueue implements RegionQueue {
    *
    * @return The list of events peeked
    */
+  @Override
   public List peek(int batchSize, int timeToWait) throws InterruptedException {
     long start = System.currentTimeMillis();
     long end = start + timeToWait;
@@ -1531,10 +1531,12 @@ public class HARegionQueue implements RegionQueue {
     return batch;
   }
 
+  @Override
   public void addCacheListener(CacheListener listener) {
     // nothing
   }
 
+  @Override
   public void removeCacheListener() {
     // nothing
   }
@@ -1738,6 +1740,7 @@ public class HARegionQueue implements RegionQueue {
    *
    * @return the size of the queue
    */
+  @Override
   public int size() {
     acquireReadLock();
     try {
@@ -1983,8 +1986,9 @@ public class HARegionQueue implements RegionQueue {
                 .toLocalizedString(new Object[] {BLOCKING_HA_QUEUE, NON_BLOCKING_HA_QUEUE}));
     }
     if (!isDurable) {
-      Integer expiryTime = Integer.getInteger(REGION_ENTRY_EXPIRY_TIME, hrqa.getExpiryTime());
-      hrqa.setExpiryTime(expiryTime);
+      Optional<Integer> expiryTime =
+          getProductIntegerProperty(HA_REGION_QUEUE_EXPIRY_TIME_PROPERTY);
+      hrqa.setExpiryTime(expiryTime.orElseGet(hrqa::getExpiryTime));
       ExpirationAttributes ea =
           new ExpirationAttributes(hrqa.getExpiryTime(), ExpirationAction.LOCAL_INVALIDATE);
       hrq.region.getAttributesMutator().setEntryTimeToLive(ea);
@@ -3266,6 +3270,7 @@ public class HARegionQueue implements RegionQueue {
      *
      * @see org.apache.geode.internal.DataSerializableFixedID#fromData(java.io.DataInput)
      */
+    @Override
     public void fromData(DataInput in) throws IOException, ClassNotFoundException {
       synchronized (this) {
         this.lastDispatchedSequenceId = in.readLong();
@@ -3278,6 +3283,7 @@ public class HARegionQueue implements RegionQueue {
      *
      * @see org.apache.geode.internal.DataSerializableFixedID#getDSFID()
      */
+    @Override
     public int getDSFID() {
       return DISPATCHED_AND_CURRENT_EVENTS;
     }
@@ -3287,6 +3293,7 @@ public class HARegionQueue implements RegionQueue {
      *
      * @see org.apache.geode.internal.DataSerializableFixedID#toData(java.io.DataOutput)
      */
+    @Override
     public void toData(DataOutput out) throws IOException {
       synchronized (this) { // fix for bug #41621
         out.writeLong(this.lastDispatchedSequenceId);
@@ -3307,6 +3314,7 @@ public class HARegionQueue implements RegionQueue {
   }
 
   // TODO:Asif : Remove this method
+  @Override
   public void remove(int top) {
     throw new UnsupportedOperationException(
         LocalizedStrings.HARegionQueue_HAREGIONQUEUE_AND_ITS_DERIVED_CLASS_DO_NOT_SUPPORT_THIS_OPERATION
@@ -3543,6 +3551,7 @@ public class HARegionQueue implements RegionQueue {
         // Start a new thread which will update the clientMessagesRegion for
         // each of the HAEventWrapper instances present in the wrapperSet
         Thread regionCleanupTask = new Thread(new Runnable() {
+          @Override
           public void run() {
             try {
               Iterator iter = wrapperSet.iterator();
@@ -3779,16 +3788,24 @@ public class HARegionQueue implements RegionQueue {
 
   /** this is used to expire thread identifiers, even in primary queues */
   static class ThreadIdentifierCustomExpiry implements CustomExpiry {
-    private static final ExpirationAttributes DEFAULT_THREAD_ID_EXP_ATTS = new ExpirationAttributes(
-        HARegionQueue.DEFAULT_THREAD_ID_EXPIRY_TIME, ExpirationAction.LOCAL_INVALIDATE);
-    private static volatile ExpirationAttributes testExpAtts = null;
 
+    /**
+     * expiry time for ThreadIdentifiers. In seconds.
+     */
+    static final int DEFAULT_THREAD_ID_EXPIRY_TIME = 300;
+
+    private static final ExpirationAttributes DEFAULT_THREAD_ID_EXP_ATTS =
+        new ExpirationAttributes(DEFAULT_THREAD_ID_EXPIRY_TIME, ExpirationAction.LOCAL_INVALIDATE);
+
+    private static volatile ExpirationAttributes testExpAtts;
+
+    @Override
     public ExpirationAttributes getExpiry(Region.Entry entry) {
       // Use key to determine expiration.
       Object key = entry.getKey();
       if (key instanceof ThreadIdentifier) {
-        final int expTime = HARegionQueue.threadIdExpiryTime;
-        if (expTime != HARegionQueue.DEFAULT_THREAD_ID_EXPIRY_TIME) {
+        final int expTime = calculateThreadIdExpiryTime();
+        if (expTime != DEFAULT_THREAD_ID_EXPIRY_TIME) {
           // This should only happen in unit test code
           ExpirationAttributes result = testExpAtts;
           if (result == null || result.getTimeout() != expTime) {
@@ -3806,6 +3823,14 @@ public class HARegionQueue implements RegionQueue {
       }
     }
 
-    public void close() {}
+    @Override
+    public void close() {
+      // nothing
+    }
+
+    private static int calculateThreadIdExpiryTime() {
+      Optional<Integer> expiryTime = getProductIntegerProperty(THREAD_ID_EXPIRY_TIME_PROPERTY);
+      return expiryTime.orElse(DEFAULT_THREAD_ID_EXPIRY_TIME);
+    }
   }
 }
diff --git a/geode-core/src/main/java/org/apache/geode/internal/lang/SystemPropertyHelper.java b/geode-core/src/main/java/org/apache/geode/internal/lang/SystemPropertyHelper.java
index fc2551d..a039628 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/lang/SystemPropertyHelper.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/lang/SystemPropertyHelper.java
@@ -61,6 +61,10 @@ public class SystemPropertyHelper {
 
   public static final String DEFAULT_DISK_DIRS_PROPERTY = "defaultDiskDirs";
 
+  public static final String HA_REGION_QUEUE_EXPIRY_TIME_PROPERTY = "MessageTimeToLive";
+
+  public static final String THREAD_ID_EXPIRY_TIME_PROPERTY = "threadIdExpiryTime";
+
   /**
    * This method will try to look up "geode." and "gemfire." versions of the system property. It
    * will check and prefer "geode." setting first, then try to check "gemfire." setting.
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48879DUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48879DUnitTest.java
deleted file mode 100644
index 8e7952e..0000000
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48879DUnitTest.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.internal.cache.ha;
-
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.junit.Assert.*;
-
-import java.util.Properties;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionFactory;
-import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.client.ClientCacheFactory;
-import org.apache.geode.cache.client.ClientRegionFactory;
-import org.apache.geode.cache.client.ClientRegionShortcut;
-import org.apache.geode.cache.server.CacheServer;
-import org.apache.geode.distributed.DistributedSystem;
-import org.apache.geode.distributed.internal.DistributionConfig;
-import org.apache.geode.internal.AvailablePort;
-import org.apache.geode.internal.OSProcess;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.ClientSubscriptionTest;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-@Category({DistributedTest.class, ClientSubscriptionTest.class})
-@SuppressWarnings("serial")
-public class Bug48879DUnitTest extends JUnit4DistributedTestCase {
-
-  private static VM vm0 = null;
-  private static VM vm1 = null;
-
-  private static GemFireCacheImpl cache;
-
-  public static final String REGION_NAME = "Bug48879DUnitTest_region";
-
-  public static final int SLEEP_TIME = 40000;
-
-  public Bug48879DUnitTest() {
-    super();
-  }
-
-  @Override
-  public final void postSetUp() throws Exception {
-    disconnectAllFromDS();
-    Host host = Host.getHost(0);
-    vm0 = host.getVM(0); // server1
-    vm1 = host.getVM(1); // server2
-
-    int port0 = (Integer) vm0.invoke(() -> Bug48879DUnitTest.createCacheServer());
-    int port1 = (Integer) vm1.invoke(() -> Bug48879DUnitTest.createCacheServer());
-
-    createClientCache(host, new Integer[] {port0, port1}, Boolean.TRUE);
-  }
-
-  @Override
-  public final void preTearDown() throws Exception {
-    closeCache();
-
-    vm0.invoke(() -> Bug48879DUnitTest.closeCache());
-    vm1.invoke(() -> Bug48879DUnitTest.closeCache());
-  }
-
-  public static void closeCache() throws Exception {
-    HARegionQueue.threadIdExpiryTime = 300;
-    System.setProperty(DistributionConfig.GEMFIRE_PREFIX + "MessageTimeToLive", "180");
-    if (cache != null) {
-      cache.close();
-    }
-  }
-
-  @SuppressWarnings({"unused", "deprecation"})
-  public static Integer createCacheServer() throws Exception {
-    Bug48879DUnitTest test = new Bug48879DUnitTest();
-    System.setProperty(DistributionConfig.GEMFIRE_PREFIX + "MessageTimeToLive", "30");
-    cache = (GemFireCacheImpl) CacheFactory.create(test.getSystem());
-    HARegionQueue.threadIdExpiryTime = (SLEEP_TIME / 1000) - 10;
-    cache.setMessageSyncInterval(SLEEP_TIME / 500);
-
-    RegionFactory<String, String> rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-
-    Region<String, String> region = rf.create(REGION_NAME);
-
-    CacheServer server = cache.addCacheServer();
-    server.setPort(AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET));
-    server.start();
-    return server.getPort();
-  }
-
-  @SuppressWarnings("deprecation")
-  public static void createClientCache(Host host, Integer[] ports, Boolean doRI) throws Exception {
-
-    Properties props = new Properties();
-    props.setProperty(STATISTIC_ARCHIVE_FILE, "client_" + OSProcess.getId() + ".gfs");
-    props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
-
-    DistributedSystem ds = new Bug48879DUnitTest().getSystem(props);
-    ds.disconnect();
-    ClientCacheFactory ccf = new ClientCacheFactory(props);
-    ccf.setPoolSubscriptionEnabled(doRI);
-    ccf.setPoolSubscriptionAckInterval(50);
-    ccf.setPoolSubscriptionRedundancy(1);
-    for (int port : ports) {
-      ccf.addPoolServer(host.getHostName(), port);
-    }
-    cache = (GemFireCacheImpl) ccf.create();
-
-    ClientRegionFactory<String, String> crf =
-        cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
-
-    Region<String, String> region = crf.create(REGION_NAME);
-
-    if (doRI) {
-      region.registerInterest("ALL_KEYS");
-    }
-
-  }
-
-  @SuppressWarnings({"unused", "unchecked"})
-  public static void doPuts(Integer numOfThreads, Integer puts) throws Exception {
-    Region<String, String> region = cache.getRegion(REGION_NAME);
-    final int putsPerThread = puts;
-
-    Thread[] threads = new Thread[numOfThreads];
-
-    for (int i = 0; i < numOfThreads; i++) {
-      final String threadId = "Thread_" + i + "X";
-      threads[i] = new Thread(new Runnable() {
-        @SuppressWarnings("rawtypes")
-        public void run() {
-          Region region = cache.getRegion(REGION_NAME);
-          for (int i = 0; i < putsPerThread; i++) {
-            region.put(threadId + i, "VALUE_" + i);
-          }
-        }
-      });
-      threads[i].start();
-    }
-
-    for (int i = 0; i < numOfThreads; i++) {
-      try {
-        threads[i].join();
-      } catch (InterruptedException ie) {
-      }
-    }
-    Thread.sleep(5000);
-    region.put("LAST", "LAST");
-  }
-
-  public static Boolean isPrimaryServer() {
-    return ((CacheClientProxy) CacheClientNotifier.getInstance().getClientProxies().toArray()[0])
-        .isPrimary();
-  }
-
-  public static void verifyStats(Integer numOfEvents, Integer expectedTids) throws Exception {
-    HARegionQueueStats stats =
-        ((CacheClientProxy) CacheClientNotifier.getInstance().getClientProxies().toArray()[0])
-            .getHARegionQueue().getStatistics();
-
-    long actualExpiry = stats.getEventsExpired();
-    long expectedExpiry = isPrimaryServer() ? 0 : numOfEvents + 1; // +1 for LAST key
-    assertEquals(
-        "Expected eventsExpired: " + expectedExpiry + " but actual eventsExpired: " + actualExpiry
-            + (isPrimaryServer() ? " at primary." : " at secondary."),
-        expectedExpiry, actualExpiry);
-
-    int actualTids = stats.getThreadIdentiferCount();
-    assertTrue("Expected ThreadIdentifier count <= 1 but actual: " + actualTids
-        + (isPrimaryServer() ? " at primary." : " at secondary."), actualTids <= 1); // Sometimes we
-                                                                                     // may see 1
-                                                                                     // threadIdentifier
-                                                                                     // due to slow
-                                                                                     // machines,
-                                                                                     // but never
-                                                                                     // equal to
-                                                                                     // expectedTids
-  }
-
-  public static void verifyThreadsBeforeExpiry(Integer expectedTids) throws Exception {
-    HARegionQueueStats stats =
-        ((CacheClientProxy) CacheClientNotifier.getInstance().getClientProxies().toArray()[0])
-            .getHARegionQueue().getStatistics();
-
-    int actualTids = stats.getThreadIdentiferCount();
-    assertTrue("Expected ThreadIdentifier count >= " + expectedTids + " but actual: " + actualTids
-        + (isPrimaryServer() ? " at primary." : " at secondary."), actualTids >= expectedTids);
-  }
-
-  @Test
-  public void testThreadIdentfiersExpiry() throws Exception {
-    // create server1 and server2
-    // create client with redundancy = 1
-    // put events in region
-    int threads = 10;
-    int putsPerThread = 1;
-    vm0.invoke(() -> Bug48879DUnitTest.doPuts(threads, putsPerThread));
-    vm0.invoke(() -> Bug48879DUnitTest.verifyThreadsBeforeExpiry(threads));
-    vm1.invoke(() -> Bug48879DUnitTest.verifyThreadsBeforeExpiry(threads));
-    // sleep till expiry time elapses
-    Thread.sleep(SLEEP_TIME * 2 + 30000);
-
-    // Assert that threadidentifiers are expired and region events are retained on primary server
-    vm0.invoke(() -> Bug48879DUnitTest.verifyStats(threads * putsPerThread, threads));
-    // Assert that region events and threadidentifiers are expired on secondary server.
-    vm1.invoke(() -> Bug48879DUnitTest.verifyStats(threads * putsPerThread, threads));
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/ClientSubscriptionExpiryDataLossRegressionTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueExpiryRegressionTest.java
similarity index 95%
rename from geode-core/src/test/java/org/apache/geode/internal/cache/ha/ClientSubscriptionExpiryDataLossRegressionTest.java
rename to geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueExpiryRegressionTest.java
index 668ea8b..ab0885b 100755
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/ClientSubscriptionExpiryDataLossRegressionTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueExpiryRegressionTest.java
@@ -19,6 +19,8 @@ import static org.apache.geode.cache30.ClientServerTestCase.configureConnectionP
 import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
 import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
 import static org.apache.geode.internal.cache.tier.sockets.ConflationDUnitTest.setIsSlowStart;
+import static org.apache.geode.internal.lang.SystemPropertyHelper.GEODE_PREFIX;
+import static org.apache.geode.internal.lang.SystemPropertyHelper.HA_REGION_QUEUE_EXPIRY_TIME_PROPERTY;
 import static org.apache.geode.test.dunit.Host.getHost;
 import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
 import static org.apache.geode.test.dunit.NetworkUtils.getServerHostName;
@@ -66,7 +68,7 @@ import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
  * TRAC #36853: HA events can expire on primary server and this can cause data loss.
  */
 @Category({DistributedTest.class, ClientSubscriptionTest.class})
-public class ClientSubscriptionExpiryDataLossRegressionTest extends CacheTestCase {
+public class HARegionQueueExpiryRegressionTest extends CacheTestCase {
 
   /** The time in milliseconds by which the start of dispatcher will be delayed */
   private static final int DISPATCHER_SLOWSTART_TIME = 10_000;
@@ -129,7 +131,7 @@ public class ClientSubscriptionExpiryDataLossRegressionTest extends CacheTestCas
   }
 
   private int createServerCache() throws IOException {
-    System.setProperty(HARegionQueue.REGION_ENTRY_EXPIRY_TIME, String.valueOf(1));
+    System.setProperty(GEODE_PREFIX + HA_REGION_QUEUE_EXPIRY_TIME_PROPERTY, String.valueOf(1));
     System.setProperty("slowStartTimeForTesting", String.valueOf(DISPATCHER_SLOWSTART_TIME));
 
     AttributesFactory factory = new AttributesFactory();
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueJUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueJUnitTest.java
index bce4688..9723d93 100755
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueJUnitTest.java
@@ -15,6 +15,8 @@
 package org.apache.geode.internal.cache.ha;
 
 import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.apache.geode.internal.lang.SystemPropertyHelper.GEODE_PREFIX;
+import static org.apache.geode.internal.lang.SystemPropertyHelper.HA_REGION_QUEUE_EXPIRY_TIME_PROPERTY;
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.not;
 import static org.hamcrest.CoreMatchers.notNullValue;
@@ -1326,7 +1328,7 @@ public class HARegionQueueJUnitTest {
    */
   @Test
   public void testExpiryUsingSystemProperty() throws Exception {
-    System.setProperty(HARegionQueue.REGION_ENTRY_EXPIRY_TIME, "1");
+    System.setProperty(GEODE_PREFIX + HA_REGION_QUEUE_EXPIRY_TIME_PROPERTY, "1");
 
     HARegionQueueAttributes haa = new HARegionQueueAttributes();
     HARegionQueue regionQueue = createHARegionQueue(testName.getMethodName(), haa);
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueThreadIdExpiryRegressionTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueThreadIdExpiryRegressionTest.java
new file mode 100644
index 0000000..7f293c6
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueThreadIdExpiryRegressionTest.java
@@ -0,0 +1,198 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.internal.cache.ha;
+
+import static java.util.concurrent.TimeUnit.MINUTES;
+import static org.apache.geode.cache.RegionShortcut.REPLICATE;
+import static org.apache.geode.cache.client.ClientRegionShortcut.CACHING_PROXY;
+import static org.apache.geode.internal.lang.SystemPropertyHelper.GEODE_PREFIX;
+import static org.apache.geode.internal.lang.SystemPropertyHelper.HA_REGION_QUEUE_EXPIRY_TIME_PROPERTY;
+import static org.apache.geode.internal.lang.SystemPropertyHelper.THREAD_ID_EXPIRY_TIME_PROPERTY;
+import static org.apache.geode.test.dunit.VM.getHostName;
+import static org.apache.geode.test.dunit.VM.getVM;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+import java.io.IOException;
+import java.io.Serializable;
+
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.client.ClientCacheFactory;
+import org.apache.geode.cache.client.ClientRegionFactory;
+import org.apache.geode.cache.server.CacheServer;
+import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
+import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.rules.CacheRule;
+import org.apache.geode.test.dunit.rules.ClientCacheRule;
+import org.apache.geode.test.dunit.rules.DistributedRestoreSystemProperties;
+import org.apache.geode.test.dunit.rules.DistributedTestRule;
+import org.apache.geode.test.junit.categories.ClientSubscriptionTest;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
+
+/**
+ * HARegionQueueThreadIdExpiryRegressionTest
+ * <p>
+ * TRAC #48879: Leaking ThreadIdentifiers and DispatchedAndCurrentEvents objects when client uses
+ * many short lived threads
+ */
+@Category({DistributedTest.class, ClientSubscriptionTest.class})
+@SuppressWarnings("serial")
+public class HARegionQueueThreadIdExpiryRegressionTest implements Serializable {
+
+  private static final int MESSAGE_SYNC_INTERVAL_SECONDS = 60;
+  private static final String EXPIRY_TIME_SECONDS = "30";
+
+  private VM server1;
+  private VM server2;
+
+  private String regionName;
+  private String hostName;
+
+  @ClassRule
+  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+
+  @Rule
+  public CacheRule cacheRule = new CacheRule();
+
+  @Rule
+  public ClientCacheRule clientCacheRule = new ClientCacheRule();
+
+  @Rule
+  public DistributedRestoreSystemProperties restoreSystemProperties =
+      new DistributedRestoreSystemProperties();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @Before
+  public void setUp() throws Exception {
+    server1 = getVM(0);
+    server2 = getVM(1);
+
+    regionName = getClass().getSimpleName() + "_" + testName.getMethodName();
+    hostName = getHostName();
+
+    int port1 = server1.invoke(() -> createCacheServer());
+    int port2 = server2.invoke(() -> createCacheServer());
+
+    createClientCache(port1, port2);
+  }
+
+  @Test
+  public void testThreadIdentifiersExpiry() throws Exception {
+    int puts = 10;
+
+    server1.invoke(() -> doPuts(puts));
+
+    server1.invoke(() -> verifyThreadsBeforeExpiration(1));
+    server2.invoke(() -> verifyThreadsBeforeExpiration(1));
+
+    server1.invoke(() -> awaitToVerifyStatsAfterExpiration(puts));
+    server2.invoke(() -> awaitToVerifyStatsAfterExpiration(puts));
+  }
+
+  private int createCacheServer() throws IOException {
+    System.setProperty(GEODE_PREFIX + HA_REGION_QUEUE_EXPIRY_TIME_PROPERTY, EXPIRY_TIME_SECONDS);
+    System.setProperty(GEODE_PREFIX + THREAD_ID_EXPIRY_TIME_PROPERTY, EXPIRY_TIME_SECONDS);
+
+    cacheRule.createCache();
+    cacheRule.getCache().setMessageSyncInterval(MESSAGE_SYNC_INTERVAL_SECONDS);
+
+    RegionFactory<String, String> rf = cacheRule.getCache().createRegionFactory(REPLICATE);
+    rf.create(regionName);
+
+    CacheServer server = cacheRule.getCache().addCacheServer();
+    server.setPort(0);
+    server.start();
+    return server.getPort();
+  }
+
+  private void createClientCache(int port1, int port2) {
+    ClientCacheFactory ccf = new ClientCacheFactory();
+    ccf.setPoolSubscriptionEnabled(true);
+    ccf.setPoolSubscriptionAckInterval(50);
+    ccf.setPoolSubscriptionRedundancy(1);
+    ccf.addPoolServer(hostName, port1);
+    ccf.addPoolServer(hostName, port2);
+
+    clientCacheRule.createClientCache(ccf);
+
+    ClientRegionFactory<String, String> crf =
+        clientCacheRule.getClientCache().createClientRegionFactory(CACHING_PROXY);
+
+    Region<String, String> region = crf.create(regionName);
+    region.registerInterest("ALL_KEYS");
+  }
+
+  private void doPuts(int puts) {
+    Region<String, String> region = cacheRule.getCache().getRegion(regionName);
+    for (int i = 1; i <= puts; i++) {
+      region.put("KEY-" + i, "VALUE-" + i);
+    }
+  }
+
+  private CacheClientProxy getCacheClientProxy() {
+    return CacheClientNotifier.getInstance().getClientProxies().iterator().next();
+  }
+
+  private boolean isPrimaryServer() {
+    return getCacheClientProxy().isPrimary();
+  }
+
+  private void verifyThreadsBeforeExpiration(int expectedThreadIds) {
+    HARegionQueueStats stats = getCacheClientProxy().getHARegionQueue().getStatistics();
+
+    int actualThreadIds = stats.getThreadIdentiferCount();
+
+    assertThat(actualThreadIds)
+        .as("Expected ThreadIdentifier count >= " + expectedThreadIds + " but actual: "
+            + actualThreadIds + (isPrimaryServer() ? " at primary." : " at secondary."))
+        .isGreaterThanOrEqualTo(expectedThreadIds);
+  }
+
+  private void awaitToVerifyStatsAfterExpiration(int numOfEvents) {
+    await().atMost(2, MINUTES).until(() -> {
+      verifyStatsAfterExpiration(numOfEvents);
+    });
+  }
+
+  private void verifyStatsAfterExpiration(int numOfEvents) {
+    HARegionQueueStats stats = getCacheClientProxy().getHARegionQueue().getStatistics();
+
+    long actualEventsExpired = stats.getEventsExpired();
+    long expectedEventsExpired = isPrimaryServer() ? 0 : numOfEvents;
+
+    assertThat(actualEventsExpired)
+        .as("Expected eventsExpired: " + expectedEventsExpired + " but actual eventsExpired: "
+            + actualEventsExpired + (isPrimaryServer() ? " at primary." : " at secondary."))
+        .isEqualTo(expectedEventsExpired);
+
+    int actualThreadIds = stats.getThreadIdentiferCount();
+
+    // Sometimes we may see 1 threadIdentifier due to slow machines, but never equal to
+    // expectedThreadIds
+    assertThat(actualThreadIds).as("Expected ThreadIdentifier count <= 1 but actual: "
+        + actualThreadIds + (isPrimaryServer() ? " at primary." : " at secondary.")).isEqualTo(0);
+  }
+}

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 03/13: GEODE-5058: Delete redundant DUnit tests with JUnit4 prefix

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit 83dd8fc2a0996ee04d89dfa5fb2c69ea9c3ef42e
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Thu Apr 12 12:00:32 2018 -0700

    GEODE-5058: Delete redundant DUnit tests with JUnit4 prefix
---
 .../test/dunit/tests/JUnit4BasicDUnitTest.java     | 243 ---------------------
 .../JUnit4GetDefaultDiskStoreNameDUnitTest.java    |  67 ------
 .../tests/JUnit4GetTestMethodNameDUnitTest.java    |  53 -----
 ...ridingGetPropertiesDisconnectsAllDUnitTest.java |  60 -----
 .../geode/test/dunit/tests/JUnit4VMDUnitTest.java  | 205 -----------------
 5 files changed, 628 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4BasicDUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4BasicDUnitTest.java
deleted file mode 100644
index d5edae7..0000000
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4BasicDUnitTest.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.test.dunit.tests;
-
-import static com.googlecode.catchexception.CatchException.*;
-import static com.googlecode.catchexception.throwable.CatchThrowable.*;
-import static org.apache.geode.test.dunit.Assert.*;
-import static org.apache.geode.test.dunit.Invoke.*;
-import static org.hamcrest.Matchers.*;
-
-import java.util.Properties;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.test.dunit.AsyncInvocation;
-import org.apache.geode.test.dunit.DUnitEnv;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.RMIException;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-/**
- * This class tests the basic functionality of the distributed unit test framework.
- */
-@Category(DistributedTest.class)
-@SuppressWarnings({"serial", "unused"})
-public class JUnit4BasicDUnitTest extends JUnit4DistributedTestCase {
-
-  private static final String MESSAGE_FOR_remoteThrowException = "Test exception.  Please ignore.";
-
-  private static Properties bindings;
-
-  private VM vm0;
-  private VM vm1;
-
-  @BeforeClass
-  public static void setUpJUnit4BasicDUnitTest() throws Exception {
-    invokeInEveryVM(() -> bindings = new Properties());
-  }
-
-  @Override
-  public final void postSetUp() throws Exception {
-    this.vm0 = Host.getHost(0).getVM(0);
-    this.vm1 = Host.getHost(0).getVM(1);
-  }
-
-  @AfterClass
-  public static void tearDownJUnit4BasicDUnitTest() {
-    invokeInEveryVM(() -> bindings = null);
-  }
-
-  @Test
-  public void testPreconditions() {
-    invokeInEveryVM(
-        () -> assertThat("getUniqueName() must not return null", getUniqueName(), notNullValue()));
-    invokeInEveryVM(() -> assertThat("bindings must not be null", bindings, notNullValue()));
-  }
-
-  @Test
-  public void testInvokeOnClassTargetWithEmptyArgs() throws Exception {
-    assertThat(this.vm0.invoke(JUnit4BasicDUnitTest.class, "booleanValue", new Object[] {}),
-        is(true));
-  }
-
-  @Test
-  public void testInvokeOnObjectTargetWithEmptyArgs() throws Exception {
-    assertThat(this.vm0.invoke(new JUnit4BasicDUnitTest(), "booleanValue", new Object[] {}),
-        is(true));
-  }
-
-  @Test
-  public void testInvokeAsyncOnClassTargetWithEmptyArgs() throws Exception {
-    AsyncInvocation<?> async =
-        this.vm0.invokeAsync(JUnit4BasicDUnitTest.class, "booleanValue", new Object[] {}).join();
-    assertThat(async.getResult(), is(true));
-  }
-
-  @Test
-  public void testInvokeAsyncOnObjectTargetWithEmptyArgs() throws Exception {
-    AsyncInvocation<?> async =
-        this.vm0.invokeAsync(new JUnit4BasicDUnitTest(), "booleanValue", new Object[] {}).join();
-    assertThat(async.getResult(), is(true));
-  }
-
-  @Test
-  public void testInvokeOnClassTargetWithNullArgs() throws Exception {
-    assertThat(this.vm0.invoke(JUnit4BasicDUnitTest.class, "booleanValue", null), is(true));
-  }
-
-  @Test
-  public void testInvokeOnObjectTargetWithNullArgs() throws Exception {
-    assertThat(this.vm0.invoke(new JUnit4BasicDUnitTest(), "booleanValue", null), is(true));
-  }
-
-  @Test
-  public void testInvokeAsyncOnClassTargetWithNullArgs() throws Exception {
-    AsyncInvocation<?> async =
-        this.vm0.invokeAsync(JUnit4BasicDUnitTest.class, "booleanValue", null).join();
-    assertThat(async.getResult(), is(true));
-  }
-
-  @Test
-  public void testInvokeAsyncOnObjectTargetWithNullArgs() throws Exception {
-    AsyncInvocation<?> async =
-        this.vm0.invokeAsync(new JUnit4BasicDUnitTest(), "booleanValue", null).join();
-    assertThat(async.getResult(), is(true));
-  }
-
-  @Test
-  public void testRemoteInvocationWithException() throws Exception {
-    catchException(this.vm0).invoke(() -> remoteThrowException());
-
-    assertThat(caughtException(), instanceOf(RMIException.class));
-    assertThat(caughtException().getCause(), notNullValue());
-    assertThat(caughtException().getCause(), instanceOf(BasicTestException.class));
-    assertThat(caughtException().getCause().getMessage(), is(MESSAGE_FOR_remoteThrowException));
-  }
-
-  @Test
-  public void testInvokeWithLambda() throws Exception {
-    assertThat(this.vm0.invoke(() -> DUnitEnv.get().getVMID()), is(0));
-    assertThat(this.vm1.invoke(() -> DUnitEnv.get().getVMID()), is(1));
-  }
-
-  @Test
-  public void testInvokeLambdaAsync() throws Throwable {
-    assertThat(this.vm0.invokeAsync(() -> DUnitEnv.get().getVMID()).getResult(), is(0));
-  }
-
-  @Test
-  public void testInvokeWithNamedLambda() {
-    assertThat(this.vm0.invoke("getVMID", () -> DUnitEnv.get().getVMID()), is(0));
-    assertThat(this.vm1.invoke("getVMID", () -> DUnitEnv.get().getVMID()), is(1));
-  }
-
-  @Test
-  public void testInvokeNamedLambdaAsync() throws Throwable {
-    assertThat(this.vm0.invokeAsync("getVMID", () -> DUnitEnv.get().getVMID()).getResult(), is(0));
-  }
-
-  @Test
-  public void testRemoteInvokeAsync() throws Exception {
-    String name = getUniqueName();
-    String value = "Hello";
-
-    this.vm0.invokeAsync(() -> remoteBind(name, value)).join().checkException();
-    this.vm0.invokeAsync(() -> remoteValidateBind(name, value)).join().checkException();
-  }
-
-  @Test
-  public void testRemoteInvokeAsyncWithException() throws Exception {
-    AsyncInvocation<?> async = this.vm0.invokeAsync(() -> remoteThrowException()).join();
-
-    assertThat(async.exceptionOccurred(), is(true));
-    assertThat(async.getException(), instanceOf(BasicTestException.class));
-
-    catchThrowable(async).checkException();
-
-    assertThat(caughtThrowable(), instanceOf(AssertionError.class));
-    assertThat(caughtThrowable().getCause(), notNullValue());
-    assertThat(caughtThrowable().getCause(), instanceOf(BasicTestException.class));
-    assertThat(caughtThrowable().getCause().getMessage(), is(MESSAGE_FOR_remoteThrowException));
-  }
-
-  @Test
-  public void testInvokeNamedRunnableLambdaAsync() throws Exception {
-    catchThrowable(this.vm0.invokeAsync("throwSomething", () -> throwException()).join())
-        .checkException();
-
-    assertThat(caughtThrowable(), notNullValue());
-    assertThat(caughtThrowable().getCause(), notNullValue());
-    assertThat(caughtThrowable().getCause(), instanceOf(BasicDUnitException.class));
-  }
-
-  @Test
-  public void testInvokeNamedRunnableLambda() throws Exception {
-    catchException(this.vm0).invoke("throwSomething", () -> throwException());
-
-    assertThat(caughtException(), notNullValue());
-    assertThat(caughtException().getCause(), notNullValue());
-    assertThat(caughtException().getCause(), instanceOf(BasicDUnitException.class));
-    assertThat(caughtException().getCause().getMessage(), nullValue());
-  }
-
-  private static boolean booleanValue() { // invoked by reflection
-    return true;
-  }
-
-  private static boolean booleanValue(final boolean value) { // invoked by reflection
-    return value;
-  }
-
-  private static void remoteThrowException() {
-    throw new BasicTestException(MESSAGE_FOR_remoteThrowException);
-  }
-
-  private static void throwException() throws BasicDUnitException {
-    throw new BasicDUnitException();
-  }
-
-  private static void remoteBind(String name, String value) {
-    assertNotNull("name must not be null", name);
-    assertNotNull("value must not be null", value);
-    assertNotNull("bindings must not be null", bindings);
-
-    new JUnit4BasicDUnitTest().getSystem(); // forces connection
-    bindings.setProperty(name, value);
-  }
-
-  private static void remoteValidateBind(String name, String expected) {
-    assertEquals(expected, bindings.getProperty(name));
-  }
-
-  private static class BasicTestException extends RuntimeException {
-    BasicTestException() {
-      this("Test exception.  Please ignore.");
-    }
-
-    BasicTestException(String s) {
-      super(s);
-    }
-  }
-
-  private static class BasicDUnitException extends RuntimeException {
-    public BasicDUnitException() {}
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4GetDefaultDiskStoreNameDUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4GetDefaultDiskStoreNameDUnitTest.java
deleted file mode 100644
index c8cd900..0000000
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4GetDefaultDiskStoreNameDUnitTest.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.test.dunit.tests;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-@Category(DistributedTest.class)
-@SuppressWarnings("serial")
-public class JUnit4GetDefaultDiskStoreNameDUnitTest extends JUnit4DistributedTestCase {
-
-  @Test
-  public void testGetTestMethodName() {
-    String expected = createDefaultDiskStoreName(0, -1, "testGetTestMethodName");
-    assertGetDefaultDiskStoreName(expected);
-  }
-
-  @Test
-  public void testGetTestMethodNameChanges() {
-    String expected = createDefaultDiskStoreName(0, -1, "testGetTestMethodNameChanges");
-    assertGetDefaultDiskStoreName(expected);
-  }
-
-  @Test
-  public void testGetTestMethodNameInAllVMs() {
-    String expected = createDefaultDiskStoreName(0, -1, "testGetTestMethodNameInAllVMs");
-    assertGetDefaultDiskStoreName(expected);
-
-    for (int vmIndex = 0; vmIndex < Host.getHost(0).getVMCount(); vmIndex++) {
-      String expectedInVM = createDefaultDiskStoreName(0, vmIndex, "testGetTestMethodNameInAllVMs");
-      Host.getHost(0).getVM(vmIndex).invoke(() -> assertGetDefaultDiskStoreName(expectedInVM));
-    }
-  }
-
-  private void assertGetDefaultDiskStoreName(final String expected) {
-    assertThat(getDefaultDiskStoreName()).isEqualTo(expected);
-  }
-
-  private String createDefaultDiskStoreName(final int hostIndex, final int vmIndex,
-      final String methodName) {
-    return "DiskStore-" + hostIndex + "-" + vmIndex + "-" + getClass().getCanonicalName() + "."
-        + methodName;
-  }
-
-  private String getDefaultDiskStoreName() {
-    return GemFireCacheImpl.getDefaultDiskStoreName(); // TODO: not thread safe
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4GetTestMethodNameDUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4GetTestMethodNameDUnitTest.java
deleted file mode 100644
index e88ec6f..0000000
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4GetTestMethodNameDUnitTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.test.dunit.tests;
-
-import static org.assertj.core.api.Assertions.*;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-@Category(DistributedTest.class)
-@SuppressWarnings("serial")
-public class JUnit4GetTestMethodNameDUnitTest extends JUnit4DistributedTestCase {
-
-  @Test
-  public void testGetTestMethodName() {
-    assertGetTestMethodName("testGetTestMethodName");
-  }
-
-  @Test
-  public void testGetTestMethodNameChanges() {
-    assertGetTestMethodName("testGetTestMethodNameChanges");
-  }
-
-  @Test
-  public void testGetTestMethodNameInAllVMs() {
-    assertGetTestMethodName("testGetTestMethodNameInAllVMs");
-
-    for (int vmIndex = 0; vmIndex < Host.getHost(0).getVMCount(); vmIndex++) {
-      Host.getHost(0).getVM(vmIndex)
-          .invoke(() -> assertGetTestMethodName("testGetTestMethodNameInAllVMs"));
-    }
-  }
-
-  private void assertGetTestMethodName(final String expected) {
-    assertThat(getTestMethodName()).isEqualTo(expected);
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4OverridingGetPropertiesDisconnectsAllDUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4OverridingGetPropertiesDisconnectsAllDUnitTest.java
deleted file mode 100644
index df6c35d..0000000
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4OverridingGetPropertiesDisconnectsAllDUnitTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.test.dunit.tests;
-
-import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
-import static org.apache.geode.test.dunit.Assert.*;
-import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
-
-import java.util.Properties;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-/**
- * Verifies that overriding {@code getDistributedSystemProperties} results in
- * {@code disconnectAllFromDS} during tear down.
- */
-@Category(DistributedTest.class)
-@SuppressWarnings("serial")
-public class JUnit4OverridingGetPropertiesDisconnectsAllDUnitTest
-    extends JUnit4DistributedTestCase {
-
-  @Override
-  public final void preTearDownAssertions() throws Exception {
-    invokeInEveryVM(() -> assertNotNull(basicGetSystem()));
-  }
-
-  @Override
-  public final void postTearDownAssertions() throws Exception {
-    invokeInEveryVM(() -> assertNull(basicGetSystem()));
-  }
-
-  @Override
-  public final Properties getDistributedSystemProperties() {
-    Properties props = new Properties();
-    props.setProperty(MCAST_PORT, "0");
-    return props;
-  }
-
-  @Test
-  public void testDisconnects() throws Exception {
-    invokeInEveryVM(() -> assertFalse(getDistributedSystemProperties().isEmpty()));
-    invokeInEveryVM(() -> assertNotNull(getSystem()));
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4VMDUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4VMDUnitTest.java
deleted file mode 100644
index 1538355..0000000
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/JUnit4VMDUnitTest.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.test.dunit.tests;
-
-import static org.apache.geode.test.dunit.Assert.*;
-
-import java.io.Serializable;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.test.dunit.AsyncInvocation;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.RMIException;
-import org.apache.geode.test.dunit.SerializableRunnableIF;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-/**
- * This class tests the functionality of the {@link VM} class.
- */
-@Category(DistributedTest.class)
-@SuppressWarnings("serial")
-public class JUnit4VMDUnitTest extends JUnit4DistributedTestCase {
-
-  private static final AtomicInteger COUNTER = new AtomicInteger();
-  private static final boolean BOOLEAN_VALUE = true;
-  private static final byte BYTE_VALUE = (byte) 40;
-  private static final long LONG_VALUE = 42L;
-  private static final String STRING_VALUE = "BLAH BLAH BLAH";
-
-  @Test
-  public void testInvokeStaticBoolean() {
-    Host host = Host.getHost(0);
-    VM vm = host.getVM(0);
-    assertEquals(BOOLEAN_VALUE, (boolean) vm.invoke(() -> remoteBooleanMethod()));
-  }
-
-  @Test
-  public void testInvokeStaticByte() {
-    Host host = Host.getHost(0);
-    VM vm = host.getVM(0);
-    assertEquals(BYTE_VALUE, (byte) vm.invoke(() -> remoteByteMethod()));
-  }
-
-  @Test
-  public void testInvokeStaticLong() {
-    Host host = Host.getHost(0);
-    VM vm = host.getVM(0);
-    assertEquals(LONG_VALUE, (long) vm.invoke(() -> remoteLongMethod()));
-  }
-
-  @Test
-  public void testInvokeInstance() {
-    Host host = Host.getHost(0);
-    VM vm = host.getVM(0);
-    assertEquals(STRING_VALUE, vm.invoke(new ClassWithString(), "getString"));
-  }
-
-  @Test
-  public void testInvokeRunnableWithException() {
-    Host host = Host.getHost(0);
-    VM vm = host.getVM(0);
-    try {
-      vm.invoke(new InvokeRunnable());
-      fail("Should have thrown a BasicTestException");
-    } catch (RMIException ex) {
-      assertTrue(ex.getCause() instanceof BasicTestException);
-    }
-  }
-
-  @Test
-  public void testReturnValue() throws Exception {
-    final Host host = Host.getHost(0);
-    final VM vm = host.getVM(0);
-    // Assert class static invocation works
-    AsyncInvocation a1 = vm.invokeAsync(() -> getAndIncStaticCount());
-    a1.join();
-    assertEquals(new Integer(0), a1.getReturnValue());
-    // Assert class static invocation with args works
-    a1 = vm.invokeAsync(() -> incrementStaticCount(new Integer(2)));
-    a1.join();
-    assertEquals(new Integer(3), a1.getReturnValue());
-    // Assert that previous values are not returned when invoking method w/ no return val
-    a1 = vm.invokeAsync(() -> incStaticCount());
-    a1.join();
-    assertNull(a1.getReturnValue());
-    // Assert that previous null returns are over-written
-    a1 = vm.invokeAsync(() -> getAndIncStaticCount());
-    a1.join();
-    assertEquals(new Integer(4), a1.getReturnValue());
-
-    // Assert object method invocation works with zero arg method
-    final VMTestObject o = new VMTestObject(0);
-    a1 = vm.invokeAsync(o, "incrementAndGet", new Object[] {});
-    a1.join();
-    assertEquals(new Integer(1), a1.getReturnValue());
-    // Assert object method invocation works with no return
-    a1 = vm.invokeAsync(o, "set", new Object[] {new Integer(3)});
-    a1.join();
-    assertNull(a1.getReturnValue());
-  }
-
-  private static Integer getAndIncStaticCount() {
-    return new Integer(COUNTER.getAndIncrement());
-  }
-
-  private static Integer incrementStaticCount(Integer inc) {
-    return new Integer(COUNTER.addAndGet(inc.intValue()));
-  }
-
-  private static void incStaticCount() {
-    COUNTER.incrementAndGet();
-  }
-
-  /**
-   * Accessed via reflection. DO NOT REMOVE
-   */
-  private static byte remoteByteMethod() {
-    return BYTE_VALUE;
-  }
-
-  /**
-   * Accessed via reflection. DO NOT REMOVE
-   */
-  private static boolean remoteBooleanMethod() {
-    return BOOLEAN_VALUE;
-  }
-
-  /**
-   * Accessed via reflection. DO NOT REMOVE
-   */
-  private static long remoteLongMethod() {
-    return LONG_VALUE;
-  }
-
-  private static class ClassWithLong implements Serializable {
-    public long getLong() {
-      return LONG_VALUE;
-    }
-  }
-
-  private static class ClassWithByte implements Serializable {
-    public byte getByte() {
-      return BYTE_VALUE;
-    }
-  }
-
-  private static class InvokeRunnable implements SerializableRunnableIF {
-    public void run() {
-      throw new BasicTestException();
-    }
-  }
-
-  private static class ClassWithString implements Serializable {
-    public String getString() {
-      return STRING_VALUE;
-    }
-  }
-
-  private static class BasicTestException extends RuntimeException {
-    BasicTestException() {
-      this("Test exception.  Please ignore.");
-    }
-
-    BasicTestException(String s) {
-      super(s);
-    }
-  }
-
-  private static class VMTestObject implements Serializable {
-    private static final long serialVersionUID = 1L;
-    private final AtomicInteger val;
-
-    public VMTestObject(int init) {
-      this.val = new AtomicInteger(init);
-    }
-
-    public Integer get() {
-      return new Integer(this.val.get());
-    }
-
-    public Integer incrementAndGet() {
-      return new Integer(this.val.incrementAndGet());
-    }
-
-    public void set(Integer newVal) {
-      this.val.set(newVal.intValue());
-    }
-  }
-}

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 07/13: GEODE-5033: Use DistributedTestRule as non-static Rule

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit 46b8dde012cc619eac61ae8038eb61b9d37896e1
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Thu Apr 12 12:57:36 2018 -0700

    GEODE-5033: Use DistributedTestRule as non-static Rule
    
    * rename *DUnitTest to *DistributedTest
    * replace Host.getVM with VM.getVM
---
 .../dunit/internal/JUnit4DistributedTestCase.java  | 60 +----------------
 .../test/dunit/rules/DistributedTestRule.java      |  2 +-
 .../tests/CacheRuleBuilderDistributedTest.java     |  5 +-
 .../rules/tests/CacheRuleDistributedTest.java      |  5 +-
 ...utedRestoreSystemPropertiesDistributedTest.java | 39 +++++------
 .../DistributedRestoreSystemPropertiesTest.java    | 56 ----------------
 .../tests/DistributedTestRuleDistributedTest.java  |  9 +--
 .../tests/SharedCountersRuleDistributedTest.java   |  5 +-
 .../tests/SharedErrorCollectorDistributedTest.java | 12 +++-
 ...sicDUnitTest.java => BasicDistributedTest.java} | 76 ++++++++++++----------
 .../tests/GetCurrentVmNumDistributedTest.java      |  6 +-
 ...=> GetDefaultDiskStoreNameDistributedTest.java} | 13 ++--
 .../GetPidAndIdAfterBounceDistributedTest.java     |  6 +-
 .../dunit/tests/GetPidAndIdDistributedTest.java    |  6 +-
 ....java => GetTestMethodNameDistributedTest.java} | 12 ++--
 ...etPropertiesDisconnectsAllDistributedTest.java} | 16 +++--
 .../{VMDUnitTest.java => VMDistributedTest.java}   | 24 +++----
 17 files changed, 127 insertions(+), 225 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java b/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
index 4790e87..d174d9a 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
@@ -43,40 +43,20 @@ import org.junit.Rule;
 
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.Region;
-import org.apache.geode.cache.query.QueryTestUtils;
-import org.apache.geode.cache.query.internal.QueryObserverHolder;
-import org.apache.geode.cache30.ClientServerTestCase;
-import org.apache.geode.cache30.GlobalLockingDUnitTest;
-import org.apache.geode.cache30.MultiVMRegionTestCase;
-import org.apache.geode.cache30.RegionTestCase;
 import org.apache.geode.distributed.DistributedSystem;
 import org.apache.geode.distributed.internal.DistributionConfig;
 import org.apache.geode.distributed.internal.DistributionMessageObserver;
 import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.distributed.internal.tcpserver.TcpClient;
 import org.apache.geode.internal.Version;
-import org.apache.geode.internal.admin.ClientStatsManager;
-import org.apache.geode.internal.cache.CacheServerLauncher;
-import org.apache.geode.internal.cache.DiskStoreObserver;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.cache.HARegion;
-import org.apache.geode.internal.cache.InitialImageOperation;
 import org.apache.geode.internal.cache.PartitionedRegion;
-import org.apache.geode.internal.cache.tier.InternalClientMembership;
-import org.apache.geode.internal.cache.tier.sockets.CacheServerTestUtil;
-import org.apache.geode.internal.cache.tier.sockets.ClientProxyMembershipID;
-import org.apache.geode.internal.cache.tier.sockets.Message;
-import org.apache.geode.internal.cache.xmlcache.CacheCreation;
 import org.apache.geode.internal.logging.LogService;
-import org.apache.geode.internal.net.SocketCreator;
-import org.apache.geode.internal.net.SocketCreatorFactory;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.pdx.internal.TypeRegistry;
 import org.apache.geode.test.dunit.DUnitBlackboard;
 import org.apache.geode.test.dunit.Disconnect;
 import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.IgnoredException;
 import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
+import org.apache.geode.test.dunit.rules.DistributedTestRule;
 import org.apache.geode.test.dunit.standalone.DUnitLauncher;
 import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
 
@@ -584,43 +564,7 @@ public abstract class JUnit4DistributedTestCase implements DistributedTestFixtur
 
   private static final void tearDownVM() {
     closeCache();
-    disconnectFromDS();
-
-    // keep alphabetized to detect duplicate lines
-    CacheCreation.clearThreadLocals();
-    CacheServerLauncher.clearStatics();
-    CacheServerTestUtil.clearCacheReference();
-    ClientProxyMembershipID.system = null;
-    ClientServerTestCase.AUTO_LOAD_BALANCE = false;
-    ClientStatsManager.cleanupForTests();
-    DiskStoreObserver.setInstance(null);
-    unregisterInstantiatorsInThisVM();
-    DistributionMessageObserver.setInstance(null);
-    GlobalLockingDUnitTest.region_testBug32356 = null;
-    InitialImageOperation.slowImageProcessing = 0;
-    InternalClientMembership.unregisterAllListeners();
-    LogWrapper.close();
-    MultiVMRegionTestCase.CCRegion = null;
-    QueryObserverHolder.reset();
-    QueryTestUtils.setCache(null);
-    RegionTestCase.preSnapshotRegion = null;
-    SocketCreator.resetHostNameCache();
-    SocketCreator.resolve_dns = true;
-    TcpClient.clearStaticData();
-
-    // clear system properties -- keep alphabetized
-    System.clearProperty(DistributionConfig.GEMFIRE_PREFIX + "log-level");
-    System.clearProperty("jgroups.resolve_dns");
-    System.clearProperty(Message.MAX_MESSAGE_SIZE_PROPERTY);
-
-    if (InternalDistributedSystem.systemAttemptingReconnect != null) {
-      InternalDistributedSystem.systemAttemptingReconnect.stopReconnecting();
-    }
-
-    IgnoredException.removeAllExpectedExceptions();
-    SocketCreatorFactory.close();
-    TypeRegistry.setPdxSerializer(null);
-    TypeRegistry.init();
+    DistributedTestRule.TearDown.tearDownInVM();
     cleanDiskDirs();
   }
 
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
index 5dcb1e5..1b7394e 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
@@ -195,7 +195,7 @@ public class DistributedTestRule extends AbstractDistributedTestRule {
       DUnitLauncher.closeAndCheckForSuspects();
     }
 
-    private static void tearDownInVM() {
+    public static void tearDownInVM() {
       // 1. Please do NOT add to this list. I'm trying to DELETE this list.
       // 2. Instead, please add to the after() of your test or your rule.
 
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/CacheRuleBuilderDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/CacheRuleBuilderDistributedTest.java
index 72c3f11..b826eeb 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/CacheRuleBuilderDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/CacheRuleBuilderDistributedTest.java
@@ -24,7 +24,6 @@ import static org.assertj.core.api.Assertions.assertThat;
 import java.io.Serializable;
 import java.util.Properties;
 
-import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -39,8 +38,8 @@ import org.apache.geode.test.junit.categories.DistributedTest;
 @SuppressWarnings("serial")
 public class CacheRuleBuilderDistributedTest {
 
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
 
   @Test
   public void defaultDoesNothing() throws Exception {
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/CacheRuleDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/CacheRuleDistributedTest.java
index a4748e5..41fbda9 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/CacheRuleDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/CacheRuleDistributedTest.java
@@ -24,7 +24,6 @@ import java.io.Serializable;
 import java.util.Properties;
 
 import org.junit.Before;
-import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -39,8 +38,8 @@ import org.apache.geode.test.junit.categories.DistributedTest;
 @SuppressWarnings("serial")
 public class CacheRuleDistributedTest {
 
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
 
   @Test
   public void defaultDoesNothing() throws Exception {
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedRestoreSystemPropertiesDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedRestoreSystemPropertiesDistributedTest.java
index 5179644..3cb7238 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedRestoreSystemPropertiesDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedRestoreSystemPropertiesDistributedTest.java
@@ -14,7 +14,8 @@
  */
 package org.apache.geode.test.dunit.rules.tests;
 
-import static org.apache.geode.test.dunit.Host.getHost;
+import static org.apache.geode.test.dunit.VM.getVM;
+import static org.apache.geode.test.dunit.VM.getVMCount;
 import static org.apache.geode.test.junit.runners.TestRunner.runTestWithValidation;
 import static org.assertj.core.api.Assertions.assertThat;
 
@@ -46,8 +47,8 @@ public class DistributedRestoreSystemPropertiesDistributedTest {
   public static void assertPreconditions() {
     assertThat(System.getProperty(NULL_PROPERTY)).isNull();
     assertThat(System.getProperty(PREEXISTING_PROPERTY)).isNull();
-    for (int i = 0; i < 4; i++) {
-      getHost(0).getVM(i).invoke(() -> {
+    for (int i = 0; i < getVMCount(); i++) {
+      getVM(i).invoke(() -> {
         assertThat(System.getProperty(NULL_PROPERTY)).isNull();
         assertThat(System.getProperty(PREEXISTING_PROPERTY)).isNull();
       });
@@ -57,8 +58,8 @@ public class DistributedRestoreSystemPropertiesDistributedTest {
   @Before
   public void setUp() {
     System.setProperty(PREEXISTING_PROPERTY, PREEXISTING_VALUE);
-    for (int i = 0; i < 4; i++) {
-      getHost(0).getVM(i).invoke(() -> {
+    for (int i = 0; i < getVMCount(); i++) {
+      getVM(i).invoke(() -> {
         System.setProperty(PREEXISTING_PROPERTY, PREEXISTING_VALUE);
       });
     }
@@ -67,8 +68,8 @@ public class DistributedRestoreSystemPropertiesDistributedTest {
   @After
   public void tearDown() {
     System.clearProperty(PREEXISTING_PROPERTY);
-    for (int i = 0; i < 4; i++) {
-      getHost(0).getVM(i).invoke(() -> {
+    for (int i = 0; i < getVMCount(); i++) {
+      getVM(i).invoke(() -> {
         System.clearProperty(PREEXISTING_PROPERTY);
       });
     }
@@ -79,8 +80,8 @@ public class DistributedRestoreSystemPropertiesDistributedTest {
     runTestWithValidation(NullPropertyWithDifferentValues.class);
 
     assertThat(System.getProperty(NULL_PROPERTY)).isNull();
-    for (int i = 0; i < 4; i++) {
-      getHost(0).getVM(i).invoke(() -> {
+    for (int i = 0; i < getVMCount(); i++) {
+      getVM(i).invoke(() -> {
         assertThat(System.getProperty(NULL_PROPERTY)).isNull();
       });
     }
@@ -91,8 +92,8 @@ public class DistributedRestoreSystemPropertiesDistributedTest {
     runTestWithValidation(NullPropertyWithDifferentValues.class);
 
     assertThat(System.getProperty(PREEXISTING_PROPERTY)).isEqualTo(PREEXISTING_VALUE);
-    for (int i = 0; i < 4; i++) {
-      getHost(0).getVM(i).invoke(() -> {
+    for (int i = 0; i < getVMCount(); i++) {
+      getVM(i).invoke(() -> {
         assertThat(System.getProperty(PREEXISTING_PROPERTY)).isEqualTo(PREEXISTING_VALUE);
       });
     }
@@ -110,10 +111,10 @@ public class DistributedRestoreSystemPropertiesDistributedTest {
     @Test
     public void nullPropertyWithDifferentValues() throws Exception {
       System.setProperty(NULL_PROPERTY, "controller");
-      getHost(0).getVM(0).invoke(() -> System.setProperty(NULL_PROPERTY, "vm0"));
-      getHost(0).getVM(1).invoke(() -> System.setProperty(NULL_PROPERTY, "vm1"));
-      getHost(0).getVM(2).invoke(() -> System.setProperty(NULL_PROPERTY, "vm2"));
-      getHost(0).getVM(3).invoke(() -> System.setProperty(NULL_PROPERTY, "vm3"));
+      getVM(0).invoke(() -> System.setProperty(NULL_PROPERTY, "vm0"));
+      getVM(1).invoke(() -> System.setProperty(NULL_PROPERTY, "vm1"));
+      getVM(2).invoke(() -> System.setProperty(NULL_PROPERTY, "vm2"));
+      getVM(3).invoke(() -> System.setProperty(NULL_PROPERTY, "vm3"));
     }
   }
 
@@ -129,10 +130,10 @@ public class DistributedRestoreSystemPropertiesDistributedTest {
     @Test
     public void preexistingPropertyWithDifferentValues() throws Exception {
       System.setProperty(PREEXISTING_PROPERTY, "controller");
-      getHost(0).getVM(0).invoke(() -> System.setProperty(PREEXISTING_PROPERTY, "vm0"));
-      getHost(0).getVM(1).invoke(() -> System.setProperty(PREEXISTING_PROPERTY, "vm1"));
-      getHost(0).getVM(2).invoke(() -> System.setProperty(PREEXISTING_PROPERTY, "vm2"));
-      getHost(0).getVM(3).invoke(() -> System.setProperty(PREEXISTING_PROPERTY, "vm3"));
+      getVM(0).invoke(() -> System.setProperty(PREEXISTING_PROPERTY, "vm0"));
+      getVM(1).invoke(() -> System.setProperty(PREEXISTING_PROPERTY, "vm1"));
+      getVM(2).invoke(() -> System.setProperty(PREEXISTING_PROPERTY, "vm2"));
+      getVM(3).invoke(() -> System.setProperty(PREEXISTING_PROPERTY, "vm3"));
     }
   }
 }
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedRestoreSystemPropertiesTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedRestoreSystemPropertiesTest.java
deleted file mode 100644
index 01793e9..0000000
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedRestoreSystemPropertiesTest.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.test.dunit.rules.tests;
-
-import static org.apache.geode.test.junit.runners.TestRunner.runTestWithExpectedFailure;
-import static org.assertj.core.api.Assertions.assertThat;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.contrib.java.lang.system.RestoreSystemProperties;
-import org.junit.experimental.categories.Category;
-import org.junit.runner.notification.Failure;
-
-import org.apache.geode.test.dunit.rules.DistributedRestoreSystemProperties;
-import org.apache.geode.test.junit.categories.UnitTest;
-
-@Category(UnitTest.class)
-public class DistributedRestoreSystemPropertiesTest {
-
-  @Test
-  public void withoutDUnitThrowsIllegalStateException() {
-    Failure failure = runTestWithExpectedFailure(WithoutDUnit.class);
-    assertThat(failure.getException()).isInstanceOf(IllegalStateException.class);
-    assertThat(failure.getMessage()).isEqualTo("DUnit VMs have not been launched");
-  }
-
-  @Test
-  public void isaRestoreSystemProperties() {
-    assertThat(new DistributedRestoreSystemProperties())
-        .isInstanceOf(RestoreSystemProperties.class);
-  }
-
-  public static class WithoutDUnit {
-
-    @Rule
-    public DistributedRestoreSystemProperties restoreSystemProperties =
-        new DistributedRestoreSystemProperties();
-
-    @Test
-    public void doTest() {
-      // nothing
-    }
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleDistributedTest.java
index 18ad269..0ad4c30 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleDistributedTest.java
@@ -14,10 +14,11 @@
  */
 package org.apache.geode.test.dunit.rules.tests;
 
+import static org.apache.geode.test.dunit.VM.DEFAULT_VM_COUNT;
 import static org.apache.geode.test.dunit.VM.getVMCount;
 import static org.assertj.core.api.Assertions.assertThat;
 
-import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -27,11 +28,11 @@ import org.apache.geode.test.junit.categories.DistributedTest;
 @Category(DistributedTest.class)
 public class DistributedTestRuleDistributedTest {
 
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
 
   @Test
   public void shouldHaveFourOrMoreDUnitVMsByDefault() throws Exception {
-    assertThat(getVMCount()).isGreaterThanOrEqualTo(4);
+    assertThat(getVMCount()).isGreaterThanOrEqualTo(DEFAULT_VM_COUNT);
   }
 }
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/SharedCountersRuleDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/SharedCountersRuleDistributedTest.java
index f8778e1..09263f5 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/SharedCountersRuleDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/SharedCountersRuleDistributedTest.java
@@ -29,7 +29,6 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 
 import com.google.common.base.Stopwatch;
-import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -50,8 +49,8 @@ public class SharedCountersRuleDistributedTest implements Serializable {
   private static CompletableFuture<Void> combined;
   private static List<CompletableFuture<Boolean>> futures;
 
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
 
   @Rule
   public SharedCountersRule sharedCountersRule = SharedCountersRule.builder().build();
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/SharedErrorCollectorDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/SharedErrorCollectorDistributedTest.java
index 4f40724..4af8fa5 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/SharedErrorCollectorDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/SharedErrorCollectorDistributedTest.java
@@ -14,6 +14,7 @@
  */
 package org.apache.geode.test.dunit.rules.tests;
 
+import static org.apache.geode.test.dunit.VM.DEFAULT_VM_COUNT;
 import static org.apache.geode.test.dunit.VM.getAllVMs;
 import static org.apache.geode.test.dunit.VM.getVM;
 import static org.apache.geode.test.dunit.VM.getVMCount;
@@ -24,7 +25,7 @@ import java.io.Serializable;
 import java.lang.reflect.Field;
 import java.util.List;
 
-import org.junit.ClassRule;
+import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
@@ -44,8 +45,13 @@ public class SharedErrorCollectorDistributedTest {
 
   static final String MESSAGE = "Failure message";
 
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
+
+  @Before
+  public void setUp() {
+    assertThat(getVMCount()).isGreaterThanOrEqualTo(DEFAULT_VM_COUNT);
+  }
 
   @Test
   public void errorCollectorHasExpectedField() throws Exception {
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/BasicDUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/BasicDistributedTest.java
similarity index 70%
rename from geode-core/src/test/java/org/apache/geode/test/dunit/tests/BasicDUnitTest.java
rename to geode-core/src/test/java/org/apache/geode/test/dunit/tests/BasicDistributedTest.java
index 2364340..17c2c10 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/BasicDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/BasicDistributedTest.java
@@ -14,11 +14,18 @@
  */
 package org.apache.geode.test.dunit.tests;
 
-import static com.googlecode.catchexception.CatchException.*;
-import static com.googlecode.catchexception.throwable.CatchThrowable.*;
-import static org.apache.geode.test.dunit.Invoke.*;
-import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.*;
+import static com.googlecode.catchexception.CatchException.catchException;
+import static com.googlecode.catchexception.CatchException.caughtException;
+import static com.googlecode.catchexception.throwable.CatchThrowable.catchThrowable;
+import static com.googlecode.catchexception.throwable.CatchThrowable.caughtThrowable;
+import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
 
 import java.util.Properties;
 
@@ -37,8 +44,8 @@ import org.apache.geode.test.junit.categories.DistributedTest;
  * This class tests the basic functionality of the distributed unit test framework.
  */
 @Category(DistributedTest.class)
-@SuppressWarnings({"serial", "unused"})
-public class BasicDUnitTest extends DistributedTestCase {
+@SuppressWarnings("serial")
+public class BasicDistributedTest extends DistributedTestCase {
 
   private static final String MESSAGE_FOR_remoteThrowException = "Test exception.  Please ignore.";
 
@@ -47,16 +54,12 @@ public class BasicDUnitTest extends DistributedTestCase {
   private VM vm0;
   private VM vm1;
 
-  public BasicDUnitTest() {
-    super();
-  }
-
   @Override
   public final void postSetUp() throws Exception {
     bindings = new Properties();
     invokeInEveryVM(() -> bindings = new Properties());
-    this.vm0 = Host.getHost(0).getVM(0);
-    this.vm1 = Host.getHost(0).getVM(1);
+    vm0 = Host.getHost(0).getVM(0);
+    vm1 = Host.getHost(0).getVM(1);
   }
 
   @Override
@@ -74,55 +77,55 @@ public class BasicDUnitTest extends DistributedTestCase {
 
   @Test
   public void testInvokeOnClassTargetWithEmptyArgs() throws Exception {
-    assertThat(this.vm0.invoke(BasicDUnitTest.class, "booleanValue", new Object[] {}), is(true));
+    assertThat(vm0.invoke(BasicDistributedTest.class, "booleanValue", new Object[] {}), is(true));
   }
 
   @Test
   public void testInvokeOnObjectTargetWithEmptyArgs() throws Exception {
-    assertThat(this.vm0.invoke(new BasicDUnitTest(), "booleanValue", new Object[] {}), is(true));
+    assertThat(vm0.invoke(new BasicDistributedTest(), "booleanValue", new Object[] {}), is(true));
   }
 
   @Test
   public void testInvokeAsyncOnClassTargetWithEmptyArgs() throws Exception {
     AsyncInvocation<?> async =
-        this.vm0.invokeAsync(BasicDUnitTest.class, "booleanValue", new Object[] {}).join();
+        vm0.invokeAsync(BasicDistributedTest.class, "booleanValue", new Object[] {}).join();
     assertThat(async.getResult(), is(true));
   }
 
   @Test
   public void testInvokeAsyncOnObjectTargetWithEmptyArgs() throws Exception {
     AsyncInvocation<?> async =
-        this.vm0.invokeAsync(new BasicDUnitTest(), "booleanValue", new Object[] {}).join();
+        vm0.invokeAsync(new BasicDistributedTest(), "booleanValue", new Object[] {}).join();
     assertThat(async.getResult(), is(true));
   }
 
   @Test
   public void testInvokeOnClassTargetWithNullArgs() throws Exception {
-    assertThat(this.vm0.invoke(BasicDUnitTest.class, "booleanValue", null), is(true));
+    assertThat(vm0.invoke(BasicDistributedTest.class, "booleanValue", null), is(true));
   }
 
   @Test
   public void testInvokeOnObjectTargetWithNullArgs() throws Exception {
-    assertThat(this.vm0.invoke(new BasicDUnitTest(), "booleanValue", null), is(true));
+    assertThat(vm0.invoke(new BasicDistributedTest(), "booleanValue", null), is(true));
   }
 
   @Test
   public void testInvokeAsyncOnClassTargetWithNullArgs() throws Exception {
     AsyncInvocation<?> async =
-        this.vm0.invokeAsync(BasicDUnitTest.class, "booleanValue", null).join();
+        vm0.invokeAsync(BasicDistributedTest.class, "booleanValue", null).join();
     assertThat(async.getResult(), is(true));
   }
 
   @Test
   public void testInvokeAsyncOnObjectTargetWithNullArgs() throws Exception {
     AsyncInvocation<?> async =
-        this.vm0.invokeAsync(new BasicDUnitTest(), "booleanValue", null).join();
+        vm0.invokeAsync(new BasicDistributedTest(), "booleanValue", null).join();
     assertThat(async.getResult(), is(true));
   }
 
   @Test
   public void testRemoteInvocationWithException() throws Exception {
-    catchException(this.vm0).invoke(() -> remoteThrowException());
+    catchException(vm0).invoke(() -> remoteThrowException());
 
     assertThat(caughtException(), instanceOf(RMIException.class));
     assertThat(caughtException().getCause(), notNullValue());
@@ -132,24 +135,24 @@ public class BasicDUnitTest extends DistributedTestCase {
 
   @Test
   public void testInvokeWithLambda() throws Exception {
-    assertThat(this.vm0.invoke(() -> DUnitEnv.get().getVMID()), is(0));
-    assertThat(this.vm1.invoke(() -> DUnitEnv.get().getVMID()), is(1));
+    assertThat(vm0.invoke(() -> DUnitEnv.get().getVMID()), is(0));
+    assertThat(vm1.invoke(() -> DUnitEnv.get().getVMID()), is(1));
   }
 
   @Test
   public void testInvokeLambdaAsync() throws Throwable {
-    assertThat(this.vm0.invokeAsync(() -> DUnitEnv.get().getVMID()).getResult(), is(0));
+    assertThat(vm0.invokeAsync(() -> DUnitEnv.get().getVMID()).getResult(), is(0));
   }
 
   @Test
   public void testInvokeWithNamedLambda() {
-    assertThat(this.vm0.invoke("getVMID", () -> DUnitEnv.get().getVMID()), is(0));
-    assertThat(this.vm1.invoke("getVMID", () -> DUnitEnv.get().getVMID()), is(1));
+    assertThat(vm0.invoke("getVMID", () -> DUnitEnv.get().getVMID()), is(0));
+    assertThat(vm1.invoke("getVMID", () -> DUnitEnv.get().getVMID()), is(1));
   }
 
   @Test
   public void testInvokeNamedLambdaAsync() throws Throwable {
-    assertThat(this.vm0.invokeAsync("getVMID", () -> DUnitEnv.get().getVMID()).getResult(), is(0));
+    assertThat(vm0.invokeAsync("getVMID", () -> DUnitEnv.get().getVMID()).getResult(), is(0));
   }
 
   @Test
@@ -157,13 +160,13 @@ public class BasicDUnitTest extends DistributedTestCase {
     String name = getUniqueName();
     String value = "Hello";
 
-    this.vm0.invokeAsync(() -> remoteBind(name, value)).join().checkException();
-    this.vm0.invokeAsync(() -> remoteValidateBind(name, value)).join().checkException();
+    vm0.invokeAsync(() -> remoteBind(name, value)).join().checkException();
+    vm0.invokeAsync(() -> remoteValidateBind(name, value)).join().checkException();
   }
 
   @Test
   public void testRemoteInvokeAsyncWithException() throws Exception {
-    AsyncInvocation<?> async = this.vm0.invokeAsync(() -> remoteThrowException()).join();
+    AsyncInvocation<?> async = vm0.invokeAsync(() -> remoteThrowException()).join();
 
     assertThat(async.exceptionOccurred(), is(true));
     assertThat(async.getException(), instanceOf(BasicTestException.class));
@@ -178,7 +181,7 @@ public class BasicDUnitTest extends DistributedTestCase {
 
   @Test
   public void testInvokeNamedRunnableLambdaAsync() throws Exception {
-    catchThrowable(this.vm0.invokeAsync("throwSomething", () -> throwException()).join())
+    catchThrowable(vm0.invokeAsync("throwSomething", () -> throwException()).join())
         .checkException();
 
     assertThat(caughtThrowable(), notNullValue());
@@ -188,7 +191,7 @@ public class BasicDUnitTest extends DistributedTestCase {
 
   @Test
   public void testInvokeNamedRunnableLambda() throws Exception {
-    catchException(this.vm0).invoke("throwSomething", () -> throwException());
+    catchException(vm0).invoke("throwSomething", () -> throwException());
 
     assertThat(caughtException(), notNullValue());
     assertThat(caughtException().getCause(), notNullValue());
@@ -217,7 +220,7 @@ public class BasicDUnitTest extends DistributedTestCase {
     assertNotNull("value must not be null", value);
     assertNotNull("bindings must not be null", bindings);
 
-    new BasicDUnitTest().getSystem(); // forces connection
+    new BasicDistributedTest().getSystem(); // forces connection
     bindings.setProperty(name, value);
   }
 
@@ -225,6 +228,7 @@ public class BasicDUnitTest extends DistributedTestCase {
     assertEquals(expected, bindings.getProperty(name));
   }
 
+  @SuppressWarnings("unused")
   private static class BasicTestException extends RuntimeException {
     BasicTestException() {
       this("Test exception.  Please ignore.");
@@ -236,6 +240,8 @@ public class BasicDUnitTest extends DistributedTestCase {
   }
 
   private static class BasicDUnitException extends RuntimeException {
-    public BasicDUnitException() {}
+    BasicDUnitException() {
+      // nothing
+    }
   }
 }
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetCurrentVmNumDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetCurrentVmNumDistributedTest.java
index 689ed37..3515c00 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetCurrentVmNumDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetCurrentVmNumDistributedTest.java
@@ -21,7 +21,7 @@ import static org.apache.geode.test.dunit.VM.getVM;
 import static org.apache.geode.test.dunit.VM.getVMCount;
 import static org.assertj.core.api.Assertions.assertThat;
 
-import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -31,8 +31,8 @@ import org.apache.geode.test.junit.categories.DistributedTest;
 @Category(DistributedTest.class)
 public class GetCurrentVmNumDistributedTest {
 
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
 
   @Test
   public void returnsNegativeOneInController() {
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetDefaultDiskStoreNameDUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetDefaultDiskStoreNameDistributedTest.java
similarity index 83%
rename from geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetDefaultDiskStoreNameDUnitTest.java
rename to geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetDefaultDiskStoreNameDistributedTest.java
index 6c271f0..d0ddc4a 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetDefaultDiskStoreNameDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetDefaultDiskStoreNameDistributedTest.java
@@ -14,19 +14,20 @@
  */
 package org.apache.geode.test.dunit.tests;
 
-import static org.assertj.core.api.Assertions.*;
+import static org.apache.geode.test.dunit.VM.getVM;
+import static org.apache.geode.test.dunit.VM.getVMCount;
+import static org.assertj.core.api.Assertions.assertThat;
 
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.test.dunit.DistributedTestCase;
-import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
 @Category(DistributedTest.class)
 @SuppressWarnings("serial")
-public class GetDefaultDiskStoreNameDUnitTest extends DistributedTestCase {
+public class GetDefaultDiskStoreNameDistributedTest extends DistributedTestCase {
 
   @Test
   public void testGetTestMethodName() {
@@ -45,9 +46,9 @@ public class GetDefaultDiskStoreNameDUnitTest extends DistributedTestCase {
     String expected = createDefaultDiskStoreName(0, -1, "testGetTestMethodNameInAllVMs");
     assertGetDefaultDiskStoreName(expected);
 
-    for (int vmIndex = 0; vmIndex < Host.getHost(0).getVMCount(); vmIndex++) {
+    for (int vmIndex = 0; vmIndex < getVMCount(); vmIndex++) {
       String expectedInVM = createDefaultDiskStoreName(0, vmIndex, "testGetTestMethodNameInAllVMs");
-      Host.getHost(0).getVM(vmIndex).invoke(() -> assertGetDefaultDiskStoreName(expectedInVM));
+      getVM(vmIndex).invoke(() -> assertGetDefaultDiskStoreName(expectedInVM));
     }
   }
 
@@ -62,6 +63,6 @@ public class GetDefaultDiskStoreNameDUnitTest extends DistributedTestCase {
   }
 
   private String getDefaultDiskStoreName() {
-    return GemFireCacheImpl.getDefaultDiskStoreName(); // TODO: not thread safe
+    return GemFireCacheImpl.getDefaultDiskStoreName();
   }
 }
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetPidAndIdAfterBounceDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetPidAndIdAfterBounceDistributedTest.java
index ef5305d..225729c 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetPidAndIdAfterBounceDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetPidAndIdAfterBounceDistributedTest.java
@@ -19,7 +19,7 @@ import static org.apache.geode.test.dunit.VM.getVMCount;
 import static org.assertj.core.api.Assertions.assertThat;
 
 import org.junit.Before;
-import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -32,8 +32,8 @@ public class GetPidAndIdAfterBounceDistributedTest {
   private int[] idsBefore;
   private int[] pidsBefore;
 
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
 
   @Before
   public void setUp() throws Exception {
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetPidAndIdDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetPidAndIdDistributedTest.java
index b389538..01b8967 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetPidAndIdDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetPidAndIdDistributedTest.java
@@ -18,7 +18,7 @@ import static org.apache.geode.test.dunit.VM.getVM;
 import static org.apache.geode.test.dunit.VM.getVMCount;
 import static org.assertj.core.api.Assertions.assertThat;
 
-import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -30,8 +30,8 @@ import org.apache.geode.test.junit.categories.DistributedTest;
 @Category(DistributedTest.class)
 public class GetPidAndIdDistributedTest {
 
-  @ClassRule
-  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
 
   @Test
   public void getId_returnsVMSequentialId() throws Exception {
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetTestMethodNameDUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetTestMethodNameDistributedTest.java
similarity index 79%
rename from geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetTestMethodNameDUnitTest.java
rename to geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetTestMethodNameDistributedTest.java
index 31ac51b..7c263e3 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetTestMethodNameDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/GetTestMethodNameDistributedTest.java
@@ -14,18 +14,19 @@
  */
 package org.apache.geode.test.dunit.tests;
 
-import static org.assertj.core.api.Assertions.*;
+import static org.apache.geode.test.dunit.VM.getVM;
+import static org.apache.geode.test.dunit.VM.getVMCount;
+import static org.assertj.core.api.Assertions.assertThat;
 
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
 import org.apache.geode.test.dunit.DistributedTestCase;
-import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
 @Category(DistributedTest.class)
 @SuppressWarnings("serial")
-public class GetTestMethodNameDUnitTest extends DistributedTestCase {
+public class GetTestMethodNameDistributedTest extends DistributedTestCase {
 
   @Test
   public void testGetTestMethodName() {
@@ -41,9 +42,8 @@ public class GetTestMethodNameDUnitTest extends DistributedTestCase {
   public void testGetTestMethodNameInAllVMs() {
     assertGetTestMethodName("testGetTestMethodNameInAllVMs");
 
-    for (int vmIndex = 0; vmIndex < Host.getHost(0).getVMCount(); vmIndex++) {
-      Host.getHost(0).getVM(vmIndex)
-          .invoke(() -> assertGetTestMethodName("testGetTestMethodNameInAllVMs"));
+    for (int vmIndex = 0; vmIndex < getVMCount(); vmIndex++) {
+      getVM(vmIndex).invoke(() -> assertGetTestMethodName("testGetTestMethodNameInAllVMs"));
     }
   }
 
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/OverridingGetPropertiesDisconnectsAllDUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/OverridingGetPropertiesDisconnectsAllDistributedTest.java
similarity index 81%
rename from geode-core/src/test/java/org/apache/geode/test/dunit/tests/OverridingGetPropertiesDisconnectsAllDUnitTest.java
rename to geode-core/src/test/java/org/apache/geode/test/dunit/tests/OverridingGetPropertiesDisconnectsAllDistributedTest.java
index 1d51b9ef..d2671ee 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/OverridingGetPropertiesDisconnectsAllDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/OverridingGetPropertiesDisconnectsAllDistributedTest.java
@@ -14,9 +14,11 @@
  */
 package org.apache.geode.test.dunit.tests;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.apache.geode.test.dunit.Invoke.*;
-import static org.junit.Assert.*;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 
 import java.util.Properties;
 
@@ -32,7 +34,7 @@ import org.apache.geode.test.junit.categories.DistributedTest;
  */
 @Category(DistributedTest.class)
 @SuppressWarnings("serial")
-public class OverridingGetPropertiesDisconnectsAllDUnitTest extends DistributedTestCase {
+public class OverridingGetPropertiesDisconnectsAllDistributedTest extends DistributedTestCase {
 
   @Override
   public final void preTearDownAssertions() throws Exception {
@@ -46,9 +48,9 @@ public class OverridingGetPropertiesDisconnectsAllDUnitTest extends DistributedT
 
   @Override
   public Properties getDistributedSystemProperties() {
-    Properties props = new Properties();
-    props.setProperty(MCAST_PORT, "0");
-    return props;
+    Properties config = new Properties();
+    config.setProperty(MCAST_PORT, "0");
+    return config;
   }
 
   @Test
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/VMDUnitTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/VMDistributedTest.java
similarity index 92%
rename from geode-core/src/test/java/org/apache/geode/test/dunit/tests/VMDUnitTest.java
rename to geode-core/src/test/java/org/apache/geode/test/dunit/tests/VMDistributedTest.java
index 862fbd3..9b9d78b 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/VMDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/VMDistributedTest.java
@@ -14,7 +14,10 @@
  */
 package org.apache.geode.test.dunit.tests;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
 import java.io.Serializable;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -23,19 +26,19 @@ import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
 import org.apache.geode.test.dunit.AsyncInvocation;
+import org.apache.geode.test.dunit.DistributedTestCase;
 import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.RMIException;
 import org.apache.geode.test.dunit.SerializableRunnableIF;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
 /**
  * This class tests the functionality of the {@link VM} class.
  */
 @Category(DistributedTest.class)
-@SuppressWarnings("serial")
-public class VMDUnitTest extends JUnit4DistributedTestCase {
+@SuppressWarnings({"serial", "unused"})
+public class VMDistributedTest extends DistributedTestCase {
 
   private static final AtomicInteger COUNTER = new AtomicInteger();
   private static final boolean BOOLEAN_VALUE = true;
@@ -43,10 +46,6 @@ public class VMDUnitTest extends JUnit4DistributedTestCase {
   private static final long LONG_VALUE = 42L;
   private static final String STRING_VALUE = "BLAH BLAH BLAH";
 
-  public VMDUnitTest() {
-    super();
-  }
-
   @Test
   public void testInvokeStaticBoolean() {
     Host host = Host.getHost(0);
@@ -165,6 +164,7 @@ public class VMDUnitTest extends JUnit4DistributedTestCase {
   }
 
   private static class InvokeRunnable implements SerializableRunnableIF {
+    @Override
     public void run() {
       throw new BasicTestException();
     }
@@ -191,19 +191,19 @@ public class VMDUnitTest extends JUnit4DistributedTestCase {
     private final AtomicInteger val;
 
     public VMTestObject(int init) {
-      this.val = new AtomicInteger(init);
+      val = new AtomicInteger(init);
     }
 
     public Integer get() {
-      return new Integer(this.val.get());
+      return new Integer(val.get());
     }
 
     public Integer incrementAndGet() {
-      return new Integer(this.val.incrementAndGet());
+      return new Integer(val.incrementAndGet());
     }
 
     public void set(Integer newVal) {
-      this.val.set(newVal.intValue());
+      val.set(newVal.intValue());
     }
   }
 }

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 01/13: GEODE-1279: Rename HARegionQueueSizeRegressionTest

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit af5d6ee7e4264df5e2ff5eeb6c33ca0bb75582ed
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Wed Apr 4 17:47:32 2018 -0700

    GEODE-1279: Rename HARegionQueueSizeRegressionTest
    
    * Bug48571DUnitTest -> HARegionQueueSizeRegressionTest
    * Overhaul test to use Rules, Awaitility and CacheListener Spy
---
 .../geode/internal/cache/ha/Bug48571DUnitTest.java | 290 ---------------------
 .../cache/ha/HARegionQueueSizeRegressionTest.java  | 245 +++++++++++++++++
 .../dunit/cache/internal/JUnit4CacheTestCase.java  |   4 +
 3 files changed, 249 insertions(+), 290 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48571DUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48571DUnitTest.java
deleted file mode 100644
index 19c5a8b..0000000
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/Bug48571DUnitTest.java
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.internal.cache.ha;
-
-import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_ID;
-import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_TIMEOUT;
-import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
-import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE;
-import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
-import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
-import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_ARCHIVE_FILE;
-import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_SAMPLING_ENABLED;
-import static org.junit.Assert.assertEquals;
-
-import java.util.Collection;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-
-import org.awaitility.Awaitility;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.EntryEvent;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionFactory;
-import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.client.ClientCacheFactory;
-import org.apache.geode.cache.client.ClientRegionFactory;
-import org.apache.geode.cache.client.ClientRegionShortcut;
-import org.apache.geode.cache.server.CacheServer;
-import org.apache.geode.cache.util.CacheListenerAdapter;
-import org.apache.geode.distributed.DistributedSystem;
-import org.apache.geode.internal.OSProcess;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
-import org.apache.geode.internal.i18n.LocalizedStrings;
-import org.apache.geode.test.dunit.DistributedTestUtils;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.IgnoredException;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.ClientSubscriptionTest;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-@Category({DistributedTest.class, ClientSubscriptionTest.class})
-public class Bug48571DUnitTest extends JUnit4DistributedTestCase {
-
-  private static VM server = null;
-  private VM client = null;
-  private static GemFireCacheImpl cache = null;
-
-  private static final String region = Bug48571DUnitTest.class.getSimpleName() + "_region";
-  private static int numOfCreates = 0;
-  private static int numOfUpdates = 0;
-  private static int numOfInvalidates = 0;
-  private static boolean lastKeyReceived = false;
-
-  @Override
-  public final void postSetUp() throws Exception {
-    final Host host = Host.getHost(0);
-    server = host.getVM(0);
-    client = host.getVM(1);
-  }
-
-  @Override
-  public final void preTearDown() throws Exception {
-    reset();
-    server.invoke(Bug48571DUnitTest::reset);
-    client.invoke(Bug48571DUnitTest::reset);
-  }
-
-  private static void reset() {
-    lastKeyReceived = false;
-    numOfCreates = 0;
-    numOfUpdates = 0;
-    numOfInvalidates = 0;
-    if (cache != null && !cache.isClosed()) {
-      cache.close();
-      cache.getDistributedSystem().disconnect();
-    }
-  }
-
-  @Test
-  public void testStatsMatchWithSize() throws Exception {
-    IgnoredException.addIgnoredException("Unexpected IOException||Connection reset");
-    // start a server
-    int port = server.invoke(Bug48571DUnitTest::createServerCache);
-    // create durable client, with durable RI
-    client.invoke(() -> Bug48571DUnitTest.createClientCache(client.getHost(), port));
-    // do puts on server from three different threads, pause after 500 puts each.
-    server.invoke(Bug48571DUnitTest::doPuts);
-    // close durable client
-    client.invoke(Bug48571DUnitTest::closeClientCache);
-
-    server.invoke("verifyProxyHasBeenPaused", Bug48571DUnitTest::verifyProxyHasBeenPaused);
-    // resume puts on server, add another 100.
-    server.invoke(Bug48571DUnitTest::resumePuts);
-    // start durable client
-    client.invoke(() -> Bug48571DUnitTest.createClientCache(client.getHost(), port));
-    // wait for full queue dispatch
-    client.invoke(Bug48571DUnitTest::waitForLastKey);
-    // verify the stats
-    server.invoke(Bug48571DUnitTest::verifyStats);
-  }
-
-  private static void verifyProxyHasBeenPaused() {
-    Awaitility.await().atMost(60, TimeUnit.SECONDS).until(() -> {
-      CacheClientNotifier ccn = CacheClientNotifier.getInstance();
-      Collection<CacheClientProxy> ccProxies = ccn.getClientProxies();
-      boolean pausedFlag = false;
-
-      for (CacheClientProxy ccp : ccProxies) {
-        System.out.println("proxy status " + ccp.getState());
-        if (ccp.isPaused()) {
-          pausedFlag = true;
-          break;
-        }
-      }
-      assertEquals("Proxy has not been paused in 1 minute", true, pausedFlag);
-    });
-  }
-
-  private static int createServerCache() throws Exception {
-    Properties props = new Properties();
-    props.setProperty(LOCATORS, "localhost[" + DistributedTestUtils.getDUnitLocatorPort() + "]");
-    props.setProperty(LOG_FILE, "server_" + OSProcess.getId() + ".log");
-    props.setProperty(LOG_LEVEL, "info");
-    props.setProperty(STATISTIC_ARCHIVE_FILE, "server_" + OSProcess.getId() + ".gfs");
-    props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
-    CacheFactory cf = new CacheFactory(props);
-
-    DistributedSystem ds = new Bug48571DUnitTest().getSystem(props);
-    ds.disconnect();
-
-    cache = (GemFireCacheImpl) cf.create();
-
-    RegionFactory<String, String> rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-    rf.setConcurrencyChecksEnabled(false);
-    rf.create(region);
-
-    CacheServer server1 = cache.addCacheServer();
-    server1.setPort(0);
-    server1.start();
-    return server1.getPort();
-  }
-
-  private static void closeClientCache() {
-    cache.close(true);
-  }
-
-  private static void createClientCache(Host host, Integer port) {
-
-    Properties props = new Properties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(LOCATORS, "");
-    props.setProperty(DURABLE_CLIENT_ID, "durable-48571");
-    props.setProperty(DURABLE_CLIENT_TIMEOUT, "300000");
-
-    props.setProperty(LOG_FILE, "client_" + OSProcess.getId() + ".log");
-    props.setProperty(LOG_LEVEL, "info");
-    props.setProperty(STATISTIC_ARCHIVE_FILE, "client_" + OSProcess.getId() + ".gfs");
-    props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
-
-    ClientCacheFactory ccf = new ClientCacheFactory(props);
-    ccf.setPoolSubscriptionEnabled(true);
-    ccf.setPoolSubscriptionAckInterval(50);
-    ccf.setPoolSubscriptionRedundancy(0);
-    ccf.addPoolServer(host.getHostName(), port);
-
-    DistributedSystem ds = new Bug48571DUnitTest().getSystem(props);
-    ds.disconnect();
-
-    cache = (GemFireCacheImpl) ccf.create();
-
-    ClientRegionFactory<String, String> crf =
-        cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
-    crf.setConcurrencyChecksEnabled(false);
-
-    crf.addCacheListener(new CacheListenerAdapter<String, String>() {
-      public void afterInvalidate(EntryEvent<String, String> event) {
-        cache.getLoggerI18n()
-            .fine("Invalidate Event: " + event.getKey() + ", " + event.getNewValue());
-        numOfInvalidates++;
-      }
-
-      public void afterCreate(EntryEvent<String, String> event) {
-        if (event.getKey().equals("last_key")) {
-          lastKeyReceived = true;
-        }
-        cache.getLoggerI18n().fine("Create Event: " + event.getKey() + ", " + event.getNewValue());
-        numOfCreates++;
-      }
-
-      public void afterUpdate(EntryEvent<String, String> event) {
-        cache.getLoggerI18n().fine("Update Event: " + event.getKey() + ", " + event.getNewValue());
-        numOfUpdates++;
-      }
-    });
-
-    Region<String, String> r = crf.create(region);
-    r.registerInterest("ALL_KEYS", true);
-    cache.readyForEvents();
-  }
-
-  private static void doPuts() throws Exception {
-    final Region<String, String> r = cache.getRegion(region);
-    Thread t1 = new Thread(() -> {
-      for (int i = 0; i < 500; i++) {
-        r.put("T1_KEY_" + i, "VALUE_" + i);
-      }
-    });
-    Thread t2 = new Thread(() -> {
-      for (int i = 0; i < 500; i++) {
-        r.put("T2_KEY_" + i, "VALUE_" + i);
-      }
-    });
-    Thread t3 = new Thread(() -> {
-      for (int i = 0; i < 500; i++) {
-        r.put("T3_KEY_" + i, "VALUE_" + i);
-      }
-    });
-
-    t1.start();
-    t2.start();
-    t3.start();
-
-    t1.join();
-    t2.join();
-    t3.join();
-  }
-
-  private static void resumePuts() {
-    Region<String, String> r = cache.getRegion(region);
-    for (int i = 0; i < 100; i++) {
-      r.put("NEWKEY_" + i, "NEWVALUE_" + i);
-    }
-    r.put("last_key", "last_value");
-  }
-
-  private static void waitForLastKey() {
-    WaitCriterion wc = new WaitCriterion() {
-      @Override
-      public boolean done() {
-        return lastKeyReceived;
-      }
-
-      @Override
-      public String description() {
-        return "Did not receive last key.";
-      }
-    };
-    Wait.waitForCriterion(wc, 60 * 1000, 500, true);
-  }
-
-  private static void verifyStats() {
-    Awaitility.await().atMost(60, TimeUnit.SECONDS).until(() -> {
-      CacheClientNotifier ccn = CacheClientNotifier.getInstance();
-      CacheClientProxy ccp = ccn.getClientProxies().iterator().next();
-      cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getQueueSize() " + ccp.getQueueSize());
-      cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-          "getQueueSizeStat() " + ccp.getQueueSizeStat());
-      cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-          "getEventsEnqued() " + ccp.getHARegionQueue().getStatistics().getEventsEnqued());
-      cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-          "getEventsDispatched() " + ccp.getHARegionQueue().getStatistics().getEventsDispatched());
-      cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-          "getEventsRemoved() " + ccp.getHARegionQueue().getStatistics().getEventsRemoved());
-      cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-          "getNumVoidRemovals() " + ccp.getHARegionQueue().getStatistics().getNumVoidRemovals());
-      assertEquals("The queue size did not match the stat value", ccp.getQueueSize(),
-          ccp.getQueueSizeStat());
-    });
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueSizeRegressionTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueSizeRegressionTest.java
new file mode 100644
index 0000000..f86c1f7
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/ha/HARegionQueueSizeRegressionTest.java
@@ -0,0 +1,245 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.internal.cache.ha;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.geode.cache.RegionShortcut.REPLICATE;
+import static org.apache.geode.cache.client.ClientRegionShortcut.CACHING_PROXY;
+import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_ID;
+import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_TIMEOUT;
+import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
+import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.apache.geode.test.dunit.VM.getHostName;
+import static org.apache.geode.test.dunit.VM.getVM;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Properties;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.awaitility.Awaitility;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.CacheListener;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.client.ClientCacheFactory;
+import org.apache.geode.cache.client.ClientRegionFactory;
+import org.apache.geode.cache.server.CacheServer;
+import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
+import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.rules.CacheRule;
+import org.apache.geode.test.dunit.rules.ClientCacheRule;
+import org.apache.geode.test.dunit.rules.DistributedTestRule;
+import org.apache.geode.test.junit.categories.ClientSubscriptionTest;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
+
+/**
+ * Client queue size statistic should not go negative when client goes offline.
+ *
+ * <p>
+ * TRAC #48571: CacheClientProxy.getQueueSizeStat() gives negative numbers when client goes down.
+ */
+@Category({DistributedTest.class, ClientSubscriptionTest.class})
+public class HARegionQueueSizeRegressionTest implements Serializable {
+
+  private static final AtomicInteger numOfPuts = new AtomicInteger();
+
+  private static volatile CacheListener<String, String> spyCacheListener;
+
+  private String regionName;
+  private String hostName;
+
+  private VM server;
+  private VM client;
+
+  @ClassRule
+  public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+
+  @Rule
+  public CacheRule cacheRule = new CacheRule();
+
+  @Rule
+  public ClientCacheRule clientCacheRule = new ClientCacheRule();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @Before
+  public void setUp() throws Exception {
+    server = getVM(0);
+    client = getVM(1);
+
+    hostName = getHostName();
+    regionName = getClass().getSimpleName() + "_" + testName.getMethodName();
+
+    addIgnoredException("Unexpected IOException||Connection reset");
+  }
+
+  @After
+  public void tearDown() throws Exception {
+    invokeInEveryVM(() -> {
+      spyCacheListener = null;
+    });
+  }
+
+  @Test
+  public void testStatsMatchWithSize() throws Exception {
+    // start a server
+    int port = server.invoke(() -> createServerCache());
+
+    // create durable client, with durable RI
+    client.invoke(() -> createClientCache(hostName, port));
+
+    // do puts on server
+    server.invoke(() -> doPuts(10));
+
+    client.invoke(() -> awaitCreates(10));
+
+    // close durable client
+    client.invoke(() -> closeClientCacheWithKeepAlive());
+
+    server.invoke(() -> awaitProxyIsPaused());
+
+    // resume puts on server
+    server.invoke(() -> resumePuts(10));
+
+    // start durable client
+    client.invoke(() -> createClientCache(hostName, port));
+
+    // wait for full queue dispatch
+    client.invoke(() -> awaitCreates(10));
+
+    // verify the stats
+    server.invoke(() -> verifyStats());
+  }
+
+  private int createServerCache() throws IOException {
+    cacheRule.createCache();
+
+    RegionFactory<String, String> rf = cacheRule.getCache().createRegionFactory(REPLICATE);
+    rf.setConcurrencyChecksEnabled(false);
+    rf.create(regionName);
+
+    CacheServer server1 = cacheRule.getCache().addCacheServer();
+    server1.setPort(0);
+    server1.start();
+    return server1.getPort();
+  }
+
+  private void createClientCache(String hostName, Integer port) {
+    Properties config = new Properties();
+    config.setProperty(MCAST_PORT, "0");
+    config.setProperty(LOCATORS, "");
+    config.setProperty(DURABLE_CLIENT_ID, "durable-48571");
+    config.setProperty(DURABLE_CLIENT_TIMEOUT, "300000");
+
+    ClientCacheFactory ccf = new ClientCacheFactory(config);
+    ccf.setPoolSubscriptionEnabled(true);
+    ccf.setPoolSubscriptionAckInterval(50);
+    ccf.setPoolSubscriptionRedundancy(0);
+    ccf.addPoolServer(hostName, port);
+
+    clientCacheRule.createClientCache(ccf);
+
+    ClientRegionFactory<String, String> crf =
+        clientCacheRule.getClientCache().createClientRegionFactory(CACHING_PROXY);
+    crf.setConcurrencyChecksEnabled(false);
+
+    spyCacheListener = spy(CacheListener.class);
+    crf.addCacheListener(spyCacheListener);
+
+    Region<String, String> region = crf.create(regionName);
+    region.registerInterest("ALL_KEYS", true);
+
+    clientCacheRule.getClientCache().readyForEvents();
+  }
+
+  private void closeClientCacheWithKeepAlive() {
+    clientCacheRule.getClientCache().close(true);
+  }
+
+  private void doPuts(int creates) {
+    Region<String, String> region = cacheRule.getCache().getRegion(regionName);
+
+    for (int i = 1; i <= creates; i++) {
+      put(region, "KEY-" + i, "VALUE-" + i);
+    }
+  }
+
+  private void awaitProxyIsPaused() {
+    Awaitility.await().atMost(60, SECONDS).until(() -> {
+      CacheClientNotifier ccn = CacheClientNotifier.getInstance();
+      Collection<CacheClientProxy> ccProxies = ccn.getClientProxies();
+
+      boolean pausedFlag = false;
+      for (CacheClientProxy ccp : ccProxies) {
+        if (ccp.isPaused()) {
+          pausedFlag = true;
+          break;
+        }
+      }
+      assertThat(pausedFlag).as("Proxy has not been paused in 1 minute").isTrue();
+    });
+  }
+
+  private void resumePuts(int creates) {
+    Region<String, String> region = cacheRule.getCache().getRegion(regionName);
+    for (int i = 1; i <= creates; i++) {
+      put(region, "NEWKEY-" + i, "VALUE_" + i);
+    }
+  }
+
+  private void put(Region<String, String> region, String key, String value) {
+    region.put(key, value);
+    numOfPuts.incrementAndGet();
+  }
+
+  private void awaitCreates(int expectedCreates) {
+    Awaitility.await().atMost(60, SECONDS).until(() -> {
+      verify(spyCacheListener, times(expectedCreates)).afterCreate(any());
+    });
+  }
+
+  private void verifyStats() {
+    Awaitility.await().atMost(60, SECONDS).until(() -> {
+      CacheClientNotifier ccn = CacheClientNotifier.getInstance();
+      CacheClientProxy ccp = ccn.getClientProxies().iterator().next();
+      // TODO: consider verifying ccp.getQueueSize()
+      // TODO: consider verifying ccp.getQueueSizeStat()
+      // TODO: consider verifying ccp.getHARegionQueue().getStatistics().getEventsEnqued()
+      // TODO: consider verifying ccp.getHARegionQueue().getStatistics().getEventsDispatched()
+      // TODO: consider verifying ccp.getHARegionQueue().getStatistics().getEventsRemoved()
+      // TODO: consider verifying ccp.getHARegionQueue().getStatistics().getNumVoidRemovals()
+      assertThat(ccp.getQueueSizeStat()).as("The queue size did not match the stat value")
+          .isEqualTo(ccp.getQueueSize());
+    });
+  }
+}
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java b/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
index ac25583..c93f921 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
@@ -262,6 +262,10 @@ public abstract class JUnit4CacheTestCase extends JUnit4DistributedTestCase
     }
   }
 
+  public final ClientCache getClientCache() {
+    return (ClientCache) cache;
+  }
+
   /**
    * Invokes {@link #getCache()} and casts the return to {@code GemFireCacheImpl}.
    *

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 13/13: GEODE-5033: Fixup OverridingGetPropertiesDisconnectsAllDistributedTest

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit d66fd4fcbadeb3dc7dce45962d4de8db55ff2ac1
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Sun Apr 22 19:41:58 2018 -0700

    GEODE-5033: Fixup OverridingGetPropertiesDisconnectsAllDistributedTest
---
 ...ngGetPropertiesDisconnectsAllDistributedTest.java | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/OverridingGetPropertiesDisconnectsAllDistributedTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/OverridingGetPropertiesDisconnectsAllDistributedTest.java
index d2671ee..03ee489 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/tests/OverridingGetPropertiesDisconnectsAllDistributedTest.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/tests/OverridingGetPropertiesDisconnectsAllDistributedTest.java
@@ -16,9 +16,7 @@ package org.apache.geode.test.dunit.tests;
 
 import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
 import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.assertj.core.api.Assertions.assertThat;
 
 import java.util.Properties;
 
@@ -38,12 +36,16 @@ public class OverridingGetPropertiesDisconnectsAllDistributedTest extends Distri
 
   @Override
   public final void preTearDownAssertions() throws Exception {
-    invokeInEveryVM(() -> assertNotNull(basicGetSystem()));
+    invokeInEveryVM(() -> {
+      assertThat(basicGetSystem().isConnected()).isTrue();
+    });
   }
 
   @Override
   public final void postTearDownAssertions() throws Exception {
-    invokeInEveryVM(() -> assertNull(basicGetSystem()));
+    invokeInEveryVM(() -> {
+      assertThat(basicGetSystem().isConnected()).isFalse();
+    });
   }
 
   @Override
@@ -55,7 +57,11 @@ public class OverridingGetPropertiesDisconnectsAllDistributedTest extends Distri
 
   @Test
   public void testDisconnects() throws Exception {
-    invokeInEveryVM(() -> assertFalse(getDistributedSystemProperties().isEmpty()));
-    invokeInEveryVM(() -> assertNotNull(getSystem()));
+    invokeInEveryVM(() -> {
+      assertThat(getDistributedSystemProperties()).isNotEmpty();
+    });
+    invokeInEveryVM(() -> {
+      assertThat(getSystem().isConnected()).isTrue();
+    });
   }
 }

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 04/13: GEODE-5033: Improve TearDown of DistributedTestRule

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit 3849147c309bfad9e81ea0cf21dfe9905aee0618
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Thu Apr 12 12:39:10 2018 -0700

    GEODE-5033: Improve TearDown of DistributedTestRule
    
    Change Distributed rules to extend AbstractDistributedTestRule to ensure
    that all DUnit VMs were launched prior to setUp of these rules.
    
    Add DistributedTestRule.TearDown which includes everything that the
    old DistributedTestCase handled during tearDown.
    
    Using DistributedTestRule as a non-static Rule is probably the best way
    to use it going forward. If you use it as a static ClassRule then you
    should also register DistributedTestRule.TearDown as a non-static Rule
    so that removal of IgnoredExceptions and grep for suspect strings are
    both properly invoked after every test method.
---
 .../dunit/cache/internal/JUnit4CacheTestCase.java  |   5 +-
 .../dunit/internal/JUnit4DistributedTestCase.java  |   2 +-
 .../dunit/rules/AbstractDistributedTestRule.java   |  94 +++++++++++
 .../apache/geode/test/dunit/rules/CacheRule.java   | 105 +++++++++++--
 .../test/dunit/rules/CleanupDUnitVMsRule.java      |   5 -
 .../geode/test/dunit/rules/ClientCacheRule.java    |   6 +-
 .../test/dunit/rules/DistributedDiskDirRule.java   |   2 +
 .../rules/DistributedRestoreSystemProperties.java  |  37 +----
 .../test/dunit/rules/DistributedTestRule.java      | 172 +++++++++++++++++++--
 .../DistributedUseJacksonForJsonPathRule.java      |  20 ++-
 .../geode/test/dunit/rules/SharedCountersRule.java |  13 +-
 .../test/dunit/rules/SharedErrorCollector.java     |  46 ++----
 12 files changed, 392 insertions(+), 115 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java b/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
index c93f921..fa9a6f2 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
@@ -41,6 +41,7 @@ import org.apache.geode.cache.TimeoutException;
 import org.apache.geode.cache.client.ClientCache;
 import org.apache.geode.cache.client.ClientCacheFactory;
 import org.apache.geode.cache.client.PoolManager;
+import org.apache.geode.cache.client.internal.InternalClientCache;
 import org.apache.geode.cache30.CacheSerializableRunnable;
 import org.apache.geode.distributed.internal.DistributionMessageObserver;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
@@ -262,8 +263,8 @@ public abstract class JUnit4CacheTestCase extends JUnit4DistributedTestCase
     }
   }
 
-  public final ClientCache getClientCache() {
-    return (ClientCache) cache;
+  public final InternalClientCache getClientCache() {
+    return (InternalClientCache) cache;
   }
 
   /**
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java b/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
index 1ecbefe..4790e87 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
@@ -572,7 +572,7 @@ public abstract class JUnit4DistributedTestCase implements DistributedTestFixtur
     }
   }
 
-  private static final void cleanupAllVms() {
+  public static final void cleanupAllVms() {
     tearDownVM();
     invokeInEveryVM("tearDownVM", () -> tearDownVM());
     invokeInLocator(() -> {
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/AbstractDistributedTestRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/AbstractDistributedTestRule.java
new file mode 100644
index 0000000..fcba9c5
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/AbstractDistributedTestRule.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.test.dunit.rules;
+
+import static org.apache.geode.test.dunit.VM.DEFAULT_VM_COUNT;
+import static org.apache.geode.test.dunit.VM.getVMCount;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+import org.apache.geode.test.dunit.standalone.DUnitLauncher;
+import org.apache.geode.test.junit.rules.serializable.SerializableStatement;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestRule;
+
+class AbstractDistributedTestRule implements SerializableTestRule {
+
+  private final int vmCount;
+  private final RemoteInvoker invoker;
+
+  private volatile int beforeVmCount;
+
+  protected AbstractDistributedTestRule() {
+    this(DEFAULT_VM_COUNT);
+  }
+
+  protected AbstractDistributedTestRule(final int vmCount) {
+    this(vmCount, new RemoteInvoker());
+  }
+
+  protected AbstractDistributedTestRule(final int vmCount, final RemoteInvoker invoker) {
+    this.vmCount = vmCount;
+    this.invoker = invoker;
+  }
+
+  @Override
+  public Statement apply(final Statement base, final Description description) {
+    return statement(base);
+  }
+
+  private Statement statement(final Statement base) {
+    return new SerializableStatement() {
+      @Override
+      public void evaluate() throws Throwable {
+        beforeDistributedTest();
+        before();
+        try {
+          base.evaluate();
+        } finally {
+          after();
+          afterDistributedTest();
+        }
+      }
+    };
+  }
+
+  private void beforeDistributedTest() throws Throwable {
+    DUnitLauncher.launchIfNeeded();
+    beforeVmCount = getVMCount();
+  }
+
+  private void afterDistributedTest() throws Throwable {
+    int afterVmCount = getVMCount();
+    assertThat(afterVmCount).isEqualTo(beforeVmCount);
+  }
+
+  protected void before() throws Throwable {
+    // override
+  }
+
+  protected void after() throws Throwable {
+    // override
+  }
+
+  protected RemoteInvoker invoker() {
+    return invoker;
+  }
+
+  protected int vmCount() {
+    return vmCount;
+  }
+}
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CacheRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CacheRule.java
index 990f45c..9b2bbf5 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CacheRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CacheRule.java
@@ -14,35 +14,61 @@
  */
 package org.apache.geode.test.dunit.rules;
 
-import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
-import static org.apache.geode.test.dunit.DistributedTestUtils.getLocators;
+import static org.apache.geode.test.dunit.Disconnect.disconnectAllFromDS;
+import static org.apache.geode.test.dunit.standalone.DUnitLauncher.getDistributedSystemProperties;
 import static org.assertj.core.api.Assertions.assertThat;
 
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
 
+import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.Region;
 import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.internal.cache.HARegion;
 import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.test.dunit.Disconnect;
+import org.apache.geode.internal.cache.PartitionedRegion;
 import org.apache.geode.test.dunit.VM;
 
 /**
  * JUnit Rule that creates Cache instances in DistributedTest VMs without {@code CacheTestCase}.
  *
  * <p>
- * {@code CacheRule} follows the standard convention of using a {@code Builder} for configuration as
- * introduced in the JUnit {@code Timeout} rule.
+ * {@code CacheRule} can be used in DistributedTests as a {@code Rule}:
+ *
+ * <pre>
+ * {@literal @}Rule
+ * public DistributedTestRule distributedTestRule = new DistributedTestRule();
+ *
+ * {@literal @}Rule
+ * public CacheRule cacheRule = new CacheRule();
+ *
+ * {@literal @}Before
+ * public void setUp() {
+ *   getVM(0).invoke(() -> cacheRule.createCache(new CacheFactory().setPdxDiskStore(myDiskStore))));
+ * }
+ *
+ * {@literal @}Test
+ * public void createRegionWithRegionFactory() {
+ *   getVM(0).invoke(() -> {
+ *     RegionFactory regionFactory = cacheRule.getCache().createRegionFactory();
+ *     ...
+ *   });
+ * }
+ * </pre>
  *
  * <p>
- * {@code CacheRule} can be used in DistributedTests as a {@code Rule}:
+ * {@link CacheRule.Builder} can be used to construct an instance with more options:
  *
  * <pre>
  * {@literal @}ClassRule
  * public static DistributedTestRule distributedTestRule = new DistributedTestRule();
  *
  * {@literal @}Rule
+ * public DistributedTestRule.TearDown tearDown = new DistributedTestRule.TearDown();
+ *
+ * {@literal @}Rule
  * public CacheRule cacheRule = CacheRule.builder().createCacheInAll().build();
  *
  * {@literal @}Test
@@ -55,17 +81,22 @@ import org.apache.geode.test.dunit.VM;
  * </pre>
  */
 @SuppressWarnings({"serial", "unused"})
-public class CacheRule extends DistributedExternalResource {
+public class CacheRule extends AbstractDistributedTestRule {
 
   private static volatile InternalCache cache;
 
   private final boolean createCacheInAll;
   private final boolean createCache;
   private final boolean disconnectAfter;
+  private final boolean destroyRegions;
+  private final boolean replaceConfig;
   private final List<VM> createCacheInVMs;
   private final Properties config;
   private final Properties systemProperties;
 
+  /**
+   * Use {@code Builder} for more options in constructing {@code CacheRule}.
+   */
   public static Builder builder() {
     return new Builder();
   }
@@ -78,6 +109,8 @@ public class CacheRule extends DistributedExternalResource {
     createCacheInAll = builder.createCacheInAll;
     createCache = builder.createCache;
     disconnectAfter = builder.disconnectAfter;
+    destroyRegions = builder.destroyRegions;
+    replaceConfig = builder.replaceConfig;
     createCacheInVMs = builder.createCacheInVMs;
     config = builder.config;
     systemProperties = builder.systemProperties;
@@ -86,13 +119,13 @@ public class CacheRule extends DistributedExternalResource {
   @Override
   protected void before() {
     if (createCacheInAll) {
-      invoker().invokeInEveryVMAndController(() -> createCache(config, systemProperties));
+      invoker().invokeInEveryVMAndController(() -> createCache(config(), systemProperties));
     } else {
       if (createCache) {
-        createCache(config, systemProperties);
+        createCache(config(), systemProperties);
       }
       for (VM vm : createCacheInVMs) {
-        vm.invoke(() -> createCache(config, systemProperties));
+        vm.invoke(() -> createCache(config(), systemProperties));
       }
     }
   }
@@ -103,8 +136,17 @@ public class CacheRule extends DistributedExternalResource {
     invoker().invokeInEveryVMAndController(() -> closeAndNullCache());
 
     if (disconnectAfter) {
-      Disconnect.disconnectAllFromDS();
+      disconnectAllFromDS();
+    }
+  }
+
+  private Properties config() {
+    if (replaceConfig) {
+      return config;
     }
+    Properties allConfig = getDistributedSystemProperties();
+    allConfig.putAll(config);
+    return allConfig;
   }
 
   public InternalCache getCache() {
@@ -116,7 +158,7 @@ public class CacheRule extends DistributedExternalResource {
   }
 
   public void createCache() {
-    cache = (InternalCache) new CacheFactory(config).create();
+    cache = (InternalCache) new CacheFactory(config()).create();
   }
 
   public void createCache(final CacheFactory cacheFactory) {
@@ -140,14 +182,17 @@ public class CacheRule extends DistributedExternalResource {
     return cache;
   }
 
-  private static void closeAndNullCache() {
+  private void closeAndNullCache() {
     closeCache();
     nullCache();
   }
 
-  private static void closeCache() {
+  private void closeCache() {
     try {
       if (cache != null) {
+        if (destroyRegions) {
+          destroyRegions(cache);
+        }
         cache.close();
       }
     } catch (Exception ignored) {
@@ -159,6 +204,23 @@ public class CacheRule extends DistributedExternalResource {
     cache = null;
   }
 
+  private static void destroyRegions(final Cache cache) {
+    if (cache != null && !cache.isClosed()) {
+      // try to destroy the root regions first so that we clean up any persistent files.
+      for (Region<?, ?> root : cache.rootRegions()) {
+        String regionFullPath = root == null ? null : root.getFullPath();
+        // for colocated regions you can't locally destroy a partitioned region.
+        if (root.isDestroyed() || root instanceof HARegion || root instanceof PartitionedRegion) {
+          continue;
+        }
+        try {
+          root.localDestroyRegion("CacheRule_tearDown");
+        } catch (Exception ignore) {
+        }
+      }
+    }
+  }
+
   /**
    * Builds an instance of CacheRule.
    */
@@ -167,12 +229,14 @@ public class CacheRule extends DistributedExternalResource {
     private boolean createCacheInAll;
     private boolean createCache;
     private boolean disconnectAfter;
+    private boolean destroyRegions;
+    private boolean replaceConfig;
     private List<VM> createCacheInVMs = new ArrayList<>();
     private Properties config = new Properties();
     private Properties systemProperties = new Properties();
 
     public Builder() {
-      config.setProperty(LOCATORS, getLocators());
+      // nothing
     }
 
     /**
@@ -210,8 +274,19 @@ public class CacheRule extends DistributedExternalResource {
       return this;
     }
 
+    /**
+     * Destroy all Regions before closing the Cache. This will cleanup the presence of each Region
+     * in DiskStores, but this is not needed if the disk files are on a TemporaryFolder. Default is
+     * false.
+     */
+    public Builder destroyRegions() {
+      destroyRegions = true;
+      return this;
+    }
+
     public Builder replaceConfig(final Properties config) {
       this.config = config;
+      replaceConfig = true;
       return this;
     }
 
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CleanupDUnitVMsRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CleanupDUnitVMsRule.java
index ea1cd49..73ccad7 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CleanupDUnitVMsRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/CleanupDUnitVMsRule.java
@@ -14,13 +14,8 @@
  */
 package org.apache.geode.test.dunit.rules;
 
-import static org.apache.geode.test.dunit.Host.getHost;
 import static org.apache.geode.test.dunit.Host.getHostCount;
 
-import java.io.Serializable;
-
-import org.junit.rules.ExternalResource;
-
 import org.apache.geode.test.dunit.VM;
 
 public class CleanupDUnitVMsRule extends ExternalResource implements Serializable {
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/ClientCacheRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/ClientCacheRule.java
index a97f302..9391e2b 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/ClientCacheRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/ClientCacheRule.java
@@ -14,8 +14,6 @@
  */
 package org.apache.geode.test.dunit.rules;
 
-import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
-import static org.apache.geode.test.dunit.DistributedTestUtils.getLocators;
 import static org.assertj.core.api.Assertions.assertThat;
 
 import java.util.ArrayList;
@@ -53,7 +51,7 @@ import org.apache.geode.test.dunit.VM;
  * </pre>
  */
 @SuppressWarnings({"serial", "unused"})
-public class ClientCacheRule extends DistributedExternalResource {
+public class ClientCacheRule extends AbstractDistributedTestRule {
 
   private static volatile InternalClientCache clientCache;
 
@@ -163,7 +161,7 @@ public class ClientCacheRule extends DistributedExternalResource {
     private Properties systemProperties = new Properties();
 
     public Builder() {
-      config.setProperty(LOCATORS, getLocators());
+      // nothing
     }
 
     /**
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDiskDirRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDiskDirRule.java
index 1ada67b..7a25148 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDiskDirRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDiskDirRule.java
@@ -31,6 +31,7 @@ import org.junit.rules.TestName;
 import org.junit.runner.Description;
 
 import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.standalone.DUnitLauncher;
 import org.apache.geode.test.junit.rules.DiskDirRule;
 import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
 import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
@@ -124,6 +125,7 @@ public class DistributedDiskDirRule extends DiskDirRule implements SerializableT
 
   @Override
   protected void before(Description description) throws Exception {
+    DUnitLauncher.launchIfNeeded();
     beforeVmCount = getVMCount();
 
     if (initializeHelperRules) {
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
index 2fcf128..d93502a 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
@@ -14,48 +14,29 @@
  */
 package org.apache.geode.test.dunit.rules;
 
-import static org.apache.geode.test.dunit.Host.getHost;
-import static org.assertj.core.api.Assertions.assertThat;
-
 import org.apache.geode.test.junit.rules.accessible.AccessibleRestoreSystemProperties;
-import org.apache.geode.test.junit.rules.serializable.SerializableTestRule;
 
 /**
  * Distributed version of RestoreSystemProperties which affects all DUnit JVMs including the Locator
  * JVM.
  */
-public class DistributedRestoreSystemProperties extends AccessibleRestoreSystemProperties
-    implements SerializableTestRule {
+public class DistributedRestoreSystemProperties extends AbstractDistributedTestRule {
 
   private static final AccessibleRestoreSystemProperties restoreSystemProperties =
       new AccessibleRestoreSystemProperties();
 
-  private final RemoteInvoker invoker;
-
-  private volatile int beforeVmCount;
-
   public DistributedRestoreSystemProperties() {
-    this(new RemoteInvoker());
-  }
-
-  public DistributedRestoreSystemProperties(final RemoteInvoker invoker) {
-    super();
-    this.invoker = invoker;
+    // nothing
   }
 
   @Override
-  public void before() throws Throwable {
-    beforeVmCount = getVMCount();
-
-    invoker.invokeInEveryVMAndController(() -> invokeBefore());
+  public void before() throws Exception {
+    invoker().invokeInEveryVMAndController(() -> invokeBefore());
   }
 
   @Override
   public void after() {
-    int afterVmCount = getVMCount();
-    assertThat(afterVmCount).isEqualTo(beforeVmCount);
-
-    invoker.invokeInEveryVMAndController(() -> invokeAfter());
+    invoker().invokeInEveryVMAndController(() -> invokeAfter());
   }
 
   private void invokeBefore() throws Exception {
@@ -72,12 +53,4 @@ public class DistributedRestoreSystemProperties extends AccessibleRestoreSystemP
   private void invokeAfter() {
     restoreSystemProperties.after();
   }
-
-  private int getVMCount() {
-    try {
-      return getHost(0).getVMCount();
-    } catch (IllegalArgumentException e) {
-      throw new IllegalStateException("DUnit VMs have not been launched");
-    }
-  }
 }
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
index c14968b..5dcb1e5 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
@@ -14,38 +14,90 @@
  */
 package org.apache.geode.test.dunit.rules;
 
+import static org.apache.geode.test.dunit.Disconnect.disconnectFromDS;
+import static org.apache.geode.test.dunit.DistributedTestUtils.unregisterInstantiatorsInThisVM;
+import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.apache.geode.test.dunit.Invoke.invokeInLocator;
 import static org.apache.geode.test.dunit.VM.DEFAULT_VM_COUNT;
 import static org.apache.geode.test.dunit.VM.getVM;
 import static org.assertj.core.api.Assertions.assertThat;
 
+import org.apache.geode.cache.query.QueryTestUtils;
+import org.apache.geode.cache.query.internal.QueryObserverHolder;
+import org.apache.geode.cache30.ClientServerTestCase;
+import org.apache.geode.cache30.GlobalLockingDUnitTest;
+import org.apache.geode.cache30.MultiVMRegionTestCase;
+import org.apache.geode.cache30.RegionTestCase;
+import org.apache.geode.distributed.internal.DistributionConfig;
+import org.apache.geode.distributed.internal.DistributionMessageObserver;
+import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.distributed.internal.tcpserver.TcpClient;
+import org.apache.geode.internal.admin.ClientStatsManager;
+import org.apache.geode.internal.cache.CacheServerLauncher;
+import org.apache.geode.internal.cache.DiskStoreObserver;
+import org.apache.geode.internal.cache.InitialImageOperation;
+import org.apache.geode.internal.cache.tier.InternalClientMembership;
+import org.apache.geode.internal.cache.tier.sockets.CacheServerTestUtil;
+import org.apache.geode.internal.cache.tier.sockets.ClientProxyMembershipID;
+import org.apache.geode.internal.cache.tier.sockets.Message;
+import org.apache.geode.internal.cache.xmlcache.CacheCreation;
+import org.apache.geode.internal.net.SocketCreator;
+import org.apache.geode.internal.net.SocketCreatorFactory;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.pdx.internal.TypeRegistry;
+import org.apache.geode.test.dunit.IgnoredException;
 import org.apache.geode.test.dunit.standalone.DUnitLauncher;
+import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource;
 
 /**
- * JUnit Rule that launches DistributedTest VMs without {@code DistributedTestCase}. Class may need
- * to implement {@code Serializable}.
+ * JUnit Rule that launches DistributedTest VMs without {@code DistributedTestCase}. Test class may
+ * need to implement {@code Serializable}.
  *
  * <p>
- * {@code DistributedTestRule} follows the standard convention of using a {@code Builder} for
- * configuration as introduced in the JUnit {@code Timeout} rule.
- *
- * <p>
- * {@code DistributedTestRule} can be used in DistributedTests as a {@code ClassRule}:
+ * {@code DistributedTestRule} can be used in DistributedTests as a {@code ClassRule}. This ensures
+ * that DUnit VMs will be available to non-Class {@code Rule}s. Unfortunately, you will need to
+ * declare {@code DistributedTestRule.TearDown} as a non-Class {@code Rule}. Without
+ * {@code DistributedTestRule.TearDown} grep for suspect strings will not be invoked after each
+ * test.
  *
  * <pre>
  * {@literal @}ClassRule
  * public static DistributedTestRule distributedTestRule = new DistributedTestRule();
  *
+ * {@literal @}Rule
+ * public DistributedTestRule.TearDown tearDownRule = new DistributedTestRule.TearDown();
+ *
+ * {@literal @}Test
+ * public void shouldHaveFourDUnitVMsByDefault() {
+ *   assertThat(getVMCount()).isEqualTo(4);
+ * }
+ * </pre>
+ *
+ * <p>
+ * Or as a non-Class {@code Rule}. This usage does <bold>not</bold> require separate declaration of
+ * {@code DistributedTestRule.TearDown}:
+ *
+ * <pre>
+ * {@literal @}Rule
+ * public DistributedTestRule distributedTestRule = new DistributedTestRule();
+ *
+ * {@literal @}Rule
+ * public DistributedTestRule.TearDown tearDownRule = new DistributedTestRule.TearDown();
+ *
  * {@literal @}Test
  * public void shouldHaveFourDUnitVMsByDefault() {
- *   assertThat(Host.getHost(0).getVMCount()).isEqualTo(4);
+ *   assertThat(getVMCount()).isEqualTo(4);
  * }
  * </pre>
  */
 @SuppressWarnings("unused")
-public class DistributedTestRule extends DistributedExternalResource {
+public class DistributedTestRule extends AbstractDistributedTestRule {
 
   private final int vmCount;
 
+  /**
+   * Use {@code Builder} for more options in constructing {@code DistributedTestRule}.
+   */
   public static Builder builder() {
     return new Builder();
   }
@@ -63,13 +115,21 @@ public class DistributedTestRule extends DistributedExternalResource {
   }
 
   @Override
-  protected void before() throws Throwable {
+  protected void before() throws Exception {
     DUnitLauncher.launchIfNeeded();
     for (int i = 0; i < vmCount; i++) {
       assertThat(getVM(i)).isNotNull();
     }
   }
 
+  @Override
+  protected void after() {
+    TearDown.doTearDown();
+  }
+
+  /**
+   * Builds an instance of CacheRule.
+   */
   public static class Builder {
 
     private int vmCount = DEFAULT_VM_COUNT;
@@ -86,4 +146,96 @@ public class DistributedTestRule extends DistributedExternalResource {
       return new DistributedTestRule(this);
     }
   }
+
+  /**
+   * Cleans up horrendous things like static state and non-default instances in Geode.
+   *
+   * <p>
+   * {@link DistributedTestRule#after()} invokes the same cleanup that this Rule does, but if you
+   * defined {@code DistributedTestRule} as a {@code ClassRule} then you should declare TearDown
+   * as a non-class {@code Rule} in your test:
+   *
+   * <pre>
+   * {@literal @}ClassRule
+   * public static DistributedTestRule distributedTestRule = new DistributedTestRule();
+   *
+   * {@literal @}Rule
+   * public DistributedTestRule.TearDown tearDownRule = new DistributedTestRule.TearDown();
+   *
+   * {@literal @}Test
+   * public void shouldHaveFourDUnitVMsByDefault() {
+   *   assertThat(getVMCount()).isEqualTo(4);
+   * }
+   * </pre>
+   *
+   * <p>
+   * Note: {@link CacheRule} handles its own cleanup of Cache and Regions.
+   */
+  public static class TearDown extends SerializableExternalResource {
+
+    @Override
+    protected void before() throws Exception {
+      // nothing
+    }
+
+    @Override
+    protected void after() {
+      doTearDown();
+    }
+
+    static void doTearDown() {
+      tearDownInVM();
+      invokeInEveryVM(() -> {
+        tearDownInVM();
+      });
+      invokeInLocator(() -> {
+        DistributionMessageObserver.setInstance(null);
+        unregisterInstantiatorsInThisVM();
+      });
+      DUnitLauncher.closeAndCheckForSuspects();
+    }
+
+    private static void tearDownInVM() {
+      // 1. Please do NOT add to this list. I'm trying to DELETE this list.
+      // 2. Instead, please add to the after() of your test or your rule.
+
+      disconnectFromDS();
+
+      // keep alphabetized to detect duplicate lines
+      CacheCreation.clearThreadLocals();
+      CacheServerLauncher.clearStatics();
+      CacheServerTestUtil.clearCacheReference();
+      ClientProxyMembershipID.system = null;
+      ClientServerTestCase.AUTO_LOAD_BALANCE = false;
+      ClientStatsManager.cleanupForTests();
+      DiskStoreObserver.setInstance(null);
+      unregisterInstantiatorsInThisVM();
+      DistributionMessageObserver.setInstance(null);
+      GlobalLockingDUnitTest.region_testBug32356 = null;
+      InitialImageOperation.slowImageProcessing = 0;
+      InternalClientMembership.unregisterAllListeners();
+      LogWrapper.close();
+      MultiVMRegionTestCase.CCRegion = null;
+      QueryObserverHolder.reset();
+      QueryTestUtils.setCache(null);
+      RegionTestCase.preSnapshotRegion = null;
+      SocketCreator.resetHostNameCache();
+      SocketCreator.resolve_dns = true;
+      TcpClient.clearStaticData();
+
+      // clear system properties -- keep alphabetized
+      System.clearProperty(DistributionConfig.GEMFIRE_PREFIX + "log-level");
+      System.clearProperty("jgroups.resolve_dns");
+      System.clearProperty(Message.MAX_MESSAGE_SIZE_PROPERTY);
+
+      if (InternalDistributedSystem.systemAttemptingReconnect != null) {
+        InternalDistributedSystem.systemAttemptingReconnect.stopReconnecting();
+      }
+
+      IgnoredException.removeAllExpectedExceptions();
+      SocketCreatorFactory.close();
+      TypeRegistry.setPdxSerializer(null);
+      TypeRegistry.init();
+    }
+  }
 }
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java
index 8c85775..ca81b2c 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java
@@ -14,14 +14,20 @@
  */
 package org.apache.geode.test.dunit.rules;
 
+import static org.apache.geode.test.dunit.VM.getVMCount;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.apache.geode.test.dunit.standalone.DUnitLauncher;
 import org.apache.geode.test.junit.rules.UseJacksonForJsonPathRule;
 
 public class DistributedUseJacksonForJsonPathRule extends UseJacksonForJsonPathRule {
 
-  private static UseJacksonForJsonPathRule instance = new UseJacksonForJsonPathRule();
+  private static volatile UseJacksonForJsonPathRule instance = new UseJacksonForJsonPathRule();
 
   private final RemoteInvoker invoker;
 
+  private volatile int beforeVmCount;
+
   public DistributedUseJacksonForJsonPathRule() {
     this(new RemoteInvoker());
   }
@@ -32,19 +38,27 @@ public class DistributedUseJacksonForJsonPathRule extends UseJacksonForJsonPathR
 
   @Override
   public void before() {
-    this.invoker.invokeInEveryVMAndController(DistributedUseJacksonForJsonPathRule::invokeBefore);
+    DUnitLauncher.launchIfNeeded();
+    beforeVmCount = getVMCount();
+
+    invoker.invokeInEveryVMAndController(() -> invokeBefore());
   }
 
   @Override
   public void after() {
-    this.invoker.invokeInEveryVMAndController(DistributedUseJacksonForJsonPathRule::invokeAfter);
+    int afterVmCount = getVMCount();
+    assertThat(afterVmCount).isEqualTo(beforeVmCount);
+
+    invoker.invokeInEveryVMAndController(() -> invokeAfter());
   }
 
   private static void invokeBefore() {
+    instance = new UseJacksonForJsonPathRule();
     instance.before();
   }
 
   private static void invokeAfter() {
     instance.after();
+    instance = null;
   }
 }
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/SharedCountersRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/SharedCountersRule.java
index f1dbfae..9aa0273 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/SharedCountersRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/SharedCountersRule.java
@@ -14,7 +14,7 @@
  */
 package org.apache.geode.test.dunit.rules;
 
-import static org.apache.geode.test.dunit.Host.getHost;
+import static org.apache.geode.test.dunit.VM.getAllVMs;
 
 import java.io.Serializable;
 import java.util.ArrayList;
@@ -56,7 +56,7 @@ import org.apache.geode.test.dunit.VM;
  * </pre>
  */
 @SuppressWarnings({"serial", "unused"})
-public class SharedCountersRule extends DistributedExternalResource {
+public class SharedCountersRule extends AbstractDistributedTestRule {
 
   private static volatile Map<Serializable, AtomicInteger> counters;
 
@@ -67,15 +67,10 @@ public class SharedCountersRule extends DistributedExternalResource {
   }
 
   public SharedCountersRule() {
-    this(new Builder(), new RemoteInvoker());
+    this(new Builder());
   }
 
   SharedCountersRule(final Builder builder) {
-    this(builder, new RemoteInvoker());
-  }
-
-  SharedCountersRule(final Builder builder, final RemoteInvoker invoker) {
-    super(invoker);
     idsToInitInBefore.addAll(builder.ids);
   }
 
@@ -148,7 +143,7 @@ public class SharedCountersRule extends DistributedExternalResource {
    */
   public int getTotal(final Serializable id) {
     int total = counters.get(id).get();
-    for (VM vm : getHost(0).getAllVMs()) {
+    for (VM vm : getAllVMs()) {
       total += vm.invoke(() -> counters.get(id).get());
     }
     return total;
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/SharedErrorCollector.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/SharedErrorCollector.java
index 93b9f94..350ea00 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/SharedErrorCollector.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/SharedErrorCollector.java
@@ -14,6 +14,8 @@
  */
 package org.apache.geode.test.dunit.rules;
 
+import static org.apache.geode.test.dunit.VM.getAllVMs;
+
 import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.List;
@@ -21,12 +23,8 @@ import java.util.concurrent.Callable;
 
 import org.hamcrest.Matcher;
 import org.junit.rules.ErrorCollector;
-import org.junit.runner.Description;
-import org.junit.runners.model.Statement;
 
-import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.junit.rules.serializable.SerializableTestRule;
 
 /**
  * JUnit Rule that provides a shared ErrorCollector in all DistributedTest VMs. In particular, this
@@ -52,50 +50,31 @@ import org.apache.geode.test.junit.rules.serializable.SerializableTestRule;
  * </pre>
  */
 @SuppressWarnings({"serial", "unused"})
-public class SharedErrorCollector implements SerializableTestRule {
+public class SharedErrorCollector extends AbstractDistributedTestRule {
 
   private static volatile ProtectedErrorCollector errorCollector;
 
-  private final RemoteInvoker invoker;
-
   public SharedErrorCollector() {
-    this(new RemoteInvoker());
-  }
-
-  SharedErrorCollector(final RemoteInvoker invoker) {
-    this.invoker = invoker;
+    // nothing
   }
 
   @Override
-  public Statement apply(final Statement base, Description description) {
-    return new Statement() {
-      @Override
-      public void evaluate() throws Throwable {
-        before();
-        try {
-          base.evaluate();
-        } finally {
-          after();
-        }
-      }
-    };
-  }
-
   protected void before() throws Throwable {
-    invoker.invokeInEveryVMAndController(() -> errorCollector = new ProtectedErrorCollector());
+    invoker().invokeInEveryVMAndController(() -> errorCollector = new ProtectedErrorCollector());
   }
 
+  @Override
   protected void after() throws Throwable {
     ProtectedErrorCollector allErrors = errorCollector;
     try {
-      for (VM vm : Host.getHost(0).getAllVMs()) {
+      for (VM vm : getAllVMs()) {
         List<Throwable> remoteFailures = new ArrayList<>();
         remoteFailures.addAll(vm.invoke(() -> errorCollector.errors()));
         for (Throwable t : remoteFailures) {
           allErrors.addError(t);
         }
       }
-      invoker.invokeInEveryVMAndController(() -> errorCollector = null);
+      invoker().invokeInEveryVMAndController(() -> errorCollector = null);
     } finally {
       allErrors.verify();
     }
@@ -135,20 +114,19 @@ public class SharedErrorCollector implements SerializableTestRule {
    */
   private static class ProtectedErrorCollector extends ErrorCollector {
 
-    protected final List<Throwable> protectedErrors;
+    private final List<Throwable> protectedErrors;
 
-    public ProtectedErrorCollector() {
-      super();
+    ProtectedErrorCollector() {
       try {
         Field superErrors = ErrorCollector.class.getDeclaredField("errors");
         superErrors.setAccessible(true);
-        this.protectedErrors = (List<Throwable>) superErrors.get(this);
+        protectedErrors = (List<Throwable>) superErrors.get(this);
       } catch (IllegalAccessException | NoSuchFieldException e) {
         throw new RuntimeException(e);
       }
     }
 
-    public List<Throwable> errors() {
+    List<Throwable> errors() {
       return protectedErrors;
     }
 

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 12/13: GEODE-1279: Rename QueueRemovalMessageProcessingDistributedTest

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit 130a13d803d0dc5bf46bba8e1f9f4f408b952135
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Fri Apr 20 16:14:36 2018 -0700

    GEODE-1279: Rename QueueRemovalMessageProcessingDistributedTest
    
    * Bug47388DUnitTest -> QueueRemovalMessageProcessingDistributedTest
---
 .../cache/partitioned/Bug47388DUnitTest.java       | 265 --------------------
 ...eueRemovalMessageProcessingDistributedTest.java | 269 +++++++++++++++++++++
 2 files changed, 269 insertions(+), 265 deletions(-)

diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug47388DUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug47388DUnitTest.java
deleted file mode 100644
index 11e0ab1..0000000
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug47388DUnitTest.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.internal.cache.partitioned;
-
-import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_ID;
-import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_TIMEOUT;
-
-import java.util.Properties;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.EntryEvent;
-import org.apache.geode.cache.ExpirationAction;
-import org.apache.geode.cache.ExpirationAttributes;
-import org.apache.geode.cache.PartitionAttributesFactory;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionFactory;
-import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.client.ClientCacheFactory;
-import org.apache.geode.cache.client.ClientRegionFactory;
-import org.apache.geode.cache.client.ClientRegionShortcut;
-import org.apache.geode.cache.server.CacheServer;
-import org.apache.geode.cache.util.CacheListenerAdapter;
-import org.apache.geode.distributed.DistributedSystem;
-import org.apache.geode.internal.AvailablePort;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.ha.HARegionQueueStats;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
-import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-/**
- * The test creates two datastores with a partitioned region, and also running a cache server each.
- * A publisher client is connected to one server while a subscriber client is connected to both the
- * servers. The partitioned region has entry expiry set with ttl of 3 seconds and action as DESTROY.
- * The test ensures that the EXPIRE_DESTROY events are propagated to the subscriber client and the
- * secondary server does process the QRMs for the EXPIRE_DESTROY events.
- */
-@Category(DistributedTest.class)
-@SuppressWarnings("serial")
-public class Bug47388DUnitTest extends JUnit4DistributedTestCase {
-
-  private static VM vm0 = null;
-  private static VM vm1 = null;
-  private static VM vm2 = null;
-  private static VM vm3 = null;
-
-  private static GemFireCacheImpl cache;
-
-  private static volatile boolean lastKeyDestroyed = false;
-
-  public static final String REGION_NAME = Bug47388DUnitTest.class.getSimpleName() + "_region";
-
-  @Override
-  public final void postSetUp() throws Exception {
-    disconnectFromDS();
-    Host host = Host.getHost(0);
-    vm0 = host.getVM(0); // datastore and server
-    vm1 = host.getVM(1); // datastore and server
-    vm2 = host.getVM(2); // durable client with subscription
-    vm3 = host.getVM(3); // durable client without subscription
-
-    int port0 = (Integer) vm0.invoke(() -> Bug47388DUnitTest.createCacheServerWithPRDatastore());
-    int port1 = (Integer) vm1.invoke(() -> Bug47388DUnitTest.createCacheServerWithPRDatastore());
-
-    vm2.invoke(Bug47388DUnitTest.class, "createClientCache",
-        new Object[] {vm2.getHost(), new Integer[] {port0, port1}, Boolean.TRUE});
-    vm3.invoke(Bug47388DUnitTest.class, "createClientCache",
-        new Object[] {vm3.getHost(), new Integer[] {port0}, Boolean.FALSE});
-
-  }
-
-  @Override
-  public final void preTearDown() throws Exception {
-    closeCache();
-
-    vm2.invoke(() -> Bug47388DUnitTest.closeCache());
-    vm3.invoke(() -> Bug47388DUnitTest.closeCache());
-
-    vm0.invoke(() -> Bug47388DUnitTest.closeCache());
-    vm1.invoke(() -> Bug47388DUnitTest.closeCache());
-  }
-
-  public static void closeCache() throws Exception {
-    if (cache != null) {
-      cache.close();
-    }
-    lastKeyDestroyed = false;
-  }
-
-  @SuppressWarnings("deprecation")
-  public static Integer createCacheServerWithPRDatastore() throws Exception {
-    Properties props = new Properties();
-    Bug47388DUnitTest test = new Bug47388DUnitTest();
-    DistributedSystem ds = test.getSystem(props);
-    ds.disconnect();
-    cache = (GemFireCacheImpl) CacheFactory.create(test.getSystem());
-
-    RegionFactory<String, String> rf = cache.createRegionFactory(RegionShortcut.PARTITION);
-
-    rf.setEntryTimeToLive(new ExpirationAttributes(3, ExpirationAction.DESTROY))
-        .setPartitionAttributes(new PartitionAttributesFactory<String, String>()
-            .setRedundantCopies(1).setTotalNumBuckets(4).create())
-        .setConcurrencyChecksEnabled(false);
-
-    rf.create(REGION_NAME);
-
-    CacheServer server = cache.addCacheServer();
-    server.setPort(AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET));
-    server.start();
-    return server.getPort();
-  }
-
-  @SuppressWarnings("deprecation")
-  public static void createClientCache(Host host, Integer[] ports, Boolean doRI) throws Exception {
-    Properties props = new Properties();
-    props.setProperty(DURABLE_CLIENT_ID, "my-durable-client-" + ports.length);
-    props.setProperty(DURABLE_CLIENT_TIMEOUT, "300000");
-
-    DistributedSystem ds = new Bug47388DUnitTest().getSystem(props);
-    ds.disconnect();
-    ClientCacheFactory ccf = new ClientCacheFactory(props);
-    ccf.setPoolSubscriptionEnabled(doRI);
-    ccf.setPoolSubscriptionAckInterval(50);
-    ccf.setPoolSubscriptionRedundancy(1);
-    for (int port : ports) {
-      ccf.addPoolServer(host.getHostName(), port);
-    }
-    cache = (GemFireCacheImpl) ccf.create();
-
-    ClientRegionFactory<String, String> crf =
-        cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
-
-    if (doRI) {
-      crf.addCacheListener(new CacheListenerAdapter<String, String>() {
-        @Override
-        public void afterDestroy(EntryEvent<String, String> event) {
-          if (event.getKey().equalsIgnoreCase("LAST_KEY")) {
-            lastKeyDestroyed = true;
-          }
-        }
-      });
-    }
-
-    Region<String, String> region = crf.create(REGION_NAME);
-
-    if (doRI) {
-      region.registerInterest("ALL_KEYS", true);
-      cache.readyForEvents();
-    }
-  }
-
-  @SuppressWarnings("unchecked")
-  public static void doPuts(Integer numOfSets, Integer numOfPuts) throws Exception {
-    Region<String, String> region = cache.getRegion(REGION_NAME);
-
-    for (int i = 0; i < numOfSets; i++) {
-      for (int j = 0; j < numOfPuts; j++) {
-        region.put("KEY_" + i + "_" + j, "VALUE_" + j);
-      }
-    }
-    region.put("LAST_KEY", "LAST_KEY");
-  }
-
-  public static Boolean isPrimaryServer() {
-    return ((CacheClientProxy) CacheClientNotifier.getInstance().getClientProxies().toArray()[0])
-        .isPrimary();
-  }
-
-  public static void verifyClientSubscriptionStats(final Boolean isPrimary, final Integer events)
-      throws Exception {
-
-    WaitCriterion wc = new WaitCriterion() {
-      private long dispatched;
-      private long qrmed;
-
-      @Override
-      public boolean done() {
-        HARegionQueueStats stats =
-            ((CacheClientProxy) CacheClientNotifier.getInstance().getClientProxies().toArray()[0])
-                .getHARegionQueue().getStatistics();
-
-        final int numOfEvents;
-        if (!isPrimary) {
-          numOfEvents = events - 1; // No marker
-        } else {
-          numOfEvents = events;
-        }
-
-        if (isPrimary) {
-          this.dispatched = stats.getEventsDispatched();
-          return numOfEvents == this.dispatched;
-        } else {
-          this.qrmed = stats.getEventsRemovedByQrm();
-          return this.qrmed == numOfEvents || (this.qrmed + 1) == numOfEvents;
-          // Why +1 above? Because sometimes(TODO: explain further) there may
-          // not be any QRM sent to the secondary for the last event dispatched
-          // at primary.
-        }
-      }
-
-      @Override
-      public String description() {
-        return "Expected events: " + events + " but actual eventsDispatched: " + this.dispatched
-            + " and actual eventsRemovedByQrm: " + this.qrmed;
-      }
-    };
-
-    Wait.waitForCriterion(wc, 60 * 1000, 500, true);
-  }
-
-  public static void waitForLastKeyDestroyed() throws Exception {
-    WaitCriterion wc = new WaitCriterion() {
-      @Override
-      public boolean done() {
-        return lastKeyDestroyed;
-      }
-
-      @Override
-      public String description() {
-        return "Last key's destroy not received";
-      }
-
-    };
-
-    Wait.waitForCriterion(wc, 60 * 1000, 500, true);
-  }
-
-  @Ignore("TODO: test is disabled due to bug51931")
-  @Test
-  public void testQRMOfExpiredEventsProcessedSuccessfully() throws Exception {
-    int numOfSets = 2, numOfPuts = 5;
-    int totalEvents = 23; // = (numOfSets * numOfPuts) * 2 [eviction-destroys] +
-                          // 2 [last key's put and eviction-destroy] + 1 [marker
-                          // message]
-    vm3.invoke(() -> Bug47388DUnitTest.doPuts(numOfSets, numOfPuts));
-
-    boolean isvm0Primary = (Boolean) vm0.invoke(() -> Bug47388DUnitTest.isPrimaryServer());
-
-    vm2.invoke(() -> Bug47388DUnitTest.waitForLastKeyDestroyed());
-
-    vm0.invoke(() -> Bug47388DUnitTest.verifyClientSubscriptionStats(isvm0Primary, totalEvents));
-    vm1.invoke(() -> Bug47388DUnitTest.verifyClientSubscriptionStats(!isvm0Primary, totalEvents));
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/QueueRemovalMessageProcessingDistributedTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/QueueRemovalMessageProcessingDistributedTest.java
new file mode 100644
index 0000000..52e6eb0
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/QueueRemovalMessageProcessingDistributedTest.java
@@ -0,0 +1,269 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.internal.cache.partitioned;
+
+import static java.util.concurrent.TimeUnit.MINUTES;
+import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_ID;
+import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_TIMEOUT;
+import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.apache.geode.test.dunit.VM.getHostName;
+import static org.apache.geode.test.dunit.VM.getVM;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.Properties;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.EntryEvent;
+import org.apache.geode.cache.ExpirationAction;
+import org.apache.geode.cache.ExpirationAttributes;
+import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.client.ClientCacheFactory;
+import org.apache.geode.cache.client.ClientRegionFactory;
+import org.apache.geode.cache.client.ClientRegionShortcut;
+import org.apache.geode.cache.server.CacheServer;
+import org.apache.geode.cache.util.CacheListenerAdapter;
+import org.apache.geode.internal.cache.ha.HARegionQueueStats;
+import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
+import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.rules.CacheRule;
+import org.apache.geode.test.dunit.rules.ClientCacheRule;
+import org.apache.geode.test.dunit.rules.DistributedTestRule;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
+
+/**
+ * The test creates two datastores with a partitioned region, and also running a cache server each.
+ * A publisher client is connected to one server while a subscriber client is connected to both the
+ * servers. The partitioned region has entry expiry set with ttl of 3 seconds and action as DESTROY.
+ * The test ensures that the EXPIRE_DESTROY events are propagated to the subscriber client and the
+ * secondary server does process the QRMs for the EXPIRE_DESTROY events.
+ */
+@Category(DistributedTest.class)
+@SuppressWarnings("serial")
+public class QueueRemovalMessageProcessingDistributedTest implements Serializable {
+
+  private static final int TOTAL_NUM_BUCKETS = 4;
+
+  private static final AtomicInteger destroyedCount = new AtomicInteger();
+
+  private String regionName;
+  private String hostName;
+
+  private VM primary;
+  private VM secondary;
+
+  private VM server1;
+  private VM server2;
+  private VM client1;
+  private VM client2;
+
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
+
+  @Rule
+  public CacheRule cacheRule = new CacheRule();
+
+  @Rule
+  public ClientCacheRule clientCacheRule = new ClientCacheRule();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @Before
+  public void setUp() throws Exception {
+    server1 = getVM(0); // datastore and server
+    server2 = getVM(1); // datastore and server
+    client1 = getVM(2); // durable client with subscription
+    client2 = getVM(3); // durable client without subscription
+
+    regionName = getClass().getSimpleName() + "_" + testName.getMethodName();
+    hostName = getHostName();
+
+    int port1 = server1.invoke(() -> createCacheServerWithPRDatastore());
+    int port2 = server2.invoke(() -> createCacheServerWithPRDatastore());
+
+    client1.invoke(() -> createClientCacheWithRI(port1, port2, "client1"));
+    client2.invoke(() -> createClientCache(port1, "client2"));
+  }
+
+  @After
+  public void tearDown() throws Exception {
+    destroyedCount.set(0);
+    invokeInEveryVM(() -> {
+      destroyedCount.set(0);
+    });
+  }
+
+  @Test
+  public void testQRMOfExpiredEventsProcessedSuccessfully() throws Exception {
+    int putCount = 10;
+
+    // totalEvents = putCount * 2 [eviction-destroys] + 1 [marker message]
+    int totalEvents = putCount * 2 + 1;
+
+    client2.invoke(() -> doPuts(putCount));
+
+    identifyPrimaryServer();
+
+    client1.invoke(() -> await().atMost(1, MINUTES).until(() -> destroyedCount.get() == 10));
+
+    primary.invoke(() -> verifyClientSubscriptionStatsOnPrimary(totalEvents));
+    secondary.invoke(() -> verifyClientSubscriptionStatsOnSecondary(totalEvents));
+  }
+
+  private int createCacheServerWithPRDatastore() throws IOException {
+    cacheRule.createCache();
+
+    PartitionAttributesFactory<String, String> paf = new PartitionAttributesFactory<>();
+    paf.setRedundantCopies(1);
+    paf.setTotalNumBuckets(TOTAL_NUM_BUCKETS);
+
+    RegionFactory<String, String> rf =
+        cacheRule.getCache().createRegionFactory(RegionShortcut.PARTITION);
+    rf.setConcurrencyChecksEnabled(false);
+    rf.setEntryTimeToLive(new ExpirationAttributes(3, ExpirationAction.DESTROY));
+    rf.setPartitionAttributes(paf.create());
+
+    rf.create(regionName);
+
+    CacheServer server = cacheRule.getCache().addCacheServer();
+    server.setPort(0);
+    server.start();
+    return server.getPort();
+  }
+
+  private void createClientCacheWithRI(int port1, int port2, String durableClientId) {
+    Properties config = new Properties();
+    config.setProperty(DURABLE_CLIENT_ID, durableClientId);
+    config.setProperty(DURABLE_CLIENT_TIMEOUT, "300000");
+
+    ClientCacheFactory ccf = new ClientCacheFactory(config);
+    ccf.addPoolServer(hostName, port1);
+    ccf.addPoolServer(hostName, port2);
+    ccf.setPoolSubscriptionAckInterval(50);
+    ccf.setPoolSubscriptionEnabled(true);
+    ccf.setPoolSubscriptionRedundancy(1);
+
+    clientCacheRule.createClientCache(ccf);
+
+    ClientRegionFactory<String, String> crf = clientCacheRule.getClientCache()
+        .createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
+
+    crf.addCacheListener(new CacheListenerAdapter<String, String>() {
+      @Override
+      public void afterDestroy(EntryEvent<String, String> event) {
+        destroyedCount.incrementAndGet();
+      }
+    });
+
+    Region<String, String> region = crf.create(regionName);
+
+    region.registerInterest("ALL_KEYS", true);
+    clientCacheRule.getClientCache().readyForEvents();
+  }
+
+  private void createClientCache(int port, String durableClientId) {
+    Properties config = new Properties();
+    config.setProperty(DURABLE_CLIENT_ID, durableClientId);
+    config.setProperty(DURABLE_CLIENT_TIMEOUT, "300000");
+
+    ClientCacheFactory ccf = new ClientCacheFactory(config);
+    ccf.setPoolSubscriptionAckInterval(50);
+    ccf.setPoolSubscriptionRedundancy(1);
+    ccf.addPoolServer(hostName, port);
+
+    clientCacheRule.createClientCache(ccf);
+
+    ClientRegionFactory<String, String> crf = clientCacheRule.getClientCache()
+        .createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
+
+    crf.create(regionName);
+  }
+
+  private void doPuts(int putCount) {
+    Region<String, String> region = clientCacheRule.getClientCache().getRegion(regionName);
+
+    for (int i = 1; i <= putCount; i++) {
+      region.put("KEY-" + i, "VALUE-" + i);
+    }
+  }
+
+  private void verifyClientSubscriptionStatsOnPrimary(final int eventsCount) {
+    await().atMost(1, MINUTES).until(() -> allEventsHaveBeenDispatched(eventsCount));
+  }
+
+  private boolean allEventsHaveBeenDispatched(final int eventsCount) {
+    HARegionQueueStats stats = getCacheClientProxy().getHARegionQueue().getStatistics();
+
+    int numOfEvents = eventsCount;
+    long dispatched = stats.getEventsDispatched();
+
+    return numOfEvents == dispatched;
+  }
+
+  private void verifyClientSubscriptionStatsOnSecondary(final int eventsCount) {
+    await().atMost(1, MINUTES).until(() -> {
+      HARegionQueueStats stats = getCacheClientProxy().getHARegionQueue().getStatistics();
+
+      int numOfEvents = eventsCount - 1; // No marker
+
+      long qrmed = stats.getEventsRemovedByQrm();
+
+      return qrmed == numOfEvents || (qrmed + 1) == numOfEvents;
+      // Why +1 above? Because sometimes(TODO: explain further) there may
+      // not be any QRM sent to the secondary for the last event dispatched
+      // at primary.
+    });
+  }
+
+  private void identifyPrimaryServer() {
+    boolean primaryIsServer1 = server1.invoke(() -> isPrimaryServerForClient());
+
+    assertThat(primaryIsServer1).isNotEqualTo(server2.invoke(() -> isPrimaryServerForClient()));
+
+    if (primaryIsServer1) {
+      primary = server1;
+      secondary = server2;
+    } else {
+      primary = server2;
+      secondary = server1;
+    }
+
+    assertThat(primary).isNotNull();
+    assertThat(secondary).isNotNull();
+    assertThat(primary).isNotEqualTo(secondary);
+  }
+
+  private static CacheClientProxy getCacheClientProxy() {
+    return (CacheClientProxy) CacheClientNotifier.getInstance().getClientProxies().toArray()[0];
+  }
+
+  private static boolean isPrimaryServerForClient() {
+    return getCacheClientProxy().isPrimary();
+  }
+}

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.

[geode] 10/13: GEODE-1279: Rename RegisterInterestKeysValuesDistributedTest

Posted by kl...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

klund pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git

commit fcc943602726a74be68ffefb5843726a7c0f4f00
Author: Kirk Lund <kl...@apache.org>
AuthorDate: Fri Apr 20 16:11:46 2018 -0700

    GEODE-1279: Rename RegisterInterestKeysValuesDistributedTest
    
    * Bug43684DUnitTest -> RegisterInterestKeysValuesDistributedTest
    * Add "boolean containsTombstone(Object key)" to InternalRegion
---
 .../geode/internal/cache/InternalRegion.java       |   2 +
 .../cache/partitioned/Bug43684DUnitTest.java       | 359 -------------------
 .../RegisterInterestKeysValuesDistributedTest.java | 394 +++++++++++++++++++++
 3 files changed, 396 insertions(+), 359 deletions(-)

diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/InternalRegion.java b/geode-core/src/main/java/org/apache/geode/internal/cache/InternalRegion.java
index 7c5d722..65a2b73 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/InternalRegion.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/InternalRegion.java
@@ -238,4 +238,6 @@ public interface InternalRegion extends Region, HasCachePerfStats, RegionEntryCo
    * @return boolean indicating whether to generate eventID or not
    */
   boolean generateEventID();
+
+  boolean containsTombstone(Object key);
 }
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug43684DUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug43684DUnitTest.java
deleted file mode 100644
index 0f6ea80..0000000
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/Bug43684DUnitTest.java
+++ /dev/null
@@ -1,359 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
- * agreements. See the NOTICE file distributed with this work for additional information regarding
- * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
- */
-package org.apache.geode.internal.cache.partitioned;
-
-import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.PartitionAttributesFactory;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionFactory;
-import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.client.ClientCacheFactory;
-import org.apache.geode.cache.client.ClientRegionFactory;
-import org.apache.geode.cache.client.ClientRegionShortcut;
-import org.apache.geode.internal.AvailablePort;
-import org.apache.geode.internal.OSProcess;
-import org.apache.geode.internal.cache.CacheServerImpl;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.LocalRegion;
-import org.apache.geode.internal.cache.RegionEntry;
-import org.apache.geode.internal.i18n.LocalizedStrings;
-import org.apache.geode.test.dunit.DistributedTestUtils;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.IgnoredException;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-/**
- * TODO This doesn't really test the optimised RI behaviour but only that RI works. But there must
- * be other tests doing the same.
- */
-@Category(DistributedTest.class)
-@SuppressWarnings("serial")
-public class Bug43684DUnitTest extends JUnit4DistributedTestCase {
-
-  private static final String REGION_NAME = Bug43684DUnitTest.class.getSimpleName();
-
-  private static GemFireCacheImpl cache;
-
-  private Host host;
-
-  private static VM server1;
-
-  private static VM server2;
-
-  private static VM server3;
-
-  private static VM client1;
-
-  private static int numBuckets = 11;
-
-  @Override
-  public final void postSetUp() throws Exception {
-    host = Host.getHost(0);
-    server1 = host.getVM(0);
-    server2 = host.getVM(1);
-    server3 = host.getVM(2);
-    client1 = host.getVM(3);
-    IgnoredException.addIgnoredException("Connection refused: connect");
-  }
-
-  @Override
-  public final void preTearDown() throws Exception {
-    closeCache();
-    client1.invoke(() -> Bug43684DUnitTest.closeCache());
-    server1.invoke(() -> Bug43684DUnitTest.closeCache());
-    server2.invoke(() -> Bug43684DUnitTest.closeCache());
-    server3.invoke(() -> Bug43684DUnitTest.closeCache());
-  }
-
-  public static void closeCache() {
-    if (cache != null && !cache.isClosed()) {
-      cache.close();
-    }
-    disconnectFromDS();
-  }
-
-  @Test
-  public void testRIWithSingleKeyOnRR() throws Exception {
-    doRegisterInterest("KEY_1", null, numBuckets, true, false);
-  }
-
-  @Test
-  public void testRIWithAllKeysOnRR() throws Exception {
-    doRegisterInterest(null, null, numBuckets, true, false);
-  }
-
-  @Test
-  public void testRIWithKeyListOnRR() throws Exception {
-    ArrayList<String> riKeys = new ArrayList<String>();
-    riKeys.add("KEY_0");
-    riKeys.add("KEY_1");
-    riKeys.add("KEY_2");
-    riKeys.add("KEY_5");
-    riKeys.add("KEY_6");
-    riKeys.add("KEY_7");
-    riKeys.add("KEY_9");
-
-    doRegisterInterest(riKeys, null, numBuckets, true, false);
-  }
-
-  @Test
-  public void testRIWithRegularExpressionOnRR() throws Exception {
-    doRegisterInterest(null, "^[X][_].*", numBuckets, true, false);
-  }
-
-  @Test
-  public void testRIWithSingleKeyOnPR() throws Exception {
-    doRegisterInterest("KEY_1", null);
-  }
-
-  @Test
-  public void testRIWithAllKeysOnPR() throws Exception {
-    doRegisterInterest(null, null);
-  }
-
-  @Test
-  public void testRIWithKeyListOnPR() throws Exception {
-    ArrayList<String> riKeys = new ArrayList<String>();
-    riKeys.add("KEY_0");
-    riKeys.add("KEY_1");
-    riKeys.add("KEY_2");
-    riKeys.add("KEY_5");
-    riKeys.add("KEY_6");
-    riKeys.add("KEY_7");
-    riKeys.add("KEY_9");
-
-    doRegisterInterest(riKeys, null);
-  }
-
-  @Test
-  public void testRIWithRegularExpressionOnPR() throws Exception {
-    doRegisterInterest(null, "^[X][_].*");
-  }
-
-  @Test
-  public void testRIWithMoreEntriesOnPR() throws Exception {
-    doRegisterInterest(null, null, 5147, false, false);
-  }
-
-  @Test
-  public void testRIWithSingleKeyOnEmptyPrimaryOnPR() throws Exception {
-    doRegisterInterest("KEY_1", null, numBuckets, false, true);
-  }
-
-  @Test
-  public void testRIWithAllKeysOnEmptyPrimaryOnPR() throws Exception {
-    doRegisterInterest(null, null, numBuckets, false, true);
-  }
-
-  @Test
-  public void testRIWithKeyListOnEmptyPrimaryOnPR() throws Exception {
-    ArrayList<String> riKeys = new ArrayList<String>();
-    riKeys.add("KEY_0");
-    riKeys.add("KEY_1");
-    riKeys.add("KEY_2");
-    riKeys.add("KEY_5");
-    riKeys.add("KEY_6");
-    riKeys.add("KEY_7");
-    riKeys.add("KEY_9");
-
-    doRegisterInterest(riKeys, null, numBuckets, false, true);
-  }
-
-  @Test
-  public void testRIWithRegularExpressionOnEmptyPrimaryOnPR() throws Exception {
-    doRegisterInterest(null, "^[X][_].*", numBuckets, false, true);
-  }
-
-  @Test
-  public void testNativeClientIssueOnPR() throws Exception {
-    ArrayList<String> riKeys = new ArrayList<String>();
-    riKeys.add("OPKEY_0");
-    riKeys.add("OPKEY_1");
-    riKeys.add("OPKEY_2");
-    riKeys.add("OPKEY_3");
-    riKeys.add("OPKEY_4");
-    riKeys.add("OPKEY_5");
-    riKeys.add("OPKEY_6");
-    riKeys.add("OPKEY_7");
-    riKeys.add("OPKEY_8");
-    riKeys.add("OPKEY_9");
-    riKeys.add("OPKEY_10");
-    riKeys.add("OPKEY_11");
-    riKeys.add("OPKEY_12");
-    riKeys.add("OPKEY_13");
-    doRegisterInterest2(riKeys, false, false);
-  }
-
-  private void doRegisterInterest(Object keys, String regEx) throws Exception {
-    doRegisterInterest(keys, regEx, numBuckets, false, false);
-  }
-
-  @SuppressWarnings("rawtypes")
-  private void doRegisterInterest(Object keys, String regEx, Integer numOfPuts,
-      Boolean isReplicated, Boolean isPrimaryEmpty) throws Exception {
-    int port1 = (Integer) server1
-        .invoke(() -> Bug43684DUnitTest.createServerCache(isReplicated, isPrimaryEmpty));
-    server2.invoke(() -> Bug43684DUnitTest.createServerCache(isReplicated, false));
-    server3.invoke(() -> Bug43684DUnitTest.createServerCache(isReplicated, false));
-
-    int regexNum = 20;
-    server1.invoke(() -> Bug43684DUnitTest.doPuts(numOfPuts, regEx, regexNum));
-
-    client1.invoke(() -> Bug43684DUnitTest.createClientCache(host, port1));
-    client1.invoke(() -> Bug43684DUnitTest.registerInterest(keys, regEx));
-
-    server1.invoke(() -> Bug43684DUnitTest.closeCache());
-    int size = keys != null ? (keys instanceof List ? ((List) keys).size() : 1)
-        : regEx == null ? numOfPuts : regexNum;
-    client1.invoke(() -> Bug43684DUnitTest.verifyResponse(size));
-  }
-
-  @SuppressWarnings("rawtypes")
-  private void doRegisterInterest2(Object keys, Boolean isReplicated, Boolean isPrimaryEmpty)
-      throws Exception {
-    int port1 = (Integer) server1
-        .invoke(() -> Bug43684DUnitTest.createServerCache(isReplicated, isPrimaryEmpty));
-    server2.invoke(() -> Bug43684DUnitTest.createServerCache(isReplicated, false));
-    server3.invoke(() -> Bug43684DUnitTest.createServerCache(isReplicated, false));
-
-    client1.invoke(() -> Bug43684DUnitTest.createClientCache(host, port1));
-    createClientCache(host, port1);
-    doOps();
-
-    client1.invoke(() -> Bug43684DUnitTest.registerInterest(keys, null));
-    client1.invoke(() -> Bug43684DUnitTest.verifyResponse2());
-  }
-
-  public static Integer createServerCache() throws Exception {
-    return createServerCache(false, false);
-  }
-
-  @SuppressWarnings("rawtypes")
-  public static Integer createServerCache(Boolean isReplicated, Boolean isPrimaryEmpty)
-      throws Exception {
-    disconnectFromDS();
-    Properties props = new Properties();
-    props.setProperty(LOCATORS, "localhost[" + DistributedTestUtils.getDUnitLocatorPort() + "]");
-    props.setProperty(STATISTIC_ARCHIVE_FILE, "server_" + OSProcess.getId() + ".gfs");
-    props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
-    CacheFactory cf = new CacheFactory(props);
-    cache = (GemFireCacheImpl) cf.create();
-
-    RegionFactory rf;
-    if (isReplicated) {
-      RegionShortcut rs =
-          isPrimaryEmpty ? RegionShortcut.REPLICATE_PROXY : RegionShortcut.REPLICATE;
-      rf = cache.createRegionFactory(rs);
-    } else {
-      RegionShortcut rs =
-          isPrimaryEmpty ? RegionShortcut.PARTITION_PROXY : RegionShortcut.PARTITION;
-      rf = cache.createRegionFactory(rs);
-      rf.setPartitionAttributes(
-          new PartitionAttributesFactory().setTotalNumBuckets(numBuckets).create());
-    }
-    rf.create(REGION_NAME);
-    CacheServerImpl server = (CacheServerImpl) cache.addCacheServer();
-    server.setPort(AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET));
-    server.start();
-    return server.getPort();
-  }
-
-  @SuppressWarnings({"unchecked", "rawtypes"})
-  public static void createClientCache(Host host, Integer port) {
-    disconnectFromDS();
-    Properties props = new Properties();
-    props.setProperty(STATISTIC_ARCHIVE_FILE, "client_" + OSProcess.getId() + ".gfs");
-    props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
-    ClientCacheFactory ccf = new ClientCacheFactory(props);
-    ccf.addPoolServer(host.getHostName(), port).setPoolSubscriptionEnabled(true);
-    cache = (GemFireCacheImpl) ccf.create();
-    ClientRegionFactory crf = cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
-    crf.create(REGION_NAME);
-  }
-
-  @SuppressWarnings({"unchecked", "rawtypes"})
-  public static void registerInterest(Object keys, String regEx) {
-    Region region = cache.getRegion(REGION_NAME);
-    if (keys == null && regEx == null) {
-      region.registerInterest("ALL_KEYS");
-    } else if (keys != null) {
-      region.registerInterest(keys);
-      region.registerInterest("UNKNOWN_KEY");
-    } else if (regEx != null) {
-      region.registerInterestRegex(regEx);
-    }
-  }
-
-  @SuppressWarnings({"rawtypes", "unchecked"})
-  public static void doPuts(Integer num, String regex, int regexNum) throws Exception {
-    Region r = cache.getRegion(REGION_NAME);
-    for (int i = 0; i < num; i++) {
-      r.create("KEY_" + i, "VALUE__" + i);
-    }
-    if (regex != null) {
-      for (int i = 0; i < regexNum; i++) {
-        r.create("X_KEY_" + i, "X_VALUE__" + i);
-      }
-    }
-  }
-
-  @SuppressWarnings({"rawtypes", "unchecked"})
-  public static void doOps() throws Exception {
-    Region r = cache.getRegion(REGION_NAME);
-    for (int i = 0; i < 14; i++) {
-      r.create("OPKEY_" + i, "OPVALUE__" + i);
-    }
-
-    for (int i = 7; i < 14; i++) {
-      r.destroy("OPKEY_" + i);
-    }
-  }
-
-  public static void verifyResponse2() throws Exception {
-    LocalRegion r = (LocalRegion) cache.getRegion(REGION_NAME);
-    for (int i = 0; i < 7; i++) {
-      assertTrue(r.containsKey("OPKEY_" + i));
-    }
-    for (int i = 7; i < 14; i++) {
-      assertFalse(r.containsKey("OPKEY_" + i));
-      assertTrue(r.containsTombstone("OPKEY_" + i));
-    }
-  }
-
-  public static void verifyResponse(Integer size) throws Exception {
-    LocalRegion r = (LocalRegion) cache.getRegion(REGION_NAME);
-    assertEquals(size.intValue(), r.size());
-  }
-
-  public static void getLocally() throws Exception {
-    LocalRegion r = (LocalRegion) cache.getRegion(REGION_NAME);
-    for (int i = 0; i < numBuckets; i++) {
-      RegionEntry e = r.getRegionEntry("KEY_" + i);
-      cache.getLoggerI18n().info(LocalizedStrings.DEBUG, e.getValue());
-    }
-  }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/RegisterInterestKeysValuesDistributedTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/RegisterInterestKeysValuesDistributedTest.java
new file mode 100644
index 0000000..2ff7edc
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/partitioned/RegisterInterestKeysValuesDistributedTest.java
@@ -0,0 +1,394 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.internal.cache.partitioned;
+
+import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
+import static org.apache.geode.test.dunit.VM.getHostName;
+import static org.apache.geode.test.dunit.VM.getVM;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.client.ClientCacheFactory;
+import org.apache.geode.cache.client.ClientRegionFactory;
+import org.apache.geode.cache.client.ClientRegionShortcut;
+import org.apache.geode.cache.client.internal.InternalClientCache;
+import org.apache.geode.cache.server.CacheServer;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.cache.InternalRegion;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.rules.CacheRule;
+import org.apache.geode.test.dunit.rules.ClientCacheRule;
+import org.apache.geode.test.dunit.rules.DistributedTestRule;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
+
+/**
+ * Functional distributed tests for Register Interest with KEYS_VALUES policy.
+ *
+ * <p>
+ * TRAC #43684: Register interest with policy KEYS_VALUES is inefficient
+ */
+@Category(DistributedTest.class)
+@SuppressWarnings("serial")
+public class RegisterInterestKeysValuesDistributedTest implements Serializable {
+
+  private VM server1;
+  private VM server2;
+  private VM server3;
+  private VM client1;
+
+  private String regionName;
+  private String hostName;
+  private int bucketCount;
+  private int regexCount;
+  private int port1;
+
+  @Rule
+  public DistributedTestRule distributedTestRule = new DistributedTestRule();
+
+  @Rule
+  public CacheRule cacheRule = new CacheRule();
+
+  @Rule
+  public ClientCacheRule clientCacheRule = new ClientCacheRule();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @Before
+  public void setUp() throws Exception {
+    server1 = getVM(0);
+    server2 = getVM(1);
+    server3 = getVM(2);
+    client1 = getVM(3);
+
+    regionName = getClass().getSimpleName() + "_" + testName.getMethodName();
+    hostName = getHostName();
+    bucketCount = 11;
+    regexCount = 20;
+
+    addIgnoredException("Connection refused: connect");
+  }
+
+  @Test
+  public void testRIWithSingleKeyOnRR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(true, false));
+    server2.invoke(() -> createServerCache(true, false));
+    server3.invoke(() -> createServerCache(true, false));
+
+    doRegisterInterest("KEY_1", null, bucketCount);
+  }
+
+  @Test
+  public void testRIWithAllKeysOnRR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(true, false));
+    server2.invoke(() -> createServerCache(true, false));
+    server3.invoke(() -> createServerCache(true, false));
+
+    doRegisterInterest(null, null, bucketCount);
+  }
+
+  @Test
+  public void testRIWithKeyListOnRR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(true, false));
+    server2.invoke(() -> createServerCache(true, false));
+    server3.invoke(() -> createServerCache(true, false));
+
+    List<String> riKeys = new ArrayList<>();
+    riKeys.add("KEY_0");
+    riKeys.add("KEY_1");
+    riKeys.add("KEY_2");
+    riKeys.add("KEY_5");
+    riKeys.add("KEY_6");
+    riKeys.add("KEY_7");
+    riKeys.add("KEY_9");
+
+    doRegisterInterest(riKeys, null, bucketCount);
+  }
+
+  @Test
+  public void testRIWithRegularExpressionOnRR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(true, false));
+    server2.invoke(() -> createServerCache(true, false));
+    server3.invoke(() -> createServerCache(true, false));
+
+    doRegisterInterest(null, "^[X][_].*", bucketCount);
+  }
+
+  @Test
+  public void testRIWithSingleKeyOnPR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(false, false));
+    server2.invoke(() -> createServerCache(false, false));
+    server3.invoke(() -> createServerCache(false, false));
+
+    doRegisterInterest("KEY_1", null, bucketCount);
+  }
+
+  @Test
+  public void testRIWithAllKeysOnPR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(false, false));
+    server2.invoke(() -> createServerCache(false, false));
+    server3.invoke(() -> createServerCache(false, false));
+
+    doRegisterInterest(null, null, bucketCount);
+  }
+
+  @Test
+  public void testRIWithKeyListOnPR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(false, false));
+    server2.invoke(() -> createServerCache(false, false));
+    server3.invoke(() -> createServerCache(false, false));
+
+    List<String> riKeys = new ArrayList<>();
+    riKeys.add("KEY_0");
+    riKeys.add("KEY_1");
+    riKeys.add("KEY_2");
+    riKeys.add("KEY_5");
+    riKeys.add("KEY_6");
+    riKeys.add("KEY_7");
+    riKeys.add("KEY_9");
+
+    doRegisterInterest(riKeys, null, bucketCount);
+  }
+
+  @Test
+  public void testRIWithRegularExpressionOnPR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(false, false));
+    server2.invoke(() -> createServerCache(false, false));
+    server3.invoke(() -> createServerCache(false, false));
+
+    doRegisterInterest(null, "^[X][_].*", bucketCount);
+  }
+
+  @Test
+  public void testRIWithMoreEntriesOnPR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(false, false));
+    server2.invoke(() -> createServerCache(false, false));
+    server3.invoke(() -> createServerCache(false, false));
+
+    doRegisterInterest(null, null, 5147);
+  }
+
+  @Test
+  public void testRIWithSingleKeyOnEmptyPrimaryOnPR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(false, true));
+    server2.invoke(() -> createServerCache(false, false));
+    server3.invoke(() -> createServerCache(false, false));
+
+    doRegisterInterest("KEY_1", null, bucketCount);
+  }
+
+  @Test
+  public void testRIWithAllKeysOnEmptyPrimaryOnPR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(false, true));
+    server2.invoke(() -> createServerCache(false, false));
+    server3.invoke(() -> createServerCache(false, false));
+
+    doRegisterInterest(null, null, bucketCount);
+  }
+
+  @Test
+  public void testRIWithKeyListOnEmptyPrimaryOnPR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(false, true));
+    server2.invoke(() -> createServerCache(false, false));
+    server3.invoke(() -> createServerCache(false, false));
+
+    List<String> riKeys = new ArrayList<>();
+    riKeys.add("KEY_0");
+    riKeys.add("KEY_1");
+    riKeys.add("KEY_2");
+    riKeys.add("KEY_5");
+    riKeys.add("KEY_6");
+    riKeys.add("KEY_7");
+    riKeys.add("KEY_9");
+
+    doRegisterInterest(riKeys, null, bucketCount);
+  }
+
+  @Test
+  public void testRIWithRegularExpressionOnEmptyPrimaryOnPR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(false, true));
+    server2.invoke(() -> createServerCache(false, false));
+    server3.invoke(() -> createServerCache(false, false));
+
+    doRegisterInterest(null, "^[X][_].*", bucketCount);
+  }
+
+  @Test
+  public void testNativeClientIssueOnPR() throws Exception {
+    port1 = server1.invoke(() -> createServerCache(false, false));
+    server2.invoke(() -> createServerCache(false, false));
+    server3.invoke(() -> createServerCache(false, false));
+
+    List<String> keys = new ArrayList<>();
+    keys.add("OPKEY_0");
+    keys.add("OPKEY_1");
+    keys.add("OPKEY_2");
+    keys.add("OPKEY_3");
+    keys.add("OPKEY_4");
+    keys.add("OPKEY_5");
+    keys.add("OPKEY_6");
+    keys.add("OPKEY_7");
+    keys.add("OPKEY_8");
+    keys.add("OPKEY_9");
+    keys.add("OPKEY_10");
+    keys.add("OPKEY_11");
+    keys.add("OPKEY_12");
+    keys.add("OPKEY_13");
+
+    client1.invoke(() -> createClientCache(port1));
+    createClientCache(port1);
+    doOps();
+
+    client1.invoke(() -> {
+      Region region = clientCache().getRegion(regionName);
+      region.registerInterest(keys);
+      region.registerInterest("UNKNOWN_KEY");
+    });
+
+    client1.invoke(() -> {
+      InternalRegion region = (InternalRegion) clientCache().getRegion(regionName);
+      for (int i = 0; i < 7; i++) {
+        assertTrue(region.containsKey("OPKEY_" + i));
+      }
+      for (int i = 7; i < 14; i++) {
+        assertFalse(region.containsKey("OPKEY_" + i));
+        assertTrue(region.containsTombstone("OPKEY_" + i));
+      }
+    });
+  }
+
+  private void doRegisterInterest(Object keys, String regEx, int numOfPuts) {
+    server1.invoke(() -> doPuts(numOfPuts, regEx, regexCount));
+
+    client1.invoke(() -> createClientCache(port1));
+    client1.invoke(() -> registerInterest(keys, regEx));
+
+    server1.invoke(() -> cache().close());
+
+    // int size = getExpectedSize(keys, regEx, numOfPuts);
+    client1.invoke(() -> verifyResponse(getExpectedSize(keys, regEx, numOfPuts)));
+  }
+
+  private int getExpectedSize(Object keys, String regEx, int numOfPuts) {
+    return keys != null ? (keys instanceof List ? ((List) keys).size() : 1)
+        : regEx == null ? numOfPuts : regexCount;
+  }
+
+  private int createServerCache(boolean isReplicated, boolean isPrimaryEmpty) throws IOException {
+    createCache();
+
+    RegionFactory rf;
+    if (isReplicated) {
+      RegionShortcut rs =
+          isPrimaryEmpty ? RegionShortcut.REPLICATE_PROXY : RegionShortcut.REPLICATE;
+      rf = cache().createRegionFactory(rs);
+    } else {
+      RegionShortcut rs =
+          isPrimaryEmpty ? RegionShortcut.PARTITION_PROXY : RegionShortcut.PARTITION;
+      rf = cache().createRegionFactory(rs);
+      rf.setPartitionAttributes(
+          new PartitionAttributesFactory().setTotalNumBuckets(bucketCount).create());
+    }
+    rf.create(regionName);
+
+    CacheServer server = cache().addCacheServer();
+    server.setPort(0);
+    server.start();
+    return server.getPort();
+  }
+
+  private void createClientCache(int port) {
+    ClientCacheFactory ccf = new ClientCacheFactory();
+    ccf.addPoolServer(hostName, port).setPoolSubscriptionEnabled(true);
+
+    createClientCache(ccf);
+
+    ClientRegionFactory crf =
+        clientCache().createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
+    crf.create(regionName);
+  }
+
+  private void registerInterest(Object keys, String regEx) {
+    Region region = clientCache().getRegion(regionName);
+    if (keys == null && regEx == null) {
+      region.registerInterest("ALL_KEYS");
+    } else if (keys != null) {
+      region.registerInterest(keys);
+      region.registerInterest("UNKNOWN_KEY");
+    } else if (regEx != null) {
+      region.registerInterestRegex(regEx);
+    }
+  }
+
+  private void doPuts(int count, String regex, int regexNum) {
+    Region region = cache().getRegion(regionName);
+    for (int i = 0; i < count; i++) {
+      region.create("KEY_" + i, "VALUE__" + i);
+    }
+    if (regex != null) {
+      for (int i = 0; i < regexNum; i++) {
+        region.create("X_KEY_" + i, "X_VALUE__" + i);
+      }
+    }
+  }
+
+  private void doOps() {
+    Region region = clientCache().getRegion(regionName);
+    for (int i = 0; i < 14; i++) {
+      region.create("OPKEY_" + i, "OPVALUE__" + i);
+    }
+
+    for (int i = 7; i < 14; i++) {
+      region.destroy("OPKEY_" + i);
+    }
+  }
+
+  private void verifyResponse(int size) {
+    Region region = clientCache().getRegion(regionName);
+    assertEquals(size, region.size());
+  }
+
+  private InternalCache cache() {
+    return cacheRule.getCache();
+  }
+
+  private InternalClientCache clientCache() {
+    return clientCacheRule.getClientCache();
+  }
+
+  private void createCache() {
+    cacheRule.createCache();
+  }
+
+  private void createClientCache(ClientCacheFactory ccf) {
+    clientCacheRule.createClientCache(ccf);
+  }
+}

-- 
To stop receiving notification emails like this one, please contact
klund@apache.org.