Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

18 improve mocking of usermanager #24

Merged
merged 3 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

import javax.jcr.RepositoryException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.UUID;

import static de.ibmix.magkit.test.cms.context.ContextMockUtils.mockWebContext;
Expand All @@ -46,7 +47,7 @@
import static org.mockito.Mockito.when;

/**
* An util class to create Mockito mocks of magnolia security classes.
* A util class to create Mockito mocks of magnolia security classes.
*
* @author [email protected]
* @since 2013-04-30
Expand Down Expand Up @@ -80,13 +81,17 @@ public static AccessManager mockAccessManager(String repositoryId, AccessManager
return am;
}

public static UserManager mockUserManager(String realm) {
public static UserManager mockUserManager(String realm, UserManagerStubbingOperation... stubbings) {
assertThat(realm, notNullValue());
SecuritySupport security = mockSecuritySupport();
UserManager userManager = security.getUserManager(realm);
if (userManager == null) {
userManager = mock(UserManager.class);
when(userManager.getAllUsers()).thenReturn(new HashSet<>());
when(security.getUserManager(realm)).thenReturn(userManager);
}
UserManager finalManager = userManager;
Arrays.stream(stubbings).forEach(stubbing -> stubbing.of(finalManager));
return userManager;
}

Expand Down Expand Up @@ -115,37 +120,20 @@ public static RoleManager mockRoleManager(RoleManagerStubbingOperation... stubbi
return finalManager;
}

public static void register(String realm, User user) {
UserManager userManager = mockUserManager(realm);
when(userManager.getUser(user.getName())).thenReturn(user);
when(userManager.getUserById(user.getIdentifier())).thenReturn(user);
}

public static void register(Group group) throws AccessDeniedException {
GroupManager manager = mockGroupManager();
when(manager.getGroup(group.getName())).thenReturn(group);
}

public static void register(Role role) {
mockRoleManager(RoleManagerStubbingOperation.stubRole(role));
}

public static User mockUser(final String name, UserStubbingOperation... stubbings) {
return mockUser(WEBSITE, name, UUID.randomUUID().toString(), stubbings);
}

public static User mockUser(final String realm, final String name, final String uuid, UserStubbingOperation... stubbings) {
assertThat(stubbings, notNullValue());
User user = mockUserManager(realm).getUser(name);
UserManager userManager = mockUserManager(realm);
User user = userManager.getUser(name);
if (user == null) {
user = mock(User.class);
UserStubbingOperation.stubName(name).of(user);
UserStubbingOperation.stubIdentifier(uuid).of(user);
register(realm, user);
UserManagerStubbingOperation.stubUser(name, uuid).of(userManager);
}
User finalUser = user;
User finalUser = userManager.getUser(name);
Arrays.stream(stubbings).forEach(stubbing -> stubbing.of(finalUser));
return user;
return finalUser;
}

public static Group mockGroup(final String name, GroupStubbingOperation... stubbings) throws AccessDeniedException {
Expand All @@ -154,12 +142,13 @@ public static Group mockGroup(final String name, GroupStubbingOperation... stubb

public static Group mockGroup(final String name, final String uuid, GroupStubbingOperation... stubbings) throws AccessDeniedException {
assertThat(stubbings, notNullValue());
Group group = mockGroupManager().getGroup(name);
GroupManager manager = mockGroupManager();
Group group = manager.getGroup(name);
if (group == null) {
group = mock(Group.class);
GroupStubbingOperation.stubName(name).of(group);
GroupStubbingOperation.stubId(uuid).of(group);
register(group);
GroupManagerStubbingOperation.stubGroup(group).of(manager);
}
Group finalGroup = group;
Arrays.stream(stubbings).forEach(stubbing -> stubbing.of(finalGroup));
Expand All @@ -171,12 +160,13 @@ public static Role mockRole(final String name) {
}

public static Role mockRole(final String name, final String uuid) {
Role role = mockRoleManager().getRole(name);
RoleManager roleManager = mockRoleManager();
Role role = roleManager.getRole(name);
if (role == null) {
role = mock(Role.class);
RoleStubbingOperation.stubName(name).of(role);
RoleStubbingOperation.stubId(uuid).of(role);
register(role);
RoleManagerStubbingOperation.stubRole(role).of(roleManager);
}
return role;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
package de.ibmix.magkit.test.cms.security;

/*-
* #%L
* magkit-test-cms Magnolia Module
* %%
* Copyright (C) 2023 IBM iX
* %%
* Licensed 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.
* #L%
*/

import de.ibmix.magkit.test.StubbingOperation;
import info.magnolia.cms.security.User;
import info.magnolia.cms.security.UserManager;
import org.mockito.Mockito;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.UUID;

import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.mockito.Mockito.when;

/**
* Utility class that provides factory methods for UserManagerStubbingOperation.
* Stubbing operations to be used as parameters in SecurityMockUtils.mockUserManager(...).
*
* @author [email protected]
* @since 2024-08-15
*/
public abstract class UserManagerStubbingOperation implements StubbingOperation<UserManager> {

/**
* Creates a stubbing operation, that creates a User mock with the given name and uuid, registers it at a UserManager mock and add it to the list of all Users of a UserManager.
*
* @param name the name of the new user, not null
* @param uuid the identifier of the new user, a random UUID is used if null or an empty String is passed
* @param stubbings optional UserStubbingOperations to modify the new User mock
* @return a UserManagerStubbingOperation for adding a User to a UserManager
*/
public static UserManagerStubbingOperation stubUser(final String name, final String uuid, UserStubbingOperation... stubbings) {
return new UserManagerStubbingOperation() {
@Override
public void of(UserManager mock) {
assertThat(mock, notNullValue());
assertThat(name, notNullValue());
User user = mock.getUser(name);
if (user == null) {
user = Mockito.mock(User.class);
UserStubbingOperation.stubName(name).of(user);
UserStubbingOperation.stubIdentifier(uuid).of(user);
stubUser(user).of(mock);
}
User finalUser = user;
Arrays.stream(stubbings).forEach(stubbing -> stubbing.of(finalUser));
}
};
}

/**
* Creates a stubbing operation, that registers the User at a UserManager mock and add it to the list of all Users of a UserManager.
*
* @param user the User mock to be added to a UserManager mock
* @return a UserManagerStubbingOperation for adding a User to a UserManager
*/
public static UserManagerStubbingOperation stubUser(final User user) {
return new UserManagerStubbingOperation() {
@Override
public void of(UserManager mock) {
assertThat(mock, notNullValue());
assertThat(user, notNullValue());
Collection<User> allUsers = mock.getAllUsers();
String userName = user.getName();
if (isNotEmpty(userName)) {
when(mock.getUser(userName)).thenReturn(user);
}
String uuid = user.getIdentifier();
if (isNotEmpty(uuid)) {
User existing = mock.getUserById(uuid);
if (existing != null) {
allUsers.remove(existing);
}
when(mock.getUserById(uuid)).thenReturn(user);
}
allUsers.add(user);
}
};
}

/**
* Creates a stubbing operation, that creates a system User mock with name "superuser", a random uuid and password "superuser",
* registers it at a UserManager mock and add it to the list of all Users of a UserManager.
* Existing system user will be replaced.
*
* @param stubbings optional UserStubbingOperations to modify the new User mock
* @return a UserManagerStubbingOperation for adding a system User to a UserManager
*/
public static UserManagerStubbingOperation stubSystemUser(UserStubbingOperation... stubbings) {
return new UserManagerStubbingOperation() {
@Override
public void of(UserManager mock) {
assertThat(mock, notNullValue());
User systemUser = mock.getSystemUser();
if (systemUser == null) {
String identifier = UUID.randomUUID().toString();
stubUser(UserManager.SYSTEM_USER, identifier, UserStubbingOperation.stubPassword(UserManager.SYSTEM_USER)).of(mock);
systemUser = mock.getUserById(identifier);
when(mock.getSystemUser()).thenReturn(systemUser);
}
User finalUser = systemUser;
Arrays.stream(stubbings).forEach(stubbing -> stubbing.of(finalUser));
}
};
}

/**
* Creates a stubbing operation, that creates an anonymous User mock with name "anonymous", and random uuid,
* registers it at a UserManager mock and adds it to the list of all Users of a UserManager.
* Existing anonymous user will be replaced.
*
* @param stubbings optional UserStubbingOperations to modify the new User mock
* @return a UserManagerStubbingOperation for adding a system User to a UserManager
*/
public static UserManagerStubbingOperation stubAnonymousUser(UserStubbingOperation... stubbings) {
return new UserManagerStubbingOperation() {
@Override
public void of(UserManager mock) {
assertThat(mock, notNullValue());
User anonymous = mock.getAnonymousUser();
if (anonymous == null) {
String identifier = UUID.randomUUID().toString();
stubUser(UserManager.ANONYMOUS_USER, identifier).of(mock);
anonymous = mock.getUserById(identifier);
when(mock.getAnonymousUser()).thenReturn(anonymous);
}
User finalUser = anonymous;
Arrays.stream(stubbings).forEach(stubbing -> stubbing.of(finalUser));
}
};
}

/**
* Creates a stubbing operation, that replaces all existing Users of a UserManager by the new List of User mocks.
*
* @param allUsers the new Collection of User mocks to be registered at a UserManager
* @return a UserManagerStubbingOperation for adding new Users to a UserManager
*/
public static UserManagerStubbingOperation stubAllUsers(final Collection<User> allUsers) {
return new UserManagerStubbingOperation() {
@Override
public void of(UserManager mock) {
assertThat(mock, notNullValue());
// remove stubbings for existing users (ignore anonymous & system user):
for (User old : mock.getAllUsers()) {
when(mock.getUserById(old.getIdentifier())).thenReturn(null);
when(mock.getUser(old.getName())).thenReturn(null);
}
// assert that we always use a Set internally (no dublettes - well almost :-) )
Collection<User> newUsers = new HashSet<>();
if (allUsers != null) {
newUsers.addAll(allUsers);
}
for (User newUser : newUsers) {
when(mock.getUserById(newUser.getIdentifier())).thenReturn(newUser);
when(mock.getUser(newUser.getName())).thenReturn(newUser);
}
when(mock.getAllUsers()).thenReturn(newUsers);
}
};
}

/**
* Creates a stubbing operation, that stubs the lock-time period of a UserManager.
*
* @param lockTimePeriod the new Value for the lock-time as int
* @return a UserManagerStubbingOperation for stubbing the lock-time period to a UserManager
*/
public static UserManagerStubbingOperation stubLockTimePeriod(int lockTimePeriod) {
return new UserManagerStubbingOperation() {
@Override
public void of(UserManager mock) {
assertThat(mock, notNullValue());
when(mock.getLockTimePeriod()).thenReturn(lockTimePeriod);
}
};
}

/**
* Creates a stubbing operation, that stubs the max number of failed login attempts of a UserManager.
*
* @param maxFailedLoginAttempts the new limit of failed login attempts as int
* @return a UserManagerStubbingOperation for stubbing the max number of failed login attempts of a UserManager
*/
public static UserManagerStubbingOperation stubMaxFailedLoginAttempts(int maxFailedLoginAttempts) {
return new UserManagerStubbingOperation() {
@Override
public void of(UserManager mock) {
assertThat(mock, notNullValue());
when(mock.getMaxFailedLoginAttempts()).thenReturn(maxFailedLoginAttempts);
}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;

import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.doReturn;
Expand Down Expand Up @@ -55,7 +57,8 @@ public static UserStubbingOperation stubIdentifier(final String uuid) {
@Override
public void of(User user) {
assertThat(user, notNullValue());
doReturn(uuid).when(user).getIdentifier();
String identifier = isNotBlank(uuid) ? uuid : UUID.randomUUID().toString();
doReturn(identifier).when(user).getIdentifier();
}
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
import static de.ibmix.magkit.test.cms.security.SecurityMockUtils.mockSecuritySupport;
import static de.ibmix.magkit.test.cms.security.SecurityMockUtils.mockUser;
import static de.ibmix.magkit.test.cms.security.SecurityMockUtils.mockUserManager;
import static de.ibmix.magkit.test.cms.security.SecurityMockUtils.register;
import static info.magnolia.repository.RepositoryConstants.WEBSITE;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
Expand All @@ -52,7 +51,6 @@
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
* Testing SecurityMockUtils.
Expand Down Expand Up @@ -106,25 +104,16 @@ public void testMockUserManager() {

UserManager manager = mockUserManager("test");
assertThat(manager, notNullValue());
assertThat(manager.getAllUsers(), notNullValue());
assertThat(manager.getAllUsers().size(), is(0));
assertThat(manager.getAnonymousUser(), nullValue());
assertThat(manager.getSystemUser(), nullValue());

support = getComponentSingleton(SecuritySupport.class);
assertThat(support, notNullValue());

assertThat(support.getUserManager("test"), is(manager));
}

@Test
public void testRegister() {
UserManager manager = mockUserManager("test");
User fritz = mock(User.class);
when(fritz.getName()).thenReturn("Fritz");

assertThat(manager.getUser("Fritz"), nullValue());

register("test", fritz);
assertThat(manager.getUser("Fritz"), is(fritz));
}

@Test
public void testMockUser() {
UserStubbingOperation op = mock(UserStubbingOperation.class);
Expand Down
Loading
Loading