Repository: ambari Updated Branches: refs/heads/branch-2.5 7ba1495e1 -> a5fdae802
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/StackUpgradeConfigurationMergeTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/StackUpgradeConfigurationMergeTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/StackUpgradeConfigurationMergeTest.java index 1bc9125..ca36e39 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/StackUpgradeConfigurationMergeTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/StackUpgradeConfigurationMergeTest.java @@ -31,6 +31,8 @@ import org.apache.ambari.server.controller.AbstractRootServiceResponseFactory; import org.apache.ambari.server.controller.AmbariManagementController; import org.apache.ambari.server.controller.KerberosHelper; import org.apache.ambari.server.controller.spi.ClusterController; +import org.apache.ambari.server.hooks.HookContextFactory; +import org.apache.ambari.server.hooks.HookService; import org.apache.ambari.server.orm.DBAccessor; import org.apache.ambari.server.orm.dao.HostRoleCommandDAO; import org.apache.ambari.server.orm.dao.RepositoryVersionDAO; @@ -291,6 +293,9 @@ public class StackUpgradeConfigurationMergeTest extends EasyMockSupport { binder.bind(Users.class).toInstance(createNiceMock(Users.class)); binder.bind(ConfigHelper.class).toInstance(createNiceMock(ConfigHelper.class)); binder.bind(RepositoryVersionDAO.class).toInstance(createNiceMock(RepositoryVersionDAO.class)); + binder.bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + binder.bind(HookService.class).toInstance(createMock(HookService.class)); + binder.requestStaticInjection(UpgradeResourceProvider.class); } http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/UserAuthorizationResourceProviderTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/UserAuthorizationResourceProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/UserAuthorizationResourceProviderTest.java index 013d42d..c93d1fb 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/UserAuthorizationResourceProviderTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/UserAuthorizationResourceProviderTest.java @@ -43,6 +43,8 @@ import org.apache.ambari.server.controller.spi.ResourceProvider; import org.apache.ambari.server.controller.spi.SystemException; import org.apache.ambari.server.controller.utilities.PredicateBuilder; import org.apache.ambari.server.controller.utilities.PropertyHelper; +import org.apache.ambari.server.hooks.HookContextFactory; +import org.apache.ambari.server.hooks.HookService; import org.apache.ambari.server.metadata.CachedRoleCommandOrderProvider; import org.apache.ambari.server.metadata.RoleCommandOrderProvider; import org.apache.ambari.server.orm.DBAccessor; @@ -413,6 +415,8 @@ public class UserAuthorizationResourceProviderTest extends EasyMockSupport { bind(ResourceTypeDAO.class).toInstance(createMock(ResourceTypeDAO.class)); bind(PermissionDAO.class).toInstance(createMock(PermissionDAO.class)); bind(HostRoleCommandDAO.class).toInstance(createMock(HostRoleCommandDAO.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); } http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/UserResourceProviderTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/UserResourceProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/UserResourceProviderTest.java index bed5be3..a90474d 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/UserResourceProviderTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/UserResourceProviderTest.java @@ -38,6 +38,8 @@ import org.apache.ambari.server.controller.spi.Resource; import org.apache.ambari.server.controller.spi.ResourceProvider; import org.apache.ambari.server.controller.utilities.PredicateBuilder; import org.apache.ambari.server.controller.utilities.PropertyHelper; +import org.apache.ambari.server.hooks.HookContextFactory; +import org.apache.ambari.server.hooks.HookService; import org.apache.ambari.server.metadata.CachedRoleCommandOrderProvider; import org.apache.ambari.server.metadata.RoleCommandOrderProvider; import org.apache.ambari.server.orm.DBAccessor; @@ -246,6 +248,8 @@ public class UserResourceProviderTest extends EasyMockSupport { bind(RoleCommandOrderProvider.class).to(CachedRoleCommandOrderProvider.class); bind(CredentialStoreService.class).to(CredentialStoreServiceImpl.class); bind(HostRoleCommandDAO.class).toInstance(createMock(HostRoleCommandDAO.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); } }); } http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/hooks/users/UserHookServiceTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/hooks/users/UserHookServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/hooks/users/UserHookServiceTest.java new file mode 100644 index 0000000..293b22a --- /dev/null +++ b/ambari-server/src/test/java/org/apache/ambari/server/hooks/users/UserHookServiceTest.java @@ -0,0 +1,224 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ambari.server.hooks.users; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.ambari.server.Role; +import org.apache.ambari.server.RoleCommand; +import org.apache.ambari.server.actionmanager.ActionManager; +import org.apache.ambari.server.actionmanager.RequestFactory; +import org.apache.ambari.server.actionmanager.Stage; +import org.apache.ambari.server.actionmanager.StageFactory; +import org.apache.ambari.server.configuration.Configuration; +import org.apache.ambari.server.events.publishers.AmbariEventPublisher; +import org.apache.ambari.server.hooks.AmbariEventFactory; +import org.apache.ambari.server.hooks.HookContext; +import org.apache.ambari.server.state.Cluster; +import org.apache.ambari.server.state.Clusters; +import org.apache.ambari.server.state.SecurityType; +import org.apache.ambari.server.state.svccomphost.ServiceComponentHostServerActionEvent; +import org.codehaus.jackson.map.ObjectMapper; +import org.easymock.Capture; +import org.easymock.EasyMock; +import org.easymock.EasyMockRule; +import org.easymock.EasyMockSupport; +import org.easymock.Mock; +import org.easymock.TestSubject; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + + +public class UserHookServiceTest extends EasyMockSupport { + + @Rule + public EasyMockRule mocks = new EasyMockRule(this); + + @Mock + private AmbariEventFactory eventFactoryMock; + + @Mock + private AmbariEventPublisher ambariEventPublisherMock; + + @Mock + private ActionManager actionManagerMock; + + @Mock + private RequestFactory requestFactoryMock; + + @Mock + private StageFactory stageFactoryMock; + + @Mock + private Configuration configurationMock; + + @Mock + private Clusters clustersMock; + + @Mock + private ObjectMapper objectMapperMock; + + @Mock + private Map<String, Cluster> clustersMap; + + @Mock + private Cluster clusterMock; + + @Mock + private Stage stageMock; + + @TestSubject + private UserHookService hookService = new UserHookService(); + + + private HookContext hookContext; + private Map<String, Set<String>> usersToGroups; + private UserCreatedEvent userCreatedEvent; + + @Before + public void before() throws Exception { + usersToGroups = new HashMap<>(); + usersToGroups.put("testUser", new HashSet<String>(Arrays.asList("hdfs", "yarn"))); + hookContext = new PostUserCreationHookContext(usersToGroups); + + userCreatedEvent = new UserCreatedEvent(hookContext); + + resetAll(); + + } + + @Test + public void shouldServiceQuitWhenFeatureIsDisabled() { + // GIVEN + EasyMock.expect(configurationMock.isUserHookEnabled()).andReturn(Boolean.FALSE); + replayAll(); + + // WHEN + Boolean triggered = hookService.execute(hookContext); + + //THEN + Assert.assertFalse("The hook must not be triggered if feature is disabled!", triggered); + + } + + + @Test + public void shouldServiceQuitWhenClusterDoesNotExist() { + // GIVEN + EasyMock.expect(configurationMock.isUserHookEnabled()).andReturn(Boolean.TRUE); + EasyMock.expect(clustersMap.isEmpty()).andReturn(Boolean.TRUE); + EasyMock.expect(clustersMock.getClusters()).andReturn(clustersMap); + + + replayAll(); + + // WHEN + Boolean triggered = hookService.execute(hookContext); + + //THEN + Assert.assertFalse("The hook must not be triggered if there's no cluster!", triggered); + + } + + + @Test + public void shouldServiceQuitWhenCalledWithEmptyContext() { + // GIVEN + EasyMock.expect(configurationMock.isUserHookEnabled()).andReturn(Boolean.TRUE); + EasyMock.expect(clustersMap.isEmpty()).andReturn(Boolean.FALSE); + EasyMock.expect(clustersMock.getClusters()).andReturn(clustersMap); + + replayAll(); + + // WHEN + Boolean triggered = hookService.execute(new PostUserCreationHookContext(Collections.<String, Set<String>>emptyMap())); + + //THEN + Assert.assertFalse("The hook should not be triggered if there is no users in the context!", triggered); + + } + + + @Test + public void shouldServiceTriggerHookWhenPrerequisitesAreSatisfied() { + // GIVEN + EasyMock.expect(configurationMock.isUserHookEnabled()).andReturn(Boolean.TRUE); + EasyMock.expect(clustersMap.isEmpty()).andReturn(Boolean.FALSE); + EasyMock.expect(clustersMock.getClusters()).andReturn(clustersMap); + + Capture<HookContext> contextCapture = EasyMock.newCapture(); + EasyMock.expect(eventFactoryMock.newUserCreatedEvent(EasyMock.capture(contextCapture))).andReturn(userCreatedEvent); + + Capture<UserCreatedEvent> userCreatedEventCapture = EasyMock.newCapture(); + ambariEventPublisherMock.publish(EasyMock.capture(userCreatedEventCapture)); + + replayAll(); + + // WHEN + Boolean triggered = hookService.execute(hookContext); + + //THEN + Assert.assertTrue("The hook must be triggered if prerequisites satisfied!", triggered); + Assert.assertEquals("The hook context the event is generated from is not as expected ", hookContext, contextCapture.getValue()); + Assert.assertEquals("The user created event is not the expected ", userCreatedEvent, userCreatedEventCapture.getValue()); + + } + + @Test + public void shouldCommandParametersBeSet() throws Exception { + // GIVEN + Map<String, Cluster> clsMap = new HashMap<>(); + clsMap.put("test-cluster", clusterMock); + + EasyMock.expect(clusterMock.getClusterId()).andReturn(1l); + EasyMock.expect(clusterMock.getClusterName()).andReturn("test-cluster"); + EasyMock.expect(clusterMock.getSecurityType()).andReturn(SecurityType.NONE).times(3); + + + EasyMock.expect(actionManagerMock.getNextRequestId()).andReturn(1l); + EasyMock.expect(clustersMock.getClusters()).andReturn(clsMap); + EasyMock.expect(configurationMock.getServerTempDir()).andReturn("/var/lib/ambari-server/tmp").times(2); + EasyMock.expect(configurationMock.getProperty(Configuration.POST_USER_CREATION_HOOK)).andReturn("/var/lib/ambari-server/resources/scripts/post-user-creation-hook.sh").anyTimes(); + EasyMock.expect(objectMapperMock.writeValueAsString(((PostUserCreationHookContext) userCreatedEvent.getContext()).getUserGroups())).andReturn("{testUser=[hdfs, yarn]}"); + stageMock.setStageId(-1); + + // TBD refine expectations to validate the logic / eg capture arguments + stageMock.addServerActionCommand(EasyMock.anyString(), EasyMock.anyString(), EasyMock.anyObject(Role.class), EasyMock.anyObject(RoleCommand.class), EasyMock.anyString(), EasyMock.anyObject(ServiceComponentHostServerActionEvent.class), + EasyMock.anyObject(Map.class), EasyMock.anyString(), EasyMock.anyObject(Map.class), EasyMock.anyInt(), EasyMock.anyBoolean(), EasyMock.anyBoolean()); + EasyMock.expect(requestFactoryMock.createNewFromStages(Arrays.asList(stageMock))).andReturn(null); + EasyMock.expect(stageFactoryMock.createNew(1, "/var/lib/ambari-server/tmp:1", "test-cluster", 1, "Post user creation hook for [ 1 ] users", "{}", "{}", "{}")).andReturn(stageMock); + + + replayAll(); + + //WHEN + hookService.onUserCreatedEvent(userCreatedEvent); + + //THEN + // TBD assertions on the captured arguments! + + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariAuthorizationFilterTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariAuthorizationFilterTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariAuthorizationFilterTest.java index 10de0a9..5031473 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariAuthorizationFilterTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariAuthorizationFilterTest.java @@ -28,6 +28,8 @@ import junit.framework.Assert; import org.apache.ambari.server.audit.AuditLogger; import org.apache.ambari.server.configuration.Configuration; +import org.apache.ambari.server.hooks.HookContextFactory; +import org.apache.ambari.server.hooks.HookService; import org.apache.ambari.server.orm.DBAccessor; import org.apache.ambari.server.orm.dao.UserDAO; import org.apache.ambari.server.security.AmbariEntryPoint; @@ -322,6 +324,8 @@ public class AmbariAuthorizationFilterTest { bind(PasswordEncoder.class).toInstance(EasyMock.createMock(PasswordEncoder.class)); bind(OsFamily.class).toInstance(EasyMock.createMock(OsFamily.class)); bind(AuditLogger.class).toInstance(EasyMock.createNiceMock(AuditLogger.class)); + bind(HookService.class).toInstance(EasyMock.createMock(HookService.class)); + bind(HookContextFactory.class).toInstance(EasyMock.createMock(HookContextFactory.class)); } }); http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java index 95b1860..7136472 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java @@ -17,13 +17,18 @@ */ package org.apache.ambari.server.security.authorization; +import java.util.Properties; + import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.persist.PersistService; +import com.google.inject.persist.jpa.AmbariJpaPersistModule; +import com.google.inject.persist.jpa.AmbariJpaPersistService; import org.apache.ambari.server.audit.AuditLoggerModule; import org.apache.ambari.server.configuration.Configuration; +import org.apache.ambari.server.controller.ControllerModule; import org.apache.ambari.server.orm.GuiceJpaInitializer; import org.apache.ambari.server.orm.dao.UserDAO; import org.apache.ambari.server.security.ClientSecurityType; @@ -71,14 +76,16 @@ public class AmbariLdapAuthenticationProviderForDNWithSpaceTest extends AmbariLd private UserDAO userDAO; @Inject private Users users; + @Inject Configuration configuration; @Before - public void setUp() { - injector = Guice.createInjector(new AuditLoggerModule(), new AuthorizationTestModuleForLdapDNWithSpace()); - injector.injectMembers(this); + public void setUp() throws Exception { + injector = Guice.createInjector(new ControllerModule(getTestProperties()), new AuditLoggerModule()); injector.getInstance(GuiceJpaInitializer.class); + injector.injectMembers(this); + configuration.setClientSecurityType(ClientSecurityType.LDAP); configuration.setProperty(Configuration.LDAP_PRIMARY_URL, "localhost:" + getLdapServer().getPort()); } @@ -112,4 +119,19 @@ public class AmbariLdapAuthenticationProviderForDNWithSpaceTest extends AmbariLd Authentication auth = authenticationProvider.authenticate(authentication); assertTrue(auth == null); } + + + protected Properties getTestProperties() { + Properties properties = new Properties(); + properties.setProperty(Configuration.CLIENT_SECURITY.getKey(), "ldap"); + properties.setProperty(Configuration.SERVER_PERSISTENCE_TYPE.getKey(), "in-memory"); + properties.setProperty(Configuration.METADATA_DIR_PATH.getKey(), "src/test/resources/stacks"); + properties.setProperty(Configuration.SERVER_VERSION_FILE.getKey(), "src/test/resources/version"); + properties.setProperty(Configuration.OS_VERSION.getKey(), "centos5"); + properties.setProperty(Configuration.SHARED_RESOURCES_DIR.getKey(), "src/test/resources/"); + //make ambari detect active configuration + properties.setProperty(Configuration.LDAP_BASE_DN.getKey(), "dc=ambari,dc=the apache,dc=org"); + properties.setProperty(Configuration.LDAP_GROUP_BASE.getKey(), "ou=the groups,dc=ambari,dc=the apache,dc=org"); + return properties; + } } http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/UsersTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/UsersTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/UsersTest.java index f059abc..6ba384c 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/UsersTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/UsersTest.java @@ -21,7 +21,12 @@ package org.apache.ambari.server.security.authorization; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; + import junit.framework.Assert; + +import org.apache.ambari.server.hooks.HookContextFactory; +import org.apache.ambari.server.hooks.HookService; +import org.apache.ambari.server.hooks.users.UserHookService; import org.apache.ambari.server.orm.DBAccessor; import org.apache.ambari.server.orm.dao.MemberDAO; import org.apache.ambari.server.orm.dao.PrivilegeDAO; @@ -51,6 +56,8 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.newCapture; public class UsersTest extends EasyMockSupport { + + @Test public void testGetUserAuthorities() throws Exception { Injector injector = getInjector(); @@ -106,6 +113,7 @@ public class UsersTest extends EasyMockSupport { expect(privilegeDAO.findAllByPrincipal(capture(principalEntitiesCapture))).andReturn(privilegeEntities).times(1); expect(privilegeDAO.findAllByPrincipal(capture(rolePrincipalEntitiesCapture))).andReturn(rolePrivilegeEntities).times(1); + replayAll(); Users user = injector.getInstance(Users.class); @@ -139,6 +147,8 @@ public class UsersTest extends EasyMockSupport { bind(MemberDAO.class).toInstance(createMock(MemberDAO.class)); bind(PrivilegeDAO.class).toInstance(createMock(PrivilegeDAO.class)); bind(PasswordEncoder.class).toInstance(createMock(PasswordEncoder.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); } }); } http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/serveraction/users/PostUserCreationHookServerActionTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/serveraction/users/PostUserCreationHookServerActionTest.java b/ambari-server/src/test/java/org/apache/ambari/server/serveraction/users/PostUserCreationHookServerActionTest.java new file mode 100644 index 0000000..f5cdf48 --- /dev/null +++ b/ambari-server/src/test/java/org/apache/ambari/server/serveraction/users/PostUserCreationHookServerActionTest.java @@ -0,0 +1,182 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ambari.server.serveraction.users; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentMap; + +import org.apache.ambari.server.AmbariException; +import org.apache.ambari.server.Role; +import org.apache.ambari.server.RoleCommand; +import org.apache.ambari.server.actionmanager.HostRoleCommand; +import org.apache.ambari.server.agent.CommandReport; +import org.apache.ambari.server.agent.ExecutionCommand; +import org.apache.ambari.server.hooks.users.UserHookParams; +import org.apache.ambari.server.state.SecurityType; +import org.apache.ambari.server.utils.ShellCommandUtil; +import org.codehaus.jackson.map.ObjectMapper; +import org.easymock.Capture; +import org.easymock.EasyMock; +import org.easymock.EasyMockRule; +import org.easymock.EasyMockSupport; +import org.easymock.Mock; +import org.easymock.TestSubject; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.collect.Maps; + +/** + * Test suite for the PostUserCreationHookServer action class. + */ +public class PostUserCreationHookServerActionTest extends EasyMockSupport { + + private static final Logger LOGGER = LoggerFactory.getLogger(PostUserCreationHookServerActionTest.class); + + @Rule + public EasyMockRule mocks = new EasyMockRule(this); + + @Mock + private ShellCommandUtilityWrapper shellCommandUtilityWrapper; + + @Mock + private ExecutionCommand executionCommand; + + @Mock + private HostRoleCommand hostRoleCommand; + + @Mock + private ObjectMapper objectMapperMock; + + @Mock + private CollectionPersisterServiceFactory collectionPersisterServiceFactoryMock; + + @Mock + private CsvFilePersisterService collectionPersisterService; + + @TestSubject + private PostUserCreationHookServerAction customScriptServerAction = new PostUserCreationHookServerAction(); + + private ConcurrentMap<String, Object> requestSharedDataContext = Maps.newConcurrentMap(); + + private Capture<String[]> commandCapture = null; + + private Map<String, List<String>> payload = new HashMap<>(); + + private ObjectMapper om = new ObjectMapper(); + + @Before + public void before() throws IOException, InterruptedException { + payload.clear(); + resetAll(); + + EasyMock.expect(hostRoleCommand.getRequestId()).andReturn(-1l).times(2); + EasyMock.expect(hostRoleCommand.getStageId()).andReturn(-1l).times(2); + } + + + @Test + public void shouldCommandStringBeAssembledCorrectlyForSingleUser() throws Exception { + // GIVEN + + payload = mockPayload(1); + mockExecutionCommand(payload.size()); + String payloadJson = om.writeValueAsString(payload); + + // command params as passed to the serveraction implementation + Map<String, String> commandParams = new HashMap<>(); + commandParams.put(UserHookParams.PAYLOAD.param(), payloadJson); + commandParams.put(UserHookParams.SCRIPT.param(), "/hookfolder/hook.name"); + commandParams.put(UserHookParams.CMD_TIME_FRAME.param(), "1000"); + commandParams.put(UserHookParams.CMD_INPUT_FILE.param(), "/test/user_data.csv"); + commandParams.put(UserHookParams.CLUSTER_SECURITY_TYPE.param(), SecurityType.KERBEROS.name()); + + EasyMock.expect(executionCommand.getCommandParams()).andReturn(commandParams); + EasyMock.expect(objectMapperMock.readValue(payloadJson, Map.class)).andReturn(payload); + + // captures the command arguments passed to the shell callable through the factory + commandCapture = EasyMock.newCapture(); + + // the callable mock returns a dummy result, no assertions made on the result + EasyMock.expect(shellCommandUtilityWrapper.runCommand(EasyMock.capture(commandCapture))).andReturn(new ShellCommandUtil.Result(0, null, null)).times(payload.size()); + + customScriptServerAction.setExecutionCommand(executionCommand); + + EasyMock.expect(collectionPersisterServiceFactoryMock.createCsvFilePersisterService(EasyMock.anyString())).andReturn(collectionPersisterService); + EasyMock.expect(collectionPersisterService.persistMap(EasyMock.anyObject(Map.class))).andReturn(Boolean.TRUE); + + replayAll(); + + // WHEN + CommandReport commandReport = customScriptServerAction.execute(requestSharedDataContext); + + // THEN + String[] commandArray = commandCapture.getValue(); + Assert.assertNotNull("The command to be executed must not be null!", commandArray); + + Assert.assertEquals("The command argument array length is not as expected!", 5, commandArray.length); + Assert.assertEquals("The command script is not as expected", "/hookfolder/hook.name", commandArray[0]); + } + + + @Test(expected = AmbariException.class) + public void shouldServerActionFailWhenCommandParametersAreMissing() throws Exception { + //GIVEN + Map<String, String> commandParams = new HashMap<>(); + // the execution command lacks the required command parameters (commandparams is an empty list) + EasyMock.expect(executionCommand.getCommandParams()).andReturn(commandParams).times(2); + + customScriptServerAction.setExecutionCommand(executionCommand); + replayAll(); + + // WHEN + CommandReport commandReport = customScriptServerAction.execute(requestSharedDataContext); + + //THEN + //exception is thrown + } + + private void mockExecutionCommand(int callCnt) { + EasyMock.expect(executionCommand.getRoleCommand()).andReturn(RoleCommand.EXECUTE).times(callCnt); + EasyMock.expect(executionCommand.getClusterName()).andReturn("unit-test-cluster").times(callCnt); + EasyMock.expect(executionCommand.getConfigurationTags()).andReturn(Collections.<String, Map<String, String>>emptyMap()).times(callCnt); + EasyMock.expect(executionCommand.getRole()).andReturn(Role.AMBARI_SERVER_ACTION.toString()).times(callCnt); + EasyMock.expect(executionCommand.getServiceName()).andReturn("custom-hook-script").times(callCnt); + EasyMock.expect(executionCommand.getTaskId()).andReturn(-1l).times(callCnt); + } + + private Map<String, List<String>> mockPayload(int size) { + Map<String, List<String>> ret = new HashMap<>(); + for (int i = 0; i < size; i++) { + ret.put("user-" + i, Arrays.asList("hdfs" + i, "yarn" + i)); + } + return ret; + } + + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/state/cluster/ClusterEffectiveVersionTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/state/cluster/ClusterEffectiveVersionTest.java b/ambari-server/src/test/java/org/apache/ambari/server/state/cluster/ClusterEffectiveVersionTest.java index 99bd312..8ba891a 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/state/cluster/ClusterEffectiveVersionTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/state/cluster/ClusterEffectiveVersionTest.java @@ -32,6 +32,8 @@ import org.apache.ambari.server.controller.AmbariManagementController; import org.apache.ambari.server.controller.KerberosHelper; import org.apache.ambari.server.controller.spi.ClusterController; import org.apache.ambari.server.events.publishers.AmbariEventPublisher; +import org.apache.ambari.server.hooks.HookContextFactory; +import org.apache.ambari.server.hooks.HookService; import org.apache.ambari.server.orm.DBAccessor; import org.apache.ambari.server.orm.dao.ClusterDAO; import org.apache.ambari.server.orm.dao.HostRoleCommandDAO; @@ -270,7 +272,8 @@ public class ClusterEffectiveVersionTest extends EasyMockSupport { binder.bind(KerberosHelper.class).toInstance(EasyMock.createNiceMock(KerberosHelper.class)); binder.bind(Users.class).toInstance(EasyMock.createNiceMock(Users.class)); binder.bind(AmbariEventPublisher.class).toInstance(createNiceMock(AmbariEventPublisher.class)); - + binder.bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + binder.bind(HookService.class).toInstance(createMock(HookService.class)); binder.install(new FactoryModuleBuilder().implement( Cluster.class, ClusterImpl.class).build(ClusterFactory.class)); http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/topology/AsyncCallableServiceTest.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/topology/AsyncCallableServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/topology/AsyncCallableServiceTest.java index 00d6fe4..7e79934 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/topology/AsyncCallableServiceTest.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/topology/AsyncCallableServiceTest.java @@ -19,6 +19,7 @@ package org.apache.ambari.server.topology; import org.easymock.EasyMockRule; +import org.easymock.EasyMockSupport; import org.easymock.Mock; import org.easymock.MockType; import org.junit.Assert; @@ -29,14 +30,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -public class AsyncCallableServiceTest { +public class AsyncCallableServiceTest extends EasyMockSupport { public static final Logger LOGGER = LoggerFactory.getLogger(AsyncCallableService.class); @Rule @@ -45,7 +49,11 @@ public class AsyncCallableServiceTest { @Mock(type = MockType.STRICT) private Callable<Boolean> taskMock; - private ExecutorService singleThreadedExecutor = Executors.newSingleThreadExecutor(); + @Mock + private ScheduledExecutorService executorServiceMock; + + @Mock + private ScheduledFuture<Boolean> futureMock; private long timeout; @@ -66,18 +74,30 @@ public class AsyncCallableServiceTest { @Test public void testCallableServiceShouldCancelTaskWhenTimeoutExceeded() throws Exception { // GIVEN + + //the timeout period should be small!!! + timeout = 1l; + // the task to be executed never completes successfully - expect(taskMock.call()).andThrow(new IllegalStateException("Prerequisites are not yet satisfied!")).anyTimes(); - replay(taskMock); - asyncCallableService = new AsyncCallableService(taskMock, timeout, delay, Executors.newScheduledThreadPool(1)); + expect(futureMock.get(timeout, TimeUnit.MILLISECONDS)).andThrow(new TimeoutException("Testing the timeout exceeded case")); + expect(futureMock.isDone()).andReturn(Boolean.FALSE); + + // this is only called when a timeout occurs + expect(futureMock.cancel(true)).andReturn(Boolean.TRUE); + + expect(executorServiceMock.submit(taskMock)).andReturn(futureMock); + + replayAll(); + + asyncCallableService = new AsyncCallableService(taskMock, timeout, delay, executorServiceMock); // WHEN Boolean serviceResult = asyncCallableService.call(); // THEN verify(); - Assert.assertNotNull("Service result must not be null", serviceResult); - Assert.assertFalse("The expected boolean result is 'false'!", serviceResult); + Assert.assertNull("Service result must be null", serviceResult); + Assert.assertFalse("The service should have errors!", asyncCallableService.getErrors().isEmpty()); } @Test @@ -98,8 +118,8 @@ public class AsyncCallableServiceTest { Boolean serviceResult = asyncCallableService.call(); // THEN - Assert.assertNotNull("Service result must not be null", serviceResult); - Assert.assertFalse("The expected boolean result is 'false'!", serviceResult); + Assert.assertNull("Service result must be null", serviceResult); + Assert.assertFalse("The service should have errors!", asyncCallableService.getErrors().isEmpty()); } @Test @@ -107,7 +127,8 @@ public class AsyncCallableServiceTest { // GIVEN // the task to be executed never completes successfully expect(taskMock.call()).andReturn(Boolean.TRUE).times(1); - replay(taskMock); + + replayAll(); asyncCallableService = new AsyncCallableService(taskMock, timeout, delay, Executors.newScheduledThreadPool(2)); // WHEN @@ -124,9 +145,8 @@ public class AsyncCallableServiceTest { // GIVEN // the task to be throws exception - expect(taskMock.call()).andThrow(new IllegalStateException("****************** TESTING ****************")).times - (2,3); - replay(taskMock); + expect(taskMock.call()).andThrow(new IllegalStateException("****************** TESTING ****************")).times(2, 3); + replayAll(); asyncCallableService = new AsyncCallableService(taskMock, timeout, delay, Executors.newScheduledThreadPool(2)); // WHEN @@ -135,8 +155,7 @@ public class AsyncCallableServiceTest { // THEN verify(); // THEN - Assert.assertNotNull("Service result must not be null", serviceResult); - Assert.assertFalse("The expected boolean result is 'false'!", serviceResult); + Assert.assertNull("Service result must be null", serviceResult); } @@ -158,9 +177,7 @@ public class AsyncCallableServiceTest { Boolean serviceResult = asyncCallableService.call(); // THEN - Assert.assertNotNull("Service result must not be null", serviceResult); - Assert.assertFalse("The expected boolean result is 'false'!", serviceResult); - - + verify(); + Assert.assertNull("Service result must be null", serviceResult); } } \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ambari/blob/a5fdae80/ambari-server/src/test/java/org/apache/ambari/server/upgrade/UpgradeCatalog240Test.java ---------------------------------------------------------------------- diff --git a/ambari-server/src/test/java/org/apache/ambari/server/upgrade/UpgradeCatalog240Test.java b/ambari-server/src/test/java/org/apache/ambari/server/upgrade/UpgradeCatalog240Test.java index cf2d87d..5e46133 100644 --- a/ambari-server/src/test/java/org/apache/ambari/server/upgrade/UpgradeCatalog240Test.java +++ b/ambari-server/src/test/java/org/apache/ambari/server/upgrade/UpgradeCatalog240Test.java @@ -67,6 +67,8 @@ import org.apache.ambari.server.controller.AmbariManagementController; import org.apache.ambari.server.controller.AmbariManagementControllerImpl; import org.apache.ambari.server.controller.KerberosHelper; import org.apache.ambari.server.controller.MaintenanceStateHelper; +import org.apache.ambari.server.hooks.HookContextFactory; +import org.apache.ambari.server.hooks.HookService; import org.apache.ambari.server.orm.DBAccessor; import org.apache.ambari.server.orm.GuiceJpaInitializer; import org.apache.ambari.server.orm.InMemoryDefaultTestModule; @@ -338,6 +340,8 @@ public class UpgradeCatalog240Test { binder.bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class)); binder.bind(EntityManager.class).toInstance(entityManager); binder.bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + binder.bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + binder.bind(HookService.class).toInstance(createMock(HookService.class)); } }; @@ -736,6 +740,8 @@ public class UpgradeCatalog240Test { binder.bind(DBAccessor.class).toInstance(createNiceMock(DBAccessor.class)); binder.bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class)); binder.bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + binder.bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + binder.bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -818,6 +824,8 @@ public class UpgradeCatalog240Test { binder.bind(DBAccessor.class).toInstance(createNiceMock(DBAccessor.class)); binder.bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class)); binder.bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + binder.bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + binder.bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -885,6 +893,9 @@ public class UpgradeCatalog240Test { binder.bind(DBAccessor.class).toInstance(createNiceMock(DBAccessor.class)); binder.bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class)); binder.bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + binder.bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + binder.bind(HookService.class).toInstance(createMock(HookService.class)); + } }); @@ -1526,6 +1537,8 @@ public class UpgradeCatalog240Test { bind(OsFamily.class).toInstance(osFamily); bind(EntityManager.class).toInstance(entityManager); bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -1662,6 +1675,8 @@ public class UpgradeCatalog240Test { bind(OsFamily.class).toInstance(osFamily); bind(EntityManager.class).toInstance(entityManager); bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -1720,6 +1735,8 @@ public class UpgradeCatalog240Test { bind(DBAccessor.class).toInstance(createNiceMock(DBAccessor.class)); bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class)); bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -1780,6 +1797,8 @@ public class UpgradeCatalog240Test { bind(DBAccessor.class).toInstance(createNiceMock(DBAccessor.class)); bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class)); bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -1982,6 +2001,8 @@ public class UpgradeCatalog240Test { bind(DBAccessor.class).toInstance(ems.createNiceMock(DBAccessor.class)); bind(OsFamily.class).toInstance(ems.createNiceMock(OsFamily.class)); bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -2040,6 +2061,8 @@ public class UpgradeCatalog240Test { bind(StackManagerFactory.class).toInstance(createNiceMock(StackManagerFactory.class)); bind(AmbariMetaInfo.class).toInstance(metaInfo); bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); expect(controller.getClusters()).andReturn(clusters).anyTimes(); @@ -2097,6 +2120,8 @@ public class UpgradeCatalog240Test { bind(RemoteAmbariClusterDAO.class).toInstance(clusterDAO); bind(ViewInstanceDAO.class).toInstance(instanceDAO); bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -2248,6 +2273,8 @@ public class UpgradeCatalog240Test { bind(DBAccessor.class).toInstance(createNiceMock(DBAccessor.class)); bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class)); bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -2375,6 +2402,8 @@ public class UpgradeCatalog240Test { bind(EntityManager.class).toInstance(entityManager); bind(DBAccessor.class).toInstance(createNiceMock(DBAccessor.class)); bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class)); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -2499,6 +2528,8 @@ public class UpgradeCatalog240Test { bind(DBAccessor.class).toInstance(createMock(DBAccessor.class)); bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class)); bind(EntityManager.class).toInstance(entityManager); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } }); @@ -2535,6 +2566,8 @@ public class UpgradeCatalog240Test { bind(DBAccessor.class).toInstance(createMock(DBAccessor.class)); bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class)); bind(EntityManager.class).toInstance(entityManager); + bind(HookContextFactory.class).toInstance(createMock(HookContextFactory.class)); + bind(HookService.class).toInstance(createMock(HookService.class)); } });