Return-Path: X-Original-To: archive-asf-public-internal@cust-asf2.ponee.io Delivered-To: archive-asf-public-internal@cust-asf2.ponee.io Received: from cust-asf.ponee.io (cust-asf.ponee.io [163.172.22.183]) by cust-asf2.ponee.io (Postfix) with ESMTP id 1A6FE200AC6 for ; Sat, 7 May 2016 01:55:31 +0200 (CEST) Received: by cust-asf.ponee.io (Postfix) id 18F4E160A0D; Fri, 6 May 2016 23:55:31 +0000 (UTC) Delivered-To: archive-asf-public@cust-asf.ponee.io Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by cust-asf.ponee.io (Postfix) with SMTP id C3903160A0C for ; Sat, 7 May 2016 01:55:28 +0200 (CEST) Received: (qmail 86962 invoked by uid 500); 6 May 2016 23:55:28 -0000 Mailing-List: contact commits-help@geode.incubator.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@geode.incubator.apache.org Delivered-To: mailing list commits@geode.incubator.apache.org Received: (qmail 86953 invoked by uid 99); 6 May 2016 23:55:28 -0000 Received: from pnap-us-west-generic-nat.apache.org (HELO spamd3-us-west.apache.org) (209.188.14.142) by apache.org (qpsmtpd/0.29) with ESMTP; Fri, 06 May 2016 23:55:27 +0000 Received: from localhost (localhost [127.0.0.1]) by spamd3-us-west.apache.org (ASF Mail Server at spamd3-us-west.apache.org) with ESMTP id 6C65B1804D9 for ; Fri, 6 May 2016 23:55:27 +0000 (UTC) X-Virus-Scanned: Debian amavisd-new at spamd3-us-west.apache.org X-Spam-Flag: NO X-Spam-Score: -3.221 X-Spam-Level: X-Spam-Status: No, score=-3.221 tagged_above=-999 required=6.31 tests=[KAM_ASCII_DIVIDERS=0.8, KAM_LAZY_DOMAIN_SECURITY=1, RCVD_IN_DNSWL_HI=-5, RCVD_IN_MSPIKE_H3=-0.01, RCVD_IN_MSPIKE_WL=-0.01, RP_MATCHES_RCVD=-0.001] autolearn=disabled Received: from mx1-lw-eu.apache.org ([10.40.0.8]) by localhost (spamd3-us-west.apache.org [10.40.0.10]) (amavisd-new, port 10024) with ESMTP id Mg2X2dBlygeM for ; Fri, 6 May 2016 23:55:15 +0000 (UTC) Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by mx1-lw-eu.apache.org (ASF Mail Server at mx1-lw-eu.apache.org) with SMTP id 77C855FB9A for ; Fri, 6 May 2016 23:55:01 +0000 (UTC) Received: (qmail 85032 invoked by uid 99); 6 May 2016 23:55:00 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Fri, 06 May 2016 23:55:00 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id 517C3E049D; Fri, 6 May 2016 23:55:00 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: klund@apache.org To: commits@geode.incubator.apache.org Date: Fri, 06 May 2016 23:55:12 -0000 Message-Id: <07950025b51343deb8df54a59a2762ac@git.apache.org> In-Reply-To: <947e11e8f5d64e8b8c40653348c7bff8@git.apache.org> References: <947e11e8f5d64e8b8c40653348c7bff8@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [13/18] incubator-geode git commit: GEODE-1276: Change UnitTests file system to IntegrationTest category GEODE-1307: Rename HeterogenousLuceneSerializer to HeterogeneousLuceneSerializer GEODE-1279: Tests for old TRAC bugs should be renamed to useful name archived-at: Fri, 06 May 2016 23:55:31 -0000 http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/GMSMemberJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/GMSMemberJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/GMSMemberJUnitTest.java index 606ae1a..7eef594 100644 --- a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/GMSMemberJUnitTest.java +++ b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/GMSMemberJUnitTest.java @@ -16,32 +16,32 @@ */ package com.gemstone.gemfire.distributed.internal.membership.gms; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.net.InetAddress; import org.jgroups.util.UUID; -import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import com.gemstone.gemfire.distributed.internal.membership.MemberAttributes; +import com.gemstone.gemfire.test.junit.categories.SecurityTest; import com.gemstone.gemfire.test.junit.categories.UnitTest; -@Category(UnitTest.class) +@Category({ UnitTest.class, SecurityTest.class }) public class GMSMemberJUnitTest { @Test public void testEqualsNotSameType() { GMSMember member = new GMSMember(); - Assert.assertFalse(member.equals("Not a GMSMember")); + assertFalse(member.equals("Not a GMSMember")); } @Test public void testEqualsIsSame() { GMSMember member = new GMSMember(); - Assert.assertTrue(member.equals(member)); + assertTrue(member.equals(member)); } @Test @@ -49,7 +49,7 @@ public class GMSMemberJUnitTest { GMSMember member = new GMSMember(); UUID uuid = new UUID(0, 0); member.setUUID(uuid); - Assert.assertEquals(0, member.compareTo(member)); + assertEquals(0, member.compareTo(member)); } private GMSMember createGMSMember(byte[] inetAddress, int viewId, long msb, long lsb) { @@ -66,84 +66,85 @@ public class GMSMemberJUnitTest { public void testCompareToInetAddressIsLongerThan() { GMSMember member1 = createGMSMember(new byte[] {1, 1, 1, 1, 1}, 1, 1, 1); GMSMember member2 = createGMSMember(new byte[] {1, 1, 1, 1}, 1, 1, 1); - Assert.assertEquals(1, member1.compareTo(member2)); + assertEquals(1, member1.compareTo(member2)); } @Test public void testCompareToInetAddressIsShorterThan() { GMSMember member1 = createGMSMember(new byte[] {1, 1, 1, 1}, 1, 1, 1); GMSMember member2 = createGMSMember(new byte[] {1, 1, 1, 1, 1}, 1, 1, 1); - Assert.assertEquals(-1, member1.compareTo(member2)); + assertEquals(-1, member1.compareTo(member2)); } @Test public void testCompareToInetAddressIsGreater() { GMSMember member1 = createGMSMember(new byte[] {1, 2, 1, 1, 1}, 1, 1, 1); GMSMember member2 = createGMSMember(new byte[] {1, 1, 1, 1, 1}, 1, 1, 1); - Assert.assertEquals(1, member1.compareTo(member2)); + assertEquals(1, member1.compareTo(member2)); } @Test public void testCompareToInetAddressIsLessThan() { GMSMember member1 = createGMSMember(new byte[] {1, 1, 1, 1, 1}, 1, 1, 1); GMSMember member2 = createGMSMember(new byte[] {1, 2, 1, 1, 1}, 1, 1, 1); - Assert.assertEquals(-1, member1.compareTo(member2)); + assertEquals(-1, member1.compareTo(member2)); } @Test public void testCompareToMyViewIdLarger() { GMSMember member1 = createGMSMember(new byte[] {1}, 2, 1, 1); GMSMember member2 = createGMSMember(new byte[] {1}, 1, 1, 1); - Assert.assertEquals(1, member1.compareTo(member2)); + assertEquals(1, member1.compareTo(member2)); } @Test public void testCompareToTheirViewIdLarger() { GMSMember member1 = createGMSMember(new byte[] {1}, 1, 1, 1); GMSMember member2 = createGMSMember(new byte[] {1}, 2, 1, 1); - Assert.assertEquals(-1, member1.compareTo(member2)); + assertEquals(-1, member1.compareTo(member2)); } @Test public void testCompareToMyMSBLarger() { GMSMember member1 = createGMSMember(new byte[] {1}, 1, 2, 1); GMSMember member2 = createGMSMember(new byte[] {1}, 1, 1, 1); - Assert.assertEquals(1, member1.compareTo(member2)); + assertEquals(1, member1.compareTo(member2)); } @Test public void testCompareToTheirMSBLarger() { GMSMember member1 = createGMSMember(new byte[] {1}, 1, 1, 1); GMSMember member2 = createGMSMember(new byte[] {1}, 1, 2, 1); - Assert.assertEquals(-1, member1.compareTo(member2)); + assertEquals(-1, member1.compareTo(member2)); } @Test public void testCompareToMyLSBLarger() { GMSMember member1 = createGMSMember(new byte[] {1}, 1, 1, 2); GMSMember member2 = createGMSMember(new byte[] {1}, 1, 1, 1); - Assert.assertEquals(1, member1.compareTo(member2)); + assertEquals(1, member1.compareTo(member2)); } @Test public void testCompareToTheirLSBLarger() { GMSMember member1 = createGMSMember(new byte[] {1}, 1, 1, 1); GMSMember member2 = createGMSMember(new byte[] {1}, 1, 1, 2); - Assert.assertEquals(-1, member1.compareTo(member2)); + assertEquals(-1, member1.compareTo(member2)); } - - //Makes sure a NPE is not thrown + /** + * Makes sure a NPE is not thrown + */ @Test public void testNoNPEWhenSetAttributesWithNull() { GMSMember member = new GMSMember(); member.setAttributes(null); MemberAttributes attrs = member.getAttributes(); MemberAttributes invalid = MemberAttributes.INVALID; - Assert.assertEquals(attrs.getVmKind(), invalid.getVmKind()); - Assert.assertEquals(attrs.getPort(), invalid.getPort()); - Assert.assertEquals(attrs.getVmViewId(), invalid.getVmViewId()); - Assert.assertEquals(attrs.getName(), invalid.getName()); + assertEquals(attrs.getVmKind(), invalid.getVmKind()); + assertEquals(attrs.getPort(), invalid.getPort()); + assertEquals(attrs.getVmViewId(), invalid.getVmViewId()); + assertEquals(attrs.getName(), invalid.getName()); } @Test @@ -151,7 +152,7 @@ public class GMSMemberJUnitTest { GMSMember member = new GMSMember(); UUID uuid = new UUID(0, 0); member.setUUID(uuid); - Assert.assertNull(member.getUUID()); + assertNull(member.getUUID()); } @Test @@ -159,6 +160,6 @@ public class GMSMemberJUnitTest { GMSMember member = new GMSMember(); UUID uuid = new UUID(1, 1); member.setUUID(uuid); - Assert.assertNotNull(member.getUUID()); + assertNotNull(member.getUUID()); } } http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/auth/GMSAuthenticatorJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/auth/GMSAuthenticatorJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/auth/GMSAuthenticatorJUnitTest.java index 8246a43..022d1c7 100644 --- a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/auth/GMSAuthenticatorJUnitTest.java +++ b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/auth/GMSAuthenticatorJUnitTest.java @@ -16,6 +16,18 @@ */ package com.gemstone.gemfire.distributed.internal.membership.gms.auth; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.security.Principal; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.contrib.java.lang.system.RestoreSystemProperties; +import org.junit.experimental.categories.Category; + import com.gemstone.gemfire.LogWriter; import com.gemstone.gemfire.distributed.DistributedMember; import com.gemstone.gemfire.distributed.internal.membership.gms.Services; @@ -24,45 +36,34 @@ import com.gemstone.gemfire.security.AuthInitialize; import com.gemstone.gemfire.security.AuthenticationFailedException; import com.gemstone.gemfire.security.Authenticator; import com.gemstone.gemfire.security.GemFireSecurityException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import com.gemstone.gemfire.test.junit.categories.SecurityTest; import com.gemstone.gemfire.test.junit.categories.UnitTest; -import java.security.Principal; -import java.util.Properties; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.junit.Assert.*; - -@Category(UnitTest.class) +@Category({ UnitTest.class, SecurityTest.class }) public class GMSAuthenticatorJUnitTest { - static String prefix = "com.gemstone.gemfire.distributed.internal.membership.gms.auth.GMSAuthenticatorJUnitTest$"; + private String prefix; + private Properties props; + private Services services; + private GMSAuthenticator authenticator; + private DistributedMember member; - Properties originalSystemProps = null; - Properties props = null; - Services services = null; - GMSAuthenticator authenticator = null; - DistributedMember member = null; + @Rule + public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties(); @Before public void setUp() throws Exception { - originalSystemProps = System.getProperties(); + prefix = getClass().getName() + "$"; props = new Properties(); authenticator = new GMSAuthenticator(); + services = mock(Services.class); InternalLogWriter securityLog = mock(InternalLogWriter.class); - when(services.getSecurityLogWriter()).thenReturn(securityLog); + when(services.getSecurityLogWriter()).thenReturn(mock(InternalLogWriter.class)); + authenticator.init(services); - member = mock(DistributedMember.class); - } - @After - public void tearDown() throws Exception { - System.setProperties(originalSystemProps); + member = mock(DistributedMember.class); } @Test @@ -126,12 +127,12 @@ public class GMSAuthenticatorJUnitTest { verifyNegativeGetCredential(props, "expected get credential error"); } - void verifyNegativeGetCredential(Properties props, String expectedError) throws Exception { + private void verifyNegativeGetCredential(Properties props, String expectedError) throws Exception { try { authenticator.getCredentials(member, props); fail("should catch: " + expectedError); - } catch (GemFireSecurityException e) { - assertTrue(e.getMessage().startsWith(expectedError)); + } catch (GemFireSecurityException expected) { + assertTrue(expected.getMessage().startsWith(expectedError)); } } @@ -149,8 +150,8 @@ public class GMSAuthenticatorJUnitTest { @Test public void testAuthenticatorWithNoAuth() throws Exception { - String result = authenticator.authenticate(member, props, props, member); - assertNull(result); + String result = authenticator.authenticate(member, props, props, member); + assertNull(result); } @Test @@ -195,27 +196,29 @@ public class GMSAuthenticatorJUnitTest { assertTrue(result, result.startsWith(expectedError)); } - // ---------------------------------------- - // Test AuthInitialize - // ---------------------------------------- - - public static class TestAuthInit1 implements AuthInitialize { + private static class TestAuthInit1 implements AuthInitialize { public static AuthInitialize create() { return null; } + @Override public void init(LogWriter systemLogger, LogWriter securityLogger) throws AuthenticationFailedException { } - public Properties getCredentials(Properties props, DistributedMember server, boolean isPeer) - throws AuthenticationFailedException { + @Override + public Properties getCredentials(Properties props, DistributedMember server, boolean isPeer) throws AuthenticationFailedException { throw new AuthenticationFailedException("expected get credential error"); } + @Override public void close() { } } - public static class TestAuthInit2 extends TestAuthInit1 { - static TestAuthInit2 instance = null; - static int createCount = 0; + private static class TestAuthInit2 extends TestAuthInit1 { + + private static TestAuthInit2 instance = null; + private static int createCount = 0; + + boolean closed = false; + public static void setAuthInitialize(TestAuthInit2 auth) { instance = auth; } @@ -223,11 +226,11 @@ public class GMSAuthenticatorJUnitTest { createCount ++; return instance; } - public Properties getCredentials(Properties props, DistributedMember server, boolean isPeer) - throws AuthenticationFailedException { + @Override + public Properties getCredentials(Properties props, DistributedMember server, boolean isPeer) throws AuthenticationFailedException { return props; } - boolean closed = false; + @Override public void close() { closed = true; } @@ -239,59 +242,66 @@ public class GMSAuthenticatorJUnitTest { } } - public static class TestAuthInit3 extends TestAuthInit1 { + // used by reflection by test + private static class TestAuthInit3 extends TestAuthInit1 { public static AuthInitialize create() { return new TestAuthInit3(); } + @Override public void init(LogWriter systemLogger, LogWriter securityLogger) throws AuthenticationFailedException { throw new AuthenticationFailedException("expected init error"); } } - public static class TestAuthInit4 extends TestAuthInit1 { + private static class TestAuthInit4 extends TestAuthInit1 { public static AuthInitialize create() { return new TestAuthInit4(); } } - // ---------------------------------------- - // Test Authenticator - // ---------------------------------------- - - public static class TestAuthenticator1 implements Authenticator { + private static class TestAuthenticator1 implements Authenticator { public static Authenticator create() { return null; } + @Override public void init(Properties securityProps, LogWriter systemLogger, LogWriter securityLogger) throws AuthenticationFailedException { } + @Override public Principal authenticate(Properties props, DistributedMember member) throws AuthenticationFailedException { return null; } + @Override public void close() { } } - public static class TestAuthenticator2 extends TestAuthenticator1 { + private static class TestAuthenticator2 extends TestAuthenticator1 { public static Authenticator create() { return new TestAuthenticator2(); } + @Override public void init(Properties securityProps, LogWriter systemLogger, LogWriter securityLogger) throws AuthenticationFailedException { throw new AuthenticationFailedException("expected init error"); } } - public static class TestAuthenticator3 extends TestAuthenticator1 { + private static class TestAuthenticator3 extends TestAuthenticator1 { public static Authenticator create() { return new TestAuthenticator3(); } + @Override public Principal authenticate(Properties props, DistributedMember member) throws AuthenticationFailedException { throw new AuthenticationFailedException("expected authenticate error"); } } - public static class TestAuthenticator4 extends TestAuthenticator1 { - static Authenticator instance = null; - static int createCount = 0; + private static class TestAuthenticator4 extends TestAuthenticator1 { + + private static Authenticator instance = null; + private static int createCount = 0; + + private boolean closed = false; + public static void setAuthenticator(Authenticator auth) { instance = auth; } @@ -299,10 +309,11 @@ public class GMSAuthenticatorJUnitTest { createCount ++; return instance; } + @Override public Principal authenticate(Properties props, DistributedMember member) throws AuthenticationFailedException { return null; } - boolean closed = false; + @Override public void close() { closed = true; } http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/locator/GMSLocatorRecoveryJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/locator/GMSLocatorRecoveryJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/locator/GMSLocatorRecoveryJUnitTest.java index 2d042fc..00d9d05 100644 --- a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/locator/GMSLocatorRecoveryJUnitTest.java +++ b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/locator/GMSLocatorRecoveryJUnitTest.java @@ -16,6 +16,20 @@ */ package com.gemstone.gemfire.distributed.internal.membership.gms.locator; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.ObjectOutputStream; +import java.net.InetAddress; +import java.util.Properties; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; + import com.gemstone.gemfire.DataSerializer; import com.gemstone.gemfire.InternalGemFireException; import com.gemstone.gemfire.distributed.Locator; @@ -30,28 +44,12 @@ import com.gemstone.gemfire.distributed.internal.membership.MemberFactory; import com.gemstone.gemfire.distributed.internal.membership.MembershipManager; import com.gemstone.gemfire.distributed.internal.membership.NetView; import com.gemstone.gemfire.internal.AvailablePortHelper; -import com.gemstone.gemfire.internal.OSProcess; import com.gemstone.gemfire.internal.SocketCreator; import com.gemstone.gemfire.internal.Version; import com.gemstone.gemfire.internal.admin.remote.RemoteTransportConfig; +import com.gemstone.gemfire.test.junit.categories.IntegrationTest; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import com.gemstone.gemfire.test.junit.categories.UnitTest; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.ObjectOutputStream; -import java.net.InetAddress; -import java.util.Properties; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; - -@Category(UnitTest.class) +@Category(IntegrationTest.class) public class GMSLocatorRecoveryJUnitTest { File tempStateFile = null; http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/membership/StatRecorderJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/membership/StatRecorderJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/membership/StatRecorderJUnitTest.java index b7b80ac..ed50a3a 100755 --- a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/membership/StatRecorderJUnitTest.java +++ b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/membership/StatRecorderJUnitTest.java @@ -16,6 +16,23 @@ */ package com.gemstone.gemfire.distributed.internal.membership.gms.membership; +import static org.junit.Assert.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.*; + +import java.util.Properties; +import java.util.concurrent.RejectedExecutionException; + +import org.jgroups.Event; +import org.jgroups.Message; +import org.jgroups.protocols.UNICAST3.Header; +import org.jgroups.protocols.pbcast.NakAckHeader2; +import org.jgroups.stack.Protocol; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; + import com.gemstone.gemfire.distributed.internal.DistributionConfig; import com.gemstone.gemfire.distributed.internal.DistributionConfigImpl; import com.gemstone.gemfire.distributed.internal.DistributionManager; @@ -27,23 +44,6 @@ import com.gemstone.gemfire.distributed.internal.membership.gms.messenger.JGroup import com.gemstone.gemfire.distributed.internal.membership.gms.messenger.StatRecorder; import com.gemstone.gemfire.internal.admin.remote.RemoteTransportConfig; import com.gemstone.gemfire.test.junit.categories.UnitTest; -import org.jgroups.Event; -import org.jgroups.Message; -import org.jgroups.protocols.UNICAST3.Header; -import org.jgroups.protocols.pbcast.NakAckHeader2; -import org.jgroups.stack.Protocol; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import java.util.Properties; -import java.util.concurrent.RejectedExecutionException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.*; /** * This class tests the GMS StatRecorder class, which records JGroups @@ -51,18 +51,24 @@ import static org.mockito.Mockito.*; */ @Category(UnitTest.class) public class StatRecorderJUnitTest { - Protocol mockDownProtocol, mockUpProtocol; - StatRecorder recorder; - MyStats stats = new MyStats(); - Services services; + + private Protocol mockDownProtocol; + private Protocol mockUpProtocol; + private StatRecorder recorder; + private MyStats stats; + private Services services; @Before - public void initMocks() throws Exception { + public void setUp() throws Exception { + stats = new MyStats(); + // create a StatRecorder that has mock up/down protocols and stats mockDownProtocol = mock(Protocol.class); mockUpProtocol = mock(Protocol.class); + services = mock(Services.class); when(services.getStatistics()).thenReturn(stats); + recorder = new StatRecorder(); recorder.setServices(services); recorder.setUpProtocol(mockUpProtocol); @@ -105,7 +111,6 @@ public class StatRecorderJUnitTest { when(msg.getHeader(any(Short.class))).thenReturn(Header.createDataHeader(1L, (short)1, true)); when(msg.size()).thenReturn(150L); - // GEODE-1178, the TP protocol may throw a RejectedExecutionException & StatRecorder should retry when(mockDownProtocol.down(any(Event.class))).thenThrow(new RejectedExecutionException()); @@ -161,8 +166,7 @@ public class StatRecorderJUnitTest { assertTrue("mcastRetransmits = " + stats.mcastRetransmits, stats.mcastRetransmits == 1); } - - + /** * Ensure that the messenger JGroups configuration XML strings contain * the statistics recorder protocol @@ -201,7 +205,8 @@ public class StatRecorderJUnitTest { assertTrue(jgroupsConfig.contains("gms.messenger.StatRecorder")); } - static class MyStats extends DummyDMStats { + private static class MyStats extends DummyDMStats { + public int ucastMessagesReceived; public int ucastMessageBytesReceived; public int ucastMessagesSent; http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/messenger/GMSQuorumCheckerJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/messenger/GMSQuorumCheckerJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/messenger/GMSQuorumCheckerJUnitTest.java index 904a206..0e2a617 100644 --- a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/messenger/GMSQuorumCheckerJUnitTest.java +++ b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/messenger/GMSQuorumCheckerJUnitTest.java @@ -16,12 +16,11 @@ */ package com.gemstone.gemfire.distributed.internal.membership.gms.messenger; +import static org.junit.Assert.*; import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; import java.io.IOException; -import java.net.UnknownHostException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; @@ -33,7 +32,6 @@ import org.jgroups.Message; import org.jgroups.Receiver; import org.jgroups.stack.IpAddress; import org.jgroups.util.UUID; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; @@ -44,60 +42,17 @@ import org.mockito.stubbing.Answer; import com.gemstone.gemfire.distributed.internal.DistributionManager; import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember; import com.gemstone.gemfire.distributed.internal.membership.NetView; -import com.gemstone.gemfire.distributed.internal.membership.gms.Services; import com.gemstone.gemfire.test.junit.categories.UnitTest; @Category(UnitTest.class) public class GMSQuorumCheckerJUnitTest { private InternalDistributedMember[] mockMembers; - - private Services services; - private JChannel channel; - private JGAddress address; - private class PingMessageAnswer implements Answer { - private int pingCount = 0; - private JChannel channel; - private GMSPingPonger pingPonger = new GMSPingPonger(); - private Set simulatedPongRespondersByPort; - - public PingMessageAnswer(JChannel channel, Set simulatedPongRespondersByPort) { - this.channel = channel; - this.simulatedPongRespondersByPort = simulatedPongRespondersByPort; - } - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - for (int i = 0; i < args.length; i++) { - if (args[i] instanceof Message) { - Message msg = (Message) args[i]; - Object content = null; - content = msg.getBuffer(); - if (content instanceof byte[]) { - if (pingPonger.isPingMessage((byte[]) content)) { - pingCount++; - if (simulatedPongRespondersByPort.contains(((JGAddress)msg.getDest()).getPort())) { - channel.getReceiver().receive(pingPonger.createPongMessage(msg.getDest(), msg.getSrc())); - } - } - } - } - } - return null; - } - - public int getPingCount() { - return pingCount; - } - - } - @Before - public void initMocks() throws UnknownHostException, Exception { + public void initMocks() throws Exception { mockMembers = new InternalDistributedMember[12]; for (int i = 0; i < mockMembers.length; i++) { mockMembers[i] = new InternalDistributedMember("localhost", 8888 + i); @@ -111,22 +66,6 @@ public class GMSQuorumCheckerJUnitTest { Mockito.doReturn(address).when(channel).down(any(Event.class)); } - private NetView prepareView() throws IOException { - return prepareView(mockMembers.length); - } - - private NetView prepareView(int numMembers) throws IOException { - int viewId = 1; - List mbrs = new LinkedList(); - for (int i = 0; i < numMembers; i++) { - mbrs.add(mockMembers[i]); - } - - // prepare the view - NetView netView = new NetView(mockMembers[0], viewId, mbrs); - return netView; - } - @Test public void testQuorumCheckerAllRespond() throws Exception { NetView view = prepareView(); @@ -140,10 +79,10 @@ public class GMSQuorumCheckerJUnitTest { GMSQuorumChecker qc = new GMSQuorumChecker(view, 51, channel); qc.initialize(); boolean quorum = qc.checkForQuorum(500); - Assert.assertTrue(quorum); - Assert.assertSame(view.getMembers().size(), answerer.getPingCount()); - Assert.assertTrue(qc.checkForQuorum(500)); - Assert.assertSame(qc.getMembershipInfo(), channel); + assertTrue(quorum); + assertSame(view.getMembers().size(), answerer.getPingCount()); + assertTrue(qc.checkForQuorum(500)); + assertSame(qc.getMembershipInfo(), channel); } @Test @@ -159,8 +98,8 @@ public class GMSQuorumCheckerJUnitTest { GMSQuorumChecker qc = new GMSQuorumChecker(view, 51, channel); qc.initialize(); boolean quorum = qc.checkForQuorum(500); - Assert.assertTrue(quorum); - Assert.assertSame(view.getMembers().size(), answerer.getPingCount()); + assertTrue(quorum); + assertSame(view.getMembers().size(), answerer.getPingCount()); } @Test @@ -174,8 +113,8 @@ public class GMSQuorumCheckerJUnitTest { GMSQuorumChecker qc = new GMSQuorumChecker(view, 51, channel); qc.initialize(); boolean quorum = qc.checkForQuorum(500); - Assert.assertFalse(quorum); - Assert.assertSame(view.getMembers().size(), answerer.getPingCount()); + assertFalse(quorum); + assertSame(view.getMembers().size(), answerer.getPingCount()); } @Test @@ -188,8 +127,8 @@ public class GMSQuorumCheckerJUnitTest { GMSQuorumChecker qc = new GMSQuorumChecker(view, 51, channel); qc.initialize(); boolean quorum = qc.checkForQuorum(500); - Assert.assertFalse(quorum); - Assert.assertSame(view.getMembers().size(), answerer.getPingCount()); + assertFalse(quorum); + assertSame(view.getMembers().size(), answerer.getPingCount()); } @Test @@ -202,6 +141,7 @@ public class GMSQuorumCheckerJUnitTest { for (int i = 0; i < mockMembers.length; i++) { pongResponders.add(mockMembers[i].getPort()); } + //remove 4 servers pongResponders.remove(mockMembers[8].getPort()); pongResponders.remove(mockMembers[9].getPort()); @@ -214,8 +154,8 @@ public class GMSQuorumCheckerJUnitTest { GMSQuorumChecker qc = new GMSQuorumChecker(view, 51, channel); qc.initialize(); boolean quorum = qc.checkForQuorum(500); - Assert.assertTrue(quorum); - Assert.assertSame(view.getMembers().size(), answerer.getPingCount()); + assertTrue(quorum); + assertSame(view.getMembers().size(), answerer.getPingCount()); } @Test @@ -228,23 +168,24 @@ public class GMSQuorumCheckerJUnitTest { for (int i = 0; i < mockMembers.length; i++) { pongResponders.add(mockMembers[i].getPort()); } + //remove 4 servers pongResponders.remove(mockMembers[8].getPort()); pongResponders.remove(mockMembers[9].getPort()); pongResponders.remove(mockMembers[10].getPort()); pongResponders.remove(mockMembers[11].getPort()); + //remove 1 locator pongResponders.remove(mockMembers[1].getPort()); - PingMessageAnswer answerer = new PingMessageAnswer(channel, pongResponders); Mockito.doAnswer(answerer).when(channel).send(any(Message.class)); GMSQuorumChecker qc = new GMSQuorumChecker(view, 51, channel); qc.initialize(); boolean quorum = qc.checkForQuorum(500); - Assert.assertTrue(quorum); - Assert.assertSame(view.getMembers().size(), answerer.getPingCount()); + assertTrue(quorum); + assertSame(view.getMembers().size(), answerer.getPingCount()); } @Test @@ -257,12 +198,14 @@ public class GMSQuorumCheckerJUnitTest { for (int i = 0; i < mockMembers.length; i++) { pongResponders.add(mockMembers[i].getPort()); } + //remove 5 servers pongResponders.remove(mockMembers[7].getPort()); pongResponders.remove(mockMembers[8].getPort()); pongResponders.remove(mockMembers[9].getPort()); pongResponders.remove(mockMembers[10].getPort()); pongResponders.remove(mockMembers[11].getPort()); + //remove locators pongResponders.remove(mockMembers[0].getPort()); pongResponders.remove(mockMembers[1].getPort()); @@ -273,8 +216,8 @@ public class GMSQuorumCheckerJUnitTest { GMSQuorumChecker qc = new GMSQuorumChecker(view, 51, channel); qc.initialize(); boolean quorum = qc.checkForQuorum(500); - Assert.assertFalse(quorum); - Assert.assertSame(view.getMembers().size(), answerer.getPingCount()); + assertFalse(quorum); + assertSame(view.getMembers().size(), answerer.getPingCount()); } @Test @@ -303,8 +246,8 @@ public class GMSQuorumCheckerJUnitTest { GMSQuorumChecker qc = new GMSQuorumChecker(view, 51, channel); qc.initialize(); boolean quorum = qc.checkForQuorum(500); - Assert.assertFalse(quorum); - Assert.assertSame(view.getMembers().size(), answerer.getPingCount()); + assertFalse(quorum); + assertSame(view.getMembers().size(), answerer.getPingCount()); } @Test @@ -327,8 +270,8 @@ public class GMSQuorumCheckerJUnitTest { GMSQuorumChecker qc = new GMSQuorumChecker(view, 51, channel); qc.initialize(); boolean quorum = qc.checkForQuorum(500); - Assert.assertTrue(quorum); - Assert.assertSame(view.getMembers().size(), answerer.getPingCount()); + assertTrue(quorum); + assertSame(view.getMembers().size(), answerer.getPingCount()); } @Test @@ -352,8 +295,61 @@ public class GMSQuorumCheckerJUnitTest { GMSQuorumChecker qc = new GMSQuorumChecker(view, 51, channel); qc.initialize(); boolean quorum = qc.checkForQuorum(500); - Assert.assertFalse(quorum); - Assert.assertSame(view.getMembers().size(), answerer.getPingCount()); + assertFalse(quorum); + assertSame(view.getMembers().size(), answerer.getPingCount()); + } + + private NetView prepareView() throws IOException { + return prepareView(mockMembers.length); + } + + private NetView prepareView(int numMembers) throws IOException { + int viewId = 1; + List mbrs = new LinkedList(); + for (int i = 0; i < numMembers; i++) { + mbrs.add(mockMembers[i]); + } + + // prepare the view + NetView netView = new NetView(mockMembers[0], viewId, mbrs); + return netView; + } + + private static class PingMessageAnswer implements Answer { + + private int pingCount = 0; + private JChannel channel; + private GMSPingPonger pingPonger = new GMSPingPonger(); + private Set simulatedPongRespondersByPort; + + public PingMessageAnswer(JChannel channel, Set simulatedPongRespondersByPort) { + this.channel = channel; + this.simulatedPongRespondersByPort = simulatedPongRespondersByPort; + } + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + for (int i = 0; i < args.length; i++) { + if (args[i] instanceof Message) { + Message msg = (Message) args[i]; + Object content = null; + content = msg.getBuffer(); + if (content instanceof byte[]) { + if (pingPonger.isPingMessage((byte[]) content)) { + pingCount++; + if (simulatedPongRespondersByPort.contains(((JGAddress)msg.getDest()).getPort())) { + channel.getReceiver().receive(pingPonger.createPongMessage(msg.getDest(), msg.getSrc())); + } + } + } + } + } + return null; + } + + public int getPingCount() { + return pingCount; + } } - } http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/mgr/GMSMembershipManagerJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/mgr/GMSMembershipManagerJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/mgr/GMSMembershipManagerJUnitTest.java index 952f347..a1d7a2d 100755 --- a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/mgr/GMSMembershipManagerJUnitTest.java +++ b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/membership/gms/mgr/GMSMembershipManagerJUnitTest.java @@ -16,18 +16,11 @@ */ package com.gemstone.gemfire.distributed.internal.membership.gms.mgr; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.Arrays; @@ -77,6 +70,9 @@ import com.gemstone.gemfire.test.junit.categories.UnitTest; @Category(UnitTest.class) public class GMSMembershipManagerJUnitTest { + + private static final long WAIT_FOR_REPLIES_MILLIS = 2000; + private Services services; private ServiceConfig mockConfig; private DistributionConfig distConfig; @@ -88,7 +84,7 @@ public class GMSMembershipManagerJUnitTest { private Messenger messenger; private JoinLeave joinLeave; private Stopper stopper; - DistributedMembershipListener listener; + private DistributedMembershipListener listener; private GMSMembershipManager manager; private List members; private DirectChannel dc; @@ -107,10 +103,8 @@ public class GMSMembershipManagerJUnitTest { nonDefault.put(DistributionConfig.LOCATORS_NAME, "localhost[10344]"); distConfig = new DistributionConfigImpl(nonDefault); distProperties = nonDefault; - RemoteTransportConfig tconfig = new RemoteTransportConfig(distConfig, - DistributionManager.NORMAL_DM_TYPE); + RemoteTransportConfig tconfig = new RemoteTransportConfig(distConfig, DistributionManager.NORMAL_DM_TYPE); - mockConfig = mock(ServiceConfig.class); when(mockConfig.getDistributionConfig()).thenReturn(distConfig); when(mockConfig.getTransport()).thenReturn(tconfig); @@ -257,7 +251,6 @@ public class GMSMembershipManagerJUnitTest { manager.handleOrDeferSurpriseConnect(surpriseMember); assertEquals(5, manager.getStartupEvents().size()); - // process a new view after we finish joining but before event processing has started manager.isJoining = false; mockMembers[4].setVmViewId(4); @@ -296,26 +289,6 @@ public class GMSMembershipManagerJUnitTest { verify(listener).memberSuspect(suspectMember, mockMembers[0], "testing"); } - /** - * Some tests require a DirectChannel mock - */ - private void setUpDirectChannelMock() throws Exception { - dc = mock(DirectChannel.class); - when(dc.send(any(GMSMembershipManager.class), any(mockMembers.getClass()), any(DistributionMessage.class), anyInt(), anyInt())) - .thenReturn(100); - - manager.start(); - manager.started(); - - manager.setDirectChannel(dc); - - NetView view = new NetView(myMemberId, 1, members); - manager.installView(view); - when(joinLeave.getView()).thenReturn(view); - - manager.startEventProcessing(); - } - @Test public void testDirectChannelSend() throws Exception { setUpDirectChannelMock(); @@ -357,9 +330,8 @@ public class GMSMembershipManagerJUnitTest { when(stopper.cancelInProgress()).thenReturn("stopping for test"); try { manager.directChannelSend(recipients, m, null); - throw new RuntimeException("expected directChannelSend to throw an exception"); - } catch (DistributedSystemDisconnectedException e) { - // expected + fail("expected directChannelSend to throw an exception"); + } catch (DistributedSystemDisconnectedException expected) { } } @@ -427,10 +399,29 @@ public class GMSMembershipManagerJUnitTest { mbrs.add(mockMembers[0]); ReplyProcessor21 rp = new ReplyProcessor21(dm, mbrs); rp.enableSevereAlertProcessing(); - boolean result = rp.waitForReplies(2000); + boolean result = rp.waitForReplies(WAIT_FOR_REPLIES_MILLIS); assertFalse(result); // the wait should have timed out verify(healthMonitor, atLeastOnce()).checkIfAvailable(isA(InternalDistributedMember.class), isA(String.class), isA(Boolean.class)); } - -} + /** + * Some tests require a DirectChannel mock + */ + private void setUpDirectChannelMock() throws Exception { + dc = mock(DirectChannel.class); + when(dc.send(any(GMSMembershipManager.class), any(mockMembers.getClass()), any(DistributionMessage.class), anyInt(), anyInt())) + .thenReturn(100); + + manager.start(); + manager.started(); + + manager.setDirectChannel(dc); + + NetView view = new NetView(myMemberId, 1, members); + manager.installView(view); + when(joinLeave.getView()).thenReturn(view); + + manager.startEventProcessing(); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/tcpserver/TcpServerBackwardCompatDUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/tcpserver/TcpServerBackwardCompatDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/tcpserver/TcpServerBackwardCompatDUnitTest.java index 8723505..5fd0f27 100644 --- a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/tcpserver/TcpServerBackwardCompatDUnitTest.java +++ b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/tcpserver/TcpServerBackwardCompatDUnitTest.java @@ -158,8 +158,8 @@ public class TcpServerBackwardCompatDUnitTest extends DistributedTestCase { TcpServer.OLDTESTVERSION -= 100; TcpServer.getGossipVersionMapForTestOnly().put(TcpServer.TESTVERSION, Version.CURRENT_ORDINAL); TcpServer.getGossipVersionMapForTestOnly().put(TcpServer.OLDTESTVERSION, Version.GFE_57.ordinal()); -// assertEquals("Gossip Version and Test version are not same", TcpServer.GOSSIPVERSION, TcpServer.TESTVERSION); -// assertEquals("Previous Gossip Version and Test version are not same", TcpServer.OLDGOSSIPVERSION, TcpServer.OLDTESTVERSION); +// assertIndexDetailsEquals("Gossip Version and Test version are not same", TcpServer.GOSSIPVERSION, TcpServer.TESTVERSION); +// assertIndexDetailsEquals("Previous Gossip Version and Test version are not same", TcpServer.OLDGOSSIPVERSION, TcpServer.OLDTESTVERSION); Locator.startLocatorAndDS(port1, logFile1, props); @@ -198,8 +198,8 @@ public class TcpServerBackwardCompatDUnitTest extends DistributedTestCase { TcpServer.OLDTESTVERSION -= 100; TcpServer.getGossipVersionMapForTestOnly().put(TcpServer.TESTVERSION, Version.CURRENT_ORDINAL); TcpServer.getGossipVersionMapForTestOnly().put(TcpServer.OLDTESTVERSION, Version.GFE_57.ordinal()); -// assertEquals("Gossip Version and Test version are not same", TcpServer.GOSSIPVERSION, TcpServer.TESTVERSION); -// assertEquals("Previous Gossip Version and Test version are not same", TcpServer.OLDGOSSIPVERSION, TcpServer.OLDTESTVERSION); +// assertIndexDetailsEquals("Gossip Version and Test version are not same", TcpServer.GOSSIPVERSION, TcpServer.TESTVERSION); +// assertIndexDetailsEquals("Previous Gossip Version and Test version are not same", TcpServer.OLDGOSSIPVERSION, TcpServer.OLDTESTVERSION); Locator.startLocatorAndDS(port0, logFile0, props); http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/tcpserver/TcpServerJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/tcpserver/TcpServerJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/tcpserver/TcpServerJUnitTest.java index 4594889..9b1b8d3 100644 --- a/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/tcpserver/TcpServerJUnitTest.java +++ b/geode-core/src/test/java/com/gemstone/gemfire/distributed/internal/tcpserver/TcpServerJUnitTest.java @@ -39,11 +39,9 @@ import com.gemstone.gemfire.distributed.DistributedSystem; import com.gemstone.gemfire.distributed.internal.PoolStatHelper; import com.gemstone.gemfire.distributed.internal.SharedConfiguration; import com.gemstone.gemfire.internal.AvailablePort; -//import com.gemstone.org.jgroups.stack.GossipClient; -//import com.gemstone.org.jgroups.stack.IpAddress; -import com.gemstone.gemfire.test.junit.categories.UnitTest; +import com.gemstone.gemfire.test.junit.categories.IntegrationTest; -@Category(UnitTest.class) +@Category(IntegrationTest.class) public class TcpServerJUnitTest { protected/*GemStoneAddition*/ InetAddress localhost; http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/internal/AbstractConfigJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/AbstractConfigJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/AbstractConfigJUnitTest.java index 80c92e6..234d032 100644 --- a/geode-core/src/test/java/com/gemstone/gemfire/internal/AbstractConfigJUnitTest.java +++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/AbstractConfigJUnitTest.java @@ -18,97 +18,74 @@ package com.gemstone.gemfire.internal; import static org.junit.Assert.*; -import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.TestName; -import com.gemstone.gemfire.distributed.internal.DistributionConfigImpl; - -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; -import java.util.Properties; -import junit.framework.TestCase; + +import org.junit.Test; import org.junit.experimental.categories.Category; + import com.gemstone.gemfire.test.junit.categories.UnitTest; @Category(UnitTest.class) -public class AbstractConfigJUnitTest extends TestCase { +public class AbstractConfigJUnitTest { @Test - public void testDisplayPropertyValue(){ - AbstractConfigTestClass actc=new AbstractConfigTestClass(); - Method method=null; - try{ - method=actc.getClass().getSuperclass().getDeclaredMethod("okToDisplayPropertyValue",String.class); - method.setAccessible(true); - assertFalse((Boolean) method.invoke(actc, "password")); - assertFalse((Boolean)method.invoke(actc,"cluster-ssl-truststore-password")); - assertTrue((Boolean) method.invoke(actc, "cluster-ssl-enabled")); - assertFalse((Boolean)method.invoke(actc,"gateway-ssl-truststore-password")); - assertFalse((Boolean)method.invoke(actc,"server-ssl-keystore-password")); - assertTrue((Boolean) method.invoke(actc, "ssl-enabled")); - assertTrue((Boolean)method.invoke(actc,"conserve-sockets")); - assertFalse((Boolean)method.invoke(actc,"javax.net.ssl.keyStorePassword")); - assertFalse((Boolean)method.invoke(actc,"javax.net.ssl.keyStoreType")); - assertFalse((Boolean)method.invoke(actc,"sysprop-value")); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch(Exception e){ - e.printStackTrace(); - } - } - -} - -class AbstractConfigTestClass extends AbstractConfig{ + public void testDisplayPropertyValue() throws Exception { + AbstractConfigTestClass actc = new AbstractConfigTestClass(); + Method method = actc.getClass().getSuperclass().getDeclaredMethod("okToDisplayPropertyValue", String.class); + method.setAccessible(true); + assertFalse((Boolean) method.invoke(actc, "password")); + assertFalse((Boolean) method.invoke(actc, "cluster-ssl-truststore-password")); + assertTrue((Boolean) method.invoke(actc, "cluster-ssl-enabled")); + assertFalse((Boolean) method.invoke(actc, "gateway-ssl-truststore-password")); + assertFalse((Boolean) method.invoke(actc, "server-ssl-keystore-password")); + assertTrue((Boolean) method.invoke(actc, "ssl-enabled")); + assertTrue((Boolean) method.invoke(actc, "conserve-sockets")); + assertFalse((Boolean) method.invoke(actc, "javax.net.ssl.keyStorePassword")); + assertFalse((Boolean) method.invoke(actc, "javax.net.ssl.keyStoreType")); + assertFalse((Boolean) method.invoke(actc, "sysprop-value")); + } + private static class AbstractConfigTestClass extends AbstractConfig { - @Override - protected Map getAttDescMap() { - return null; - } + @Override + protected Map getAttDescMap() { + return null; + } - @Override - protected Map getAttSourceMap() { - return null; - } + @Override + protected Map getAttSourceMap() { + return null; + } - @Override - public Object getAttributeObject(String attName) { - return null; - } + @Override + public Object getAttributeObject(String attName) { + return null; + } - @Override - public void setAttributeObject(String attName, Object attValue, ConfigSource source) { + @Override + public void setAttributeObject(String attName, Object attValue, ConfigSource source) { - } + } - @Override - public boolean isAttributeModifiable(String attName) { - return false; - } + @Override + public boolean isAttributeModifiable(String attName) { + return false; + } - @Override - public Class getAttributeType(String attName) { - return null; - } + @Override + public Class getAttributeType(String attName) { + return null; + } - @Override - public String[] getAttributeNames() { - return new String[0]; - } + @Override + public String[] getAttributeNames() { + return new String[0]; + } - @Override - public String[] getSpecificAttributeNames() { - return new String[0]; + @Override + public String[] getSpecificAttributeNames() { + return new String[0]; + } } } - http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/internal/ArrayEqualsJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/ArrayEqualsJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/ArrayEqualsJUnitTest.java deleted file mode 100644 index 714a7fe..0000000 --- a/geode-core/src/test/java/com/gemstone/gemfire/internal/ArrayEqualsJUnitTest.java +++ /dev/null @@ -1,193 +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 com.gemstone.gemfire.internal; - -import static org.junit.Assert.fail; - -import java.util.Properties; - -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import com.gemstone.gemfire.cache.CacheFactory; -import com.gemstone.gemfire.cache.Region; -import com.gemstone.gemfire.cache.RegionShortcut; -import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; -import com.gemstone.gemfire.test.junit.categories.UnitTest; - - -/** - * See bug 52093. - * Make sure that the contents of arrays are - * used to test equality on regions ops. - */ -@Category(UnitTest.class) -public class ArrayEqualsJUnitTest { - private GemFireCacheImpl createCache() { - Properties props = new Properties(); - props.setProperty("locators", ""); - props.setProperty("mcast-port", "0"); - GemFireCacheImpl result = (GemFireCacheImpl) new CacheFactory(props).create(); - return result; - } - private void closeCache(GemFireCacheImpl gfc) { - gfc.close(); - } - - private void doOps(Region r) { - { - byte[] bytesValue = new byte[]{1,2,3,4}; - r.put("bytesValue", bytesValue.clone()); - if (r.replace("bytesValue", "", "")) fail("expected replace to fail"); - if (!r.replace("bytesValue", bytesValue, "")) { - fail("expected replace to happen"); - } - r.put("bytesValue", bytesValue.clone()); - if (r.remove("bytesValue", "")) fail("expected remove to fail"); - if (!r.remove("bytesValue", bytesValue)) { - fail("expected remove to happen"); - } - } - { - boolean[] booleanValue = new boolean[]{true,false,true,false}; - r.put("booleanValue", booleanValue.clone()); - if (r.replace("booleanValue", "", "")) fail("expected replace to fail"); - if (!r.replace("booleanValue", booleanValue, "")) { - fail("expected replace to happen"); - } - r.put("booleanValue", booleanValue.clone()); - if (r.remove("booleanValue", "")) fail("expected remove to fail"); - if (!r.remove("booleanValue", booleanValue)) { - fail("expected remove to happen"); - } - } - { - short[] shortValue = new short[]{1,2,3,4}; - r.put("shortValue", shortValue.clone()); - if (r.replace("shortValue", "", "")) fail("expected replace to fail"); - if (!r.replace("shortValue", shortValue, "")) { - fail("expected replace to happen"); - } - r.put("shortValue", shortValue.clone()); - if (r.remove("shortValue", "")) fail("expected remove to fail"); - if (!r.remove("shortValue", shortValue)) { - fail("expected remove to happen"); - } - } - { - char[] charValue = new char[]{1,2,3,4}; - r.put("charValue", charValue.clone()); - if (r.replace("charValue", "", "")) fail("expected replace to fail"); - if (!r.replace("charValue", charValue, "")) { - fail("expected replace to happen"); - } - r.put("charValue", charValue.clone()); - if (r.remove("charValue", "")) fail("expected remove to fail"); - if (!r.remove("charValue", charValue)) { - fail("expected remove to happen"); - } - } - { - int[] intValue = new int[]{1,2,3,4}; - r.put("intValue", intValue.clone()); - if (r.replace("intValue", "", "")) fail("expected replace to fail"); - if (!r.replace("intValue", intValue, "")) { - fail("expected replace to happen"); - } - r.put("intValue", intValue.clone()); - if (r.remove("intValue", "")) fail("expected remove to fail"); - if (!r.remove("intValue", intValue)) { - fail("expected remove to happen"); - } - } - { - long[] longValue = new long[]{1,2,3,4}; - r.put("longValue", longValue.clone()); - if (r.replace("longValue", "", "")) fail("expected replace to fail"); - if (!r.replace("longValue", longValue, "")) { - fail("expected replace to happen"); - } - r.put("longValue", longValue.clone()); - if (r.remove("longValue", "")) fail("expected remove to fail"); - if (!r.remove("longValue", longValue)) { - fail("expected remove to happen"); - } - } - { - float[] floatValue = new float[]{1,2,3,4}; - r.put("floatValue", floatValue.clone()); - if (r.replace("floatValue", "", "")) fail("expected replace to fail"); - if (!r.replace("floatValue", floatValue, "")) { - fail("expected replace to happen"); - } - r.put("floatValue", floatValue.clone()); - if (r.remove("floatValue", "")) fail("expected remove to fail"); - if (!r.remove("floatValue", floatValue)) { - fail("expected remove to happen"); - } - } - { - double[] doubleValue = new double[]{1,2,3,4}; - r.put("doubleValue", doubleValue.clone()); - if (r.replace("doubleValue", "", "")) fail("expected replace to fail"); - if (!r.replace("doubleValue", doubleValue, "")) { - fail("expected replace to happen"); - } - r.put("doubleValue", doubleValue.clone()); - if (r.remove("doubleValue", "")) fail("expected remove to fail"); - if (!r.remove("doubleValue", doubleValue)) { - fail("expected remove to happen"); - } - } - { - Object[] oaValue = new Object[]{new byte[]{1,2,3,4},new short[]{1,2,3,4},new int[]{1,2,3,4}, "hello sweet world!"}; - r.put("oaValue", oaValue); - Object[] deepCloneOaValue = new Object[]{new byte[]{1,2,3,4},new short[]{1,2,3,4},new int[]{1,2,3,4}, "hello sweet world!"}; - if (r.replace("oaValue", "", "")) fail("expected replace to fail"); - if (!r.replace("oaValue", deepCloneOaValue, "")) { - fail("expected replace to happen"); - } - r.put("oaValue", oaValue); - if (r.remove("oaValue", "")) fail("expected remove to fail"); - if (!r.remove("oaValue", deepCloneOaValue)) { - fail("expected remove to happen"); - } - } - } - - @Test - public void testPartition() { - GemFireCacheImpl gfc = createCache(); - try { - Region r = gfc.createRegionFactory(RegionShortcut.PARTITION).create("ArrayEqualsJUnitTestPartitionRegion"); - doOps(r); - } finally { - closeCache(gfc); - } - } - @Test - public void testLocal() { - GemFireCacheImpl gfc = createCache(); - try { - Region r = gfc.createRegionFactory(RegionShortcut.LOCAL).create("ArrayEqualsJUnitTestLocalRegion"); - doOps(r); - } finally { - closeCache(gfc); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/internal/AvailablePortJUnitTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/AvailablePortJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/AvailablePortJUnitTest.java index 25184de..706702d 100644 --- a/geode-core/src/test/java/com/gemstone/gemfire/internal/AvailablePortJUnitTest.java +++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/AvailablePortJUnitTest.java @@ -17,11 +17,6 @@ package com.gemstone.gemfire.internal; import static org.junit.Assert.*; -import static org.junit.Assume.*; - -import com.gemstone.gemfire.admin.internal.InetAddressUtil; -import com.gemstone.gemfire.internal.lang.SystemUtils; -import com.gemstone.gemfire.test.junit.categories.UnitTest; import java.io.IOException; import java.net.InetAddress; @@ -32,9 +27,13 @@ import org.junit.After; import org.junit.Test; import org.junit.experimental.categories.Category; +import com.gemstone.gemfire.admin.internal.InetAddressUtil; +import com.gemstone.gemfire.test.junit.categories.IntegrationTest; + /** + * multicast availability is tested in JGroupsMessengerJUnitTest */ -@Category(UnitTest.class) +@Category(IntegrationTest.class) public class AvailablePortJUnitTest { private ServerSocket socket; @@ -69,5 +68,4 @@ public class AvailablePortJUnitTest { assertFalse(AvailablePort.isPortAvailable(port, AvailablePort.SOCKET)); } - // multicast availability is tested in JGroupsMessengerJUnitTest } http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/bf258f62/geode-core/src/test/java/com/gemstone/gemfire/internal/ClassPathLoaderIntegrationTest.java ---------------------------------------------------------------------- diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/ClassPathLoaderIntegrationTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/ClassPathLoaderIntegrationTest.java new file mode 100644 index 0000000..4c836bd --- /dev/null +++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/ClassPathLoaderIntegrationTest.java @@ -0,0 +1,503 @@ +/* + * 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 com.gemstone.gemfire.internal; + +import static org.junit.Assert.*; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.util.Enumeration; +import java.util.Vector; + +import org.apache.bcel.Constants; +import org.apache.bcel.classfile.JavaClass; +import org.apache.bcel.generic.ClassGen; +import org.junit.After; +import org.junit.Before; +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.rules.TemporaryFolder; + +import com.gemstone.gemfire.internal.ClassPathLoaderTest.BrokenClassLoader; +import com.gemstone.gemfire.internal.ClassPathLoaderTest.NullClassLoader; +import com.gemstone.gemfire.internal.ClassPathLoaderTest.SimpleClassLoader; + +import com.gemstone.gemfire.test.junit.categories.IntegrationTest; + +/** + * Integration tests for {@link ClassPathLoader}. + * + * Extracted from ClassPathLoaderTest. + */ +@Category(IntegrationTest.class) +public class ClassPathLoaderIntegrationTest { + + private static final int TEMP_FILE_BYTES_COUNT = 256; + + private volatile File tempFile; + private volatile File tempFile2; + + @Rule + public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties(); + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Before + public void setUp() throws Exception { + System.setProperty(ClassPathLoader.EXCLUDE_TCCL_PROPERTY, "false"); + System.setProperty(ClassPathLoader.EXT_LIB_DIR_PARENT_PROPERTY, this.temporaryFolder.getRoot().getAbsolutePath()); + + this.tempFile = this.temporaryFolder.newFile("tempFile1.tmp"); + FileOutputStream fos = new FileOutputStream(this.tempFile); + fos.write(new byte[TEMP_FILE_BYTES_COUNT]); + fos.close(); + + this.tempFile2 = this.temporaryFolder.newFile("tempFile2.tmp"); + fos = new FileOutputStream(this.tempFile2); + fos.write(new byte[TEMP_FILE_BYTES_COUNT]); + fos.close(); + } + + /** + * Verifies that getResource works with custom loader from {@link ClassPathLoader}. + */ + @Test + public void testGetResourceWithCustomLoader() throws Exception { + System.out.println("\nStarting ClassPathLoaderTest#testGetResourceWithCustomLoader"); + + ClassPathLoader dcl = ClassPathLoader.createWithDefaults(false); + dcl = dcl.addOrReplace(new GeneratingClassLoader()); + + String resourceToGet = "com/nowhere/testGetResourceWithCustomLoader.rsc"; + URL url = dcl.getResource(resourceToGet); + assertNotNull(url); + + InputStream is = url != null ? url.openStream() : null; + assertNotNull(is); + + int totalBytesRead = 0; + byte[] input = new byte[128]; + + BufferedInputStream bis = new BufferedInputStream(is); + for (int bytesRead = bis.read(input); bytesRead > -1;) { + totalBytesRead += bytesRead; + bytesRead = bis.read(input); + } + bis.close(); + + assertEquals(TEMP_FILE_BYTES_COUNT, totalBytesRead); + } + + /** + * Verifies that getResources works with custom loader from {@link ClassPathLoader}. + */ + @Test + public void testGetResourcesWithCustomLoader() throws Exception { + System.out.println("\nStarting ClassPathLoaderTest#testGetResourceWithCustomLoader"); + + ClassPathLoader dcl = ClassPathLoader.createWithDefaults(false); + dcl = dcl.addOrReplace(new GeneratingClassLoader()); + + String resourceToGet = "com/nowhere/testGetResourceWithCustomLoader.rsc"; + Enumeration urls = dcl.getResources(resourceToGet); + assertNotNull(urls); + assertTrue(urls.hasMoreElements()); + + URL url = urls.nextElement(); + InputStream is = url != null ? url.openStream() : null; + assertNotNull(is); + + int totalBytesRead = 0; + byte[] input = new byte[128]; + + BufferedInputStream bis = new BufferedInputStream(is); + for (int bytesRead = bis.read(input); bytesRead > -1;) { + totalBytesRead += bytesRead; + bytesRead = bis.read(input); + } + bis.close(); + + assertEquals(TEMP_FILE_BYTES_COUNT, totalBytesRead); + } + + /** + * Verifies that getResourceAsStream works with custom loader from {@link ClassPathLoader}. + */ + @Test + public void testGetResourceAsStreamWithCustomLoader() throws Exception { + System.out.println("\nStarting ClassPathLoaderTest#testGetResourceAsStreamWithCustomLoader"); + + ClassPathLoader dcl = ClassPathLoader.createWithDefaults(false); + dcl = dcl.addOrReplace(new GeneratingClassLoader()); + + String resourceToGet = "com/nowhere/testGetResourceAsStreamWithCustomLoader.rsc"; + InputStream is = dcl.getResourceAsStream(resourceToGet); + assertNotNull(is); + + int totalBytesRead = 0; + byte[] input = new byte[128]; + + BufferedInputStream bis = new BufferedInputStream(is); + for (int bytesRead = bis.read(input); bytesRead > -1;) { + totalBytesRead += bytesRead; + bytesRead = bis.read(input); + } + bis.close(); + + assertEquals(TEMP_FILE_BYTES_COUNT, totalBytesRead); + } + + /** + * Verifies that getResource works with TCCL from {@link ClassPathLoader}. + */ + @Test + public void testGetResourceWithTCCL() throws Exception { + System.out.println("\nStarting ClassPathLoaderTest#testGetResourceWithTCCL"); + + ClassPathLoader dcl = ClassPathLoader.createWithDefaults(false); + + String resourceToGet = "com/nowhere/testGetResourceWithTCCL.rsc"; + assertNull(dcl.getResource(resourceToGet)); + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(new GeneratingClassLoader()); + URL url = dcl.getResource(resourceToGet); + assertNotNull(url); + + InputStream is = url.openStream(); + assertNotNull(is); + + int totalBytesRead = 0; + byte[] input = new byte[128]; + + BufferedInputStream bis = new BufferedInputStream(is); + for (int bytesRead = bis.read(input); bytesRead > -1;) { + totalBytesRead += bytesRead; + bytesRead = bis.read(input); + } + bis.close(); + + assertEquals(TEMP_FILE_BYTES_COUNT, totalBytesRead); + } finally { + Thread.currentThread().setContextClassLoader(cl); + } + } + + /** + * Verifies that getResources works with TCCL from {@link ClassPathLoader}. + */ + @Test + public void testGetResourcesWithTCCL() throws Exception { + System.out.println("\nStarting ClassPathLoaderTest#testGetResourceWithTCCL"); + + ClassPathLoader dcl = ClassPathLoader.createWithDefaults(false); + + String resourceToGet = "com/nowhere/testGetResourceWithTCCL.rsc"; + Enumeration urls = dcl.getResources(resourceToGet); + assertNotNull(urls); + assertFalse(urls.hasMoreElements()); + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(new GeneratingClassLoader()); + urls = dcl.getResources(resourceToGet); + assertNotNull(urls); + + URL url = urls.nextElement(); + InputStream is = url.openStream(); + assertNotNull(is); + + int totalBytesRead = 0; + byte[] input = new byte[128]; + + BufferedInputStream bis = new BufferedInputStream(is); + for (int bytesRead = bis.read(input); bytesRead > -1;) { + totalBytesRead += bytesRead; + bytesRead = bis.read(input); + } + bis.close(); + + assertEquals(TEMP_FILE_BYTES_COUNT, totalBytesRead); + } finally { + Thread.currentThread().setContextClassLoader(cl); + } + } + + /** + * Verifies that getResourceAsStream works with TCCL from {@link ClassPathLoader}. + */ + @Test + public void testGetResourceAsStreamWithTCCL() throws Exception { + System.out.println("\nStarting ClassPathLoaderTest#testGetResourceAsStreamWithTCCL"); + + ClassPathLoader dcl = ClassPathLoader.createWithDefaults(false); + + String resourceToGet = "com/nowhere/testGetResourceAsStreamWithTCCL.rsc"; + assertNull(dcl.getResourceAsStream(resourceToGet)); + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { + // ensure that TCCL is only CL that can find this resource + Thread.currentThread().setContextClassLoader(new GeneratingClassLoader()); + InputStream is = dcl.getResourceAsStream(resourceToGet); + assertNotNull(is); + + int totalBytesRead = 0; + byte[] input = new byte[128]; + + BufferedInputStream bis = new BufferedInputStream(is); + for (int bytesRead = bis.read(input); bytesRead > -1;) { + totalBytesRead += bytesRead; + bytesRead = bis.read(input); + } + bis.close(); + + assertEquals(TEMP_FILE_BYTES_COUNT, totalBytesRead); + } finally { + Thread.currentThread().setContextClassLoader(cl); + } + } + + /** + * Verifies that JAR files found in the extlib directory will be correctly + * added to the {@link ClassPathLoader}. + */ + @Test + public void testJarsInExtLib() throws Exception { + System.out.println("\nStarting ClassPathLoaderTest#testJarsInExtLib"); + + File EXT_LIB_DIR = ClassPathLoader.defineEXT_LIB_DIR(); + EXT_LIB_DIR.mkdir(); + + File subdir = new File(EXT_LIB_DIR, "cplju"); + subdir.mkdir(); + + final ClassBuilder classBuilder = new ClassBuilder(); + + writeJarBytesToFile(new File(EXT_LIB_DIR, "ClassPathLoaderJUnit1.jar"), + classBuilder.createJarFromClassContent("com/cpljunit1/ClassPathLoaderJUnit1", "package com.cpljunit1; public class ClassPathLoaderJUnit1 {}")); + writeJarBytesToFile(new File(subdir, "ClassPathLoaderJUnit2.jar"), + classBuilder.createJarFromClassContent("com/cpljunit2/ClassPathLoaderJUnit2", "package com.cpljunit2; public class ClassPathLoaderJUnit2 {}")); + + ClassPathLoader classPathLoader = ClassPathLoader.createWithDefaults(false); + try { + classPathLoader.forName("com.cpljunit1.ClassPathLoaderJUnit1"); + } catch (ClassNotFoundException cnfex) { + fail("JAR file not correctly added to Classpath"); + } + + try { + classPathLoader.forName("com.cpljunit2.ClassPathLoaderJUnit2"); + } catch (ClassNotFoundException cnfex) { + fail("JAR file not correctly added to Classpath"); + } + + assertNotNull(classPathLoader.getResource("com/cpljunit2/ClassPathLoaderJUnit2.class")); + + Enumeration urls = classPathLoader.getResources("com/cpljunit1"); + if (!urls.hasMoreElements()) { + fail("Resources should return one element"); + } + } + + /** + * Verifies that the 3rd custom loader will get the resource. Parent cannot find it and TCCL is broken. This verifies + * that all custom loaders are checked and that the custom loaders are all checked before TCCL. + */ + @Test + public void testGetResourceAsStreamWithMultipleCustomLoaders() throws Exception { + System.out.println("\nStarting ClassPathLoaderTest#testGetResourceAsStreamWithMultipleCustomLoaders"); + + // create DCL such that the 3rd loader should find the resource + // first custom loader becomes parent which won't find anything + ClassPathLoader dcl = ClassPathLoader.createWithDefaults(false); + dcl = dcl.addOrReplace(new GeneratingClassLoader()); + dcl = dcl.addOrReplace(new SimpleClassLoader(getClass().getClassLoader())); + dcl = dcl.addOrReplace(new NullClassLoader()); + + String resourceToGet = "com/nowhere/testGetResourceAsStreamWithMultipleCustomLoaders.rsc"; + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { + // set TCCL to throw errors which makes sure we find before checking TCCL + Thread.currentThread().setContextClassLoader(new BrokenClassLoader()); + + InputStream is = dcl.getResourceAsStream(resourceToGet); + assertNotNull(is); + is.close(); + } finally { + Thread.currentThread().setContextClassLoader(cl); + } + } + + /** + * Verifies that the 3rd custom loader will get the resource. Parent cannot find it and TCCL is broken. This verifies + * that all custom loaders are checked and that the custom loaders are all checked before TCCL. + */ + @Test + public void testGetResourceWithMultipleCustomLoaders() throws Exception { + System.out.println("\nStarting ClassPathLoaderTest#testGetResourceWithMultipleCustomLoaders"); + + // create DCL such that the 3rd loader should find the resource + // first custom loader becomes parent which won't find anything + ClassPathLoader dcl = ClassPathLoader.createWithDefaults(false); + dcl = dcl.addOrReplace(new GeneratingClassLoader()); + dcl = dcl.addOrReplace(new SimpleClassLoader(getClass().getClassLoader())); + dcl = dcl.addOrReplace(new NullClassLoader()); + + String resourceToGet = "com/nowhere/testGetResourceWithMultipleCustomLoaders.rsc"; + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { + // set TCCL to throw errors which makes sure we find before checking TCCL + Thread.currentThread().setContextClassLoader(new BrokenClassLoader()); + + URL url = dcl.getResource(resourceToGet); + assertNotNull(url); + } finally { + Thread.currentThread().setContextClassLoader(cl); + } + } + + /** + * Verifies that the 3rd custom loader will get the resources. Parent cannot find it and TCCL is broken. This verifies + * that all custom loaders are checked and that the custom loaders are all checked before TCCL. + */ + @Test + public void testGetResourcesWithMultipleCustomLoaders() throws Exception { + System.out.println("\nStarting ClassPathLoaderTest#testGetResourceWithMultipleCustomLoaders"); + + // create DCL such that the 3rd loader should find the resource + // first custom loader becomes parent which won't find anything + ClassPathLoader dcl = ClassPathLoader.createWithDefaults(false); + dcl = dcl.addOrReplace(new GeneratingClassLoader()); + dcl = dcl.addOrReplace(new GeneratingClassLoader2()); + dcl = dcl.addOrReplace(new SimpleClassLoader(getClass().getClassLoader())); + dcl = dcl.addOrReplace(new NullClassLoader()); + + String resourceToGet = "com/nowhere/testGetResourceWithMultipleCustomLoaders.rsc"; + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { + // set TCCL to throw errors which makes sure we find before checking TCCL + Thread.currentThread().setContextClassLoader(new BrokenClassLoader()); + + Enumeration urls = dcl.getResources(resourceToGet); + assertNotNull(urls); + assertTrue(urls.hasMoreElements()); + + URL url = urls.nextElement(); + assertNotNull(url); + + // Should find two with unique URLs + assertTrue("Did not find all resources.", urls.hasMoreElements()); + URL url2 = urls.nextElement(); + assertNotNull(url2); + assertTrue("Resource URLs should be unique.", !url.equals(url2)); + + } finally { + Thread.currentThread().setContextClassLoader(cl); + } + } + + private void writeJarBytesToFile(File jarFile, byte[] jarBytes) throws IOException { + final OutputStream outStream = new FileOutputStream(jarFile); + outStream.write(jarBytes); + outStream.close(); + } + + /** + * Custom class loader which uses BCEL to always dynamically generate a class for any class name it tries to load. + */ + private class GeneratingClassLoader extends ClassLoader { + + /** + * Currently unused but potentially useful for some future test. This causes this loader to only generate a class + * that the parent could not find. + * + * @param parent + * the parent class loader to check with first + */ + @SuppressWarnings("unused") + public GeneratingClassLoader(ClassLoader parent) { + super(parent); + } + + /** + * Specifies no parent to ensure that this loader generates the named class. + */ + public GeneratingClassLoader() { + super(null); // no parent!! + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + ClassGen cg = new ClassGen(name, "java.lang.Object", "", Constants.ACC_PUBLIC | Constants.ACC_SUPER, null); + cg.addEmptyConstructor(Constants.ACC_PUBLIC); + JavaClass jClazz = cg.getJavaClass(); + byte[] bytes = jClazz.getBytes(); + return defineClass(jClazz.getClassName(), bytes, 0, bytes.length); + } + + @Override + protected URL findResource(String name) { + URL url = null; + try { + url = getTempFile().getAbsoluteFile().toURI().toURL(); + System.out.println("GeneratingClassLoader#findResource returning " + url); + } catch (IOException e) { + } + return url; + } + + @Override + protected Enumeration findResources(String name) throws IOException { + URL url = null; + try { + url = getTempFile().getAbsoluteFile().toURI().toURL(); + System.out.println("GeneratingClassLoader#findResources returning " + url); + } catch (IOException e) { + } + Vector urls = new Vector(); + urls.add(url); + return urls.elements(); + } + + protected File getTempFile() { + return tempFile; + } + } + + /** + * Custom class loader which uses BCEL to always dynamically generate a class for any class name it tries to load. + */ + private class GeneratingClassLoader2 extends GeneratingClassLoader { + @Override + protected File getTempFile() { + return tempFile2; + } + } +}