Merge with 2.0.0-m3

This commit is contained in:
René Pfeuffer
2018-10-17 13:58:53 +02:00
42 changed files with 424 additions and 218 deletions

View File

@@ -5,6 +5,7 @@ import org.jboss.resteasy.mock.MockDispatcherFactory;
import sonia.scm.api.rest.AlreadyExistsExceptionMapper;
import sonia.scm.api.rest.AuthorizationExceptionMapper;
import sonia.scm.api.rest.ConcurrentModificationExceptionMapper;
import sonia.scm.api.rest.IllegalArgumentExceptionMapper;
public class DispatcherMock {
public static Dispatcher createDispatcher(Object resource) {
@@ -17,6 +18,7 @@ public class DispatcherMock {
dispatcher.getProviderFactory().registerProvider(InternalRepositoryExceptionMapper.class);
dispatcher.getProviderFactory().registerProvider(ChangePasswordNotAllowedExceptionMapper.class);
dispatcher.getProviderFactory().registerProvider(InvalidPasswordExceptionMapper.class);
dispatcher.getProviderFactory().registerProvider(IllegalArgumentExceptionMapper.class);
return dispatcher;
}
}

View File

@@ -13,10 +13,12 @@ import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import sonia.scm.user.InvalidPasswordException;
import sonia.scm.user.User;
import sonia.scm.user.UserManager;
import sonia.scm.web.VndMediaType;
import javax.lang.model.util.Types;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;
@@ -26,6 +28,7 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
@@ -69,7 +72,6 @@ public class MeResourceTest {
doNothing().when(userManager).modify(userCaptor.capture());
doNothing().when(userManager).delete(userCaptor.capture());
when(userManager.isTypeDefault(userCaptor.capture())).thenCallRealMethod();
when(userManager.getUserTypeChecker()).thenCallRealMethod();
when(userManager.getDefaultType()).thenReturn("xml");
MeResource meResource = new MeResource(userToDtoMapper, userManager, passwordService);
when(uriInfo.getApiRestUri()).thenReturn(URI.create("/"));
@@ -97,38 +99,40 @@ public class MeResourceTest {
public void shouldEncryptPasswordBeforeChanging() throws Exception {
String newPassword = "pwd123";
String encryptedNewPassword = "encrypted123";
String oldPassword = "notEncriptedSecret";
String encryptedOldPassword = "encryptedOld";
String oldPassword = "secret";
String content = String.format("{ \"oldPassword\": \"%s\" , \"newPassword\": \"%s\" }", oldPassword, newPassword);
MockHttpRequest request = MockHttpRequest
.put("/" + MeResource.ME_PATH_V2 + "password")
.contentType(VndMediaType.PASSWORD_CHANGE)
.content(content.getBytes());
MockHttpResponse response = new MockHttpResponse();
when(passwordService.encryptPassword(eq(newPassword))).thenReturn(encryptedNewPassword);
when(passwordService.encryptPassword(eq(oldPassword))).thenReturn("secret");
when(passwordService.encryptPassword(newPassword)).thenReturn(encryptedNewPassword);
when(passwordService.encryptPassword(oldPassword)).thenReturn(encryptedOldPassword);
ArgumentCaptor<String> encryptedOldPasswordCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> encryptedNewPasswordCaptor = ArgumentCaptor.forClass(String.class);
doNothing().when(userManager).changePasswordForLoggedInUser(encryptedOldPasswordCaptor.capture(), encryptedNewPasswordCaptor.capture());
dispatcher.invoke(request, response);
assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
verify(userManager).modify(any(User.class));
User updatedUser = userCaptor.getValue();
assertEquals(encryptedNewPassword, updatedUser.getPassword());
assertEquals(encryptedNewPassword, encryptedNewPasswordCaptor.getValue());
assertEquals(encryptedOldPassword, encryptedOldPasswordCaptor.getValue());
}
@Test
@SubjectAware(username = "trillian", password = "secret")
public void shouldGet400OnChangePasswordOfUserWithNonDefaultType() throws Exception {
public void shouldGet400OnMissingOldPassword() throws Exception {
originalUser.setType("not an xml type");
String newPassword = "pwd123";
String oldPassword = "notEncriptedSecret";
String content = String.format("{ \"oldPassword\": \"%s\" , \"newPassword\": \"%s\" }", oldPassword, newPassword);
String content = String.format("{ \"newPassword\": \"%s\" }", newPassword);
MockHttpRequest request = MockHttpRequest
.put("/" + MeResource.ME_PATH_V2 + "password")
.contentType(VndMediaType.PASSWORD_CHANGE)
.content(content.getBytes());
MockHttpResponse response = new MockHttpResponse();
when(passwordService.encryptPassword(newPassword)).thenReturn("encrypted123");
when(passwordService.encryptPassword(eq(oldPassword))).thenReturn("secret");
dispatcher.invoke(request, response);
@@ -137,17 +141,34 @@ public class MeResourceTest {
@Test
@SubjectAware(username = "trillian", password = "secret")
public void shouldGet400OnChangePasswordIfOldPasswordDoesNotMatchOriginalPassword() throws Exception {
public void shouldGet400OnMissingEmptyPassword() throws Exception {
String newPassword = "pwd123";
String oldPassword = "notEncriptedSecret";
String oldPassword = "";
String content = String.format("{ \"oldPassword\": \"%s\" , \"newPassword\": \"%s\" }", oldPassword, newPassword);
MockHttpRequest request = MockHttpRequest
.put("/" + MeResource.ME_PATH_V2 + "password")
.contentType(VndMediaType.PASSWORD_CHANGE)
.content(content.getBytes());
MockHttpResponse response = new MockHttpResponse();
when(passwordService.encryptPassword(newPassword)).thenReturn("encrypted123");
when(passwordService.encryptPassword(eq(oldPassword))).thenReturn("differentThanSecret");
dispatcher.invoke(request, response);
assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
}
@Test
@SubjectAware(username = "trillian", password = "secret")
public void shouldMapExceptionFromManager() throws Exception {
String newPassword = "pwd123";
String oldPassword = "secret";
String content = String.format("{ \"oldPassword\": \"%s\" , \"newPassword\": \"%s\" }", oldPassword, newPassword);
MockHttpRequest request = MockHttpRequest
.put("/" + MeResource.ME_PATH_V2 + "password")
.contentType(VndMediaType.PASSWORD_CHANGE)
.content(content.getBytes());
MockHttpResponse response = new MockHttpResponse();
doThrow(InvalidPasswordException.class).when(userManager).changePasswordForLoggedInUser(any(), any());
dispatcher.invoke(request, response);

View File

@@ -14,7 +14,9 @@ import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import sonia.scm.NotFoundException;
import sonia.scm.PageResult;
import sonia.scm.user.ChangePasswordNotAllowedException;
import sonia.scm.user.User;
import sonia.scm.user.UserManager;
import sonia.scm.web.VndMediaType;
@@ -31,6 +33,7 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -69,7 +72,6 @@ public class UserRootResourceTest {
originalUser = createDummyUser("Neo");
when(userManager.create(userCaptor.capture())).thenAnswer(invocation -> invocation.getArguments()[0]);
when(userManager.isTypeDefault(userCaptor.capture())).thenCallRealMethod();
when(userManager.getUserTypeChecker()).thenCallRealMethod();
doNothing().when(userManager).modify(userCaptor.capture());
doNothing().when(userManager).delete(userCaptor.capture());
when(userManager.getDefaultType()).thenReturn("xml");
@@ -143,7 +145,7 @@ public class UserRootResourceTest {
String content = String.format("{\"newPassword\": \"%s\"}", newPassword);
MockHttpRequest request = MockHttpRequest
.put("/" + UserRootResource.USERS_PATH_V2 + "Neo/password")
.contentType(VndMediaType.PASSWORD_CHANGE)
.contentType(VndMediaType.PASSWORD_OVERWRITE)
.content(content.getBytes());
MockHttpResponse response = new MockHttpResponse();
when(passwordService.encryptPassword(newPassword)).thenReturn("encrypted123");
@@ -151,26 +153,61 @@ public class UserRootResourceTest {
dispatcher.invoke(request, response);
assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
verify(userManager).modify(any(User.class));
User updatedUser = userCaptor.getValue();
assertEquals("encrypted123", updatedUser.getPassword());
verify(userManager).overwritePassword("Neo", "encrypted123");
}
@Test
public void shouldGet400OnChangePasswordOfUserWithNonDefaultType() throws Exception {
public void shouldGet400OnOverwritePasswordWhenManagerThrowsNotAllowed() throws Exception {
originalUser.setType("not an xml type");
String newPassword = "pwd123";
String content = String.format("{\"newPassword\": \"%s\"}", newPassword);
MockHttpRequest request = MockHttpRequest
.put("/" + UserRootResource.USERS_PATH_V2 + "Neo/password")
.contentType(VndMediaType.PASSWORD_CHANGE)
.contentType(VndMediaType.PASSWORD_OVERWRITE)
.content(content.getBytes());
MockHttpResponse response = new MockHttpResponse();
doThrow(ChangePasswordNotAllowedException.class).when(userManager).overwritePassword(any(), any());
dispatcher.invoke(request, response);
assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
}
@Test
public void shouldGet404OnOverwritePasswordWhenNotFound() throws Exception {
originalUser.setType("not an xml type");
String newPassword = "pwd123";
String content = String.format("{\"newPassword\": \"%s\"}", newPassword);
MockHttpRequest request = MockHttpRequest
.put("/" + UserRootResource.USERS_PATH_V2 + "Neo/password")
.contentType(VndMediaType.PASSWORD_OVERWRITE)
.content(content.getBytes());
MockHttpResponse response = new MockHttpResponse();
doThrow(NotFoundException.class).when(userManager).overwritePassword(any(), any());
dispatcher.invoke(request, response);
assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
}
@Test
public void shouldEncryptPasswordOnOverwritePassword() throws Exception {
originalUser.setType("not an xml type");
String newPassword = "pwd123";
String content = String.format("{\"newPassword\": \"%s\"}", newPassword);
MockHttpRequest request = MockHttpRequest
.put("/" + UserRootResource.USERS_PATH_V2 + "Neo/password")
.contentType(VndMediaType.PASSWORD_OVERWRITE)
.content(content.getBytes());
MockHttpResponse response = new MockHttpResponse();
when(passwordService.encryptPassword(newPassword)).thenReturn("encrypted123");
dispatcher.invoke(request, response);
assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
verify(userManager).overwritePassword("Neo", "encrypted123");
}
@Test

View File

@@ -65,7 +65,7 @@ public class UserToUserDtoMapperTest {
}
@Test
public void shouldGetPasswordLinkOnlyForDefaultUserType() {
public void shouldGetPasswordLinkForAdmin() {
User user = createDefaultUser();
when(subject.isPermitted("user:modify:abc")).thenReturn(true);
when(userManager.isTypeDefault(eq(user))).thenReturn(true);
@@ -73,14 +73,15 @@ public class UserToUserDtoMapperTest {
UserDto userDto = mapper.map(user);
assertEquals("expected password link with modify permission", expectedBaseUri.resolve("abc/password").toString(), userDto.getLinks().getLinkBy("password").get().getHref());
}
when(subject.isPermitted("user:modify:abc")).thenReturn(false);
userDto = mapper.map(user);
assertEquals("expected password link on mission modify permission", expectedBaseUri.resolve("abc/password").toString(), userDto.getLinks().getLinkBy("password").get().getHref());
@Test
public void shouldGetPasswordLinkOnlyForDefaultUserType() {
User user = createDefaultUser();
when(subject.isPermitted("user:modify:abc")).thenReturn(true);
when(userManager.isTypeDefault(eq(user))).thenReturn(false);
userDto = mapper.map(user);
UserDto userDto = mapper.map(user);
assertFalse("expected no password link", userDto.getLinks().getLinkBy("password").isPresent());
}

View File

@@ -152,7 +152,7 @@ public class DefaultRepositoryManagerTest extends ManagerTestBase<Repository> {
}
@Test(expected = NotFoundException.class)
public void testDeleteNotFound() throws NotFoundException {
public void testDeleteNotFound(){
manager.delete(createRepositoryWithId());
}
@@ -304,7 +304,7 @@ public class DefaultRepositoryManagerTest extends ManagerTestBase<Repository> {
}
@Test
public void testModify() throws NotFoundException, AlreadyExistsException {
public void testModify() throws AlreadyExistsException {
Repository heartOfGold = createTestRepository();
heartOfGold.setDescription("prototype ship");
@@ -328,12 +328,12 @@ public class DefaultRepositoryManagerTest extends ManagerTestBase<Repository> {
}
@Test(expected = NotFoundException.class)
public void testModifyNotFound() throws NotFoundException {
public void testModifyNotFound(){
manager.modify(createRepositoryWithId());
}
@Test
public void testRefresh() throws NotFoundException, AlreadyExistsException {
public void testRefresh() throws AlreadyExistsException {
Repository heartOfGold = createTestRepository();
String description = heartOfGold.getDescription();
@@ -354,7 +354,7 @@ public class DefaultRepositoryManagerTest extends ManagerTestBase<Repository> {
}
@Test(expected = RepositoryNotFoundException.class)
public void testRefreshNotFound() throws NotFoundException {
public void testRefreshNotFound(){
manager.refresh(createRepositoryWithId());
}
@@ -495,7 +495,7 @@ public class DefaultRepositoryManagerTest extends ManagerTestBase<Repository> {
return createRepository(RepositoryTestData.createHeartOfGold());
}
private void delete(Manager<Repository> manager, Repository repository) throws NotFoundException {
private void delete(Manager<Repository> manager, Repository repository){
String id = repository.getId();

View File

@@ -1,10 +1,10 @@
/**
* Copyright (c) 2014, Sebastian Sdorra
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
@@ -13,7 +13,7 @@
* 3. Neither the name of SCM-Manager; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
@@ -24,9 +24,9 @@
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* http://bitbucket.org/sdorra/scm-manager
*
*
*/
package sonia.scm.security;
@@ -57,7 +57,6 @@ import sonia.scm.repository.RepositoryTestData;
import sonia.scm.user.User;
import sonia.scm.user.UserTestData;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.nullValue;
@@ -70,7 +69,7 @@ import static org.mockito.Mockito.when;
/**
* Unit tests for {@link AuthorizationCollector}.
*
*
* @author Sebastian Sdorra
*/
@SuppressWarnings("unchecked")
@@ -79,28 +78,28 @@ public class DefaultAuthorizationCollectorTest {
@Mock
private Cache cache;
@Mock
private CacheManager cacheManager;
@Mock
private RepositoryDAO repositoryDAO;
@Mock
private SecuritySystem securitySystem;
private DefaultAuthorizationCollector collector;
@Rule
public ShiroRule shiro = new ShiroRule();
/**
* Set up object to test.
*/
@Before
public void setUp(){
when(cacheManager.getCache(Mockito.any(String.class))).thenReturn(cache);
collector = new DefaultAuthorizationCollector(cacheManager, repositoryDAO, securitySystem);
}
@@ -116,7 +115,7 @@ public class DefaultAuthorizationCollectorTest {
assertThat(authInfo.getStringPermissions(), nullValue());
assertThat(authInfo.getObjectPermissions(), nullValue());
}
/**
* Tests {@link AuthorizationCollector#collect()} from cache.
*/
@@ -124,16 +123,15 @@ public class DefaultAuthorizationCollectorTest {
@SubjectAware(
configuration = "classpath:sonia/scm/shiro-001.ini"
)
public void testCollectFromCache()
{
public void testCollectFromCache() {
AuthorizationInfo info = new SimpleAuthorizationInfo();
when(cache.get(anyObject())).thenReturn(info);
authenticate(UserTestData.createTrillian(), "main");
AuthorizationInfo authInfo = collector.collect();
assertSame(info, authInfo);
}
/**
* Tests {@link AuthorizationCollector#collect()} with cache.
*/
@@ -141,13 +139,13 @@ public class DefaultAuthorizationCollectorTest {
@SubjectAware(
configuration = "classpath:sonia/scm/shiro-001.ini"
)
public void testCollectWithCache(){
public void testCollectWithCache() {
authenticate(UserTestData.createTrillian(), "main");
AuthorizationInfo authInfo = collector.collect();
verify(cache).put(any(), any());
}
/**
* Tests {@link AuthorizationCollector#collect()} without permissions.
*/
@@ -155,17 +153,16 @@ public class DefaultAuthorizationCollectorTest {
@SubjectAware(
configuration = "classpath:sonia/scm/shiro-001.ini"
)
public void testCollectWithoutPermissions()
{
public void testCollectWithoutPermissions() {
authenticate(UserTestData.createTrillian(), "main");
AuthorizationInfo authInfo = collector.collect();
assertThat(authInfo.getRoles(), Matchers.contains(Role.USER));
assertThat(authInfo.getStringPermissions(), hasSize(3));
assertThat(authInfo.getStringPermissions(), containsInAnyOrder("user:autocomplete", "group:autocomplete", "user:read:trillian"));
assertThat(authInfo.getStringPermissions(), hasSize(4));
assertThat(authInfo.getStringPermissions(), containsInAnyOrder("user:autocomplete", "group:autocomplete", "user:changePassword:trillian", "user:read:trillian"));
assertThat(authInfo.getObjectPermissions(), nullValue());
}
/**
* Tests {@link AuthorizationCollector#collect()} as admin.
*/
@@ -173,18 +170,17 @@ public class DefaultAuthorizationCollectorTest {
@SubjectAware(
configuration = "classpath:sonia/scm/shiro-001.ini"
)
public void testCollectAsAdmin()
{
public void testCollectAsAdmin() {
User trillian = UserTestData.createTrillian();
trillian.setAdmin(true);
authenticate(trillian, "main");
AuthorizationInfo authInfo = collector.collect();
assertThat(authInfo.getRoles(), Matchers.containsInAnyOrder(Role.USER, Role.ADMIN));
assertThat(authInfo.getObjectPermissions(), nullValue());
assertThat(authInfo.getStringPermissions(), Matchers.contains("*"));
}
/**
* Tests {@link AuthorizationCollector#collect()} with repository permissions.
*/
@@ -192,8 +188,7 @@ public class DefaultAuthorizationCollectorTest {
@SubjectAware(
configuration = "classpath:sonia/scm/shiro-001.ini"
)
public void testCollectWithRepositoryPermissions()
{
public void testCollectWithRepositoryPermissions() {
String group = "heart-of-gold-crew";
authenticate(UserTestData.createTrillian(), group);
Repository heartOfGold = RepositoryTestData.createHeartOfGold();
@@ -204,14 +199,14 @@ public class DefaultAuthorizationCollectorTest {
sonia.scm.repository.Permission permission = new sonia.scm.repository.Permission(group, PermissionType.WRITE, true);
puzzle42.setPermissions(Lists.newArrayList(permission));
when(repositoryDAO.getAll()).thenReturn(Lists.newArrayList(heartOfGold, puzzle42));
// execute and assert
AuthorizationInfo authInfo = collector.collect();
assertThat(authInfo.getRoles(), Matchers.containsInAnyOrder(Role.USER));
assertThat(authInfo.getObjectPermissions(), nullValue());
assertThat(authInfo.getStringPermissions(), containsInAnyOrder("user:autocomplete", "group:autocomplete", "repository:read,pull:one", "repository:read,pull,push:two", "user:read:trillian"));
assertThat(authInfo.getStringPermissions(), containsInAnyOrder("user:autocomplete", "group:autocomplete", "user:changePassword:trillian", "repository:read,pull:one", "repository:read,pull,push:two", "user:read:trillian"));
}
/**
* Tests {@link AuthorizationCollector#collect()} with global permissions.
*/
@@ -219,20 +214,20 @@ public class DefaultAuthorizationCollectorTest {
@SubjectAware(
configuration = "classpath:sonia/scm/shiro-001.ini"
)
public void testCollectWithGlobalPermissions(){
public void testCollectWithGlobalPermissions() {
authenticate(UserTestData.createTrillian(), "main");
StoredAssignedPermission p1 = new StoredAssignedPermission("one", new AssignedPermission("one", "one:one"));
StoredAssignedPermission p2 = new StoredAssignedPermission("two", new AssignedPermission("two", "two:two"));
when(securitySystem.getPermissions(Mockito.any(Predicate.class))).thenReturn(Lists.newArrayList(p1, p2));
// execute and assert
AuthorizationInfo authInfo = collector.collect();
assertThat(authInfo.getRoles(), Matchers.containsInAnyOrder(Role.USER));
assertThat(authInfo.getObjectPermissions(), nullValue());
assertThat(authInfo.getStringPermissions(), containsInAnyOrder("one:one", "two:two", "user:read:trillian", "user:autocomplete" , "group:autocomplete" ));
assertThat(authInfo.getStringPermissions(), containsInAnyOrder("one:one", "two:two", "user:read:trillian", "user:autocomplete", "group:autocomplete", "user:changePassword:trillian"));
}
private void authenticate(User user, String group, String... groups) {
SimplePrincipalCollection spc = new SimplePrincipalCollection();
spc.add(user.getName(), "unit");
@@ -249,9 +244,9 @@ public class DefaultAuthorizationCollectorTest {
public void testInvalidateCache() {
collector.invalidateCache(AuthorizationChangedEvent.createForEveryUser());
verify(cache).clear();
collector.invalidateCache(AuthorizationChangedEvent.createForUser("dent"));
verify(cache).removeAll(Mockito.any(Predicate.class));
}
}

View File

@@ -39,9 +39,13 @@ import com.github.sdorra.shiro.ShiroRule;
import com.github.sdorra.shiro.SubjectAware;
import com.google.common.collect.Lists;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import sonia.scm.NotFoundException;
import sonia.scm.store.JAXBConfigurationStoreFactory;
import sonia.scm.user.xml.XmlUserDAO;
import sonia.scm.util.MockUtil;
@@ -70,6 +74,10 @@ public class DefaultUserManagerTest extends UserManagerTestBase
@Rule
public ShiroRule shiro = new ShiroRule();
private UserDAO userDAO = mock(UserDAO.class);
private User trillian;
/**
* Method description
*
@@ -82,6 +90,16 @@ public class DefaultUserManagerTest extends UserManagerTestBase
return new DefaultUserManager(createXmlUserDAO());
}
@Before
public void initDao() {
trillian = UserTestData.createTrillian();
trillian.setPassword("oldEncrypted");
userDAO = mock(UserDAO.class);
when(userDAO.getType()).thenReturn("xml");
when(userDAO.get("trillian")).thenReturn(trillian);
}
/**
* Method description
*
@@ -89,7 +107,6 @@ public class DefaultUserManagerTest extends UserManagerTestBase
@Test
public void testDefaultAccountAfterFristStart()
{
UserDAO userDAO = mock(UserDAO.class);
List<User> users = Lists.newArrayList(new User("tuser"));
when(userDAO.getAll()).thenReturn(users);
@@ -108,8 +125,6 @@ public class DefaultUserManagerTest extends UserManagerTestBase
@SuppressWarnings("unchecked")
public void testDefaultAccountCreation()
{
UserDAO userDAO = mock(UserDAO.class);
when(userDAO.getAll()).thenReturn(Collections.EMPTY_LIST);
UserManager userManager = new DefaultUserManager(userDAO);
@@ -118,6 +133,55 @@ public class DefaultUserManagerTest extends UserManagerTestBase
verify(userDAO, times(2)).add(any(User.class));
}
@Test(expected = InvalidPasswordException.class)
public void shouldFailChangePasswordForWrongOldPassword() {
UserManager userManager = new DefaultUserManager(userDAO);
userManager.changePasswordForLoggedInUser("wrongPassword", "---");
}
@Test
public void shouldSucceedChangePassword() {
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
doNothing().when(userDAO).modify(userCaptor.capture());
UserManager userManager = new DefaultUserManager(userDAO);
userManager.changePasswordForLoggedInUser("oldEncrypted", "newEncrypted");
Assertions.assertThat(userCaptor.getValue().getPassword()).isEqualTo("newEncrypted");
}
@Test(expected = ChangePasswordNotAllowedException.class)
public void shouldFailOverwritePasswordForWrongType() {
trillian.setType("wrongType");
UserManager userManager = new DefaultUserManager(userDAO);
userManager.overwritePassword("trillian", "---");
}
@Test(expected = NotFoundException.class)
public void shouldFailOverwritePasswordForMissingUser() {
UserManager userManager = new DefaultUserManager(userDAO);
userManager.overwritePassword("notExisting", "---");
}
@Test
public void shouldSucceedOverwritePassword() {
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
doNothing().when(userDAO).modify(userCaptor.capture());
UserManager userManager = new DefaultUserManager(userDAO);
userManager.overwritePassword("trillian", "newEncrypted");
Assertions.assertThat(userCaptor.getValue().getPassword()).isEqualTo("newEncrypted");
}
//~--- methods --------------------------------------------------------------
private XmlUserDAO createXmlUserDAO() {