From 39b64349c0d25c88176beea91266d6b7bda2913d Mon Sep 17 00:00:00 2001 From: jialiang Date: Fri, 1 Nov 2024 16:16:59 +0800 Subject: [PATCH] AMBARI-26222: Fix ClientConfigResourceProviderTest & PreUpgradeCheckResourceProviderTest& ExecutionSchedulerTest& AmbariProxiedUserDetailsServiceTest --- ambari-server/pom.xml | 2 + .../commands/StackAdvisorCommandTest.java | 1 - .../HostsRepositoryVersionCheckTest.java | 6 +- .../server/checks/ServicesUpCheckTest.java | 4 +- .../ClientConfigResourceProviderTest.java | 63 ++++++---- .../PreUpgradeCheckResourceProviderTest.java | 35 ++++-- .../scheduler/ExecutionSchedulerTest.java | 106 +++++++--------- .../AmbariProxiedUserDetailsServiceTest.java | 118 +++++++++++------- .../orchestrate/UpgradeHelperTest.java | 16 ++- 9 files changed, 203 insertions(+), 148 deletions(-) diff --git a/ambari-server/pom.xml b/ambari-server/pom.xml index 81c9bf86200..dbe78d7fbcc 100644 --- a/ambari-server/pom.xml +++ b/ambari-server/pom.xml @@ -738,6 +738,7 @@ --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.xml/jdk.xml.internal=ALL-UNNAMED --add-opens java.naming/com.sun.jndi.ldap=ALL-UNNAMED + --add-opens java.base/java.security=ALL-UNNAMED @@ -1307,6 +1308,7 @@ org.mockito mockito-core + 3.5.10 test diff --git a/ambari-server/src/test/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommandTest.java b/ambari-server/src/test/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommandTest.java index 4b290bc2947..52ae4248b7c 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommandTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommandTest.java @@ -24,7 +24,6 @@ import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; diff --git a/ambari-server/src/test/java/org/apache/ambari/server/checks/HostsRepositoryVersionCheckTest.java b/ambari-server/src/test/java/org/apache/ambari/server/checks/HostsRepositoryVersionCheckTest.java index 96626c0a565..4fbe582e1c0 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/checks/HostsRepositoryVersionCheckTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/checks/HostsRepositoryVersionCheckTest.java @@ -17,10 +17,11 @@ */ package org.apache.ambari.server.checks; +import static org.mockito.ArgumentMatchers.nullable; + import java.util.HashMap; import java.util.Map; -import org.apache.ambari.server.api.services.AmbariMetaInfo; import org.apache.ambari.server.orm.dao.HostVersionDAO; import org.apache.ambari.server.orm.dao.RepositoryVersionDAO; import org.apache.ambari.server.orm.entities.HostVersionEntity; @@ -37,7 +38,6 @@ import org.apache.ambari.server.state.repository.ClusterVersionSummary; import org.apache.ambari.server.state.repository.VersionDefinitionXml; import org.apache.ambari.spi.ClusterInformation; -import org.apache.ambari.spi.RepositoryType; import org.apache.ambari.spi.RepositoryVersion; import org.apache.ambari.spi.upgrade.UpgradeCheckRequest; import org.apache.ambari.spi.upgrade.UpgradeCheckResult; @@ -53,7 +53,7 @@ import com.google.inject.Provider; -import static org.mockito.ArgumentMatchers.nullable; + /** * Unit tests for HostsRepositoryVersionCheck diff --git a/ambari-server/src/test/java/org/apache/ambari/server/checks/ServicesUpCheckTest.java b/ambari-server/src/test/java/org/apache/ambari/server/checks/ServicesUpCheckTest.java index 35170a0f797..ad84f02aaaf 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/checks/ServicesUpCheckTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/checks/ServicesUpCheckTest.java @@ -17,6 +17,8 @@ */ package org.apache.ambari.server.checks; +import static org.mockito.ArgumentMatchers.nullable; + import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -61,8 +63,6 @@ import com.google.inject.Provider; -import static org.mockito.ArgumentMatchers.nullable; - /** * Unit tests for ServicesUpCheck diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ClientConfigResourceProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ClientConfigResourceProviderTest.java index e6e59b3aa95..9c30ccf114e 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ClientConfigResourceProviderTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ClientConfigResourceProviderTest.java @@ -23,11 +23,9 @@ import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.createNiceMock; import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertFalse; -import static org.powermock.api.mockito.PowerMockito.whenNew; import java.io.ByteArrayInputStream; import java.io.File; @@ -80,10 +78,10 @@ import org.easymock.EasyMock; import org.junit.After; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; -import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.security.core.Authentication; @@ -93,8 +91,13 @@ * ClientConfigResourceProviderTest tests. */ @RunWith(PowerMockRunner.class) -@PrepareForTest({ClientConfigResourceProvider.class, StageUtils.class}) +@PrepareForTest({ClientConfigResourceProvider.class, StageUtils.class,ClientConfigResourceProvider.TarUtils.class}) public class ClientConfigResourceProviderTest { + @Before + public void setUp() throws Exception { + PowerMock.resetAll(); + } + @After public void clearAuthentication() { SecurityContextHolder.getContext().setAuthentication(null); @@ -273,29 +276,29 @@ public void testDeleteResources() throws Exception { private void testGetResources(Authentication authentication) throws Exception { Resource.Type type = Resource.Type.ClientConfig; - AmbariManagementController managementController = createNiceMock(AmbariManagementController.class); - Clusters clusters = createNiceMock(Clusters.class); - - Cluster cluster = createNiceMock(Cluster.class); - AmbariMetaInfo ambariMetaInfo = createNiceMock(AmbariMetaInfo.class); - StackId stackId = createNiceMock(StackId.class); - ComponentInfo componentInfo = createNiceMock(ComponentInfo.class); - ServiceInfo serviceInfo = createNiceMock(ServiceInfo.class); - CommandScriptDefinition commandScriptDefinition = createNiceMock(CommandScriptDefinition.class); - Config clusterConfig = createNiceMock(Config.class); - DesiredConfig desiredConfig = createNiceMock(DesiredConfig.class); - Host host = createNiceMock(Host.class); - Service service = createNiceMock(Service.class); - ServiceComponent serviceComponent = createNiceMock(ServiceComponent.class); - ServiceComponentHost serviceComponentHost = createNiceMock(ServiceComponentHost.class); - ConfigHelper configHelper = createNiceMock(ConfigHelper.class); + AmbariManagementController managementController = PowerMock.createNiceMock(AmbariManagementController.class); + Clusters clusters = PowerMock.createNiceMock(Clusters.class); + + Cluster cluster = PowerMock.createNiceMock(Cluster.class); + AmbariMetaInfo ambariMetaInfo = PowerMock.createNiceMock(AmbariMetaInfo.class); + StackId stackId = PowerMock.createNiceMock(StackId.class); + ComponentInfo componentInfo = PowerMock.createNiceMock(ComponentInfo.class); + ServiceInfo serviceInfo = PowerMock.createNiceMock(ServiceInfo.class); + CommandScriptDefinition commandScriptDefinition = PowerMock.createNiceMock(CommandScriptDefinition.class); + Config clusterConfig = PowerMock.createNiceMock(Config.class); + DesiredConfig desiredConfig = PowerMock.createNiceMock(DesiredConfig.class); + Host host = PowerMock.createNiceMock(Host.class); + Service service = PowerMock.createNiceMock(Service.class); + ServiceComponent serviceComponent = PowerMock.createNiceMock(ServiceComponent.class); + ServiceComponentHost serviceComponentHost = PowerMock.createNiceMock(ServiceComponentHost.class); + ConfigHelper configHelper = PowerMock.createNiceMock(ConfigHelper.class); Configuration configuration = PowerMock.createStrictMockAndExpectNew(Configuration.class); File newFile = File.createTempFile("config", ".json", new File("/tmp/")); newFile.deleteOnExit(); - Runtime runtime = createMock(Runtime.class); - Process process = createNiceMock(Process.class); + Runtime runtime = PowerMock.createNiceMock(Runtime.class); + Process process = PowerMock.createNiceMock(Process.class); Map desiredConfigMap = new HashMap<>(); desiredConfigMap.put("hive-site", desiredConfig); @@ -456,10 +459,16 @@ private void testGetResources(Authentication authentication) throws Exception { InputStream inputStream = new ByteArrayInputStream("some logging info".getBytes()); expect(process.getInputStream()).andReturn(inputStream); - ClientConfigResourceProvider.TarUtils tarUtilMock = PowerMockito.mock(ClientConfigResourceProvider.TarUtils.class); - whenNew(ClientConfigResourceProvider.TarUtils.class).withAnyArguments().thenReturn(tarUtilMock); + + ClientConfigResourceProvider.TarUtils tarUtilMock = + PowerMock.createMock(ClientConfigResourceProvider.TarUtils.class); + + PowerMock.expectNew(ClientConfigResourceProvider.TarUtils.class, + EasyMock.anyString(), EasyMock.anyString(), EasyMock.anyObject()).andReturn(tarUtilMock); + tarUtilMock.tarConfigFiles(); - expectLastCall().once(); + EasyMock.expectLastCall().once(); + // create the request Request request = PropertyHelper.getReadRequest(ClientConfigResourceProvider.COMPONENT_CLUSTER_NAME_PROPERTY_ID, "c1", @@ -470,7 +479,7 @@ private void testGetResources(Authentication authentication) throws Exception { equals("c1").and().property(ClientConfigResourceProvider.COMPONENT_SERVICE_NAME_PROPERTY_ID).equals("PIG").toPredicate(); // replay - replay(managementController, clusters, cluster, ambariMetaInfo, stackId, componentInfo, commandScriptDefinition, + PowerMock.replay(managementController, clusters, cluster, ambariMetaInfo, stackId, componentInfo, commandScriptDefinition, clusterConfig, host, service, serviceComponent, serviceComponentHost, serviceInfo, configHelper, runtime, process); PowerMock.replayAll(); @@ -590,6 +599,8 @@ private void testGetResourcesFromCommonServices(Authentication authentication) t expect(managementController.getHostComponents(EasyMock.anyObject())).andReturn(responses).anyTimes(); PowerMock.mockStaticPartial(StageUtils.class, "getClusterHostInfo"); + + Map> clusterHostInfo = new HashMap<>(); Set all_hosts = new HashSet<>(Arrays.asList("Host100", "Host101", "Host102")); Set some_hosts = new HashSet<>(Arrays.asList("0-1", "2")); diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/PreUpgradeCheckResourceProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/PreUpgradeCheckResourceProviderTest.java index 9b094b5dd13..a8490a3192f 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/PreUpgradeCheckResourceProviderTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/PreUpgradeCheckResourceProviderTest.java @@ -23,6 +23,7 @@ import static org.junit.Assert.assertNotNull; import java.io.File; +import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Collections; @@ -225,16 +226,35 @@ public void testGetResources() throws Exception{ expect(upgradePack.getType()).andReturn(UpgradeType.ROLLING).atLeastOnce(); expect(ambariMetaInfo.getServices("Stack100", "1.0")).andReturn(allServiceInfoMap).anyTimes(); - String checks = ClassLoader.getSystemClassLoader().getResource("checks").getPath(); - expect(serviceInfo.getChecksFolder()).andReturn(new File(checks)); +// String checks = ClassLoader.getSystemClassLoader().getResource("checks").getPath(); + expect(serviceInfo.getChecksFolder()).andReturn(new File("checks")); + + + class TestClassLoader extends URLClassLoader { + public TestClassLoader() { + super(new URL[0], TestClassLoader.class.getClassLoader()); + } + + @Override + public URL[] getURLs() { + try { + return new URL[] { new URL("file://foo") }; + } catch (MalformedURLException e) { + return new URL[0]; + } + } + } + TestClassLoader testClassLoader = new TestClassLoader(); + - URL url = new URL("file://foo"); - URLClassLoader classLoader = createNiceMock(URLClassLoader.class); - expect(classLoader.getURLs()).andReturn(new URL[] { url }).once(); StackInfo stackInfo = createNiceMock(StackInfo.class); - expect(ambariMetaInfo.getStack(targetStackId)).andReturn(stackInfo).atLeastOnce(); - expect(stackInfo.getLibraryClassLoader()).andReturn(classLoader).atLeastOnce(); + + expect(ambariMetaInfo.getStack(targetStackId)).andReturn(stackInfo).anyTimes(); +// String tname = targetStackId.getStackName(); +// String tv = targetStackId.getStackVersion(); + expect(ambariMetaInfo.getStack("Stack100", "1.1") ).andReturn(stackInfo).atLeastOnce(); + expect(stackInfo.getLibraryClassLoader()).andReturn(testClassLoader).anyTimes(); expect(stackInfo.getLibraryInstance(EasyMock.anyObject(), EasyMock.eq(TEST_SERVICE_CHECK_CLASS_NAME))) .andReturn(new SampleServiceCheck()).atLeastOnce(); @@ -294,7 +314,6 @@ public void testGetResources() throws Exception{ UpgradeType upgradeType = (UpgradeType) customUpgradeCheck.getPropertyValue(PreUpgradeCheckResourceProvider.UPGRADE_CHECK_UPGRADE_TYPE_PROPERTY_ID); Assert.assertEquals(UpgradeType.NON_ROLLING, upgradeType); - PowerMock.verifyAll(); } /** diff --git a/ambari-server/src/test/java/org/apache/ambari/server/scheduler/ExecutionSchedulerTest.java b/ambari-server/src/test/java/org/apache/ambari/server/scheduler/ExecutionSchedulerTest.java index 1ee7ef02909..f1b42cc117e 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/scheduler/ExecutionSchedulerTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/scheduler/ExecutionSchedulerTest.java @@ -17,34 +17,31 @@ */ package org.apache.ambari.server.scheduler; -import static org.easymock.EasyMock.expect; -import static org.mockito.Mockito.spy; -import static org.powermock.api.easymock.PowerMock.createNiceMock; -import static org.powermock.api.easymock.PowerMock.expectNew; -import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.util.Properties; import org.apache.ambari.server.configuration.Configuration; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.powermock.api.easymock.PowerMock; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; import org.quartz.Scheduler; -import org.quartz.impl.StdSchedulerFactory; import junit.framework.Assert; -@RunWith(PowerMockRunner.class) -@PowerMockIgnore("javax.management.*") + +@RunWith(MockitoJUnitRunner.class) public class ExecutionSchedulerTest { private Configuration configuration; + @Mock + private Scheduler scheduler; + @Before public void setup() throws Exception { Properties properties = new Properties(); @@ -57,55 +54,49 @@ public void setup() throws Exception { properties.setProperty(Configuration.SERVER_DB_NAME.getKey(), "derby"); configuration = new Configuration(properties); - } - @After - public void teardown() throws Exception { + private class TestExecutionScheduler extends ExecutionSchedulerImpl { + public TestExecutionScheduler(Configuration config) throws Exception { + super(config); + this.scheduler = ExecutionSchedulerTest.this.scheduler; + this.isInitialized = true; + } + + @Override + protected synchronized void initializeScheduler() { + // Do nothing - we've already initialized in constructor + } } @Test - @PrepareForTest({ ExecutionSchedulerImpl.class }) public void testSchedulerInitialize() throws Exception { + ExecutionSchedulerImpl executionScheduler = new ExecutionSchedulerImpl(configuration); - ExecutionSchedulerImpl executionScheduler = - spy(new ExecutionSchedulerImpl(configuration)); - - Properties actualProperties = executionScheduler - .getQuartzSchedulerProperties(); + Properties actualProperties = executionScheduler.getQuartzSchedulerProperties(); Assert.assertEquals("2", actualProperties.getProperty("org.quartz.threadPool.threadCount")); Assert.assertEquals("2", actualProperties.getProperty("org.quartz.dataSource.myDS.maxConnections")); Assert.assertEquals("false", actualProperties.getProperty("org.quartz.jobStore.isClustered")); Assert.assertEquals("org.quartz.impl.jdbcjobstore.PostgreSQLDelegate", - actualProperties.getProperty("org.quartz.jobStore.driverDelegateClass")); + actualProperties.getProperty("org.quartz.jobStore.driverDelegateClass")); Assert.assertEquals("select 0", - actualProperties.getProperty("org.quartz.dataSource.myDS.validationQuery")); + actualProperties.getProperty("org.quartz.dataSource.myDS.validationQuery")); Assert.assertEquals(ExecutionSchedulerImpl.DEFAULT_SCHEDULER_NAME, - actualProperties.getProperty("org.quartz.scheduler.instanceName")); + actualProperties.getProperty("org.quartz.scheduler.instanceName")); Assert.assertEquals("org.quartz.simpl.SimpleThreadPool", - actualProperties.getProperty("org.quartz.threadPool.class")); + actualProperties.getProperty("org.quartz.threadPool.class")); } @Test - @PrepareForTest({ ExecutionSchedulerImpl.class }) public void testSchedulerStartStop() throws Exception { - StdSchedulerFactory factory = createNiceMock(StdSchedulerFactory.class); - Scheduler scheduler = createNiceMock(Scheduler.class); - - expect(factory.getScheduler()).andReturn(scheduler); - expectPrivate(scheduler, "startDelayed", new Integer(180)).once(); - expectNew(StdSchedulerFactory.class).andReturn(factory); - expectPrivate(scheduler, "shutdown").once(); - - PowerMock.replay(factory, StdSchedulerFactory.class, scheduler); - - ExecutionSchedulerImpl executionScheduler = new ExecutionSchedulerImpl(configuration); + ExecutionSchedulerImpl executionScheduler = new TestExecutionScheduler(configuration); executionScheduler.startScheduler(180); executionScheduler.stopScheduler(); - PowerMock.verify(factory, StdSchedulerFactory.class, scheduler); + verify(scheduler).startDelayed(180); + verify(scheduler).shutdown(); Assert.assertTrue(executionScheduler.isInitialized()); } @@ -114,22 +105,20 @@ public void testSchedulerStartStop() throws Exception { public void testGetQuartzDbDelegateClassAndValidationQuery() throws Exception { Properties testProperties = new Properties(); testProperties.setProperty(Configuration.SERVER_JDBC_URL.getKey(), - "jdbc:postgresql://host:port/dbname"); + "jdbc:postgresql://host:port/dbname"); testProperties.setProperty(Configuration.SERVER_DB_NAME.getKey(), "ambari"); Configuration configuration1 = new Configuration(testProperties); - ExecutionSchedulerImpl executionScheduler = - spy(new ExecutionSchedulerImpl(configuration1)); + ExecutionSchedulerImpl executionScheduler = new ExecutionSchedulerImpl(configuration1); - String[] subProps = executionScheduler - .getQuartzDbDelegateClassAndValidationQuery(); + String[] subProps = executionScheduler.getQuartzDbDelegateClassAndValidationQuery(); Assert.assertEquals("org.quartz.impl.jdbcjobstore.PostgreSQLDelegate", subProps[0]); Assert.assertEquals("select 0", subProps[1]); testProperties.setProperty(Configuration.SERVER_JDBC_URL.getKey(), - "jdbc:mysql://host:port/dbname"); + "jdbc:mysql://host:port/dbname"); configuration1 = new Configuration(testProperties); - executionScheduler = spy(new ExecutionSchedulerImpl(configuration1)); + executionScheduler = new ExecutionSchedulerImpl(configuration1); subProps = executionScheduler.getQuartzDbDelegateClassAndValidationQuery(); @@ -137,9 +126,9 @@ public void testGetQuartzDbDelegateClassAndValidationQuery() throws Exception { Assert.assertEquals("select 0", subProps[1]); testProperties.setProperty(Configuration.SERVER_JDBC_URL.getKey(), - "jdbc:oracle:thin://host:port/dbname"); + "jdbc:oracle:thin://host:port/dbname"); configuration1 = new Configuration(testProperties); - executionScheduler = spy(new ExecutionSchedulerImpl(configuration1)); + executionScheduler = new ExecutionSchedulerImpl(configuration1); subProps = executionScheduler.getQuartzDbDelegateClassAndValidationQuery(); @@ -148,25 +137,22 @@ public void testGetQuartzDbDelegateClassAndValidationQuery() throws Exception { } @Test - @PrepareForTest({ ExecutionSchedulerImpl.class }) public void testSchedulerStartDelay() throws Exception { - StdSchedulerFactory factory = createNiceMock(StdSchedulerFactory.class); - Scheduler scheduler = createNiceMock(Scheduler.class); - expect(factory.getScheduler()).andReturn(scheduler).anyTimes(); - expectNew(StdSchedulerFactory.class).andReturn(factory); - expect(scheduler.isStarted()).andReturn(false).anyTimes(); - expectPrivate(scheduler, "startDelayed", new Integer(180)).once(); - expectPrivate(scheduler, "start").once(); + // 设置模拟行为 + when(scheduler.isStarted()).thenReturn(false); - PowerMock.replay(factory, StdSchedulerFactory.class, scheduler); - - ExecutionSchedulerImpl executionScheduler = new ExecutionSchedulerImpl(configuration); + // 创建测试实例 + TestExecutionScheduler executionScheduler = new TestExecutionScheduler(configuration); + // 调用测试方法 executionScheduler.startScheduler(180); executionScheduler.startScheduler(null); - PowerMock.verify(factory, StdSchedulerFactory.class, scheduler); + // 验证调用 + verify(scheduler).startDelayed(180); + verify(scheduler).start(); + verify(scheduler, atLeastOnce()).isStarted(); Assert.assertTrue(executionScheduler.isInitialized()); } diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/kerberos/AmbariProxiedUserDetailsServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/kerberos/AmbariProxiedUserDetailsServiceTest.java index ba310d4a2d4..90703fe176c 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/kerberos/AmbariProxiedUserDetailsServiceTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authentication/kerberos/AmbariProxiedUserDetailsServiceTest.java @@ -29,6 +29,7 @@ import org.apache.ambari.server.orm.entities.UserEntity; import org.apache.ambari.server.security.authentication.tproxy.AmbariTProxyConfiguration; import org.apache.ambari.server.security.authorization.Users; +import org.easymock.EasyMock; import org.easymock.EasyMockSupport; import org.junit.Assert; import org.junit.Test; @@ -36,55 +37,80 @@ public class AmbariProxiedUserDetailsServiceTest extends EasyMockSupport { @Test public void testValidateHost() throws UnknownHostException { - AmbariProxiedUserDetailsService service = createMockBuilder(AmbariProxiedUserDetailsService.class) - .withConstructor(createNiceMock(Configuration.class), createNiceMock(Users.class)) - .addMockedMethod("getIpAddress", String.class) - .createMock(); - expect(service.getIpAddress("host1.example.com")).andReturn("192.168.74.101").anyTimes(); - expect(service.getIpAddress("host2.example.com")).andReturn("192.168.74.102").anyTimes(); - - AmbariTProxyConfiguration tproxyConfigration = createMock(AmbariTProxyConfiguration.class); - expect(tproxyConfigration.getAllowedHosts("proxyUser")).andReturn("*").once(); - expect(tproxyConfigration.getAllowedHosts("proxyUser")).andReturn("192.168.74.101").once(); - expect(tproxyConfigration.getAllowedHosts("proxyUser")).andReturn("host1.example.com").once(); - expect(tproxyConfigration.getAllowedHosts("proxyUser")).andReturn("192.168.74.0/24").once(); - expect(tproxyConfigration.getAllowedHosts("proxyUser")).andReturn(null).once(); - expect(tproxyConfigration.getAllowedHosts("proxyUser")).andReturn("").once(); - expect(tproxyConfigration.getAllowedHosts("proxyUser")).andReturn("192.168.74.102").once(); - expect(tproxyConfigration.getAllowedHosts("proxyUser")).andReturn("host2.example.com").once(); - expect(tproxyConfigration.getAllowedHosts("proxyUser")).andReturn("192.168.74.1/32").once(); - - replayAll(); - - // ambari.tproxy.proxyuser.proxyUser.users = "*" - Assert.assertTrue(service.validateHost(tproxyConfigration, "proxyUser", "192.168.74.101")); - - // ambari.tproxy.proxyuser.proxyUser.users = "192.168.74.101" - Assert.assertTrue(service.validateHost(tproxyConfigration, "proxyUser", "192.168.74.101")); - - // ambari.tproxy.proxyuser.proxyUser.users = "host1.example.com" - Assert.assertTrue(service.validateHost(tproxyConfigration, "proxyUser", "192.168.74.101")); - - // ambari.tproxy.proxyuser.proxyUser.users = "192.168.74.0/24" - Assert.assertTrue(service.validateHost(tproxyConfigration, "proxyUser", "192.168.74.101")); - - // ambari.tproxy.proxyuser.proxyUser.users = null - Assert.assertFalse(service.validateHost(tproxyConfigration, "proxyUser", "192.168.74.101")); - - // ambari.tproxy.proxyuser.proxyUser.users = "" - Assert.assertFalse(service.validateHost(tproxyConfigration, "proxyUser", "192.168.74.101")); - - // ambari.tproxy.proxyuser.proxyUser.users = "192.168.74.102" - Assert.assertFalse(service.validateHost(tproxyConfigration, "proxyUser", "192.168.74.101")); + Configuration configuration = createNiceMock(Configuration.class); + Users users = createNiceMock(Users.class); + + // Create service with strict mock + AmbariProxiedUserDetailsService service = EasyMock.partialMockBuilder(AmbariProxiedUserDetailsService.class) + .withConstructor(configuration, users) + .addMockedMethod("getIpAddress") + .createStrictMock(); + + // Set up IP resolution expectations + service.getIpAddress(EasyMock.anyString()); + EasyMock.expectLastCall().andStubAnswer(() -> { + String hostname = (String) EasyMock.getCurrentArguments()[0]; + if ("host1.example.com".equals(hostname)) { + return "192.168.74.101"; + } else if ("host2.example.com".equals(hostname)) { + return "192.168.74.102"; + } + return null; + }); + + // Create strict mock for proxy configuration + AmbariTProxyConfiguration tproxyConfiguration = createStrictMock(AmbariTProxyConfiguration.class); + + // Define strict ordering of getAllowedHosts calls + EasyMock.expect(tproxyConfiguration.getAllowedHosts("proxyUser")).andReturn("*"); + EasyMock.expect(tproxyConfiguration.getAllowedHosts("proxyUser")).andReturn("192.168.74.101"); + EasyMock.expect(tproxyConfiguration.getAllowedHosts("proxyUser")).andReturn("host1.example.com"); + EasyMock.expect(tproxyConfiguration.getAllowedHosts("proxyUser")).andReturn("192.168.74.0/24"); + EasyMock.expect(tproxyConfiguration.getAllowedHosts("proxyUser")).andReturn(null); + EasyMock.expect(tproxyConfiguration.getAllowedHosts("proxyUser")).andReturn(""); + EasyMock.expect(tproxyConfiguration.getAllowedHosts("proxyUser")).andReturn("192.168.74.102"); + EasyMock.expect(tproxyConfiguration.getAllowedHosts("proxyUser")).andReturn("host2.example.com"); + EasyMock.expect(tproxyConfiguration.getAllowedHosts("proxyUser")).andReturn("192.168.74.1/32"); + + // Replay all mocks + EasyMock.replay(configuration, users, service, tproxyConfiguration); + + try { + // Test each case with detailed assertion messages + Assert.assertTrue("Wildcard (*) should allow access", + service.validateHost(tproxyConfiguration, "proxyUser", "192.168.74.101")); + + Assert.assertTrue("Exact IP match should allow access", + service.validateHost(tproxyConfiguration, "proxyUser", "192.168.74.101")); + + Assert.assertTrue("Hostname match should allow access", + service.validateHost(tproxyConfiguration, "proxyUser", "192.168.74.101")); + + Assert.assertTrue("Subnet match should allow access", + service.validateHost(tproxyConfiguration, "proxyUser", "192.168.74.101")); + + Assert.assertFalse("Null should deny access", + service.validateHost(tproxyConfiguration, "proxyUser", "192.168.74.101")); + + Assert.assertFalse("Empty string should deny access", + service.validateHost(tproxyConfiguration, "proxyUser", "192.168.74.101")); + + Assert.assertFalse("Non-matching IP should deny access", + service.validateHost(tproxyConfiguration, "proxyUser", "192.168.74.101")); + + Assert.assertFalse("Non-matching hostname should deny access", + service.validateHost(tproxyConfiguration, "proxyUser", "192.168.74.101")); + + Assert.assertFalse("Non-matching subnet should deny access", + service.validateHost(tproxyConfiguration, "proxyUser", "192.168.74.101")); + } finally { + // Verify all mocks + EasyMock.verify(configuration, users, service, tproxyConfiguration); + } + } - // ambari.tproxy.proxyuser.proxyUser.users = "host1.example.com" - Assert.assertFalse(service.validateHost(tproxyConfigration, "proxyUser", "192.168.74.101")); - // ambari.tproxy.proxyuser.proxyUser.users = "192.168.74.1/32" - Assert.assertFalse(service.validateHost(tproxyConfigration, "proxyUser", "192.168.74.101")); - verifyAll(); - } @Test public void testValidateUser() { diff --git a/ambari-server/src/test/java/org/apache/ambari/server/stack/upgrade/orchestrate/UpgradeHelperTest.java b/ambari-server/src/test/java/org/apache/ambari/server/stack/upgrade/orchestrate/UpgradeHelperTest.java index cfdf7607f91..19ec8ec28f8 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/stack/upgrade/orchestrate/UpgradeHelperTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/stack/upgrade/orchestrate/UpgradeHelperTest.java @@ -122,13 +122,16 @@ import org.apache.ambari.spi.upgrade.OrchestrationOptions; import org.apache.ambari.spi.upgrade.UpgradeType; import org.apache.commons.io.FileUtils; -import org.easymock.*; +import org.easymock.Capture; +import org.easymock.EasyMock; +import org.easymock.EasyMockSupport; +import org.easymock.IAnswer; +import org.easymock.IArgumentMatcher; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import org.mockito.ArgumentMatcher; import org.springframework.security.core.context.SecurityContextHolder; import com.google.common.collect.ImmutableMap; @@ -228,12 +231,21 @@ protected void configure() { SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createAdministrator("admin")); } + @After public void teardown() throws AmbariException, SQLException { + try{ H2DatabaseCleaner.clearDatabaseAndStopPersistenceService(injector); // Clear the authenticated user SecurityContextHolder.getContext().setAuthentication(null); + + if (stackManagerMock != null) { + stackManagerMock.invalidateCurrentPaths(); + } + }finally { + EasyMock.reset(m_configHelper, m_masterHostResolver); + } } @Test