Let git handle line endings for us.

This commit is contained in:
Tom Page
2016-09-21 13:47:25 +01:00
parent 183ee64545
commit d4937aeda4
1030 changed files with 138995 additions and 138966 deletions

View File

@@ -1,54 +1,54 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.action;
import static org.mockito.Mockito.doReturn;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.action.Action;
import org.mockito.Mock;
/**
* Declare as version record action unit test.
*
* @author Roy Wetherall
* @since 2.3
*/
public abstract class BaseActionUnitTest extends BaseUnitTest
{
/** mocked action */
private @Mock Action mockedAction;
/**
* @return mocked action
*/
protected Action getMockedAction()
{
return mockedAction;
}
/**
* Helper to mock an action parameter value
*/
protected void mockActionParameterValue(String name, Object value)
{
doReturn(value).when(mockedAction).getParameterValue(name);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.action;
import static org.mockito.Mockito.doReturn;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.action.Action;
import org.mockito.Mock;
/**
* Declare as version record action unit test.
*
* @author Roy Wetherall
* @since 2.3
*/
public abstract class BaseActionUnitTest extends BaseUnitTest
{
/** mocked action */
private @Mock Action mockedAction;
/**
* @return mocked action
*/
protected Action getMockedAction()
{
return mockedAction;
}
/**
* Helper to mock an action parameter value
*/
protected void mockActionParameterValue(String name, Object value)
{
doReturn(value).when(mockedAction).getParameterValue(name);
}
}

View File

@@ -1,293 +1,293 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.action.dm;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.BaseActionUnitTest;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Declare as version record action unit test.
*
* @author Roy Wetherall
* @since 2.3
*/
public class DeclareAsVersionRecordActionUnitTest extends BaseActionUnitTest
{
/** Sync Model */
private static final String SYNC_MODEL_1_0_URI = "http://www.alfresco.org/model/sync/1.0";
private static final QName ASPECT_SYNCED = QName.createQName(SYNC_MODEL_1_0_URI, "synced");
/** actioned upon node reference */
private NodeRef actionedUponNodeRef;
/** declare as version record action */
private @InjectMocks DeclareAsVersionRecordAction declareAsVersionRecordAction;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Override
public void before() throws Exception
{
super.before();
// mocked action
declareAsVersionRecordAction.setAuditable(false);
// mocked actioned upon noderef
actionedUponNodeRef = generateNodeRef();
}
/**
* Given that the actioned upon node reference doesn't exist
* When I execute the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefDoesntExist()
{
doReturn(false).when(mockedNodeService).exists(actionedUponNodeRef);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference isn't a subtype of cm:content
* When I execute the action
* Then nothing happens
*/
@Test
public void aciontedUponNodeRefIsntSubTypeOfCmContent()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(false).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference doesn't have the versionable aspect applied
* When I executed the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefDoesntHaveVersionableApplied()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference is already an record
* When I execute the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefAlreadyRecord()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference is a working copy
* When I execute the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefWorkingCopy()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference is a rejected record
* When I execute the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefRejectedRecord()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference is synced to the cloud
* When I execute the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefSynced()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_SYNCED);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that no file plan is provided
* And no default file plan exists
* When I execute the action
* Then an exception is thrown
*/
@Test
public void noFilePlanParameterNoDefaultFilePlan()
{
// setup
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_SYNCED);
// no default file plan
doReturn(null).when(mockedFilePlanService).getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
// expect exception
exception.expect(AlfrescoRuntimeException.class);
// exceute action
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
}
/**
* Given that no file plan is provided
* And adefault file plan exists
* When I execute the action
* Then a version record is declared
*/
@Test
public void noFilePlanParameterDefaultFilePlan()
{
// setup
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_SYNCED);
// no default file plan
doReturn(filePlan).when(mockedFilePlanService).getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
// exceute action
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, times(1)).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that a file plan is provided
* And it isn't a file plan
* When I execute the action
* Then an exception is thrown
*/
@Test
public void invalidFilePlanParameter()
{
// setup
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_SYNCED);
// not a file plan is provided in the parameters
mockActionParameterValue(DeclareAsVersionRecordAction.PARAM_FILE_PLAN, generateNodeRef());
// expect exception
exception.expect(AlfrescoRuntimeException.class);
// exceute action
declareAsVersionRecordAction.executeImpl(getMockedAction(), actionedUponNodeRef);
}
/**
* Given that a file plan is provided
* And it is a file plan
* When I execute the action
* Then a version record is declared
*/
@Test
public void validFilePlanParameter()
{
// setup
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_SYNCED);
// not a file plan is provided in the parameters
NodeRef myFilePlan = generateNodeRef(TYPE_FILE_PLAN);
doReturn(true).when(mockedFilePlanService).isFilePlan(myFilePlan);
mockActionParameterValue(DeclareAsVersionRecordAction.PARAM_FILE_PLAN, myFilePlan);
// exceute action
declareAsVersionRecordAction.executeImpl(getMockedAction(), actionedUponNodeRef);
verify(mockedRecordableVersionService, times(1)).createRecordFromLatestVersion(myFilePlan, actionedUponNodeRef);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.action.dm;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.BaseActionUnitTest;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Declare as version record action unit test.
*
* @author Roy Wetherall
* @since 2.3
*/
public class DeclareAsVersionRecordActionUnitTest extends BaseActionUnitTest
{
/** Sync Model */
private static final String SYNC_MODEL_1_0_URI = "http://www.alfresco.org/model/sync/1.0";
private static final QName ASPECT_SYNCED = QName.createQName(SYNC_MODEL_1_0_URI, "synced");
/** actioned upon node reference */
private NodeRef actionedUponNodeRef;
/** declare as version record action */
private @InjectMocks DeclareAsVersionRecordAction declareAsVersionRecordAction;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Override
public void before() throws Exception
{
super.before();
// mocked action
declareAsVersionRecordAction.setAuditable(false);
// mocked actioned upon noderef
actionedUponNodeRef = generateNodeRef();
}
/**
* Given that the actioned upon node reference doesn't exist
* When I execute the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefDoesntExist()
{
doReturn(false).when(mockedNodeService).exists(actionedUponNodeRef);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference isn't a subtype of cm:content
* When I execute the action
* Then nothing happens
*/
@Test
public void aciontedUponNodeRefIsntSubTypeOfCmContent()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(false).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference doesn't have the versionable aspect applied
* When I executed the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefDoesntHaveVersionableApplied()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference is already an record
* When I execute the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefAlreadyRecord()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference is a working copy
* When I execute the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefWorkingCopy()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference is a rejected record
* When I execute the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefRejectedRecord()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that the actioned upon node reference is synced to the cloud
* When I execute the action
* Then nothing happens
*/
@Test
public void actionedUponNodeRefSynced()
{
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_SYNCED);
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, never()).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that no file plan is provided
* And no default file plan exists
* When I execute the action
* Then an exception is thrown
*/
@Test
public void noFilePlanParameterNoDefaultFilePlan()
{
// setup
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_SYNCED);
// no default file plan
doReturn(null).when(mockedFilePlanService).getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
// expect exception
exception.expect(AlfrescoRuntimeException.class);
// exceute action
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
}
/**
* Given that no file plan is provided
* And adefault file plan exists
* When I execute the action
* Then a version record is declared
*/
@Test
public void noFilePlanParameterDefaultFilePlan()
{
// setup
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_SYNCED);
// no default file plan
doReturn(filePlan).when(mockedFilePlanService).getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
// exceute action
declareAsVersionRecordAction.executeImpl(mock(Action.class), actionedUponNodeRef);
verify(mockedRecordableVersionService, times(1)).createRecordFromLatestVersion(filePlan, actionedUponNodeRef);
}
/**
* Given that a file plan is provided
* And it isn't a file plan
* When I execute the action
* Then an exception is thrown
*/
@Test
public void invalidFilePlanParameter()
{
// setup
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_SYNCED);
// not a file plan is provided in the parameters
mockActionParameterValue(DeclareAsVersionRecordAction.PARAM_FILE_PLAN, generateNodeRef());
// expect exception
exception.expect(AlfrescoRuntimeException.class);
// exceute action
declareAsVersionRecordAction.executeImpl(getMockedAction(), actionedUponNodeRef);
}
/**
* Given that a file plan is provided
* And it is a file plan
* When I execute the action
* Then a version record is declared
*/
@Test
public void validFilePlanParameter()
{
// setup
doReturn(true).when(mockedNodeService).exists(actionedUponNodeRef);
doReturn(true).when(mockedDictionaryService).isSubClass(any(QName.class), eq(ContentModel.TYPE_CONTENT));
doReturn(true).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ContentModel.ASPECT_WORKING_COPY);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_RECORD_REJECTION_DETAILS);
doReturn(false).when(mockedNodeService).hasAspect(actionedUponNodeRef, ASPECT_SYNCED);
// not a file plan is provided in the parameters
NodeRef myFilePlan = generateNodeRef(TYPE_FILE_PLAN);
doReturn(true).when(mockedFilePlanService).isFilePlan(myFilePlan);
mockActionParameterValue(DeclareAsVersionRecordAction.PARAM_FILE_PLAN, myFilePlan);
// exceute action
declareAsVersionRecordAction.executeImpl(getMockedAction(), actionedUponNodeRef);
verify(mockedRecordableVersionService, times(1)).createRecordFromLatestVersion(myFilePlan, actionedUponNodeRef);
}
}

View File

@@ -1,106 +1,106 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.action.impl;
import static org.mockito.Mockito.verifyZeroInteractions;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.action.BaseActionUnitTest;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Unit test for file report action.
*
* @author Roy Wetherall
* @since 2.2
*/
public class FileReportActionUnitTest extends BaseActionUnitTest
{
/** actioned upon node reference */
private NodeRef actionedUponNodeRef;
/** file report action */
private @InjectMocks FileReportAction fileReportAction;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Override
public void before() throws Exception
{
super.before();
// actioned upon node reference
actionedUponNodeRef = generateRecord();
// mocked action
fileReportAction.setAuditable(false);
}
/**
* given the destination is not set, ensure that an exception is thrown
*/
@Test
public void destinationNotSet()
{
// == given ==
// set action parameter values
mockActionParameterValue(FileReportAction.MIMETYPE, MimetypeMap.MIMETYPE_HTML);
mockActionParameterValue(FileReportAction.REPORT_TYPE, "rma:destructionReport");
// expected exception
exception.expect(AlfrescoRuntimeException.class);
// == when ==
// execute action
fileReportAction.executeImpl(getMockedAction(), actionedUponNodeRef);
// == then ==
verifyZeroInteractions(mockedReportService, mockedNodeService);
}
/**
* given no report type set, ensure that an exception is thrown
*/
@Test
public void reportTypeNotSet()
{
// == given ==
// set action parameter values
mockActionParameterValue(FileReportAction.MIMETYPE, MimetypeMap.MIMETYPE_HTML);
mockActionParameterValue(FileReportAction.DESTINATION, generateNodeRef().toString());
// expected exception
exception.expect(AlfrescoRuntimeException.class);
// == when ==
// execute action
fileReportAction.executeImpl(getMockedAction(), actionedUponNodeRef);
// == then ==
verifyZeroInteractions(mockedReportService, mockedNodeService);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.action.impl;
import static org.mockito.Mockito.verifyZeroInteractions;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.action.BaseActionUnitTest;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Unit test for file report action.
*
* @author Roy Wetherall
* @since 2.2
*/
public class FileReportActionUnitTest extends BaseActionUnitTest
{
/** actioned upon node reference */
private NodeRef actionedUponNodeRef;
/** file report action */
private @InjectMocks FileReportAction fileReportAction;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Override
public void before() throws Exception
{
super.before();
// actioned upon node reference
actionedUponNodeRef = generateRecord();
// mocked action
fileReportAction.setAuditable(false);
}
/**
* given the destination is not set, ensure that an exception is thrown
*/
@Test
public void destinationNotSet()
{
// == given ==
// set action parameter values
mockActionParameterValue(FileReportAction.MIMETYPE, MimetypeMap.MIMETYPE_HTML);
mockActionParameterValue(FileReportAction.REPORT_TYPE, "rma:destructionReport");
// expected exception
exception.expect(AlfrescoRuntimeException.class);
// == when ==
// execute action
fileReportAction.executeImpl(getMockedAction(), actionedUponNodeRef);
// == then ==
verifyZeroInteractions(mockedReportService, mockedNodeService);
}
/**
* given no report type set, ensure that an exception is thrown
*/
@Test
public void reportTypeNotSet()
{
// == given ==
// set action parameter values
mockActionParameterValue(FileReportAction.MIMETYPE, MimetypeMap.MIMETYPE_HTML);
mockActionParameterValue(FileReportAction.DESTINATION, generateNodeRef().toString());
// expected exception
exception.expect(AlfrescoRuntimeException.class);
// == when ==
// execute action
fileReportAction.executeImpl(getMockedAction(), actionedUponNodeRef);
// == then ==
verifyZeroInteractions(mockedReportService, mockedNodeService);
}
}

View File

@@ -1,143 +1,143 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.action.impl;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.action.BaseActionUnitTest;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Unit test for unlink from action
*
* @author Roy Wetherall
* @since 2.3
*/
public class UnlinkFromActionUnitTest extends BaseActionUnitTest
{
private NodeRef record;
private NodeRef recordFolder;
@InjectMocks
private UnlinkFromAction action;
@Before
@Override
public void before() throws Exception
{
super.before();
record = generateRecord();
recordFolder = generateRecordFolder();
}
/**
* Given the actioned upon node does not exist
* When the action is executed
* Then nothing happens
*/
@Test
public void nodeDoesNotExist()
{
doReturn(false).when(mockedNodeService).exists(record);
action.executeImpl(mock(Action.class), record);
verify(mockedRecordService, never()).unlink(any(NodeRef.class), any(NodeRef.class));
}
/**
* Given the actioned upon node is pending delete
* When the action is executed
* Then nothing happens
*/
@Test
public void nodePendingDelete()
{
doReturn(true).when(mockedNodeService).exists(record);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_PENDING_DELETE);
action.executeImpl(mock(Action.class), record);
verify(mockedRecordService, never()).unlink(any(NodeRef.class), any(NodeRef.class));
}
/**
* Given that actioned upon node is not a record
* When the action is executed
* Then nothing happens
*/
@Test
public void nodeNotRecord()
{
NodeRef notRecord = generateCmContent(generateText());
doReturn(true).when(mockedNodeService).exists(notRecord);
doReturn(false).when(mockedNodeService).hasAspect(notRecord, ASPECT_PENDING_DELETE);
action.executeImpl(mock(Action.class), notRecord);
verify(mockedRecordService, never()).unlink(any(NodeRef.class), any(NodeRef.class));
}
/**
* Given that the record folder parameter is not provided
* When the action is executed
* Then an exception is thrown
*/
@Test(expected=AlfrescoRuntimeException.class)
public void recordFolderParamMissing()
{
// setup record
doReturn(true).when(mockedNodeService).exists(record);
doReturn(false).when(mockedNodeService).hasAspect(record, ASPECT_PENDING_DELETE);
// create action mock
mockActionParameterValue(UnlinkFromAction.PARAM_RECORD_FOLDER, null);
// execute action
action.executeImpl(getMockedAction(), record);
}
/**
* Given that a valid record folder is provided
* When the action is executed
* Then the record is unlinked from the record folder
*/
@Test
public void validUnlink()
{
// setup record
doReturn(true).when(mockedNodeService).exists(record);
doReturn(false).when(mockedNodeService).hasAspect(record, ASPECT_PENDING_DELETE);
// create action mock
mockActionParameterValue(UnlinkFromAction.PARAM_RECORD_FOLDER, recordFolder.toString());
// execute action
action.executeImpl(getMockedAction(), record);
// verify unlink
verify(mockedRecordService, times(1)).unlink(record, recordFolder);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.action.impl;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.action.BaseActionUnitTest;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Unit test for unlink from action
*
* @author Roy Wetherall
* @since 2.3
*/
public class UnlinkFromActionUnitTest extends BaseActionUnitTest
{
private NodeRef record;
private NodeRef recordFolder;
@InjectMocks
private UnlinkFromAction action;
@Before
@Override
public void before() throws Exception
{
super.before();
record = generateRecord();
recordFolder = generateRecordFolder();
}
/**
* Given the actioned upon node does not exist
* When the action is executed
* Then nothing happens
*/
@Test
public void nodeDoesNotExist()
{
doReturn(false).when(mockedNodeService).exists(record);
action.executeImpl(mock(Action.class), record);
verify(mockedRecordService, never()).unlink(any(NodeRef.class), any(NodeRef.class));
}
/**
* Given the actioned upon node is pending delete
* When the action is executed
* Then nothing happens
*/
@Test
public void nodePendingDelete()
{
doReturn(true).when(mockedNodeService).exists(record);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_PENDING_DELETE);
action.executeImpl(mock(Action.class), record);
verify(mockedRecordService, never()).unlink(any(NodeRef.class), any(NodeRef.class));
}
/**
* Given that actioned upon node is not a record
* When the action is executed
* Then nothing happens
*/
@Test
public void nodeNotRecord()
{
NodeRef notRecord = generateCmContent(generateText());
doReturn(true).when(mockedNodeService).exists(notRecord);
doReturn(false).when(mockedNodeService).hasAspect(notRecord, ASPECT_PENDING_DELETE);
action.executeImpl(mock(Action.class), notRecord);
verify(mockedRecordService, never()).unlink(any(NodeRef.class), any(NodeRef.class));
}
/**
* Given that the record folder parameter is not provided
* When the action is executed
* Then an exception is thrown
*/
@Test(expected=AlfrescoRuntimeException.class)
public void recordFolderParamMissing()
{
// setup record
doReturn(true).when(mockedNodeService).exists(record);
doReturn(false).when(mockedNodeService).hasAspect(record, ASPECT_PENDING_DELETE);
// create action mock
mockActionParameterValue(UnlinkFromAction.PARAM_RECORD_FOLDER, null);
// execute action
action.executeImpl(getMockedAction(), record);
}
/**
* Given that a valid record folder is provided
* When the action is executed
* Then the record is unlinked from the record folder
*/
@Test
public void validUnlink()
{
// setup record
doReturn(true).when(mockedNodeService).exists(record);
doReturn(false).when(mockedNodeService).hasAspect(record, ASPECT_PENDING_DELETE);
// create action mock
mockActionParameterValue(UnlinkFromAction.PARAM_RECORD_FOLDER, recordFolder.toString());
// execute action
action.executeImpl(getMockedAction(), record);
// verify unlink
verify(mockedRecordService, times(1)).unlink(record, recordFolder);
}
}

View File

@@ -1,94 +1,94 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.bootstrap;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.alfresco.module.org_alfresco_module_rm.patch.ModulePatchExecuter;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.importer.ImporterBootstrap;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
/**
* Bootstrap importer module component unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class BootstrapImporterModuleComponentUnitTest extends BaseUnitTest
{
/** RM config node */
private static final NodeRef configNodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "rm_config_folder");
/** mocks */
@Mock(name="importer") private ImporterBootstrap mockedImporter;
@Mock(name="modulePatchExecuter") private ModulePatchExecuter mockedModulePatchExecuter;
@Mock(name="recordContributorsGroupBootstrapComponent") private RecordContributorsGroupBootstrapComponent mockedRecordContributorsGroupBootstrapComponent;
/** importer */
@InjectMocks
private BootstrapImporterModuleComponent importer;
/**
* Given that the system has already been bootstraped
* When I try and boostrap the system
* Then the system is not bootstraped again
*/
@Test
public void alreadyBootstraped() throws Throwable
{
// config node exists
doReturn(true).when(mockedNodeService).exists(configNodeRef);
// boostrap
importer.executeInternal();
// not bootstraped
verify(mockedImporter, never()).bootstrap();
verify(mockedModulePatchExecuter, never()).initSchemaVersion();
verify(mockedRecordContributorsGroupBootstrapComponent, never()).createRecordContributorsGroup();
}
/**
* Given that the system has not been bootstraped
* When I try and bootstrap the system
* Then the system is bootstraped
*/
@Test
public void boostrap() throws Throwable
{
// config node does not exist
doReturn(false).when(mockedNodeService).exists(configNodeRef);
// boostrap
importer.executeInternal();
// not bootstraped
verify(mockedImporter, times(1)).bootstrap();
verify(mockedModulePatchExecuter, times(1)).initSchemaVersion();
verify(mockedRecordContributorsGroupBootstrapComponent, times(1)).createRecordContributorsGroup();
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.bootstrap;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.alfresco.module.org_alfresco_module_rm.patch.ModulePatchExecuter;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.importer.ImporterBootstrap;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
/**
* Bootstrap importer module component unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class BootstrapImporterModuleComponentUnitTest extends BaseUnitTest
{
/** RM config node */
private static final NodeRef configNodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, "rm_config_folder");
/** mocks */
@Mock(name="importer") private ImporterBootstrap mockedImporter;
@Mock(name="modulePatchExecuter") private ModulePatchExecuter mockedModulePatchExecuter;
@Mock(name="recordContributorsGroupBootstrapComponent") private RecordContributorsGroupBootstrapComponent mockedRecordContributorsGroupBootstrapComponent;
/** importer */
@InjectMocks
private BootstrapImporterModuleComponent importer;
/**
* Given that the system has already been bootstraped
* When I try and boostrap the system
* Then the system is not bootstraped again
*/
@Test
public void alreadyBootstraped() throws Throwable
{
// config node exists
doReturn(true).when(mockedNodeService).exists(configNodeRef);
// boostrap
importer.executeInternal();
// not bootstraped
verify(mockedImporter, never()).bootstrap();
verify(mockedModulePatchExecuter, never()).initSchemaVersion();
verify(mockedRecordContributorsGroupBootstrapComponent, never()).createRecordContributorsGroup();
}
/**
* Given that the system has not been bootstraped
* When I try and bootstrap the system
* Then the system is bootstraped
*/
@Test
public void boostrap() throws Throwable
{
// config node does not exist
doReturn(false).when(mockedNodeService).exists(configNodeRef);
// boostrap
importer.executeInternal();
// not bootstraped
verify(mockedImporter, times(1)).bootstrap();
verify(mockedModulePatchExecuter, times(1)).initSchemaVersion();
verify(mockedRecordContributorsGroupBootstrapComponent, times(1)).createRecordContributorsGroup();
}
}

View File

@@ -1,83 +1,83 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.bootstrap;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.security.AuthorityType;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Record contributors group bootstrap component unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class RecordContributorsGroupBootstrapComponentUnitTest extends BaseUnitTest
{
@InjectMocks
private RecordContributorsGroupBootstrapComponent component;
/**
* Given that the record contributors group already exists
* When I try and create the group
* Then nothing happens
*/
@Test
public void groupAlreadyExists()
{
// group already exists
doReturn(true).when(mockedAuthorityService).authorityExists(RecordContributorsGroupBootstrapComponent.GROUP_RECORD_CONTRIBUTORS);
// create group
component.createRecordContributorsGroup();
// group not created
verify(mockedAuthorityService, times(1)).authorityExists(RecordContributorsGroupBootstrapComponent.GROUP_RECORD_CONTRIBUTORS);
verifyNoMoreInteractions(mockedAuthorityService);
}
/**
* Given that the record contributors group does not exist
* When I try and create the group
* Then the group is successfully created
* And 'everyone' is added to the new group
*/
@Test
public void createGroup()
{
// group does not exists
doReturn(false).when(mockedAuthorityService).authorityExists(RecordContributorsGroupBootstrapComponent.GROUP_RECORD_CONTRIBUTORS);
// create group
component.createRecordContributorsGroup();
// group not created
verify(mockedAuthorityService, times(1)).createAuthority(AuthorityType.GROUP, RecordContributorsGroupBootstrapComponent.RECORD_CONTRIBUTORS);
verify(mockedAuthorityService, times(1)).addAuthority(RecordContributorsGroupBootstrapComponent.GROUP_RECORD_CONTRIBUTORS, "admin");
verify(mockedAuthorityService, times(1)).authorityExists(RecordContributorsGroupBootstrapComponent.GROUP_RECORD_CONTRIBUTORS);
verifyNoMoreInteractions(mockedAuthorityService);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.bootstrap;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.security.AuthorityType;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Record contributors group bootstrap component unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class RecordContributorsGroupBootstrapComponentUnitTest extends BaseUnitTest
{
@InjectMocks
private RecordContributorsGroupBootstrapComponent component;
/**
* Given that the record contributors group already exists
* When I try and create the group
* Then nothing happens
*/
@Test
public void groupAlreadyExists()
{
// group already exists
doReturn(true).when(mockedAuthorityService).authorityExists(RecordContributorsGroupBootstrapComponent.GROUP_RECORD_CONTRIBUTORS);
// create group
component.createRecordContributorsGroup();
// group not created
verify(mockedAuthorityService, times(1)).authorityExists(RecordContributorsGroupBootstrapComponent.GROUP_RECORD_CONTRIBUTORS);
verifyNoMoreInteractions(mockedAuthorityService);
}
/**
* Given that the record contributors group does not exist
* When I try and create the group
* Then the group is successfully created
* And 'everyone' is added to the new group
*/
@Test
public void createGroup()
{
// group does not exists
doReturn(false).when(mockedAuthorityService).authorityExists(RecordContributorsGroupBootstrapComponent.GROUP_RECORD_CONTRIBUTORS);
// create group
component.createRecordContributorsGroup();
// group not created
verify(mockedAuthorityService, times(1)).createAuthority(AuthorityType.GROUP, RecordContributorsGroupBootstrapComponent.RECORD_CONTRIBUTORS);
verify(mockedAuthorityService, times(1)).addAuthority(RecordContributorsGroupBootstrapComponent.GROUP_RECORD_CONTRIBUTORS, "admin");
verify(mockedAuthorityService, times(1)).authorityExists(RecordContributorsGroupBootstrapComponent.GROUP_RECORD_CONTRIBUTORS);
verifyNoMoreInteractions(mockedAuthorityService);
}
}

View File

@@ -1,220 +1,220 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.junit.Assert.*;
import java.lang.reflect.Method;
import java.util.Iterator;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.ConfigAttribute;
import net.sf.acegisecurity.vote.AccessDecisionVoter;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.capability.policy.ConfigAttributeDefinition;
import org.alfresco.module.org_alfresco_module_rm.capability.policy.Policy;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
/**
* RM entry voter unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class RMEntryVoterUnitTest extends BaseUnitTest
{
private static final String POLICY_NAME = "myPolicy";
/** RM Entry */
private @InjectMocks RMEntryVoter entryVoter;
/** mocked policy */
private @Mock Policy mockedPolicy;
/** mocked authentication */
private @Mock Authentication mockedAuthentication;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Before
@Override
public void before() throws Exception
{
super.before();
// don't run as system
when(mockedAuthenticationUtil.isRunAsUserTheSystemUser())
.thenReturn(false);
// indicate that "vote" transaction value is not set
when(mockedTransactionalResourceHelper.isResourcePresent("voting"))
.thenReturn(false);
}
/**
* Given that the system is already voting
* When I vote
* Then access granted
*/
@Test
public void alreadyVoting() throws Exception
{
// indicate already voting
when(mockedTransactionalResourceHelper.isResourcePresent("voting"))
.thenReturn(true);
// given I am providing an invalid policy for a method
MethodInvocation mockedMethodInvocation = createMethodInvoation("myTestMethod", NodeRef.class);
net.sf.acegisecurity.ConfigAttributeDefinition mockedConfigDef = createConfigDefinition("RM.invalid");
// call vote
assertEquals(
AccessDecisionVoter.ACCESS_GRANTED,
entryVoter.vote(mockedAuthentication, mockedMethodInvocation, mockedConfigDef));
}
/**
* Given that I am running this as the system user
* When I evaluate
* Then access granted
*/
@Test
public void runAsSystem() throws Exception
{
// run as system
when(mockedAuthenticationUtil.isRunAsUserTheSystemUser())
.thenReturn(true);
// given I am providing an invalid policy for a method
MethodInvocation mockedMethodInvocation = createMethodInvoation("myTestMethod", NodeRef.class);
net.sf.acegisecurity.ConfigAttributeDefinition mockedConfigDef = createConfigDefinition("RM.invalid");
// call vote
assertEquals(
AccessDecisionVoter.ACCESS_GRANTED,
entryVoter.vote(mockedAuthentication, mockedMethodInvocation, mockedConfigDef));
}
/**
* Given that we have provided an invalid policy
* When I evaluate the voter
* Then an AlfrescoRuntimeException is thrown
*/
@Test
public void invalidPolicy() throws Exception
{
// given I am providing an invalid policy for a method
MethodInvocation mockedMethodInvocation = createMethodInvoation("myTestMethod", NodeRef.class);
net.sf.acegisecurity.ConfigAttributeDefinition mockedConfigDef = createConfigDefinition("RM.invalid");
// I expect an Alfresco Runtime Exception
exception.expect(AlfrescoRuntimeException.class);
// call vote
entryVoter.vote(mockedAuthentication, mockedMethodInvocation, mockedConfigDef);
}
/**
* Given that I have provided a valid policy
* When I evaluate the voter
* Then the corresponding policy will be evaluated
*/
@Test
public void validPolicy() throws Exception
{
// valid policy
when(mockedPolicy.getName())
.thenReturn(POLICY_NAME);
entryVoter.registerPolicy(mockedPolicy);
// mock calling details
MethodInvocation mockedMethodInvocation = createMethodInvoation("myTestMethod", NodeRef.class);
net.sf.acegisecurity.ConfigAttributeDefinition mockedConfigDef = createConfigDefinition("RM." + POLICY_NAME);
// call vote
entryVoter.vote(mockedAuthentication, mockedMethodInvocation, mockedConfigDef);
// verify that the policy was executed
verify(mockedPolicy, times(1)).evaluate(eq(mockedMethodInvocation), any(Class[].class), any(ConfigAttributeDefinition.class));
}
/**
* Helper method to create configuration object
*/
@SuppressWarnings("rawtypes")
private net.sf.acegisecurity.ConfigAttributeDefinition createConfigDefinition(String value)
{
net.sf.acegisecurity.ConfigAttributeDefinition mockedConfig = mock(net.sf.acegisecurity.ConfigAttributeDefinition.class);
ConfigAttribute mockedConfigAttr = mock(ConfigAttribute.class);
when(mockedConfigAttr.getAttribute())
.thenReturn(value);
Iterator mockedIter = mock(Iterator.class);
when(mockedIter.hasNext())
.thenReturn(true)
.thenReturn(false);
when(mockedIter.next())
.thenReturn(mockedConfigAttr);
when(mockedConfig.getConfigAttributes())
.thenReturn(mockedIter);
return mockedConfig;
}
/**
* Helper method to create method invocation mock
*/
private MethodInvocation createMethodInvoation(String methodName, Class<?> ... parameterTypes)
throws Exception
{
// mock method invocation
MethodInvocation mockedMethodInvocation = mock(MethodInvocation.class);
// get method object .. assumed to be a method on this object
Method method = RMEntryVoterUnitTest.class.getMethod(methodName, parameterTypes);
when(mockedMethodInvocation.getMethod())
.thenReturn(method);
return mockedMethodInvocation;
}
/** ========= Test methods ======== */
public void myTestMethod(NodeRef nodeRef)
{
// does nothing
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.junit.Assert.*;
import java.lang.reflect.Method;
import java.util.Iterator;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.ConfigAttribute;
import net.sf.acegisecurity.vote.AccessDecisionVoter;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.module.org_alfresco_module_rm.capability.policy.ConfigAttributeDefinition;
import org.alfresco.module.org_alfresco_module_rm.capability.policy.Policy;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
/**
* RM entry voter unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class RMEntryVoterUnitTest extends BaseUnitTest
{
private static final String POLICY_NAME = "myPolicy";
/** RM Entry */
private @InjectMocks RMEntryVoter entryVoter;
/** mocked policy */
private @Mock Policy mockedPolicy;
/** mocked authentication */
private @Mock Authentication mockedAuthentication;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Before
@Override
public void before() throws Exception
{
super.before();
// don't run as system
when(mockedAuthenticationUtil.isRunAsUserTheSystemUser())
.thenReturn(false);
// indicate that "vote" transaction value is not set
when(mockedTransactionalResourceHelper.isResourcePresent("voting"))
.thenReturn(false);
}
/**
* Given that the system is already voting
* When I vote
* Then access granted
*/
@Test
public void alreadyVoting() throws Exception
{
// indicate already voting
when(mockedTransactionalResourceHelper.isResourcePresent("voting"))
.thenReturn(true);
// given I am providing an invalid policy for a method
MethodInvocation mockedMethodInvocation = createMethodInvoation("myTestMethod", NodeRef.class);
net.sf.acegisecurity.ConfigAttributeDefinition mockedConfigDef = createConfigDefinition("RM.invalid");
// call vote
assertEquals(
AccessDecisionVoter.ACCESS_GRANTED,
entryVoter.vote(mockedAuthentication, mockedMethodInvocation, mockedConfigDef));
}
/**
* Given that I am running this as the system user
* When I evaluate
* Then access granted
*/
@Test
public void runAsSystem() throws Exception
{
// run as system
when(mockedAuthenticationUtil.isRunAsUserTheSystemUser())
.thenReturn(true);
// given I am providing an invalid policy for a method
MethodInvocation mockedMethodInvocation = createMethodInvoation("myTestMethod", NodeRef.class);
net.sf.acegisecurity.ConfigAttributeDefinition mockedConfigDef = createConfigDefinition("RM.invalid");
// call vote
assertEquals(
AccessDecisionVoter.ACCESS_GRANTED,
entryVoter.vote(mockedAuthentication, mockedMethodInvocation, mockedConfigDef));
}
/**
* Given that we have provided an invalid policy
* When I evaluate the voter
* Then an AlfrescoRuntimeException is thrown
*/
@Test
public void invalidPolicy() throws Exception
{
// given I am providing an invalid policy for a method
MethodInvocation mockedMethodInvocation = createMethodInvoation("myTestMethod", NodeRef.class);
net.sf.acegisecurity.ConfigAttributeDefinition mockedConfigDef = createConfigDefinition("RM.invalid");
// I expect an Alfresco Runtime Exception
exception.expect(AlfrescoRuntimeException.class);
// call vote
entryVoter.vote(mockedAuthentication, mockedMethodInvocation, mockedConfigDef);
}
/**
* Given that I have provided a valid policy
* When I evaluate the voter
* Then the corresponding policy will be evaluated
*/
@Test
public void validPolicy() throws Exception
{
// valid policy
when(mockedPolicy.getName())
.thenReturn(POLICY_NAME);
entryVoter.registerPolicy(mockedPolicy);
// mock calling details
MethodInvocation mockedMethodInvocation = createMethodInvoation("myTestMethod", NodeRef.class);
net.sf.acegisecurity.ConfigAttributeDefinition mockedConfigDef = createConfigDefinition("RM." + POLICY_NAME);
// call vote
entryVoter.vote(mockedAuthentication, mockedMethodInvocation, mockedConfigDef);
// verify that the policy was executed
verify(mockedPolicy, times(1)).evaluate(eq(mockedMethodInvocation), any(Class[].class), any(ConfigAttributeDefinition.class));
}
/**
* Helper method to create configuration object
*/
@SuppressWarnings("rawtypes")
private net.sf.acegisecurity.ConfigAttributeDefinition createConfigDefinition(String value)
{
net.sf.acegisecurity.ConfigAttributeDefinition mockedConfig = mock(net.sf.acegisecurity.ConfigAttributeDefinition.class);
ConfigAttribute mockedConfigAttr = mock(ConfigAttribute.class);
when(mockedConfigAttr.getAttribute())
.thenReturn(value);
Iterator mockedIter = mock(Iterator.class);
when(mockedIter.hasNext())
.thenReturn(true)
.thenReturn(false);
when(mockedIter.next())
.thenReturn(mockedConfigAttr);
when(mockedConfig.getConfigAttributes())
.thenReturn(mockedIter);
return mockedConfig;
}
/**
* Helper method to create method invocation mock
*/
private MethodInvocation createMethodInvoation(String methodName, Class<?> ... parameterTypes)
throws Exception
{
// mock method invocation
MethodInvocation mockedMethodInvocation = mock(MethodInvocation.class);
// get method object .. assumed to be a method on this object
Method method = RMEntryVoterUnitTest.class.getMethod(methodName, parameterTypes);
when(mockedMethodInvocation.getMethod())
.thenReturn(method);
return mockedMethodInvocation;
}
/** ========= Test methods ======== */
public void myTestMethod(NodeRef nodeRef)
{
// does nothing
}
}

View File

@@ -1,40 +1,40 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability.declarative.condition;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* capability.declarative.condition unit test suite
*
* @author Roy Wetherall
* @since 2.3
*/
@RunWith(Suite.class)
@SuiteClasses(
{
HoldCapabilityConditionUnitTest.class,
FillingOnHoldContainerCapabilityConditionUnitTest.class,
FrozenCapabilityConditionUnitTest.class
})
public class CapabilityDeclarativeConditionSuite
{
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability.declarative.condition;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* capability.declarative.condition unit test suite
*
* @author Roy Wetherall
* @since 2.3
*/
@RunWith(Suite.class)
@SuiteClasses(
{
HoldCapabilityConditionUnitTest.class,
FillingOnHoldContainerCapabilityConditionUnitTest.class,
FrozenCapabilityConditionUnitTest.class
})
public class CapabilityDeclarativeConditionSuite
{
}

View File

@@ -1,141 +1,141 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability.declarative.condition;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessStatus;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Filling on hold container capability condition unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class FillingOnHoldContainerCapabilityConditionUnitTest extends BaseUnitTest
{
/** evaluator */
private @InjectMocks FillingOnHoldContainerCapabilityCondition condition;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Before
@Override
public void before() throws Exception
{
super.before();
}
/**
* Given hold container node
* And no filling permission
* When evaluate
* Then false
*/
@Test
public void noFillingOnHoldContainer()
{
NodeRef holdContainer = generateNodeRef(TYPE_HOLD_CONTAINER);
when(mockedFilePlanService.isFilePlan(holdContainer))
.thenReturn(false);
when(mockedPermissionService.hasPermission(holdContainer, RMPermissionModel.FILE_RECORDS))
.thenReturn(AccessStatus.DENIED);
assertFalse(condition.evaluateImpl(holdContainer));
}
/**
* Given hold container node
* And filling permission
* When evaluate
* Then true
*/
@Test
public void fillingOnHoldContainer()
{
NodeRef holdContainer = generateNodeRef(TYPE_HOLD_CONTAINER);
when(mockedFilePlanService.isFilePlan(holdContainer))
.thenReturn(false);
when(mockedPermissionService.hasPermission(holdContainer, RMPermissionModel.FILE_RECORDS))
.thenReturn(AccessStatus.ALLOWED);
assertTrue(condition.evaluateImpl(holdContainer));
}
/**
* Given file-plan node
* And no filling permission on hold container
* When evaluate
* Then false
*/
@Test
public void filePlanNoFilling()
{
NodeRef holdContainer = generateNodeRef(TYPE_HOLD_CONTAINER);
when(mockedFilePlanService.getHoldContainer(filePlan))
.thenReturn(holdContainer);
when(mockedPermissionService.hasPermission(holdContainer, RMPermissionModel.FILE_RECORDS))
.thenReturn(AccessStatus.DENIED);
assertFalse(condition.evaluateImpl(holdContainer));
}
/**
* Given file-plan node
* And filling permission on hold container
* When evaluate
* Then true
*/
@Test
public void filePlanFilling()
{
NodeRef holdContainer = generateNodeRef(TYPE_HOLD_CONTAINER);
when(mockedFilePlanService.getHoldContainer(filePlan))
.thenReturn(holdContainer);
when(mockedPermissionService.hasPermission(holdContainer, RMPermissionModel.FILE_RECORDS))
.thenReturn(AccessStatus.ALLOWED);
assertTrue(condition.evaluateImpl(holdContainer));
}
/**
* Given unexpected node type
* When evaluate
* Then false
*/
@Test
public void unexpectedNode()
{
NodeRef unexpectedNode = generateNodeRef();
when(mockedFilePlanService.isFilePlan(unexpectedNode))
.thenReturn(false);
when(mockedPermissionService.hasPermission(unexpectedNode, RMPermissionModel.FILE_RECORDS))
.thenReturn(AccessStatus.ALLOWED);
assertFalse(condition.evaluateImpl(unexpectedNode));
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability.declarative.condition;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessStatus;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Filling on hold container capability condition unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class FillingOnHoldContainerCapabilityConditionUnitTest extends BaseUnitTest
{
/** evaluator */
private @InjectMocks FillingOnHoldContainerCapabilityCondition condition;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Before
@Override
public void before() throws Exception
{
super.before();
}
/**
* Given hold container node
* And no filling permission
* When evaluate
* Then false
*/
@Test
public void noFillingOnHoldContainer()
{
NodeRef holdContainer = generateNodeRef(TYPE_HOLD_CONTAINER);
when(mockedFilePlanService.isFilePlan(holdContainer))
.thenReturn(false);
when(mockedPermissionService.hasPermission(holdContainer, RMPermissionModel.FILE_RECORDS))
.thenReturn(AccessStatus.DENIED);
assertFalse(condition.evaluateImpl(holdContainer));
}
/**
* Given hold container node
* And filling permission
* When evaluate
* Then true
*/
@Test
public void fillingOnHoldContainer()
{
NodeRef holdContainer = generateNodeRef(TYPE_HOLD_CONTAINER);
when(mockedFilePlanService.isFilePlan(holdContainer))
.thenReturn(false);
when(mockedPermissionService.hasPermission(holdContainer, RMPermissionModel.FILE_RECORDS))
.thenReturn(AccessStatus.ALLOWED);
assertTrue(condition.evaluateImpl(holdContainer));
}
/**
* Given file-plan node
* And no filling permission on hold container
* When evaluate
* Then false
*/
@Test
public void filePlanNoFilling()
{
NodeRef holdContainer = generateNodeRef(TYPE_HOLD_CONTAINER);
when(mockedFilePlanService.getHoldContainer(filePlan))
.thenReturn(holdContainer);
when(mockedPermissionService.hasPermission(holdContainer, RMPermissionModel.FILE_RECORDS))
.thenReturn(AccessStatus.DENIED);
assertFalse(condition.evaluateImpl(holdContainer));
}
/**
* Given file-plan node
* And filling permission on hold container
* When evaluate
* Then true
*/
@Test
public void filePlanFilling()
{
NodeRef holdContainer = generateNodeRef(TYPE_HOLD_CONTAINER);
when(mockedFilePlanService.getHoldContainer(filePlan))
.thenReturn(holdContainer);
when(mockedPermissionService.hasPermission(holdContainer, RMPermissionModel.FILE_RECORDS))
.thenReturn(AccessStatus.ALLOWED);
assertTrue(condition.evaluateImpl(holdContainer));
}
/**
* Given unexpected node type
* When evaluate
* Then false
*/
@Test
public void unexpectedNode()
{
NodeRef unexpectedNode = generateNodeRef();
when(mockedFilePlanService.isFilePlan(unexpectedNode))
.thenReturn(false);
when(mockedPermissionService.hasPermission(unexpectedNode, RMPermissionModel.FILE_RECORDS))
.thenReturn(AccessStatus.ALLOWED);
assertFalse(condition.evaluateImpl(unexpectedNode));
}
}

View File

@@ -1,232 +1,232 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability.declarative.condition;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Frozen capability condition unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class FrozenCapabilityConditionUnitTest extends BaseUnitTest
{
/** evaluator */
private @InjectMocks FrozenCapabilityCondition condition;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Before
@Override
public void before() throws Exception
{
super.before();
}
/**
* Given hold
* When evaluate
* Then true
*/
@Test
public void evaluateHold()
{
// is a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(true);
// evaluate
assertTrue(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, never()).isFrozen(nodeRef);
verify(mockedFreezeService, never()).hasFrozenChildren(nodeRef);
}
/**
* Given is frozen
* And no check children
* When evaluate
* Then true
*/
@Test
public void frozenDontCheckChildren()
{
// is not a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(false);
// dont check children
condition.setCheckChildren(false);
// is frozen
when(mockedFreezeService.isFrozen(nodeRef))
.thenReturn(true);
// evaluate
assertTrue(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, times(1)).isFrozen(nodeRef);
verify(mockedFreezeService, never()).hasFrozenChildren(nodeRef);
}
/**
* Given is not frozen
* And no check children
* When evaluate
* Then false
*/
@Test
public void notFrozenDontCheckChildren()
{
// is not a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(false);
// dont check children
condition.setCheckChildren(false);
// is not frozen
when(mockedFreezeService.isFrozen(nodeRef))
.thenReturn(false);
// evaluate
assertFalse(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, times(1)).isFrozen(nodeRef);
verify(mockedFreezeService, never()).hasFrozenChildren(nodeRef);
}
/**
* Given is frozen
* And check children
* When evaluate
* Then true
*/
@Test
public void frozenCheckChildren()
{
// is not a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(false);
// check children
condition.setCheckChildren(true);
// is frozen
when(mockedFreezeService.isFrozen(nodeRef))
.thenReturn(true);
// evaluate
assertTrue(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, times(1)).isFrozen(nodeRef);
verify(mockedFreezeService, never()).hasFrozenChildren(nodeRef);
}
/**
* Given is not frozen
* And check children
* And children no frozen
* When evaluate
* Then false
*/
@Test
public void notFrozenCheckChildrenNotFrozen()
{
// is not a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(false);
// check children
condition.setCheckChildren(true);
// is not frozen
when(mockedFreezeService.isFrozen(nodeRef))
.thenReturn(false);
// children not frozen
when(mockedFreezeService.hasFrozenChildren(nodeRef))
.thenReturn(false);
// evaluate
assertFalse(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, times(1)).isFrozen(nodeRef);
verify(mockedFreezeService, times(1)).hasFrozenChildren(nodeRef);
}
/**
* Given is not frozen
* And check children
* And children frozen
* When evaluate
* Then true
*/
@Test
public void notFrozenCheckChildrenFrozen()
{
// is not a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(false);
// check children
condition.setCheckChildren(true);
// is not frozen
when(mockedFreezeService.isFrozen(nodeRef))
.thenReturn(false);
// children frozen
when(mockedFreezeService.hasFrozenChildren(nodeRef))
.thenReturn(true);
// evaluate
assertTrue(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, times(1)).isFrozen(nodeRef);
verify(mockedFreezeService, times(1)).hasFrozenChildren(nodeRef);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability.declarative.condition;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Frozen capability condition unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class FrozenCapabilityConditionUnitTest extends BaseUnitTest
{
/** evaluator */
private @InjectMocks FrozenCapabilityCondition condition;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Before
@Override
public void before() throws Exception
{
super.before();
}
/**
* Given hold
* When evaluate
* Then true
*/
@Test
public void evaluateHold()
{
// is a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(true);
// evaluate
assertTrue(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, never()).isFrozen(nodeRef);
verify(mockedFreezeService, never()).hasFrozenChildren(nodeRef);
}
/**
* Given is frozen
* And no check children
* When evaluate
* Then true
*/
@Test
public void frozenDontCheckChildren()
{
// is not a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(false);
// dont check children
condition.setCheckChildren(false);
// is frozen
when(mockedFreezeService.isFrozen(nodeRef))
.thenReturn(true);
// evaluate
assertTrue(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, times(1)).isFrozen(nodeRef);
verify(mockedFreezeService, never()).hasFrozenChildren(nodeRef);
}
/**
* Given is not frozen
* And no check children
* When evaluate
* Then false
*/
@Test
public void notFrozenDontCheckChildren()
{
// is not a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(false);
// dont check children
condition.setCheckChildren(false);
// is not frozen
when(mockedFreezeService.isFrozen(nodeRef))
.thenReturn(false);
// evaluate
assertFalse(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, times(1)).isFrozen(nodeRef);
verify(mockedFreezeService, never()).hasFrozenChildren(nodeRef);
}
/**
* Given is frozen
* And check children
* When evaluate
* Then true
*/
@Test
public void frozenCheckChildren()
{
// is not a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(false);
// check children
condition.setCheckChildren(true);
// is frozen
when(mockedFreezeService.isFrozen(nodeRef))
.thenReturn(true);
// evaluate
assertTrue(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, times(1)).isFrozen(nodeRef);
verify(mockedFreezeService, never()).hasFrozenChildren(nodeRef);
}
/**
* Given is not frozen
* And check children
* And children no frozen
* When evaluate
* Then false
*/
@Test
public void notFrozenCheckChildrenNotFrozen()
{
// is not a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(false);
// check children
condition.setCheckChildren(true);
// is not frozen
when(mockedFreezeService.isFrozen(nodeRef))
.thenReturn(false);
// children not frozen
when(mockedFreezeService.hasFrozenChildren(nodeRef))
.thenReturn(false);
// evaluate
assertFalse(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, times(1)).isFrozen(nodeRef);
verify(mockedFreezeService, times(1)).hasFrozenChildren(nodeRef);
}
/**
* Given is not frozen
* And check children
* And children frozen
* When evaluate
* Then true
*/
@Test
public void notFrozenCheckChildrenFrozen()
{
// is not a hold
NodeRef nodeRef = generateNodeRef();
when(mockedHoldService.isHold(nodeRef))
.thenReturn(false);
// check children
condition.setCheckChildren(true);
// is not frozen
when(mockedFreezeService.isFrozen(nodeRef))
.thenReturn(false);
// children frozen
when(mockedFreezeService.hasFrozenChildren(nodeRef))
.thenReturn(true);
// evaluate
assertTrue(condition.evaluate(nodeRef));
// verify
verify(mockedHoldService, times(1)).isHold(nodeRef);
verify(mockedFreezeService, times(1)).isFrozen(nodeRef);
verify(mockedFreezeService, times(1)).hasFrozenChildren(nodeRef);
}
}

View File

@@ -1,143 +1,143 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability.declarative.condition;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.anyBoolean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanComponentKind;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessStatus;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
/**
* Freeze evaluator unit test.
*
* @author Roy Wetherall
*/
public class HoldCapabilityConditionUnitTest extends BaseUnitTest
{
/** test data */
private NodeRef hold1;
private NodeRef hold2;
private List<NodeRef> holds;
/** mocked objects */
private @Mock(name="kinds") Set<FilePlanComponentKind> mockedKinds;
/** evaluator */
private @Spy @InjectMocks HoldCapabilityCondition evaluator;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Before
@Override
public void before() throws Exception
{
super.before();
// setup test data
hold1 = generateNodeRef(TYPE_HOLD);
hold2 = generateNodeRef(TYPE_HOLD);
holds = new ArrayList<NodeRef>(2);
holds.add(hold1);
holds.add(hold2);
// setup interactions
doReturn(false).when(mockedKinds).contains(FilePlanComponentKind.RECORD_CATEGORY);
doReturn(true).when(mockedKinds).contains(FilePlanComponentKind.RECORD_FOLDER);
doReturn(true).when(mockedKinds).contains(FilePlanComponentKind.HOLD);
}
/**
* Test given there are no holds
*/
@Test
public void noHolds()
{
// given
doReturn(Collections.EMPTY_LIST).when(mockedHoldService).heldBy(eq(recordFolder), anyBoolean());
// when
boolean result = evaluator.evaluateImpl(recordFolder);
// then
assertFalse(result);
verify(mockedPermissionService, never()).hasPermission(any(NodeRef.class), eq(RMPermissionModel.FILING));
}
/**
* Test given the user has no filling permissions on any of the available holds
*/
@Test
public void noFillingOnHolds()
{
// given
doReturn(holds).when(mockedHoldService).heldBy(eq(recordFolder), anyBoolean());
doReturn(AccessStatus.DENIED).when(mockedPermissionService).hasPermission(hold1, RMPermissionModel.FILING);
doReturn(AccessStatus.DENIED).when(mockedPermissionService).hasPermission(hold2, RMPermissionModel.FILING);
// when
boolean result = evaluator.evaluateImpl(recordFolder);
// then
assertFalse(result);
verify(mockedPermissionService, times(2)).hasPermission(any(NodeRef.class), eq(RMPermissionModel.FILING));
}
/**
* Test given the user has filling on one of the available holds
*/
@Test
public void fillingOnHolds()
{
// given
doReturn(holds).when(mockedHoldService).heldBy(eq(recordFolder), anyBoolean());
doReturn(AccessStatus.DENIED).when(mockedPermissionService).hasPermission(hold1, RMPermissionModel.FILING);
doReturn(AccessStatus.ALLOWED).when(mockedPermissionService).hasPermission(hold2, RMPermissionModel.FILING);
// when
boolean result = evaluator.evaluateImpl(recordFolder);
// then
assertTrue(result);
verify(mockedPermissionService, times(2)).hasPermission(any(NodeRef.class), eq(RMPermissionModel.FILING));
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability.declarative.condition;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.anyBoolean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanComponentKind;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessStatus;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
/**
* Freeze evaluator unit test.
*
* @author Roy Wetherall
*/
public class HoldCapabilityConditionUnitTest extends BaseUnitTest
{
/** test data */
private NodeRef hold1;
private NodeRef hold2;
private List<NodeRef> holds;
/** mocked objects */
private @Mock(name="kinds") Set<FilePlanComponentKind> mockedKinds;
/** evaluator */
private @Spy @InjectMocks HoldCapabilityCondition evaluator;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Before
@Override
public void before() throws Exception
{
super.before();
// setup test data
hold1 = generateNodeRef(TYPE_HOLD);
hold2 = generateNodeRef(TYPE_HOLD);
holds = new ArrayList<NodeRef>(2);
holds.add(hold1);
holds.add(hold2);
// setup interactions
doReturn(false).when(mockedKinds).contains(FilePlanComponentKind.RECORD_CATEGORY);
doReturn(true).when(mockedKinds).contains(FilePlanComponentKind.RECORD_FOLDER);
doReturn(true).when(mockedKinds).contains(FilePlanComponentKind.HOLD);
}
/**
* Test given there are no holds
*/
@Test
public void noHolds()
{
// given
doReturn(Collections.EMPTY_LIST).when(mockedHoldService).heldBy(eq(recordFolder), anyBoolean());
// when
boolean result = evaluator.evaluateImpl(recordFolder);
// then
assertFalse(result);
verify(mockedPermissionService, never()).hasPermission(any(NodeRef.class), eq(RMPermissionModel.FILING));
}
/**
* Test given the user has no filling permissions on any of the available holds
*/
@Test
public void noFillingOnHolds()
{
// given
doReturn(holds).when(mockedHoldService).heldBy(eq(recordFolder), anyBoolean());
doReturn(AccessStatus.DENIED).when(mockedPermissionService).hasPermission(hold1, RMPermissionModel.FILING);
doReturn(AccessStatus.DENIED).when(mockedPermissionService).hasPermission(hold2, RMPermissionModel.FILING);
// when
boolean result = evaluator.evaluateImpl(recordFolder);
// then
assertFalse(result);
verify(mockedPermissionService, times(2)).hasPermission(any(NodeRef.class), eq(RMPermissionModel.FILING));
}
/**
* Test given the user has filling on one of the available holds
*/
@Test
public void fillingOnHolds()
{
// given
doReturn(holds).when(mockedHoldService).heldBy(eq(recordFolder), anyBoolean());
doReturn(AccessStatus.DENIED).when(mockedPermissionService).hasPermission(hold1, RMPermissionModel.FILING);
doReturn(AccessStatus.ALLOWED).when(mockedPermissionService).hasPermission(hold2, RMPermissionModel.FILING);
// when
boolean result = evaluator.evaluateImpl(recordFolder);
// then
assertTrue(result);
verify(mockedPermissionService, times(2)).hasPermission(any(NodeRef.class), eq(RMPermissionModel.FILING));
}
}

View File

@@ -1,65 +1,65 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability.impl;
import static org.mockito.Mockito.when;
import java.util.Set;
import net.sf.acegisecurity.vote.AccessDecisionVoter;
import org.alfresco.module.org_alfresco_module_rm.record.RecordServiceImpl;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
/**
* Edit non records metadata capability unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class EditNonRecordsMetadataCapabilityUnitTest extends BaseUnitTest
{
/** mocked set */
@Mock private Set<Object> mockedSet;
/** test capability */
@InjectMocks private EditNonRecordMetadataCapability capability;
/**
* Given that the evaluated node is held in the transaction cache as new
* When evaluated
* Then access is granted
*/
@Test
public void newRecord()
{
NodeRef nodeRef = generateNodeRef();
when(mockedTransactionalResourceHelper.getSet(RecordServiceImpl.KEY_NEW_RECORDS))
.thenReturn(mockedSet);
when(mockedSet.contains(nodeRef))
.thenReturn(true);
Assert.assertEquals(AccessDecisionVoter.ACCESS_GRANTED, capability.evaluate(nodeRef));
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.capability.impl;
import static org.mockito.Mockito.when;
import java.util.Set;
import net.sf.acegisecurity.vote.AccessDecisionVoter;
import org.alfresco.module.org_alfresco_module_rm.record.RecordServiceImpl;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
/**
* Edit non records metadata capability unit test
*
* @author Roy Wetherall
* @since 2.3
*/
public class EditNonRecordsMetadataCapabilityUnitTest extends BaseUnitTest
{
/** mocked set */
@Mock private Set<Object> mockedSet;
/** test capability */
@InjectMocks private EditNonRecordMetadataCapability capability;
/**
* Given that the evaluated node is held in the transaction cache as new
* When evaluated
* Then access is granted
*/
@Test
public void newRecord()
{
NodeRef nodeRef = generateNodeRef();
when(mockedTransactionalResourceHelper.getSet(RecordServiceImpl.KEY_NEW_RECORDS))
.thenReturn(mockedSet);
when(mockedSet.contains(nodeRef))
.thenReturn(true);
Assert.assertEquals(AccessDecisionVoter.ACCESS_GRANTED, capability.evaluate(nodeRef));
}
}

View File

@@ -1,176 +1,176 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.forms;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.admin.RecordsManagementAdminService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.forms.Field;
import org.alfresco.repo.forms.FieldDefinition;
import org.alfresco.repo.forms.Form;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.cmr.dictionary.TypeDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
/**
* RecordsManagementTypeFormFilter Unit Test
*
* @author Roy Wetherall
* @since 2.2
*/
public class RecordsManagementTypeFormFilterUnitTest extends BaseUnitTest
{
private static final QName MY_CUSTOM_TYPE = generateQName();
@Mock private Form mockForm;
@Mock private TypeDefinition mockTypeDefinition;
@Mock(name="recordsManagementAdminService") private RecordsManagementAdminService mockRecordsManagementAdminService;
@Spy @InjectMocks RecordsManagementTypeFormFilter typeFormFilter;
/**
* Test addCustomRMProperties - no custom properties found
*/
@Test
public void testAddCustomRMPropertiesNoneFound()
{
typeFormFilter.addCustomRMProperties(MY_CUSTOM_TYPE, mockForm);
verifyZeroInteractions(mockForm);
}
/**
* Test that non-customisable types are being treated correctly
*/
@Test
public void testAfterGenerateNotCustomisable()
{
when(mockTypeDefinition.getName()).thenReturn(MY_CUSTOM_TYPE);
when(mockRecordsManagementAdminService.isCustomisable(MY_CUSTOM_TYPE)).thenReturn(false);
typeFormFilter.afterGenerate(mockTypeDefinition, null, null, mockForm, null);
verify(typeFormFilter, never()).addCustomRMProperties(any(QName.class), any(Form.class));
}
/**
* Test that customisable types are being treated correctly
*/
@Test
public void testAfterGenerateCustomisable()
{
when(mockTypeDefinition.getName()).thenReturn(MY_CUSTOM_TYPE);
when(mockRecordsManagementAdminService.isCustomisable(MY_CUSTOM_TYPE)).thenReturn(true);
typeFormFilter.afterGenerate(mockTypeDefinition, null, null, mockForm, null);
verify(typeFormFilter, times(1)).addCustomRMProperties(any(QName.class), any(Form.class));
}
/**
* Test the default values for certain properties are being set correctly
*/
@Test
public void testDefaultFormValues()
{
List<FieldDefinition> defs = new ArrayList<FieldDefinition>(3);
FieldDefinition idDef = mockFieldDefinition("rma:identifier");
defs.add(idDef);
FieldDefinition vrDef = mockFieldDefinition("rma:vitalRecordIndicator");
defs.add(vrDef);
FieldDefinition rpDef = mockFieldDefinition("rma:reviewPeriod");
defs.add(rpDef);
when(mockForm.getFieldDefinitions()).thenReturn(defs);
typeFormFilter.afterGenerate(mockTypeDefinition, null, null, mockForm, null);
verify(mockedIdentifierService).generateIdentifier(any(QName.class), any(NodeRef.class));
verify(idDef).setDefaultValue(anyString());
verify(vrDef).setDefaultValue(Boolean.FALSE.toString());
verify(rpDef).setDefaultValue("none|0");
}
/**
* Helper to mock field definition
*/
private FieldDefinition mockFieldDefinition(String name)
{
FieldDefinition def = mock(FieldDefinition.class);
when(def.getName()).thenReturn(name);
return def;
}
/**
* Test addCustomRMProperties - two custom properties found
*/
@Test
public void testAddCustomRMProperties()
{
// map of custom properties
Map<QName, PropertyDefinition> properties = mockPropertyDefintionMap(2);
// setup rm admin service to return properties for my custom type
when(mockRecordsManagementAdminService.getCustomPropertyDefinitions(MY_CUSTOM_TYPE)).thenReturn(properties);
// call method
typeFormFilter.addCustomRMProperties(MY_CUSTOM_TYPE, mockForm);
// ensure that two custom properties have been added to the form
verify(mockForm, times(1)).addFields(anyListOf(Field.class));
}
/**
* Helper method to createa a mock property definition map
*/
private Map<QName, PropertyDefinition> mockPropertyDefintionMap(int size)
{
Map<QName, PropertyDefinition> properties = new HashMap<QName, PropertyDefinition>(size);
for (int i = 0; i < size; i++)
{
QName name = generateQName();
PropertyDefinition propDef = mock(PropertyDefinition.class);
when(propDef.getName()).thenReturn(name);
DataTypeDefinition mockDataTypeDefinition = mock(DataTypeDefinition.class);
when(mockDataTypeDefinition.getName()).thenReturn(DataTypeDefinition.TEXT);
when(propDef.getDataType()).thenReturn(mockDataTypeDefinition);
properties.put(name, propDef);
}
return properties;
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.forms;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.admin.RecordsManagementAdminService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.forms.Field;
import org.alfresco.repo.forms.FieldDefinition;
import org.alfresco.repo.forms.Form;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.cmr.dictionary.TypeDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
/**
* RecordsManagementTypeFormFilter Unit Test
*
* @author Roy Wetherall
* @since 2.2
*/
public class RecordsManagementTypeFormFilterUnitTest extends BaseUnitTest
{
private static final QName MY_CUSTOM_TYPE = generateQName();
@Mock private Form mockForm;
@Mock private TypeDefinition mockTypeDefinition;
@Mock(name="recordsManagementAdminService") private RecordsManagementAdminService mockRecordsManagementAdminService;
@Spy @InjectMocks RecordsManagementTypeFormFilter typeFormFilter;
/**
* Test addCustomRMProperties - no custom properties found
*/
@Test
public void testAddCustomRMPropertiesNoneFound()
{
typeFormFilter.addCustomRMProperties(MY_CUSTOM_TYPE, mockForm);
verifyZeroInteractions(mockForm);
}
/**
* Test that non-customisable types are being treated correctly
*/
@Test
public void testAfterGenerateNotCustomisable()
{
when(mockTypeDefinition.getName()).thenReturn(MY_CUSTOM_TYPE);
when(mockRecordsManagementAdminService.isCustomisable(MY_CUSTOM_TYPE)).thenReturn(false);
typeFormFilter.afterGenerate(mockTypeDefinition, null, null, mockForm, null);
verify(typeFormFilter, never()).addCustomRMProperties(any(QName.class), any(Form.class));
}
/**
* Test that customisable types are being treated correctly
*/
@Test
public void testAfterGenerateCustomisable()
{
when(mockTypeDefinition.getName()).thenReturn(MY_CUSTOM_TYPE);
when(mockRecordsManagementAdminService.isCustomisable(MY_CUSTOM_TYPE)).thenReturn(true);
typeFormFilter.afterGenerate(mockTypeDefinition, null, null, mockForm, null);
verify(typeFormFilter, times(1)).addCustomRMProperties(any(QName.class), any(Form.class));
}
/**
* Test the default values for certain properties are being set correctly
*/
@Test
public void testDefaultFormValues()
{
List<FieldDefinition> defs = new ArrayList<FieldDefinition>(3);
FieldDefinition idDef = mockFieldDefinition("rma:identifier");
defs.add(idDef);
FieldDefinition vrDef = mockFieldDefinition("rma:vitalRecordIndicator");
defs.add(vrDef);
FieldDefinition rpDef = mockFieldDefinition("rma:reviewPeriod");
defs.add(rpDef);
when(mockForm.getFieldDefinitions()).thenReturn(defs);
typeFormFilter.afterGenerate(mockTypeDefinition, null, null, mockForm, null);
verify(mockedIdentifierService).generateIdentifier(any(QName.class), any(NodeRef.class));
verify(idDef).setDefaultValue(anyString());
verify(vrDef).setDefaultValue(Boolean.FALSE.toString());
verify(rpDef).setDefaultValue("none|0");
}
/**
* Helper to mock field definition
*/
private FieldDefinition mockFieldDefinition(String name)
{
FieldDefinition def = mock(FieldDefinition.class);
when(def.getName()).thenReturn(name);
return def;
}
/**
* Test addCustomRMProperties - two custom properties found
*/
@Test
public void testAddCustomRMProperties()
{
// map of custom properties
Map<QName, PropertyDefinition> properties = mockPropertyDefintionMap(2);
// setup rm admin service to return properties for my custom type
when(mockRecordsManagementAdminService.getCustomPropertyDefinitions(MY_CUSTOM_TYPE)).thenReturn(properties);
// call method
typeFormFilter.addCustomRMProperties(MY_CUSTOM_TYPE, mockForm);
// ensure that two custom properties have been added to the form
verify(mockForm, times(1)).addFields(anyListOf(Field.class));
}
/**
* Helper method to createa a mock property definition map
*/
private Map<QName, PropertyDefinition> mockPropertyDefintionMap(int size)
{
Map<QName, PropertyDefinition> properties = new HashMap<QName, PropertyDefinition>(size);
for (int i = 0; i < size; i++)
{
QName name = generateQName();
PropertyDefinition propDef = mock(PropertyDefinition.class);
when(propDef.getName()).thenReturn(name);
DataTypeDefinition mockDataTypeDefinition = mock(DataTypeDefinition.class);
when(mockDataTypeDefinition.getName()).thenReturn(DataTypeDefinition.TEXT);
when(propDef.getDataType()).thenReturn(mockDataTypeDefinition);
properties.put(name, propDef);
}
return properties;
}
}

View File

@@ -1,459 +1,459 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.hold;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Hold service implementation unit test
*
* @author Roy Wetherall
* @since 2.2
*/
public class HoldServiceImplUnitTest extends BaseUnitTest
{
/** test values */
private static final String HOLD_NAME = "holdname";
private static final String HOLD_REASON = "holdreason";
private static final String HOLD_DESCRIPTION = "holddescription";
protected NodeRef holdContainer;
protected NodeRef hold;
protected NodeRef hold2;
@Spy @InjectMocks HoldServiceImpl holdService;
@Before
@Override
public void before() throws Exception
{
super.before();
// setup objects used in mock interactions
holdContainer = generateNodeRef(TYPE_HOLD_CONTAINER);
hold = generateNodeRef(TYPE_HOLD);
hold2 = generateNodeRef(TYPE_HOLD);
// setup interactions
doReturn(holdContainer).when(mockedFilePlanService).getHoldContainer(filePlan);
}
@Test
public void isHold()
{
assertTrue(holdService.isHold(hold));
assertFalse(holdService.isHold(recordFolder));
}
@Test
public void heldByMultipleResults()
{
// setup record folder in multiple holds
List<ChildAssociationRef> holds = new ArrayList<ChildAssociationRef>(2);
holds.add(new ChildAssociationRef(ASSOC_FROZEN_RECORDS, hold, ASSOC_FROZEN_RECORDS, recordFolder, true, 1));
holds.add(new ChildAssociationRef(ASSOC_FROZEN_RECORDS, hold2, ASSOC_FROZEN_RECORDS, recordFolder, true, 2));
doReturn(holds).when(mockedNodeService).getParentAssocs(recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
// check that both holds are found for record folder
List<NodeRef> heldByHolds = holdService.heldBy(recordFolder, true);
assertNotNull(heldByHolds);
assertEquals(2, heldByHolds.size());
assertTrue(holdService.heldBy(recordFolder, false).isEmpty());
// check that both holds are found for record (even thou they are one level deep)
heldByHolds = holdService.heldBy(record, true);
assertNotNull(heldByHolds);
assertEquals(2, heldByHolds.size());
assertTrue(holdService.heldBy(record, false).isEmpty());
}
@Test (expected=AlfrescoRuntimeException.class)
public void getHold()
{
// setup node service interactions
when(mockedNodeService.getChildByName(eq(holdContainer), eq(ContentModel.ASSOC_CONTAINS), anyString())).thenReturn(null)
.thenReturn(hold)
.thenReturn(recordFolder);
// no hold
NodeRef noHold = holdService.getHold(filePlan, "notAHold");
assertNull(noHold);
// found hold
NodeRef someHold = holdService.getHold(filePlan, "someHold");
assertNotNull(someHold);
assertEquals(TYPE_HOLD, mockedNodeService.getType(someHold));
// ensure runtime exception is thrown
holdService.getHold(filePlan, "notHold");
}
@Test (expected=RuntimeException.class)
public void getHeldNotAHold()
{
holdService.getHeld(recordFolder);
}
@Test
public void getHeldNoResults()
{
assertTrue(holdService.getHeld(hold).isEmpty());
}
@Test
public void getHeldWithResults()
{
// setup record folder in hold
List<ChildAssociationRef> holds = new ArrayList<ChildAssociationRef>(1);
holds.add(new ChildAssociationRef(ASSOC_FROZEN_RECORDS, hold, ASSOC_FROZEN_RECORDS, recordFolder, true, 1));
doReturn(holds).when(mockedNodeService).getChildAssocs(hold, ASSOC_FROZEN_RECORDS, RegexQNamePattern.MATCH_ALL);
List<NodeRef> list = holdService.getHeld(hold);
assertEquals(1, list.size());
assertEquals(recordFolder, list.get(0));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void createHold()
{
// setup node service interactions
when(mockedNodeService.createNode(eq(holdContainer), eq(ContentModel.ASSOC_CONTAINS), any(QName.class) , eq(TYPE_HOLD), any(Map.class)))
.thenReturn(new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, holdContainer, generateQName(), hold));
// create hold
NodeRef newHold = holdService.createHold(filePlan, HOLD_NAME, HOLD_REASON, HOLD_DESCRIPTION);
assertNotNull(newHold);
assertEquals(TYPE_HOLD, mockedNodeService.getType(newHold));
assertEquals(hold, newHold);
// check the node service interactions
ArgumentCaptor<Map> propertyMapCaptor = ArgumentCaptor.forClass(Map.class);
ArgumentCaptor<QName> assocNameCaptor = ArgumentCaptor.forClass(QName.class);
verify(mockedNodeService).createNode(eq(holdContainer), eq(ContentModel.ASSOC_CONTAINS), assocNameCaptor.capture() , eq(TYPE_HOLD), propertyMapCaptor.capture());
// check property map
Map<QName, Serializable> propertyMap = (Map<QName, Serializable>)propertyMapCaptor.getValue();
assertNotNull(propertyMap);
assertEquals(3, propertyMap.size());
assertTrue(propertyMap.containsKey(ContentModel.PROP_NAME));
assertEquals(HOLD_NAME, propertyMap.get(ContentModel.PROP_NAME));
assertTrue(propertyMap.containsKey(ContentModel.PROP_DESCRIPTION));
assertEquals(HOLD_DESCRIPTION, propertyMap.get(ContentModel.PROP_DESCRIPTION));
assertTrue(propertyMap.containsKey(PROP_HOLD_REASON));
assertEquals(HOLD_REASON, propertyMap.get(PROP_HOLD_REASON));
// check assoc name
assertNotNull(assocNameCaptor.getValue());
assertEquals(NamespaceService.CONTENT_MODEL_1_0_URI, assocNameCaptor.getValue().getNamespaceURI());
assertEquals(HOLD_NAME, assocNameCaptor.getValue().getLocalName());
}
@Test
public void getHoldReason()
{
// setup node service interactions
when(mockedNodeService.exists(hold))
.thenReturn(false)
.thenReturn(true)
.thenReturn(true)
.thenReturn(true);
when(mockedNodeService.getProperty(eq(hold), eq(PROP_HOLD_REASON)))
.thenReturn(null)
.thenReturn(HOLD_REASON);
// node does not exist
assertNull(holdService.getHoldReason(hold));
// node isn't a hold
assertNull(holdService.getHoldReason(recordFolder));
// hold reason isn't set
assertNull(holdService.getHoldReason(hold));
// hold reason set
assertEquals(HOLD_REASON, holdService.getHoldReason(hold));
}
@Test
public void setHoldReason()
{
// setup node service interactions
when(mockedNodeService.exists(hold))
.thenReturn(false)
.thenReturn(true)
.thenReturn(true);
// node does not exist
holdService.setHoldReason(hold, HOLD_REASON);
verify(mockedNodeService, never()).setProperty(hold, PROP_HOLD_REASON, HOLD_REASON);
// node isn't a hold
holdService.setHoldReason(recordFolder, HOLD_REASON);
verify(mockedNodeService, never()).setProperty(hold, PROP_HOLD_REASON, HOLD_REASON);
// set hold reason
holdService.setHoldReason(hold, HOLD_REASON);
verify(mockedNodeService).setProperty(hold, PROP_HOLD_REASON, HOLD_REASON);
}
@Test (expected=AlfrescoRuntimeException.class)
public void deleteHoldNotAHold()
{
holdService.deleteHold(recordFolder);
verify(mockedNodeService, never()).deleteNode(hold);
}
@Test
public void deleteHold()
{
// delete hold
holdService.deleteHold(hold);
verify(mockedNodeService).deleteNode(hold);
// TODO check interactions with policy component!!!
}
@Test (expected=AlfrescoRuntimeException.class)
public void addToHoldNotAHold()
{
holdService.addToHold(recordFolder, recordFolder);
}
@Test (expected=AlfrescoRuntimeException.class)
public void addToHoldNotARecordFolderOrRecord()
{
NodeRef anotherThing = generateNodeRef(TYPE_RECORD_CATEGORY);
holdService.addToHold(hold, anotherThing);
}
@SuppressWarnings("unchecked")
@Test
public void addToHoldNotInHold()
{
holdService.addToHold(hold, recordFolder);
verify(mockedNodeService).addChild(hold, recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService).addAspect(eq(recordFolder), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedNodeService).addAspect(eq(record), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedRecordsManagementAuditService, times(1)).auditEvent(eq(recordFolder), anyString());
holdService.addToHold(hold, record);
verify(mockedNodeService).addChild(hold, record, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService).addAspect(eq(recordFolder), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedNodeService, times(2)).addAspect(eq(record), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedRecordsManagementAuditService, times(1)).auditEvent(eq(record), anyString());
}
@SuppressWarnings("unchecked")
@Test
public void addToHoldAlreadyInHold()
{
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold);
holdService.addToHold(hold, recordFolder);
verify(mockedNodeService, never()).addChild(hold, recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService, never()).addAspect(eq(recordFolder), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedNodeService, never()).addAspect(eq(record), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedRecordsManagementAuditService, never()).auditEvent(eq(recordFolder), anyString());
}
@SuppressWarnings("unchecked")
@Test
public void addToHoldAldeadyFrozen()
{
doReturn(true).when(mockedNodeService).hasAspect(recordFolder, ASPECT_FROZEN);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_FROZEN);
holdService.addToHold(hold, recordFolder);
verify(mockedNodeService, times(1)).addChild(hold, recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService, never()).addAspect(eq(recordFolder), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedNodeService, never()).addAspect(eq(record), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedRecordsManagementAuditService, times(1)).auditEvent(eq(recordFolder), anyString());
}
@SuppressWarnings("unchecked")
@Test
public void addToHolds()
{
// ensure the interaction indicates that a node has the frozen aspect applied if it has
doAnswer(new Answer<Void>()
{
public Void answer(InvocationOnMock invocation)
{
NodeRef nodeRef = (NodeRef)invocation.getArguments()[0];
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, ASPECT_FROZEN);
return null;
}
}).when(mockedNodeService).addAspect(any(NodeRef.class), eq(ASPECT_FROZEN), any(Map.class));
// build a list of holds
List<NodeRef> holds = new ArrayList<NodeRef>(2);
holds.add(hold);
holds.add(hold2);
// add the record folder to both holds
holdService.addToHolds(holds, recordFolder);
// verify the interactions
verify(mockedNodeService, times(1)).addChild(hold, recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService, times(1)).addChild(hold2, recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService, times(1)).addAspect(eq(recordFolder), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedNodeService, times(1)).addAspect(eq(record), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedRecordsManagementAuditService, times(2)).auditEvent(eq(recordFolder), anyString());
}
@Test (expected=AlfrescoRuntimeException.class)
public void removeFromHoldNotAHold()
{
holdService.removeFromHold(recordFolder, recordFolder);
}
@Test
public void removeFromHoldNotInHold()
{
holdService.removeFromHold(hold, recordFolder);
verify(mockedNodeService, never()).removeChild(hold, recordFolder);
verify(mockedNodeService, never()).removeAspect(recordFolder, ASPECT_FROZEN);
verify(mockedNodeService, never()).removeAspect(record, ASPECT_FROZEN);
verify(mockedRecordsManagementAuditService, never()).auditEvent(eq(recordFolder), anyString());
}
@Test
public void removeFromHold()
{
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold);
doReturn(true).when(mockedNodeService).hasAspect(recordFolder, ASPECT_FROZEN);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_FROZEN);
holdService.removeFromHold(hold, recordFolder);
verify(mockedNodeService, times(1)).removeChild(hold, recordFolder);
verify(mockedNodeService, times(1)).removeAspect(recordFolder, ASPECT_FROZEN);
verify(mockedNodeService, times(1)).removeAspect(record, ASPECT_FROZEN);
verify(mockedRecordsManagementAuditService, times(1)).auditEvent(eq(recordFolder), anyString());
}
@Test
public void removeFromHolds()
{
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold);
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold2);
doReturn(true).when(mockedNodeService).hasAspect(recordFolder, ASPECT_FROZEN);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_FROZEN);
// build a list of holds
List<NodeRef> holds = new ArrayList<NodeRef>(2);
holds.add(hold);
holds.add(hold2);
holdService.removeFromHolds(holds, recordFolder);
verify(mockedNodeService, times(1)).removeChild(hold, recordFolder);
verify(mockedNodeService, times(1)).removeChild(hold2, recordFolder);
verify(mockedNodeService, times(1)).removeAspect(recordFolder, ASPECT_FROZEN);
verify(mockedNodeService, times(1)).removeAspect(record, ASPECT_FROZEN);
verify(mockedRecordsManagementAuditService, times(2)).auditEvent(any(NodeRef.class), anyString());
}
@Test
public void removeFromAllHolds()
{
// build a list of holds
List<NodeRef> holds = new ArrayList<NodeRef>(2);
holds.add(hold);
holds.add(hold2);
doAnswer(new Answer<Void>()
{
public Void answer(InvocationOnMock invocation)
{
doReturn(Collections.singletonList(hold2)).when(holdService).heldBy(recordFolder, true);
return null;
}
}).when(mockedNodeService).removeChild(hold, recordFolder);
doAnswer(new Answer<Void>()
{
public Void answer(InvocationOnMock invocation)
{
doReturn(new ArrayList<NodeRef>()).when(holdService).heldBy(recordFolder, true);
return null;
}
}).when(mockedNodeService).removeChild(hold2, recordFolder);
// define interactions
doReturn(holds).when(holdService).heldBy(recordFolder, true);
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold);
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold2);
doReturn(true).when(mockedNodeService).hasAspect(recordFolder, ASPECT_FROZEN);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_FROZEN);
// remove record folder from all holds
holdService.removeFromAllHolds(recordFolder);
// verify interactions
verify(mockedNodeService, times(1)).removeChild(hold, recordFolder);
verify(mockedNodeService, times(1)).removeChild(hold2, recordFolder);
verify(mockedNodeService, times(1)).removeAspect(recordFolder, ASPECT_FROZEN);
verify(mockedNodeService, times(1)).removeAspect(record, ASPECT_FROZEN);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.hold;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Hold service implementation unit test
*
* @author Roy Wetherall
* @since 2.2
*/
public class HoldServiceImplUnitTest extends BaseUnitTest
{
/** test values */
private static final String HOLD_NAME = "holdname";
private static final String HOLD_REASON = "holdreason";
private static final String HOLD_DESCRIPTION = "holddescription";
protected NodeRef holdContainer;
protected NodeRef hold;
protected NodeRef hold2;
@Spy @InjectMocks HoldServiceImpl holdService;
@Before
@Override
public void before() throws Exception
{
super.before();
// setup objects used in mock interactions
holdContainer = generateNodeRef(TYPE_HOLD_CONTAINER);
hold = generateNodeRef(TYPE_HOLD);
hold2 = generateNodeRef(TYPE_HOLD);
// setup interactions
doReturn(holdContainer).when(mockedFilePlanService).getHoldContainer(filePlan);
}
@Test
public void isHold()
{
assertTrue(holdService.isHold(hold));
assertFalse(holdService.isHold(recordFolder));
}
@Test
public void heldByMultipleResults()
{
// setup record folder in multiple holds
List<ChildAssociationRef> holds = new ArrayList<ChildAssociationRef>(2);
holds.add(new ChildAssociationRef(ASSOC_FROZEN_RECORDS, hold, ASSOC_FROZEN_RECORDS, recordFolder, true, 1));
holds.add(new ChildAssociationRef(ASSOC_FROZEN_RECORDS, hold2, ASSOC_FROZEN_RECORDS, recordFolder, true, 2));
doReturn(holds).when(mockedNodeService).getParentAssocs(recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
// check that both holds are found for record folder
List<NodeRef> heldByHolds = holdService.heldBy(recordFolder, true);
assertNotNull(heldByHolds);
assertEquals(2, heldByHolds.size());
assertTrue(holdService.heldBy(recordFolder, false).isEmpty());
// check that both holds are found for record (even thou they are one level deep)
heldByHolds = holdService.heldBy(record, true);
assertNotNull(heldByHolds);
assertEquals(2, heldByHolds.size());
assertTrue(holdService.heldBy(record, false).isEmpty());
}
@Test (expected=AlfrescoRuntimeException.class)
public void getHold()
{
// setup node service interactions
when(mockedNodeService.getChildByName(eq(holdContainer), eq(ContentModel.ASSOC_CONTAINS), anyString())).thenReturn(null)
.thenReturn(hold)
.thenReturn(recordFolder);
// no hold
NodeRef noHold = holdService.getHold(filePlan, "notAHold");
assertNull(noHold);
// found hold
NodeRef someHold = holdService.getHold(filePlan, "someHold");
assertNotNull(someHold);
assertEquals(TYPE_HOLD, mockedNodeService.getType(someHold));
// ensure runtime exception is thrown
holdService.getHold(filePlan, "notHold");
}
@Test (expected=RuntimeException.class)
public void getHeldNotAHold()
{
holdService.getHeld(recordFolder);
}
@Test
public void getHeldNoResults()
{
assertTrue(holdService.getHeld(hold).isEmpty());
}
@Test
public void getHeldWithResults()
{
// setup record folder in hold
List<ChildAssociationRef> holds = new ArrayList<ChildAssociationRef>(1);
holds.add(new ChildAssociationRef(ASSOC_FROZEN_RECORDS, hold, ASSOC_FROZEN_RECORDS, recordFolder, true, 1));
doReturn(holds).when(mockedNodeService).getChildAssocs(hold, ASSOC_FROZEN_RECORDS, RegexQNamePattern.MATCH_ALL);
List<NodeRef> list = holdService.getHeld(hold);
assertEquals(1, list.size());
assertEquals(recordFolder, list.get(0));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void createHold()
{
// setup node service interactions
when(mockedNodeService.createNode(eq(holdContainer), eq(ContentModel.ASSOC_CONTAINS), any(QName.class) , eq(TYPE_HOLD), any(Map.class)))
.thenReturn(new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, holdContainer, generateQName(), hold));
// create hold
NodeRef newHold = holdService.createHold(filePlan, HOLD_NAME, HOLD_REASON, HOLD_DESCRIPTION);
assertNotNull(newHold);
assertEquals(TYPE_HOLD, mockedNodeService.getType(newHold));
assertEquals(hold, newHold);
// check the node service interactions
ArgumentCaptor<Map> propertyMapCaptor = ArgumentCaptor.forClass(Map.class);
ArgumentCaptor<QName> assocNameCaptor = ArgumentCaptor.forClass(QName.class);
verify(mockedNodeService).createNode(eq(holdContainer), eq(ContentModel.ASSOC_CONTAINS), assocNameCaptor.capture() , eq(TYPE_HOLD), propertyMapCaptor.capture());
// check property map
Map<QName, Serializable> propertyMap = (Map<QName, Serializable>)propertyMapCaptor.getValue();
assertNotNull(propertyMap);
assertEquals(3, propertyMap.size());
assertTrue(propertyMap.containsKey(ContentModel.PROP_NAME));
assertEquals(HOLD_NAME, propertyMap.get(ContentModel.PROP_NAME));
assertTrue(propertyMap.containsKey(ContentModel.PROP_DESCRIPTION));
assertEquals(HOLD_DESCRIPTION, propertyMap.get(ContentModel.PROP_DESCRIPTION));
assertTrue(propertyMap.containsKey(PROP_HOLD_REASON));
assertEquals(HOLD_REASON, propertyMap.get(PROP_HOLD_REASON));
// check assoc name
assertNotNull(assocNameCaptor.getValue());
assertEquals(NamespaceService.CONTENT_MODEL_1_0_URI, assocNameCaptor.getValue().getNamespaceURI());
assertEquals(HOLD_NAME, assocNameCaptor.getValue().getLocalName());
}
@Test
public void getHoldReason()
{
// setup node service interactions
when(mockedNodeService.exists(hold))
.thenReturn(false)
.thenReturn(true)
.thenReturn(true)
.thenReturn(true);
when(mockedNodeService.getProperty(eq(hold), eq(PROP_HOLD_REASON)))
.thenReturn(null)
.thenReturn(HOLD_REASON);
// node does not exist
assertNull(holdService.getHoldReason(hold));
// node isn't a hold
assertNull(holdService.getHoldReason(recordFolder));
// hold reason isn't set
assertNull(holdService.getHoldReason(hold));
// hold reason set
assertEquals(HOLD_REASON, holdService.getHoldReason(hold));
}
@Test
public void setHoldReason()
{
// setup node service interactions
when(mockedNodeService.exists(hold))
.thenReturn(false)
.thenReturn(true)
.thenReturn(true);
// node does not exist
holdService.setHoldReason(hold, HOLD_REASON);
verify(mockedNodeService, never()).setProperty(hold, PROP_HOLD_REASON, HOLD_REASON);
// node isn't a hold
holdService.setHoldReason(recordFolder, HOLD_REASON);
verify(mockedNodeService, never()).setProperty(hold, PROP_HOLD_REASON, HOLD_REASON);
// set hold reason
holdService.setHoldReason(hold, HOLD_REASON);
verify(mockedNodeService).setProperty(hold, PROP_HOLD_REASON, HOLD_REASON);
}
@Test (expected=AlfrescoRuntimeException.class)
public void deleteHoldNotAHold()
{
holdService.deleteHold(recordFolder);
verify(mockedNodeService, never()).deleteNode(hold);
}
@Test
public void deleteHold()
{
// delete hold
holdService.deleteHold(hold);
verify(mockedNodeService).deleteNode(hold);
// TODO check interactions with policy component!!!
}
@Test (expected=AlfrescoRuntimeException.class)
public void addToHoldNotAHold()
{
holdService.addToHold(recordFolder, recordFolder);
}
@Test (expected=AlfrescoRuntimeException.class)
public void addToHoldNotARecordFolderOrRecord()
{
NodeRef anotherThing = generateNodeRef(TYPE_RECORD_CATEGORY);
holdService.addToHold(hold, anotherThing);
}
@SuppressWarnings("unchecked")
@Test
public void addToHoldNotInHold()
{
holdService.addToHold(hold, recordFolder);
verify(mockedNodeService).addChild(hold, recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService).addAspect(eq(recordFolder), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedNodeService).addAspect(eq(record), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedRecordsManagementAuditService, times(1)).auditEvent(eq(recordFolder), anyString());
holdService.addToHold(hold, record);
verify(mockedNodeService).addChild(hold, record, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService).addAspect(eq(recordFolder), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedNodeService, times(2)).addAspect(eq(record), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedRecordsManagementAuditService, times(1)).auditEvent(eq(record), anyString());
}
@SuppressWarnings("unchecked")
@Test
public void addToHoldAlreadyInHold()
{
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold);
holdService.addToHold(hold, recordFolder);
verify(mockedNodeService, never()).addChild(hold, recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService, never()).addAspect(eq(recordFolder), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedNodeService, never()).addAspect(eq(record), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedRecordsManagementAuditService, never()).auditEvent(eq(recordFolder), anyString());
}
@SuppressWarnings("unchecked")
@Test
public void addToHoldAldeadyFrozen()
{
doReturn(true).when(mockedNodeService).hasAspect(recordFolder, ASPECT_FROZEN);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_FROZEN);
holdService.addToHold(hold, recordFolder);
verify(mockedNodeService, times(1)).addChild(hold, recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService, never()).addAspect(eq(recordFolder), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedNodeService, never()).addAspect(eq(record), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedRecordsManagementAuditService, times(1)).auditEvent(eq(recordFolder), anyString());
}
@SuppressWarnings("unchecked")
@Test
public void addToHolds()
{
// ensure the interaction indicates that a node has the frozen aspect applied if it has
doAnswer(new Answer<Void>()
{
public Void answer(InvocationOnMock invocation)
{
NodeRef nodeRef = (NodeRef)invocation.getArguments()[0];
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, ASPECT_FROZEN);
return null;
}
}).when(mockedNodeService).addAspect(any(NodeRef.class), eq(ASPECT_FROZEN), any(Map.class));
// build a list of holds
List<NodeRef> holds = new ArrayList<NodeRef>(2);
holds.add(hold);
holds.add(hold2);
// add the record folder to both holds
holdService.addToHolds(holds, recordFolder);
// verify the interactions
verify(mockedNodeService, times(1)).addChild(hold, recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService, times(1)).addChild(hold2, recordFolder, ASSOC_FROZEN_RECORDS, ASSOC_FROZEN_RECORDS);
verify(mockedNodeService, times(1)).addAspect(eq(recordFolder), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedNodeService, times(1)).addAspect(eq(record), eq(ASPECT_FROZEN), any(Map.class));
verify(mockedRecordsManagementAuditService, times(2)).auditEvent(eq(recordFolder), anyString());
}
@Test (expected=AlfrescoRuntimeException.class)
public void removeFromHoldNotAHold()
{
holdService.removeFromHold(recordFolder, recordFolder);
}
@Test
public void removeFromHoldNotInHold()
{
holdService.removeFromHold(hold, recordFolder);
verify(mockedNodeService, never()).removeChild(hold, recordFolder);
verify(mockedNodeService, never()).removeAspect(recordFolder, ASPECT_FROZEN);
verify(mockedNodeService, never()).removeAspect(record, ASPECT_FROZEN);
verify(mockedRecordsManagementAuditService, never()).auditEvent(eq(recordFolder), anyString());
}
@Test
public void removeFromHold()
{
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold);
doReturn(true).when(mockedNodeService).hasAspect(recordFolder, ASPECT_FROZEN);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_FROZEN);
holdService.removeFromHold(hold, recordFolder);
verify(mockedNodeService, times(1)).removeChild(hold, recordFolder);
verify(mockedNodeService, times(1)).removeAspect(recordFolder, ASPECT_FROZEN);
verify(mockedNodeService, times(1)).removeAspect(record, ASPECT_FROZEN);
verify(mockedRecordsManagementAuditService, times(1)).auditEvent(eq(recordFolder), anyString());
}
@Test
public void removeFromHolds()
{
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold);
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold2);
doReturn(true).when(mockedNodeService).hasAspect(recordFolder, ASPECT_FROZEN);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_FROZEN);
// build a list of holds
List<NodeRef> holds = new ArrayList<NodeRef>(2);
holds.add(hold);
holds.add(hold2);
holdService.removeFromHolds(holds, recordFolder);
verify(mockedNodeService, times(1)).removeChild(hold, recordFolder);
verify(mockedNodeService, times(1)).removeChild(hold2, recordFolder);
verify(mockedNodeService, times(1)).removeAspect(recordFolder, ASPECT_FROZEN);
verify(mockedNodeService, times(1)).removeAspect(record, ASPECT_FROZEN);
verify(mockedRecordsManagementAuditService, times(2)).auditEvent(any(NodeRef.class), anyString());
}
@Test
public void removeFromAllHolds()
{
// build a list of holds
List<NodeRef> holds = new ArrayList<NodeRef>(2);
holds.add(hold);
holds.add(hold2);
doAnswer(new Answer<Void>()
{
public Void answer(InvocationOnMock invocation)
{
doReturn(Collections.singletonList(hold2)).when(holdService).heldBy(recordFolder, true);
return null;
}
}).when(mockedNodeService).removeChild(hold, recordFolder);
doAnswer(new Answer<Void>()
{
public Void answer(InvocationOnMock invocation)
{
doReturn(new ArrayList<NodeRef>()).when(holdService).heldBy(recordFolder, true);
return null;
}
}).when(mockedNodeService).removeChild(hold2, recordFolder);
// define interactions
doReturn(holds).when(holdService).heldBy(recordFolder, true);
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold);
doReturn(Collections.singletonList(recordFolder)).when(holdService).getHeld(hold2);
doReturn(true).when(mockedNodeService).hasAspect(recordFolder, ASPECT_FROZEN);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_FROZEN);
// remove record folder from all holds
holdService.removeFromAllHolds(recordFolder);
// verify interactions
verify(mockedNodeService, times(1)).removeChild(hold, recordFolder);
verify(mockedNodeService, times(1)).removeChild(hold2, recordFolder);
verify(mockedNodeService, times(1)).removeAspect(recordFolder, ASPECT_FROZEN);
verify(mockedNodeService, times(1)).removeAspect(record, ASPECT_FROZEN);
}
}

View File

@@ -1,245 +1,245 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.job;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.anyMap;
import static org.mockito.Mockito.contains;
import java.util.Collections;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
/**
* Disposition lifecycle job execution unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class DispositionLifecycleJobExecuterUnitTest extends BaseUnitTest
{
/** disposition actions */
private static final String CUTOFF = "cutoff";
private static final String RETAIN = "retain";
private static final String DESTROY = "destroy";
/** test query snipit */
private static final String QUERY = "\"" + CUTOFF + "\" OR \"" + RETAIN + "\"";
/** mocked result set */
@Mock ResultSet mockedResultSet;
/** disposition lifecycle job executer */
@InjectMocks DispositionLifecycleJobExecuter executer;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Override
@Before
public void before() throws Exception
{
super.before();
// setup data
List<String> dispositionActions = buildList(CUTOFF, RETAIN);
executer.setDispositionActions(dispositionActions);
// setup interactions
doReturn(mockedResultSet).when(mockedSearchService).query(eq(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE), eq(SearchService.LANGUAGE_FTS_ALFRESCO), anyString());
}
/**
* Helper method to verify that the query has been executed and closed
*/
private void verifyQuery()
{
verify(mockedSearchService, times(1)).query(eq(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE), eq(SearchService.LANGUAGE_FTS_ALFRESCO), contains(QUERY));
verify(mockedResultSet, times(1)).getNodeRefs();
verify(mockedResultSet, times(1)).close();
}
/**
* When the are no results in query.
*/
@Test
public void noResultsInQuery()
{
// given
doReturn(Collections.EMPTY_LIST).when(mockedResultSet).getNodeRefs();
// when
executer.executeImpl();
// then
// ensure the query is executed and closed
verifyQuery();
// ensure nothing else happens becuase we have no results
verifyZeroInteractions(mockedNodeService, mockedRecordFolderService, mockedRetryingTransactionHelper);
}
/**
* When the disposition actions do not match those that can be processed automatically.
*/
@SuppressWarnings("unchecked")
@Test
public void dispositionActionDoesNotMatch()
{
// test data
NodeRef node1 = generateNodeRef();
NodeRef node2 = generateNodeRef();
List<NodeRef> nodeRefs = buildList(node1, node2);
// given
doReturn(nodeRefs).when(mockedResultSet).getNodeRefs();
doReturn(DESTROY).when(mockedNodeService).getProperty(node1, RecordsManagementModel.PROP_DISPOSITION_ACTION);
doReturn(DESTROY).when(mockedNodeService).getProperty(node2, RecordsManagementModel.PROP_DISPOSITION_ACTION);
// when
executer.executeImpl();
// then
// ensure the query is executed and closed
verifyQuery();
// ensure work is executed in transaction for each node processed
verify(mockedNodeService, times(2)).exists(any(NodeRef.class));
verify(mockedRetryingTransactionHelper, times(2)).doInTransaction(any(RetryingTransactionCallback.class));
// ensure each node is process correctly
verify(mockedNodeService, times(1)).getProperty(node1, RecordsManagementModel.PROP_DISPOSITION_ACTION);
verify(mockedNodeService, times(1)).getProperty(node2, RecordsManagementModel.PROP_DISPOSITION_ACTION);
// ensure no more interactions
verifyNoMoreInteractions(mockedNodeService);
verifyZeroInteractions(mockedRecordsManagementActionService);
}
/**
* When a node does not exist
*/
@Test
public void nodeDoesNotExist()
{
// test data
NodeRef node1 = generateNodeRef(null, false);
List<NodeRef> nodeRefs = buildList(node1);
// given
doReturn(nodeRefs).when(mockedResultSet).getNodeRefs();
// when
executer.executeImpl();
// then
// ensure the query is executed and closed
verifyQuery();
// ensure the node exist check is made for the node
verify(mockedNodeService, times(1)).exists(any(NodeRef.class));
// ensure no more interactions
verifyNoMoreInteractions(mockedNodeService);
verifyZeroInteractions(mockedRecordsManagementActionService, mockedRetryingTransactionHelper);
}
/**
* When there are disposition actions eligible for processing
*/
@SuppressWarnings("unchecked")
@Test
public void dispositionActionProcessed()
{
// test data
NodeRef node1 = generateNodeRef();
NodeRef node2 = generateNodeRef();
List<NodeRef> nodeRefs = buildList(node1, node2);
NodeRef parent = generateNodeRef();
ChildAssociationRef parentAssoc = new ChildAssociationRef(ASSOC_NEXT_DISPOSITION_ACTION, parent, generateQName(), generateNodeRef());
// given
doReturn(nodeRefs).when(mockedResultSet).getNodeRefs();
doReturn(CUTOFF).when(mockedNodeService).getProperty(node1, RecordsManagementModel.PROP_DISPOSITION_ACTION);
doReturn(RETAIN).when(mockedNodeService).getProperty(node2, RecordsManagementModel.PROP_DISPOSITION_ACTION);
doReturn(parentAssoc).when(mockedNodeService).getPrimaryParent(any(NodeRef.class));
// when
executer.executeImpl();
// then
// ensure the query is executed and closed
verifyQuery();
// ensure work is executed in transaction for each node processed
verify(mockedNodeService, times(2)).exists(any(NodeRef.class));
verify(mockedRetryingTransactionHelper, times(2)).doInTransaction(any(RetryingTransactionCallback.class));
// ensure each node is process correctly
// node1
verify(mockedNodeService, times(1)).getProperty(node1, RecordsManagementModel.PROP_DISPOSITION_ACTION);
verify(mockedNodeService, times(1)).getPrimaryParent(node1);
verify(mockedRecordsManagementActionService, times(1)).executeRecordsManagementAction(eq(parent), eq(CUTOFF), anyMap());
// node2
verify(mockedNodeService, times(1)).getProperty(node2, RecordsManagementModel.PROP_DISPOSITION_ACTION);
verify(mockedNodeService, times(1)).getPrimaryParent(node2);
verify(mockedRecordsManagementActionService, times(1)).executeRecordsManagementAction(eq(parent), eq(RETAIN), anyMap());
// ensure no more interactions
verifyNoMoreInteractions(mockedNodeService, mockedRecordsManagementActionService);
}
/**
* Brittle unit test that simply checks the generated query is an exact string when the supplied disposition actions
* are "CUTOFF" and "RETAIN" (see {@link #before}).
*/
@Test
public void testGetQuery()
{
String actual = executer.getQuery();
String expected = "TYPE:\"rma:dispositionAction\" + (@rma\\:dispositionAction:(\"cutoff\" OR \"retain\")) AND ISUNSET:\"rma:dispositionActionCompletedAt\" AND ( @rma\\:dispositionEventsEligible:true OR @rma\\:dispositionAsOf:[MIN TO NOW] ) ";
assertEquals(expected, actual);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.job;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.anyMap;
import static org.mockito.Mockito.contains;
import java.util.Collections;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
/**
* Disposition lifecycle job execution unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class DispositionLifecycleJobExecuterUnitTest extends BaseUnitTest
{
/** disposition actions */
private static final String CUTOFF = "cutoff";
private static final String RETAIN = "retain";
private static final String DESTROY = "destroy";
/** test query snipit */
private static final String QUERY = "\"" + CUTOFF + "\" OR \"" + RETAIN + "\"";
/** mocked result set */
@Mock ResultSet mockedResultSet;
/** disposition lifecycle job executer */
@InjectMocks DispositionLifecycleJobExecuter executer;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Override
@Before
public void before() throws Exception
{
super.before();
// setup data
List<String> dispositionActions = buildList(CUTOFF, RETAIN);
executer.setDispositionActions(dispositionActions);
// setup interactions
doReturn(mockedResultSet).when(mockedSearchService).query(eq(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE), eq(SearchService.LANGUAGE_FTS_ALFRESCO), anyString());
}
/**
* Helper method to verify that the query has been executed and closed
*/
private void verifyQuery()
{
verify(mockedSearchService, times(1)).query(eq(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE), eq(SearchService.LANGUAGE_FTS_ALFRESCO), contains(QUERY));
verify(mockedResultSet, times(1)).getNodeRefs();
verify(mockedResultSet, times(1)).close();
}
/**
* When the are no results in query.
*/
@Test
public void noResultsInQuery()
{
// given
doReturn(Collections.EMPTY_LIST).when(mockedResultSet).getNodeRefs();
// when
executer.executeImpl();
// then
// ensure the query is executed and closed
verifyQuery();
// ensure nothing else happens becuase we have no results
verifyZeroInteractions(mockedNodeService, mockedRecordFolderService, mockedRetryingTransactionHelper);
}
/**
* When the disposition actions do not match those that can be processed automatically.
*/
@SuppressWarnings("unchecked")
@Test
public void dispositionActionDoesNotMatch()
{
// test data
NodeRef node1 = generateNodeRef();
NodeRef node2 = generateNodeRef();
List<NodeRef> nodeRefs = buildList(node1, node2);
// given
doReturn(nodeRefs).when(mockedResultSet).getNodeRefs();
doReturn(DESTROY).when(mockedNodeService).getProperty(node1, RecordsManagementModel.PROP_DISPOSITION_ACTION);
doReturn(DESTROY).when(mockedNodeService).getProperty(node2, RecordsManagementModel.PROP_DISPOSITION_ACTION);
// when
executer.executeImpl();
// then
// ensure the query is executed and closed
verifyQuery();
// ensure work is executed in transaction for each node processed
verify(mockedNodeService, times(2)).exists(any(NodeRef.class));
verify(mockedRetryingTransactionHelper, times(2)).doInTransaction(any(RetryingTransactionCallback.class));
// ensure each node is process correctly
verify(mockedNodeService, times(1)).getProperty(node1, RecordsManagementModel.PROP_DISPOSITION_ACTION);
verify(mockedNodeService, times(1)).getProperty(node2, RecordsManagementModel.PROP_DISPOSITION_ACTION);
// ensure no more interactions
verifyNoMoreInteractions(mockedNodeService);
verifyZeroInteractions(mockedRecordsManagementActionService);
}
/**
* When a node does not exist
*/
@Test
public void nodeDoesNotExist()
{
// test data
NodeRef node1 = generateNodeRef(null, false);
List<NodeRef> nodeRefs = buildList(node1);
// given
doReturn(nodeRefs).when(mockedResultSet).getNodeRefs();
// when
executer.executeImpl();
// then
// ensure the query is executed and closed
verifyQuery();
// ensure the node exist check is made for the node
verify(mockedNodeService, times(1)).exists(any(NodeRef.class));
// ensure no more interactions
verifyNoMoreInteractions(mockedNodeService);
verifyZeroInteractions(mockedRecordsManagementActionService, mockedRetryingTransactionHelper);
}
/**
* When there are disposition actions eligible for processing
*/
@SuppressWarnings("unchecked")
@Test
public void dispositionActionProcessed()
{
// test data
NodeRef node1 = generateNodeRef();
NodeRef node2 = generateNodeRef();
List<NodeRef> nodeRefs = buildList(node1, node2);
NodeRef parent = generateNodeRef();
ChildAssociationRef parentAssoc = new ChildAssociationRef(ASSOC_NEXT_DISPOSITION_ACTION, parent, generateQName(), generateNodeRef());
// given
doReturn(nodeRefs).when(mockedResultSet).getNodeRefs();
doReturn(CUTOFF).when(mockedNodeService).getProperty(node1, RecordsManagementModel.PROP_DISPOSITION_ACTION);
doReturn(RETAIN).when(mockedNodeService).getProperty(node2, RecordsManagementModel.PROP_DISPOSITION_ACTION);
doReturn(parentAssoc).when(mockedNodeService).getPrimaryParent(any(NodeRef.class));
// when
executer.executeImpl();
// then
// ensure the query is executed and closed
verifyQuery();
// ensure work is executed in transaction for each node processed
verify(mockedNodeService, times(2)).exists(any(NodeRef.class));
verify(mockedRetryingTransactionHelper, times(2)).doInTransaction(any(RetryingTransactionCallback.class));
// ensure each node is process correctly
// node1
verify(mockedNodeService, times(1)).getProperty(node1, RecordsManagementModel.PROP_DISPOSITION_ACTION);
verify(mockedNodeService, times(1)).getPrimaryParent(node1);
verify(mockedRecordsManagementActionService, times(1)).executeRecordsManagementAction(eq(parent), eq(CUTOFF), anyMap());
// node2
verify(mockedNodeService, times(1)).getProperty(node2, RecordsManagementModel.PROP_DISPOSITION_ACTION);
verify(mockedNodeService, times(1)).getPrimaryParent(node2);
verify(mockedRecordsManagementActionService, times(1)).executeRecordsManagementAction(eq(parent), eq(RETAIN), anyMap());
// ensure no more interactions
verifyNoMoreInteractions(mockedNodeService, mockedRecordsManagementActionService);
}
/**
* Brittle unit test that simply checks the generated query is an exact string when the supplied disposition actions
* are "CUTOFF" and "RETAIN" (see {@link #before}).
*/
@Test
public void testGetQuery()
{
String actual = executer.getQuery();
String expected = "TYPE:\"rma:dispositionAction\" + (@rma\\:dispositionAction:(\"cutoff\" OR \"retain\")) AND ISUNSET:\"rma:dispositionActionCompletedAt\" AND ( @rma\\:dispositionEventsEligible:true OR @rma\\:dispositionAsOf:[MIN TO NOW] ) ";
assertEquals(expected, actual);
}
}

View File

@@ -1,107 +1,107 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.jscript.app.evaluator;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanComponentKind;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
/**
* Freeze evaluator unit test.
*
* @author Roy Wetherall
*/
public class FrozenEvaluatorUnitTest extends BaseUnitTest
{
@Mock(name="kinds") Set<FilePlanComponentKind> mockedKinds;
@Spy @InjectMocks FrozenEvaluator evaluator;
@Before
@Override
public void before() throws Exception
{
super.before();
// setup interactions
doReturn(false).when(mockedKinds).contains(FilePlanComponentKind.RECORD_CATEGORY);
doReturn(true).when(mockedKinds).contains(FilePlanComponentKind.RECORD_FOLDER);
doReturn(true).when(mockedKinds).contains(FilePlanComponentKind.RECORD);
}
@Test
public void isNotRecordOrRecordFolder()
{
// setup interactions
NodeRef nodeRef = generateNodeRef(TYPE_RECORD_CATEGORY);
doReturn(FilePlanComponentKind.RECORD_CATEGORY).when(mockedFilePlanService).getFilePlanComponentKind(nodeRef);
// evaluate
boolean result = evaluator.evaluate(filePlanComponent);
assertFalse(result);
// verify interactions
verify(mockedHoldService, never()).heldBy(filePlanComponent, true);
}
@Test
public void isNotHeld()
{
// setup interactions
doReturn(FilePlanComponentKind.RECORD).when(mockedFilePlanService).getFilePlanComponentKind(record);
doReturn(Collections.EMPTY_LIST).when(mockedHoldService).heldBy(record, true);
// evaluate
boolean result = evaluator.evaluate(record);
assertFalse(result);
// verify interactions
verify(mockedHoldService, times(1)).heldBy(record, true);
}
@Test
public void isHeldByAtLeastOne()
{
// setup interactions
doReturn(FilePlanComponentKind.RECORD).when(mockedFilePlanService).getFilePlanComponentKind(record);
doReturn(Collections.singletonList(generateNodeRef(TYPE_HOLD))).when(mockedHoldService).heldBy(record, true);
// evaluate
boolean result = evaluator.evaluate(record);
assertTrue(result);
// verify interactions
verify(mockedHoldService, times(1)).heldBy(record, true);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.jscript.app.evaluator;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanComponentKind;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
/**
* Freeze evaluator unit test.
*
* @author Roy Wetherall
*/
public class FrozenEvaluatorUnitTest extends BaseUnitTest
{
@Mock(name="kinds") Set<FilePlanComponentKind> mockedKinds;
@Spy @InjectMocks FrozenEvaluator evaluator;
@Before
@Override
public void before() throws Exception
{
super.before();
// setup interactions
doReturn(false).when(mockedKinds).contains(FilePlanComponentKind.RECORD_CATEGORY);
doReturn(true).when(mockedKinds).contains(FilePlanComponentKind.RECORD_FOLDER);
doReturn(true).when(mockedKinds).contains(FilePlanComponentKind.RECORD);
}
@Test
public void isNotRecordOrRecordFolder()
{
// setup interactions
NodeRef nodeRef = generateNodeRef(TYPE_RECORD_CATEGORY);
doReturn(FilePlanComponentKind.RECORD_CATEGORY).when(mockedFilePlanService).getFilePlanComponentKind(nodeRef);
// evaluate
boolean result = evaluator.evaluate(filePlanComponent);
assertFalse(result);
// verify interactions
verify(mockedHoldService, never()).heldBy(filePlanComponent, true);
}
@Test
public void isNotHeld()
{
// setup interactions
doReturn(FilePlanComponentKind.RECORD).when(mockedFilePlanService).getFilePlanComponentKind(record);
doReturn(Collections.EMPTY_LIST).when(mockedHoldService).heldBy(record, true);
// evaluate
boolean result = evaluator.evaluate(record);
assertFalse(result);
// verify interactions
verify(mockedHoldService, times(1)).heldBy(record, true);
}
@Test
public void isHeldByAtLeastOne()
{
// setup interactions
doReturn(FilePlanComponentKind.RECORD).when(mockedFilePlanService).getFilePlanComponentKind(record);
doReturn(Collections.singletonList(generateNodeRef(TYPE_HOLD))).when(mockedHoldService).heldBy(record, true);
// evaluate
boolean result = evaluator.evaluate(record);
assertTrue(result);
// verify interactions
verify(mockedHoldService, times(1)).heldBy(record, true);
}
}

View File

@@ -1,171 +1,171 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.jscript.app.evaluator;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
/**
* Transfer evaluator unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class TransferEvaluatorUnitTest extends BaseUnitTest
{
private NodeRef transfer;
@Spy @InjectMocks TransferEvaluator transferEvaluator;
@Override
public void before() throws Exception
{
super.before();
// setup node references
transfer = generateNodeRef(TYPE_TRANSFER);
}
private List<ChildAssociationRef> getParentAssocs(NodeRef provided)
{
List<ChildAssociationRef> result = new ArrayList<ChildAssociationRef>(1);
result.add(new ChildAssociationRef(ASSOC_TRANSFERRED, transfer, generateQName(), provided, false, 1));
return result;
}
@Test
public void isNotTransferringRecord()
{
// setup interactions
doReturn(Collections.emptyList()).when(mockedNodeService).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
// evaluate
assertFalse(transferEvaluator.evaluate(record));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, never()).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, times(1)).getRecordFolders(record);
}
@Test
public void isTransferringWhenExpectingAccending()
{
// setup interactions
doReturn(Boolean.FALSE).when(mockedNodeService).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
doReturn(getParentAssocs(record)).when(mockedNodeService).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
transferEvaluator.setTransferAccessionIndicator(true);
// evaluate
assertFalse(transferEvaluator.evaluate(record));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, times(1)).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, never()).getRecordFolders(record);
}
@Test
public void transferringRecord()
{
// setup interactions
doReturn(Boolean.FALSE).when(mockedNodeService).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
doReturn(getParentAssocs(record)).when(mockedNodeService).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
// evaluate
assertTrue(transferEvaluator.evaluate(record));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, times(1)).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, never()).getRecordFolders(record);
}
@Test
public void transferringRecordFolder()
{
// setup interactions
doReturn(Boolean.FALSE).when(mockedNodeService).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
doReturn(getParentAssocs(recordFolder)).when(mockedNodeService).getParentAssocs(recordFolder, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
// evaluate
assertTrue(transferEvaluator.evaluate(recordFolder));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(recordFolder, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, times(1)).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, never()).getRecordFolders(record);
}
@Test
public void transferringRecordWithinRecordFolder()
{
// setup interactions
doReturn(Boolean.FALSE).when(mockedNodeService).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
doReturn(Collections.emptyList()).when(mockedNodeService).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
doReturn(getParentAssocs(recordFolder)).when(mockedNodeService).getParentAssocs(recordFolder, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
// evaluate
assertTrue(transferEvaluator.evaluate(record));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, times(1)).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, times(1)).getRecordFolders(record);
}
@Test
public void accendingRecord()
{
// setup interactions
doReturn(Boolean.TRUE).when(mockedNodeService).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
doReturn(getParentAssocs(record)).when(mockedNodeService).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
transferEvaluator.setTransferAccessionIndicator(true);
// evaluate
assertTrue(transferEvaluator.evaluate(record));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, times(1)).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, never()).getRecordFolders(record);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.jscript.app.evaluator;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
/**
* Transfer evaluator unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class TransferEvaluatorUnitTest extends BaseUnitTest
{
private NodeRef transfer;
@Spy @InjectMocks TransferEvaluator transferEvaluator;
@Override
public void before() throws Exception
{
super.before();
// setup node references
transfer = generateNodeRef(TYPE_TRANSFER);
}
private List<ChildAssociationRef> getParentAssocs(NodeRef provided)
{
List<ChildAssociationRef> result = new ArrayList<ChildAssociationRef>(1);
result.add(new ChildAssociationRef(ASSOC_TRANSFERRED, transfer, generateQName(), provided, false, 1));
return result;
}
@Test
public void isNotTransferringRecord()
{
// setup interactions
doReturn(Collections.emptyList()).when(mockedNodeService).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
// evaluate
assertFalse(transferEvaluator.evaluate(record));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, never()).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, times(1)).getRecordFolders(record);
}
@Test
public void isTransferringWhenExpectingAccending()
{
// setup interactions
doReturn(Boolean.FALSE).when(mockedNodeService).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
doReturn(getParentAssocs(record)).when(mockedNodeService).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
transferEvaluator.setTransferAccessionIndicator(true);
// evaluate
assertFalse(transferEvaluator.evaluate(record));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, times(1)).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, never()).getRecordFolders(record);
}
@Test
public void transferringRecord()
{
// setup interactions
doReturn(Boolean.FALSE).when(mockedNodeService).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
doReturn(getParentAssocs(record)).when(mockedNodeService).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
// evaluate
assertTrue(transferEvaluator.evaluate(record));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, times(1)).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, never()).getRecordFolders(record);
}
@Test
public void transferringRecordFolder()
{
// setup interactions
doReturn(Boolean.FALSE).when(mockedNodeService).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
doReturn(getParentAssocs(recordFolder)).when(mockedNodeService).getParentAssocs(recordFolder, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
// evaluate
assertTrue(transferEvaluator.evaluate(recordFolder));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(recordFolder, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, times(1)).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, never()).getRecordFolders(record);
}
@Test
public void transferringRecordWithinRecordFolder()
{
// setup interactions
doReturn(Boolean.FALSE).when(mockedNodeService).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
doReturn(Collections.emptyList()).when(mockedNodeService).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
doReturn(getParentAssocs(recordFolder)).when(mockedNodeService).getParentAssocs(recordFolder, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
// evaluate
assertTrue(transferEvaluator.evaluate(record));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, times(1)).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, times(1)).getRecordFolders(record);
}
@Test
public void accendingRecord()
{
// setup interactions
doReturn(Boolean.TRUE).when(mockedNodeService).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
doReturn(getParentAssocs(record)).when(mockedNodeService).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
transferEvaluator.setTransferAccessionIndicator(true);
// evaluate
assertTrue(transferEvaluator.evaluate(record));
// verify interactions
verify(mockedNodeService, times(1)).getParentAssocs(record, RecordsManagementModel.ASSOC_TRANSFERRED, RegexQNamePattern.MATCH_ALL);
verify(mockedNodeService, times(1)).getProperty(transfer, RecordsManagementModel.PROP_TRANSFER_ACCESSION_INDICATOR);
verify(mockedRecordFolderService, never()).getRecordFolders(record);
}
}

View File

@@ -1,96 +1,96 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.model.compatibility;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
/**
* Dictionary bootstrap post processor unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class DictionaryBootstrapPostProcessorUnitTest extends BaseUnitTest
{
/** bean id's */
private static final String BEAN_SITESERVICE_BOOTSTRAP = "siteService_dictionaryBootstrap";
private static final String BEAN_RM_DICTIONARY_BOOTSTRAP = "org_alfresco_module_rm_dictionaryBootstrap";
@Mock private ConfigurableListableBeanFactory mockedBeanFactory;
@Mock private BeanDefinition mockedBeanDefinition;
@InjectMocks private DictionaryBootstrapPostProcessor postProcessor;
/**
* given the bean factory does not contain the site service bootstrap bean then ensure that it is
* not added as a dependency
*/
@Test
public void noSiteServiceBootstrapBeanAvailable()
{
// === given ====
doReturn(false).when(mockedBeanFactory).containsBean(BEAN_SITESERVICE_BOOTSTRAP);
// === when ===
postProcessor.postProcessBeanFactory(mockedBeanFactory);
// === then ===
verify(mockedBeanFactory, times(1)).containsBean(BEAN_SITESERVICE_BOOTSTRAP);
verifyNoMoreInteractions(mockedBeanFactory);
verifyZeroInteractions(mockedBeanDefinition);
}
/**
* given that the site service bootstrap bean is contained within the bean factory, ensure that
* it is added as a dependency
*/
@Test
public void siteServiceBootstrapBeanAvailable()
{
// === given ====
doReturn(true).when(mockedBeanFactory).containsBean(BEAN_SITESERVICE_BOOTSTRAP);
doReturn(true).when(mockedBeanFactory).containsBean(BEAN_RM_DICTIONARY_BOOTSTRAP);
doReturn(mockedBeanDefinition).when(mockedBeanFactory).getBeanDefinition(BEAN_RM_DICTIONARY_BOOTSTRAP);
// === when ===
postProcessor.postProcessBeanFactory(mockedBeanFactory);
// === then ===
verify(mockedBeanFactory, times(1)).containsBean(BEAN_SITESERVICE_BOOTSTRAP);
verify(mockedBeanFactory, times(1)).containsBean(BEAN_RM_DICTIONARY_BOOTSTRAP);
verify(mockedBeanFactory, times(1)).getBeanDefinition(BEAN_RM_DICTIONARY_BOOTSTRAP);
verify(mockedBeanDefinition, times(1)).setDependsOn(new String[]{BEAN_SITESERVICE_BOOTSTRAP});
verifyNoMoreInteractions(mockedBeanFactory, mockedBeanDefinition);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.model.compatibility;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
/**
* Dictionary bootstrap post processor unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class DictionaryBootstrapPostProcessorUnitTest extends BaseUnitTest
{
/** bean id's */
private static final String BEAN_SITESERVICE_BOOTSTRAP = "siteService_dictionaryBootstrap";
private static final String BEAN_RM_DICTIONARY_BOOTSTRAP = "org_alfresco_module_rm_dictionaryBootstrap";
@Mock private ConfigurableListableBeanFactory mockedBeanFactory;
@Mock private BeanDefinition mockedBeanDefinition;
@InjectMocks private DictionaryBootstrapPostProcessor postProcessor;
/**
* given the bean factory does not contain the site service bootstrap bean then ensure that it is
* not added as a dependency
*/
@Test
public void noSiteServiceBootstrapBeanAvailable()
{
// === given ====
doReturn(false).when(mockedBeanFactory).containsBean(BEAN_SITESERVICE_BOOTSTRAP);
// === when ===
postProcessor.postProcessBeanFactory(mockedBeanFactory);
// === then ===
verify(mockedBeanFactory, times(1)).containsBean(BEAN_SITESERVICE_BOOTSTRAP);
verifyNoMoreInteractions(mockedBeanFactory);
verifyZeroInteractions(mockedBeanDefinition);
}
/**
* given that the site service bootstrap bean is contained within the bean factory, ensure that
* it is added as a dependency
*/
@Test
public void siteServiceBootstrapBeanAvailable()
{
// === given ====
doReturn(true).when(mockedBeanFactory).containsBean(BEAN_SITESERVICE_BOOTSTRAP);
doReturn(true).when(mockedBeanFactory).containsBean(BEAN_RM_DICTIONARY_BOOTSTRAP);
doReturn(mockedBeanDefinition).when(mockedBeanFactory).getBeanDefinition(BEAN_RM_DICTIONARY_BOOTSTRAP);
// === when ===
postProcessor.postProcessBeanFactory(mockedBeanFactory);
// === then ===
verify(mockedBeanFactory, times(1)).containsBean(BEAN_SITESERVICE_BOOTSTRAP);
verify(mockedBeanFactory, times(1)).containsBean(BEAN_RM_DICTIONARY_BOOTSTRAP);
verify(mockedBeanFactory, times(1)).getBeanDefinition(BEAN_RM_DICTIONARY_BOOTSTRAP);
verify(mockedBeanDefinition, times(1)).setDependsOn(new String[]{BEAN_SITESERVICE_BOOTSTRAP});
verifyNoMoreInteractions(mockedBeanFactory, mockedBeanDefinition);
}
}

View File

@@ -1,127 +1,127 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.patch.v22;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.mock;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.role.Role;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Unit test for remove in-place roles from 'all roles' group patch unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class RMv22RemoveInPlaceRolesFromAllPatchUnitTest extends BaseUnitTest
{
/** test data */
private static final String ALL_ROLES = "allroles";
/** patch */
@InjectMocks private RMv22RemoveInPlaceRolesFromAllPatch patch;
/**
* Given there are no file plans to update then the 'all roles' group should not
* be changed.
*/
@Test
public void noFilePlans()
{
// given
doReturn(Collections.EMPTY_SET).when(mockedFilePlanService).getFilePlans();
// when
patch.applyInternal();
// then
verifyZeroInteractions(mockedAuthorityService);
}
/**
* Given that there is one file plan whose 'all roles' group does not contain the
* in-place roles the 'all roles' groups should not be changed.
*/
@Test
public void rolesDontNeedRemovingFromGroup()
{
// given
doReturn(Collections.singleton(filePlan)).when(mockedFilePlanService).getFilePlans();
doReturn(getMockedRole(FilePlanRoleService.ROLE_EXTENDED_READERS)).when(mockedFilePlanRoleService).getRole(filePlan, FilePlanRoleService.ROLE_EXTENDED_READERS);
doReturn(getMockedRole(FilePlanRoleService.ROLE_EXTENDED_WRITERS)).when(mockedFilePlanRoleService).getRole(filePlan, FilePlanRoleService.ROLE_EXTENDED_WRITERS);
doReturn(ALL_ROLES).when(mockedFilePlanRoleService).getAllRolesContainerGroup(filePlan);
doReturn(Collections.EMPTY_SET).when(mockedAuthorityService).getContainedAuthorities(null, ALL_ROLES, true);
// when
patch.applyInternal();
// then
verify(mockedAuthorityService, times(1)).getContainedAuthorities(null, ALL_ROLES, true);
verifyNoMoreInteractions(mockedAuthorityService);
}
/**
* Given that there is one file plan whose 'all roles' group contains the in-place
* roles then they should be revoved.
*/
@Test
public void removeRolesFromGroup()
{
// given
doReturn(Collections.singleton(filePlan)).when(mockedFilePlanService).getFilePlans();
doReturn(getMockedRole(FilePlanRoleService.ROLE_EXTENDED_READERS)).when(mockedFilePlanRoleService).getRole(filePlan, FilePlanRoleService.ROLE_EXTENDED_READERS);
doReturn(getMockedRole(FilePlanRoleService.ROLE_EXTENDED_WRITERS)).when(mockedFilePlanRoleService).getRole(filePlan, FilePlanRoleService.ROLE_EXTENDED_WRITERS);
doReturn(ALL_ROLES).when(mockedFilePlanRoleService).getAllRolesContainerGroup(filePlan);
Set<String> contains = new HashSet<String>(2);
contains.add(FilePlanRoleService.ROLE_EXTENDED_READERS);
contains.add(FilePlanRoleService.ROLE_EXTENDED_WRITERS);
doReturn(contains).when(mockedAuthorityService).getContainedAuthorities(null, ALL_ROLES, true);
// when
patch.applyInternal();
// then
verify(mockedAuthorityService, times(1)).getContainedAuthorities(null, ALL_ROLES, true);
verify(mockedAuthorityService, times(1)).removeAuthority(ALL_ROLES, FilePlanRoleService.ROLE_EXTENDED_READERS);
verify(mockedAuthorityService, times(1)).removeAuthority(ALL_ROLES, FilePlanRoleService.ROLE_EXTENDED_WRITERS);
verifyNoMoreInteractions(mockedAuthorityService);
}
/**
* Helper method to create a mocked role.
*/
private Role getMockedRole(String name)
{
Role mockedRole = mock(Role.class);
doReturn(name).when(mockedRole).getRoleGroupName();
return mockedRole;
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.patch.v22;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.mock;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.role.Role;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Unit test for remove in-place roles from 'all roles' group patch unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class RMv22RemoveInPlaceRolesFromAllPatchUnitTest extends BaseUnitTest
{
/** test data */
private static final String ALL_ROLES = "allroles";
/** patch */
@InjectMocks private RMv22RemoveInPlaceRolesFromAllPatch patch;
/**
* Given there are no file plans to update then the 'all roles' group should not
* be changed.
*/
@Test
public void noFilePlans()
{
// given
doReturn(Collections.EMPTY_SET).when(mockedFilePlanService).getFilePlans();
// when
patch.applyInternal();
// then
verifyZeroInteractions(mockedAuthorityService);
}
/**
* Given that there is one file plan whose 'all roles' group does not contain the
* in-place roles the 'all roles' groups should not be changed.
*/
@Test
public void rolesDontNeedRemovingFromGroup()
{
// given
doReturn(Collections.singleton(filePlan)).when(mockedFilePlanService).getFilePlans();
doReturn(getMockedRole(FilePlanRoleService.ROLE_EXTENDED_READERS)).when(mockedFilePlanRoleService).getRole(filePlan, FilePlanRoleService.ROLE_EXTENDED_READERS);
doReturn(getMockedRole(FilePlanRoleService.ROLE_EXTENDED_WRITERS)).when(mockedFilePlanRoleService).getRole(filePlan, FilePlanRoleService.ROLE_EXTENDED_WRITERS);
doReturn(ALL_ROLES).when(mockedFilePlanRoleService).getAllRolesContainerGroup(filePlan);
doReturn(Collections.EMPTY_SET).when(mockedAuthorityService).getContainedAuthorities(null, ALL_ROLES, true);
// when
patch.applyInternal();
// then
verify(mockedAuthorityService, times(1)).getContainedAuthorities(null, ALL_ROLES, true);
verifyNoMoreInteractions(mockedAuthorityService);
}
/**
* Given that there is one file plan whose 'all roles' group contains the in-place
* roles then they should be revoved.
*/
@Test
public void removeRolesFromGroup()
{
// given
doReturn(Collections.singleton(filePlan)).when(mockedFilePlanService).getFilePlans();
doReturn(getMockedRole(FilePlanRoleService.ROLE_EXTENDED_READERS)).when(mockedFilePlanRoleService).getRole(filePlan, FilePlanRoleService.ROLE_EXTENDED_READERS);
doReturn(getMockedRole(FilePlanRoleService.ROLE_EXTENDED_WRITERS)).when(mockedFilePlanRoleService).getRole(filePlan, FilePlanRoleService.ROLE_EXTENDED_WRITERS);
doReturn(ALL_ROLES).when(mockedFilePlanRoleService).getAllRolesContainerGroup(filePlan);
Set<String> contains = new HashSet<String>(2);
contains.add(FilePlanRoleService.ROLE_EXTENDED_READERS);
contains.add(FilePlanRoleService.ROLE_EXTENDED_WRITERS);
doReturn(contains).when(mockedAuthorityService).getContainedAuthorities(null, ALL_ROLES, true);
// when
patch.applyInternal();
// then
verify(mockedAuthorityService, times(1)).getContainedAuthorities(null, ALL_ROLES, true);
verify(mockedAuthorityService, times(1)).removeAuthority(ALL_ROLES, FilePlanRoleService.ROLE_EXTENDED_READERS);
verify(mockedAuthorityService, times(1)).removeAuthority(ALL_ROLES, FilePlanRoleService.ROLE_EXTENDED_WRITERS);
verifyNoMoreInteractions(mockedAuthorityService);
}
/**
* Helper method to create a mocked role.
*/
private Role getMockedRole(String name)
{
Role mockedRole = mock(Role.class);
doReturn(name).when(mockedRole).getRoleGroupName();
return mockedRole;
}
}

View File

@@ -1,62 +1,62 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.record;
import static org.mockito.Mockito.verify;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.namespace.QName;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Unit test for RecordMetadataBootstrap
*
* @author Roy Wetherall
* @since 2.2
*/
public class RecordMetadataBootstrapUnitTest extends BaseUnitTest
{
@InjectMocks private RecordMetadataBootstrap bootstrap;
/**
* Test init method to ensure set map will register correctly with record service.
*/
@Test
public void testInit()
{
// create and set map
Map<String, String> map = new HashMap<String, String>(2);
map.put("rma:test1", "rma:filePlan");
map.put("rma:test2", "rma:filePlan");
bootstrap.setRecordMetadataAspects(map);
// call init
bootstrap.init();
// verify that the metedata aspects where registered
QName test1 = QName.createQName(RM_URI, "test1");
QName test2 = QName.createQName(RM_URI, "test2");
verify(mockedRecordService).registerRecordMetadataAspect(test1, TYPE_FILE_PLAN);
verify(mockedRecordService).registerRecordMetadataAspect(test2, TYPE_FILE_PLAN);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.record;
import static org.mockito.Mockito.verify;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.service.namespace.QName;
import org.junit.Test;
import org.mockito.InjectMocks;
/**
* Unit test for RecordMetadataBootstrap
*
* @author Roy Wetherall
* @since 2.2
*/
public class RecordMetadataBootstrapUnitTest extends BaseUnitTest
{
@InjectMocks private RecordMetadataBootstrap bootstrap;
/**
* Test init method to ensure set map will register correctly with record service.
*/
@Test
public void testInit()
{
// create and set map
Map<String, String> map = new HashMap<String, String>(2);
map.put("rma:test1", "rma:filePlan");
map.put("rma:test2", "rma:filePlan");
bootstrap.setRecordMetadataAspects(map);
// call init
bootstrap.init();
// verify that the metedata aspects where registered
QName test1 = QName.createQName(RM_URI, "test1");
QName test2 = QName.createQName(RM_URI, "test2");
verify(mockedRecordService).registerRecordMetadataAspect(test1, TYPE_FILE_PLAN);
verify(mockedRecordService).registerRecordMetadataAspect(test2, TYPE_FILE_PLAN);
}
}

View File

@@ -1,455 +1,455 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.record;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionSchedule;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.policy.Behaviour;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.commons.collections.CollectionUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
/**
* Unit test for RecordServiceImpl
*
* @author Roy Wetherall
* @since 2.2
*/
public class RecordServiceImplUnitTest extends BaseUnitTest
{
private NodeRef nonStandardFilePlanComponent;
private NodeRef nonStandardFilePlan;
private static QName TYPE_MY_FILE_PLAN = generateQName();
private static QName ASPECT_FOR_FILE_PLAN = generateQName();
@Spy @InjectMocks private RecordServiceImpl recordService;
@SuppressWarnings("unchecked")
@Before
@Override
public void before() throws Exception
{
super.before();
nonStandardFilePlanComponent = generateNodeRef(TYPE_RECORD_CATEGORY);
nonStandardFilePlan = generateNodeRef(TYPE_MY_FILE_PLAN);
// set-up node service
when(mockedNodeService.getProperty(nonStandardFilePlanComponent, PROP_ROOT_NODEREF)).thenReturn(nonStandardFilePlan);
// set-up dictionary service
when(mockedDictionaryService.getAllAspects()).thenReturn(CollectionUtils.EMPTY_COLLECTION);
// mock up getting behaviours
when(recordService.getBehaviour(any(String.class))).thenReturn(mock(Behaviour.class));
}
@Test
public void testRegisterRecordMetadataAspect()
{
Map<QName, Set<QName>> map = recordService.getRecordMetadataAspectsMap();
assertTrue(map.isEmpty());
recordService.registerRecordMetadataAspect(ASPECT_FOR_FILE_PLAN, TYPE_FILE_PLAN);
map = recordService.getRecordMetadataAspectsMap();
assertEquals(1, map.size());
assertTrue(map.containsKey(ASPECT_FOR_FILE_PLAN));
Set<QName> types = map.get(ASPECT_FOR_FILE_PLAN);
assertNotNull(types);
assertEquals(1, types.size());
assertTrue(types.contains(TYPE_FILE_PLAN));
}
/**
* Given invalid types
* When linking
* Then exception thrown
*/
@Test
public void linkNonRecord()
{
NodeRef nonRecord = generateNodeRef(TYPE_CONTENT);
NodeRef recordFolder = generateRecordFolder();
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// link
recordService.link(nonRecord, recordFolder);
}
@Test
public void linkNonRecordFolder()
{
NodeRef record = generateRecord();
NodeRef nonRecordFolder = generateNodeRef(TYPE_FOLDER);
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// link
recordService.link(record, nonRecordFolder);
}
/**
* Given that the record is already a child of the record folder
* When I try to link the record to the same record folder
* Then an exception is thrown
*/
@Test
public void linkRecordToRecordFolderFailsIfAlreadyAChild()
{
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
// given that the record is already a child of the record folder
makeChildrenOf(recordFolder, record);
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// link
recordService.link(record, recordFolder);
}
/**
* Given a record that is not a child of a record folder
* When I link the record to the record folder
* Then the record is now linked to the record folder
*/
@Test
public void linkRecordToRecordFolder()
{
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
// given that the record is already a child of the record folder
makeChildrenOf(generateRecordFolder(), record);
// set the name of the record
String name = generateText();
doReturn(name).when(mockedNodeService).getProperty(record, PROP_NAME);
// link
recordService.link(record, recordFolder);
// verify link was created
verify(mockedNodeService, times(1)).addChild(
recordFolder,
record,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name));
}
/**
* Given that the source record has no disposition schedule
* When I link
* Then it is successful
*/
@Test public void linkNoSourceDisposition()
{
// create record and record folder
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
makeChildrenOf(generateRecordFolder(), record);
// set the name of the record
String name = generateText();
doReturn(name).when(mockedNodeService).getProperty(record, PROP_NAME);
// set dispositions
when(mockedDispositionService.getDispositionSchedule(record))
.thenReturn(null);
// link
recordService.link(record, recordFolder);
// verify link was created
verify(mockedNodeService, times(1)).addChild(
recordFolder,
record,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name));
}
/**
* Given that the target record folder has no disposition schedule
* When I link
* Then it is successful
*/
@Test public void linkNoTargetDisposition()
{
// create record and record folder
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
makeChildrenOf(generateRecordFolder(), record);
// set the name of the record
String name = generateText();
doReturn(name).when(mockedNodeService).getProperty(record, PROP_NAME);
// set dispositions
when(mockedDispositionService.getDispositionSchedule(record))
.thenReturn(mock(DispositionSchedule.class));
when(mockedDispositionService.getDispositionSchedule(record))
.thenReturn(null);
// link
recordService.link(record, recordFolder);
// verify link was created
verify(mockedNodeService, times(1)).addChild(
recordFolder,
record,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name));
}
/**
* Given that the source record and target record folder have incompatible disposition schedules
* When I link
* Then I expect a failure
*/
@Test public void linkIncompatibleDispositions()
{
// create record and record folder
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
makeChildrenOf(generateRecordFolder(), record);
// set the name of the record
String name = generateText();
doReturn(name).when(mockedNodeService).getProperty(record, PROP_NAME);
// set dispositions
DispositionSchedule recordDispositionSchedule = mock(DispositionSchedule.class);
when(recordDispositionSchedule.isRecordLevelDisposition())
.thenReturn(true);
when(mockedDispositionService.getDispositionSchedule(record))
.thenReturn(recordDispositionSchedule);
DispositionSchedule recordFolderDispositionSchedule = mock(DispositionSchedule.class);
when(recordFolderDispositionSchedule.isRecordLevelDisposition())
.thenReturn(false);
when(mockedDispositionService.getDispositionSchedule(recordFolder))
.thenReturn(recordFolderDispositionSchedule);
// expect exception
exception.expect(RecordLinkRuntimeException.class);
exception.expectMessage("incompatible disposition schedule");
// link
recordService.link(record, recordFolder);
}
/**
* Given that the source record and target record folder have compatible disposition schedules
* When I link
* Then it is successful
*/
@Test public void linkCompatibleDispositions()
{
// create record and record folder
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
makeChildrenOf(generateRecordFolder(), record);
// set the name of the record
String name = generateText();
doReturn(name).when(mockedNodeService).getProperty(record, PROP_NAME);
// set dispositions
DispositionSchedule recordDispositionSchedule = mock(DispositionSchedule.class);
when(recordDispositionSchedule.isRecordLevelDisposition())
.thenReturn(true);
when(mockedDispositionService.getDispositionSchedule(record))
.thenReturn(recordDispositionSchedule);
DispositionSchedule recordFolderDispositionSchedule = mock(DispositionSchedule.class);
when(recordFolderDispositionSchedule.isRecordLevelDisposition())
.thenReturn(true);
when(mockedDispositionService.getDispositionSchedule(recordFolder))
.thenReturn(recordFolderDispositionSchedule);
// link
recordService.link(record, recordFolder);
// verify link was created
verify(mockedNodeService, times(1)).addChild(
recordFolder,
record,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name));
}
/**
* Given invalid types
* When unlinking
* Then exception thrown
*/
@Test
public void unlinkNonRecord()
{
NodeRef nonRecord = generateNodeRef(TYPE_CONTENT);
NodeRef recordFolder = generateRecordFolder();
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// unlink
recordService.unlink(nonRecord, recordFolder);
}
@Test
public void unlinkNonRecordFolder()
{
NodeRef record = generateRecord();
NodeRef nonRecordFolder = generateNodeRef(TYPE_FOLDER);
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// unlink
recordService.unlink(record, nonRecordFolder);
}
/**
* Given a record folder is a records primary parent
* When I try and unlink the record from that record folder
* Then an exception is thrown
*/
@Test
public void unlinkRecordFromPrimaryRecordFolder()
{
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
// given that the record is already a child of the record folder
makePrimaryParentOf(record, recordFolder);
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// link
recordService.unlink(record, recordFolder);
}
/**
* Given a record that is linked to a record
* And that the record is not the primary parent of the record
* When I unlink the record to the record folder
* Then the record is no longer linked to the record folder
*/
@Test
public void unlinkRecordFromRecordFolder()
{
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
// the records primary parent is another record folder
makePrimaryParentOf(record, generateRecordFolder());
// unlink
recordService.unlink(record, recordFolder);
// verify link was created
verify(mockedNodeService, times(1)).removeChild(recordFolder, record);
}
/**
* Given that a new record is being created
* When the behaviour is triggered
* Then the record is stored for later reference in the transaction
*/
@SuppressWarnings("unchecked")
@Test
public void onCreateChildAssociationNewRecord()
{
// standard content node
NodeRef nodeRef = generateCmContent("test.txt");
ChildAssociationRef assoc = generateChildAssociationRef(generateNodeRef(), nodeRef);
doNothing().when(recordService).file(nodeRef);
// doesn't have no content aspect
when(mockedNodeService.hasAspect(nodeRef, ContentModel.ASPECT_NO_CONTENT))
.thenReturn(false);
Set<Object> values = mock(HashSet.class);
when(mockedTransactionalResourceHelper.getSet(RecordServiceImpl.KEY_NEW_RECORDS))
.thenReturn(values);
// trigger behaviour
recordService.onCreateChildAssociation(assoc, true);
// verify
verify(values, times(1)).add(nodeRef);
}
/**
* Given that an existing record is linked
* When the behaviour is triggered
* Then the record is not stored for later reference in the transaction
*/
@SuppressWarnings("unchecked")
@Test
public void onCreateChildAssociationExistingRecord()
{
// standard content node
NodeRef nodeRef = generateCmContent("test.txt");
ChildAssociationRef assoc = generateChildAssociationRef(generateNodeRef(), nodeRef);
doNothing().when(recordService).file(nodeRef);
// doesn't have no content aspect
when(mockedNodeService.hasAspect(nodeRef, ContentModel.ASPECT_NO_CONTENT))
.thenReturn(false);
Set<Object> values = mock(HashSet.class);
when(mockedTransactionalResourceHelper.getSet(RecordServiceImpl.KEY_NEW_RECORDS))
.thenReturn(values);
// trigger behaviour
recordService.onCreateChildAssociation(assoc, false);
// verify
verify(values, never()).add(nodeRef);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.record;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionSchedule;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.policy.Behaviour;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.commons.collections.CollectionUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
/**
* Unit test for RecordServiceImpl
*
* @author Roy Wetherall
* @since 2.2
*/
public class RecordServiceImplUnitTest extends BaseUnitTest
{
private NodeRef nonStandardFilePlanComponent;
private NodeRef nonStandardFilePlan;
private static QName TYPE_MY_FILE_PLAN = generateQName();
private static QName ASPECT_FOR_FILE_PLAN = generateQName();
@Spy @InjectMocks private RecordServiceImpl recordService;
@SuppressWarnings("unchecked")
@Before
@Override
public void before() throws Exception
{
super.before();
nonStandardFilePlanComponent = generateNodeRef(TYPE_RECORD_CATEGORY);
nonStandardFilePlan = generateNodeRef(TYPE_MY_FILE_PLAN);
// set-up node service
when(mockedNodeService.getProperty(nonStandardFilePlanComponent, PROP_ROOT_NODEREF)).thenReturn(nonStandardFilePlan);
// set-up dictionary service
when(mockedDictionaryService.getAllAspects()).thenReturn(CollectionUtils.EMPTY_COLLECTION);
// mock up getting behaviours
when(recordService.getBehaviour(any(String.class))).thenReturn(mock(Behaviour.class));
}
@Test
public void testRegisterRecordMetadataAspect()
{
Map<QName, Set<QName>> map = recordService.getRecordMetadataAspectsMap();
assertTrue(map.isEmpty());
recordService.registerRecordMetadataAspect(ASPECT_FOR_FILE_PLAN, TYPE_FILE_PLAN);
map = recordService.getRecordMetadataAspectsMap();
assertEquals(1, map.size());
assertTrue(map.containsKey(ASPECT_FOR_FILE_PLAN));
Set<QName> types = map.get(ASPECT_FOR_FILE_PLAN);
assertNotNull(types);
assertEquals(1, types.size());
assertTrue(types.contains(TYPE_FILE_PLAN));
}
/**
* Given invalid types
* When linking
* Then exception thrown
*/
@Test
public void linkNonRecord()
{
NodeRef nonRecord = generateNodeRef(TYPE_CONTENT);
NodeRef recordFolder = generateRecordFolder();
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// link
recordService.link(nonRecord, recordFolder);
}
@Test
public void linkNonRecordFolder()
{
NodeRef record = generateRecord();
NodeRef nonRecordFolder = generateNodeRef(TYPE_FOLDER);
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// link
recordService.link(record, nonRecordFolder);
}
/**
* Given that the record is already a child of the record folder
* When I try to link the record to the same record folder
* Then an exception is thrown
*/
@Test
public void linkRecordToRecordFolderFailsIfAlreadyAChild()
{
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
// given that the record is already a child of the record folder
makeChildrenOf(recordFolder, record);
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// link
recordService.link(record, recordFolder);
}
/**
* Given a record that is not a child of a record folder
* When I link the record to the record folder
* Then the record is now linked to the record folder
*/
@Test
public void linkRecordToRecordFolder()
{
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
// given that the record is already a child of the record folder
makeChildrenOf(generateRecordFolder(), record);
// set the name of the record
String name = generateText();
doReturn(name).when(mockedNodeService).getProperty(record, PROP_NAME);
// link
recordService.link(record, recordFolder);
// verify link was created
verify(mockedNodeService, times(1)).addChild(
recordFolder,
record,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name));
}
/**
* Given that the source record has no disposition schedule
* When I link
* Then it is successful
*/
@Test public void linkNoSourceDisposition()
{
// create record and record folder
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
makeChildrenOf(generateRecordFolder(), record);
// set the name of the record
String name = generateText();
doReturn(name).when(mockedNodeService).getProperty(record, PROP_NAME);
// set dispositions
when(mockedDispositionService.getDispositionSchedule(record))
.thenReturn(null);
// link
recordService.link(record, recordFolder);
// verify link was created
verify(mockedNodeService, times(1)).addChild(
recordFolder,
record,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name));
}
/**
* Given that the target record folder has no disposition schedule
* When I link
* Then it is successful
*/
@Test public void linkNoTargetDisposition()
{
// create record and record folder
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
makeChildrenOf(generateRecordFolder(), record);
// set the name of the record
String name = generateText();
doReturn(name).when(mockedNodeService).getProperty(record, PROP_NAME);
// set dispositions
when(mockedDispositionService.getDispositionSchedule(record))
.thenReturn(mock(DispositionSchedule.class));
when(mockedDispositionService.getDispositionSchedule(record))
.thenReturn(null);
// link
recordService.link(record, recordFolder);
// verify link was created
verify(mockedNodeService, times(1)).addChild(
recordFolder,
record,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name));
}
/**
* Given that the source record and target record folder have incompatible disposition schedules
* When I link
* Then I expect a failure
*/
@Test public void linkIncompatibleDispositions()
{
// create record and record folder
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
makeChildrenOf(generateRecordFolder(), record);
// set the name of the record
String name = generateText();
doReturn(name).when(mockedNodeService).getProperty(record, PROP_NAME);
// set dispositions
DispositionSchedule recordDispositionSchedule = mock(DispositionSchedule.class);
when(recordDispositionSchedule.isRecordLevelDisposition())
.thenReturn(true);
when(mockedDispositionService.getDispositionSchedule(record))
.thenReturn(recordDispositionSchedule);
DispositionSchedule recordFolderDispositionSchedule = mock(DispositionSchedule.class);
when(recordFolderDispositionSchedule.isRecordLevelDisposition())
.thenReturn(false);
when(mockedDispositionService.getDispositionSchedule(recordFolder))
.thenReturn(recordFolderDispositionSchedule);
// expect exception
exception.expect(RecordLinkRuntimeException.class);
exception.expectMessage("incompatible disposition schedule");
// link
recordService.link(record, recordFolder);
}
/**
* Given that the source record and target record folder have compatible disposition schedules
* When I link
* Then it is successful
*/
@Test public void linkCompatibleDispositions()
{
// create record and record folder
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
makeChildrenOf(generateRecordFolder(), record);
// set the name of the record
String name = generateText();
doReturn(name).when(mockedNodeService).getProperty(record, PROP_NAME);
// set dispositions
DispositionSchedule recordDispositionSchedule = mock(DispositionSchedule.class);
when(recordDispositionSchedule.isRecordLevelDisposition())
.thenReturn(true);
when(mockedDispositionService.getDispositionSchedule(record))
.thenReturn(recordDispositionSchedule);
DispositionSchedule recordFolderDispositionSchedule = mock(DispositionSchedule.class);
when(recordFolderDispositionSchedule.isRecordLevelDisposition())
.thenReturn(true);
when(mockedDispositionService.getDispositionSchedule(recordFolder))
.thenReturn(recordFolderDispositionSchedule);
// link
recordService.link(record, recordFolder);
// verify link was created
verify(mockedNodeService, times(1)).addChild(
recordFolder,
record,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name));
}
/**
* Given invalid types
* When unlinking
* Then exception thrown
*/
@Test
public void unlinkNonRecord()
{
NodeRef nonRecord = generateNodeRef(TYPE_CONTENT);
NodeRef recordFolder = generateRecordFolder();
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// unlink
recordService.unlink(nonRecord, recordFolder);
}
@Test
public void unlinkNonRecordFolder()
{
NodeRef record = generateRecord();
NodeRef nonRecordFolder = generateNodeRef(TYPE_FOLDER);
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// unlink
recordService.unlink(record, nonRecordFolder);
}
/**
* Given a record folder is a records primary parent
* When I try and unlink the record from that record folder
* Then an exception is thrown
*/
@Test
public void unlinkRecordFromPrimaryRecordFolder()
{
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
// given that the record is already a child of the record folder
makePrimaryParentOf(record, recordFolder);
// set expected exception
exception.expect(RecordLinkRuntimeException.class);
// link
recordService.unlink(record, recordFolder);
}
/**
* Given a record that is linked to a record
* And that the record is not the primary parent of the record
* When I unlink the record to the record folder
* Then the record is no longer linked to the record folder
*/
@Test
public void unlinkRecordFromRecordFolder()
{
NodeRef record = generateRecord();
NodeRef recordFolder = generateRecordFolder();
// the records primary parent is another record folder
makePrimaryParentOf(record, generateRecordFolder());
// unlink
recordService.unlink(record, recordFolder);
// verify link was created
verify(mockedNodeService, times(1)).removeChild(recordFolder, record);
}
/**
* Given that a new record is being created
* When the behaviour is triggered
* Then the record is stored for later reference in the transaction
*/
@SuppressWarnings("unchecked")
@Test
public void onCreateChildAssociationNewRecord()
{
// standard content node
NodeRef nodeRef = generateCmContent("test.txt");
ChildAssociationRef assoc = generateChildAssociationRef(generateNodeRef(), nodeRef);
doNothing().when(recordService).file(nodeRef);
// doesn't have no content aspect
when(mockedNodeService.hasAspect(nodeRef, ContentModel.ASPECT_NO_CONTENT))
.thenReturn(false);
Set<Object> values = mock(HashSet.class);
when(mockedTransactionalResourceHelper.getSet(RecordServiceImpl.KEY_NEW_RECORDS))
.thenReturn(values);
// trigger behaviour
recordService.onCreateChildAssociation(assoc, true);
// verify
verify(values, times(1)).add(nodeRef);
}
/**
* Given that an existing record is linked
* When the behaviour is triggered
* Then the record is not stored for later reference in the transaction
*/
@SuppressWarnings("unchecked")
@Test
public void onCreateChildAssociationExistingRecord()
{
// standard content node
NodeRef nodeRef = generateCmContent("test.txt");
ChildAssociationRef assoc = generateChildAssociationRef(generateNodeRef(), nodeRef);
doNothing().when(recordService).file(nodeRef);
// doesn't have no content aspect
when(mockedNodeService.hasAspect(nodeRef, ContentModel.ASPECT_NO_CONTENT))
.thenReturn(false);
Set<Object> values = mock(HashSet.class);
when(mockedTransactionalResourceHelper.getSet(RecordServiceImpl.KEY_NEW_RECORDS))
.thenReturn(values);
// trigger behaviour
recordService.onCreateChildAssociation(assoc, false);
// verify
verify(values, never()).add(nodeRef);
}
}

View File

@@ -1,53 +1,53 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.recorded.version.config;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest;
import org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionModel;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* Base test class for the recorded version config tests
*
* @author Tuna Aksoy
* @since 2.3
*/
public abstract class BaseRecordedVersionConfigTest extends BaseWebScriptUnitTest implements RecordableVersionModel
{
/** Recorded version config web script root folder */
protected static final String RECORDED_VERSION_CONFIG_WEBSCRIPT_ROOT = "alfresco/templates/webscripts/org/alfresco/slingshot/documentlibrary/action/";
/** Node ref for test document */
protected NodeRef testdoc;
/** Setup web script parameters */
protected Map<String, String> buildParameters()
{
testdoc = generateCmContent("testdoc.txt");
return buildParameters
(
"store_type", testdoc.getStoreRef().getProtocol(),
"store_id", testdoc.getStoreRef().getIdentifier(),
"id", testdoc.getId()
);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.recorded.version.config;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest;
import org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionModel;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* Base test class for the recorded version config tests
*
* @author Tuna Aksoy
* @since 2.3
*/
public abstract class BaseRecordedVersionConfigTest extends BaseWebScriptUnitTest implements RecordableVersionModel
{
/** Recorded version config web script root folder */
protected static final String RECORDED_VERSION_CONFIG_WEBSCRIPT_ROOT = "alfresco/templates/webscripts/org/alfresco/slingshot/documentlibrary/action/";
/** Node ref for test document */
protected NodeRef testdoc;
/** Setup web script parameters */
protected Map<String, String> buildParameters()
{
testdoc = generateCmContent("testdoc.txt");
return buildParameters
(
"store_type", testdoc.getStoreRef().getProtocol(),
"store_id", testdoc.getStoreRef().getIdentifier(),
"id", testdoc.getId()
);
}
}

View File

@@ -1,127 +1,127 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.recorded.version.config;
import static org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy.ALL;
import static org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy.MAJOR_ONLY;
import static org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy.NONE;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.script.slingshot.RecordedVersionConfigGet;
import org.alfresco.module.org_alfresco_module_rm.script.slingshot.Version;
import org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
/**
* Recorded Version Config REST API GET implementation unit test.
*
* @author Tuna Aksoy
* @since 2.3
*/
public class RecordedVersionConfigGetTest extends BaseRecordedVersionConfigTest
{
/** RecordedVersionConfigGet webscript instance */
protected @InjectMocks RecordedVersionConfigGet webScript;
/**
* @see org.alfresco.module.org_alfresco_module_rm.recorded.version.config.BaseRecordedVersionConfigTest#getWebScript()
*/
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.recorded.version.config.BaseRecordedVersionConfigTest#getWebScriptTemplate()
*/
@Override
protected String getWebScriptTemplate()
{
return RECORDED_VERSION_CONFIG_WEBSCRIPT_ROOT + "recorded-version-config.get.json.ftl";
}
@Test
public void getRecordedVersionConfig() throws Exception
{
// Build parameters
Map<String, String> parameters = buildParameters();
// Test document should not have any recordable version policy set
doReturn(null).when(mockedNodeService).getProperty(testdoc, PROP_RECORDABLE_VERSION_POLICY);
// Setup versions
List<Version> versions = Arrays.asList(
new Version(NONE.toString(), true),
new Version(MAJOR_ONLY.toString(), false),
new Version(ALL.toString(), false));
// Stub getVersions
doReturn(versions).when(mockedRecordableVersionConfigService).getVersions(testdoc);
// Execute web script
JSONObject json = executeJSONWebScript(parameters);
// Do checks
assertNotNull(json);
assertTrue(json.has("data"));
JSONObject data = json.getJSONObject("data");
assertNotNull(data);
assertTrue(data.has("recordableVersions"));
JSONArray recordableVersions = data.getJSONArray("recordableVersions");
assertNotNull(recordableVersions);
assertEquals(recordableVersions.length(), 3);
List<RecordableVersionPolicy> policies = new ArrayList<RecordableVersionPolicy>();
boolean isSelected = false;
int selectedOnce = 0;
for (int i = 0; i < recordableVersions.length(); i++)
{
JSONObject jsonObject = recordableVersions.getJSONObject(i);
String policy = jsonObject.getString("policy");
policies.add(RecordableVersionPolicy.valueOf(policy));
boolean selected = Boolean.valueOf(jsonObject.getString("selected")).booleanValue();
if (selected)
{
isSelected = true;
selectedOnce++;
}
}
assertEquals(policies, Arrays.asList(RecordableVersionPolicy.values()));
assertTrue(isSelected);
assertEquals(selectedOnce, 1);
// Test document should still not have any recordable version policy set
doReturn(null).when(mockedNodeService).getProperty(testdoc, PROP_RECORDABLE_VERSION_POLICY);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.recorded.version.config;
import static org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy.ALL;
import static org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy.MAJOR_ONLY;
import static org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy.NONE;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.script.slingshot.RecordedVersionConfigGet;
import org.alfresco.module.org_alfresco_module_rm.script.slingshot.Version;
import org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
/**
* Recorded Version Config REST API GET implementation unit test.
*
* @author Tuna Aksoy
* @since 2.3
*/
public class RecordedVersionConfigGetTest extends BaseRecordedVersionConfigTest
{
/** RecordedVersionConfigGet webscript instance */
protected @InjectMocks RecordedVersionConfigGet webScript;
/**
* @see org.alfresco.module.org_alfresco_module_rm.recorded.version.config.BaseRecordedVersionConfigTest#getWebScript()
*/
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.recorded.version.config.BaseRecordedVersionConfigTest#getWebScriptTemplate()
*/
@Override
protected String getWebScriptTemplate()
{
return RECORDED_VERSION_CONFIG_WEBSCRIPT_ROOT + "recorded-version-config.get.json.ftl";
}
@Test
public void getRecordedVersionConfig() throws Exception
{
// Build parameters
Map<String, String> parameters = buildParameters();
// Test document should not have any recordable version policy set
doReturn(null).when(mockedNodeService).getProperty(testdoc, PROP_RECORDABLE_VERSION_POLICY);
// Setup versions
List<Version> versions = Arrays.asList(
new Version(NONE.toString(), true),
new Version(MAJOR_ONLY.toString(), false),
new Version(ALL.toString(), false));
// Stub getVersions
doReturn(versions).when(mockedRecordableVersionConfigService).getVersions(testdoc);
// Execute web script
JSONObject json = executeJSONWebScript(parameters);
// Do checks
assertNotNull(json);
assertTrue(json.has("data"));
JSONObject data = json.getJSONObject("data");
assertNotNull(data);
assertTrue(data.has("recordableVersions"));
JSONArray recordableVersions = data.getJSONArray("recordableVersions");
assertNotNull(recordableVersions);
assertEquals(recordableVersions.length(), 3);
List<RecordableVersionPolicy> policies = new ArrayList<RecordableVersionPolicy>();
boolean isSelected = false;
int selectedOnce = 0;
for (int i = 0; i < recordableVersions.length(); i++)
{
JSONObject jsonObject = recordableVersions.getJSONObject(i);
String policy = jsonObject.getString("policy");
policies.add(RecordableVersionPolicy.valueOf(policy));
boolean selected = Boolean.valueOf(jsonObject.getString("selected")).booleanValue();
if (selected)
{
isSelected = true;
selectedOnce++;
}
}
assertEquals(policies, Arrays.asList(RecordableVersionPolicy.values()));
assertTrue(isSelected);
assertEquals(selectedOnce, 1);
// Test document should still not have any recordable version policy set
doReturn(null).when(mockedNodeService).getProperty(testdoc, PROP_RECORDABLE_VERSION_POLICY);
}
}

View File

@@ -1,104 +1,104 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.recorded.version.config;
import static org.alfresco.module.org_alfresco_module_rm.script.slingshot.RecordedVersionConfigPost.RECORDED_VERSION;
import static org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy.ALL;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.testng.Assert.assertEquals;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.script.slingshot.RecordedVersionConfigPost;
import org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy;
import org.json.JSONObject;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
/**
* Recorded Version Config REST API POST implementation unit test.
*
* @author Tuna Aksoy
* @since 2.3
*/
public class RecordedVersionConfigPostTest extends BaseRecordedVersionConfigTest
{
/** RecordedVersionConfigPost webscript instance */
protected @InjectMocks RecordedVersionConfigPost webScript;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScript()
*/
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScriptTemplate()
*/
@Override
protected String getWebScriptTemplate()
{
return RECORDED_VERSION_CONFIG_WEBSCRIPT_ROOT + "recorded-version-config.post.json.ftl";
}
@Test
public void setRecordedVersionConfig() throws Exception
{
// Build the content
String content = buildContent(ALL);
// Build parameters
Map<String, String> parameters = buildParameters();
// Test document should not have any recordable version policy set
doReturn(null).when(mockedNodeService).getProperty(testdoc, PROP_RECORDABLE_VERSION_POLICY);
// execute web script
JSONObject json = executeJSONWebScript(parameters, content);
// Do checks
assertNotNull(json);
assertEquals(json.length(), 0);
// Test document must have recordable version policy "ALL" set
doReturn(ALL).when(mockedNodeService).getProperty(testdoc, PROP_RECORDABLE_VERSION_POLICY);
}
/**
* Helper method to build the content for the POST request
* @param policy The recordable version policy
*
* @return Content for the build request
*/
private String buildContent(RecordableVersionPolicy policy)
{
StringBuilder sb = new StringBuilder();
sb.append("{\"");
sb.append(RECORDED_VERSION);
sb.append("\":\"");
sb.append(policy.toString());
sb.append("\"}");
return sb.toString();
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.recorded.version.config;
import static org.alfresco.module.org_alfresco_module_rm.script.slingshot.RecordedVersionConfigPost.RECORDED_VERSION;
import static org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy.ALL;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.testng.Assert.assertEquals;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.script.slingshot.RecordedVersionConfigPost;
import org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionPolicy;
import org.json.JSONObject;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
/**
* Recorded Version Config REST API POST implementation unit test.
*
* @author Tuna Aksoy
* @since 2.3
*/
public class RecordedVersionConfigPostTest extends BaseRecordedVersionConfigTest
{
/** RecordedVersionConfigPost webscript instance */
protected @InjectMocks RecordedVersionConfigPost webScript;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScript()
*/
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScriptTemplate()
*/
@Override
protected String getWebScriptTemplate()
{
return RECORDED_VERSION_CONFIG_WEBSCRIPT_ROOT + "recorded-version-config.post.json.ftl";
}
@Test
public void setRecordedVersionConfig() throws Exception
{
// Build the content
String content = buildContent(ALL);
// Build parameters
Map<String, String> parameters = buildParameters();
// Test document should not have any recordable version policy set
doReturn(null).when(mockedNodeService).getProperty(testdoc, PROP_RECORDABLE_VERSION_POLICY);
// execute web script
JSONObject json = executeJSONWebScript(parameters, content);
// Do checks
assertNotNull(json);
assertEquals(json.length(), 0);
// Test document must have recordable version policy "ALL" set
doReturn(ALL).when(mockedNodeService).getProperty(testdoc, PROP_RECORDABLE_VERSION_POLICY);
}
/**
* Helper method to build the content for the POST request
* @param policy The recordable version policy
*
* @return Content for the build request
*/
private String buildContent(RecordableVersionPolicy policy)
{
StringBuilder sb = new StringBuilder();
sb.append("{\"");
sb.append(RECORDED_VERSION);
sb.append("\":\"");
sb.append(policy.toString());
sb.append("\"}");
return sb.toString();
}
}

View File

@@ -1,51 +1,51 @@
package org.alfresco.module.org_alfresco_module_rm.script.hold;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* Base hold web script unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public abstract class BaseHoldWebScriptUnitTest extends BaseWebScriptUnitTest
{
/** test holds */
protected NodeRef hold1NodeRef;
protected NodeRef hold2NodeRef;
protected List<NodeRef> holds;
protected List<NodeRef> records;
protected List<NodeRef> recordFolders;
protected List<NodeRef> filePlanComponents;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Override
public void before() throws Exception
{
super.before();
// generate test holds
hold1NodeRef = generateHoldNodeRef("hold1");
hold2NodeRef = generateHoldNodeRef("hold2");
// list of holds
holds = new ArrayList<NodeRef>(2);
Collections.addAll(holds, hold1NodeRef, hold2NodeRef);
// list of records
records = Collections.singletonList(record);
// list of record folders
recordFolders = Collections.singletonList(recordFolder);
// list of file plan components
filePlanComponents = Collections.singletonList(filePlanComponent);
}
}
package org.alfresco.module.org_alfresco_module_rm.script.hold;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest;
import org.alfresco.service.cmr.repository.NodeRef;
/**
* Base hold web script unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public abstract class BaseHoldWebScriptUnitTest extends BaseWebScriptUnitTest
{
/** test holds */
protected NodeRef hold1NodeRef;
protected NodeRef hold2NodeRef;
protected List<NodeRef> holds;
protected List<NodeRef> records;
protected List<NodeRef> recordFolders;
protected List<NodeRef> filePlanComponents;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Override
public void before() throws Exception
{
super.before();
// generate test holds
hold1NodeRef = generateHoldNodeRef("hold1");
hold2NodeRef = generateHoldNodeRef("hold2");
// list of holds
holds = new ArrayList<NodeRef>(2);
Collections.addAll(holds, hold1NodeRef, hold2NodeRef);
// list of records
records = Collections.singletonList(record);
// list of record folders
recordFolders = Collections.singletonList(recordFolder);
// list of file plan components
filePlanComponents = Collections.singletonList(filePlanComponent);
}
}

View File

@@ -1,222 +1,222 @@
package org.alfresco.module.org_alfresco_module_rm.script.hold;
import static org.alfresco.module.org_alfresco_module_rm.test.util.WebScriptExceptionMatcher.badRequest;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.List;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Test;
import org.springframework.extensions.webscripts.WebScriptException;
/**
* Base hold web script with content unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public abstract class BaseHoldWebScriptWithContentUnitTest extends BaseHoldWebScriptUnitTest
{
/**
* Helper method to build JSON content to send to hold webscripts.
*/
protected String buildContent(List<NodeRef> nodeRefs, List<NodeRef> holds)
{
StringBuilder builder = new StringBuilder(255);
builder.append("{");
if (nodeRefs != null)
{
builder.append("'nodeRefs':[");
boolean bFirst = true;
for (NodeRef nodeRef : nodeRefs)
{
if (!bFirst)
{
builder.append(",");
}
else
{
bFirst = false;
}
builder.append("'" + nodeRef.toString() + "'");
}
builder.append("]");
}
if (nodeRefs != null && holds != null)
{
builder.append(",");
}
if (holds != null)
{
builder.append("'holds':[");
boolean bFirst = true;
for (NodeRef hold : holds)
{
if (!bFirst)
{
builder.append(",");
}
else
{
bFirst = false;
}
builder.append("'" + hold.toString() + "'");
}
builder.append("]");
}
builder.append("}");
return builder.toString();
}
/**
* Test for expected exception when invalid JSON sent
*/
@SuppressWarnings("unchecked")
@Test
public void sendInvalidJSON() throws Exception
{
// invalid JSON
String content = "invalid JSON";
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected exception when one of the holds doesn't exist.
*/
@SuppressWarnings("unchecked")
@Test
public void holdDoesNotExist() throws Exception
{
// setup interactions
when(mockedNodeService.exists(eq(hold1NodeRef))).thenReturn(false);
// build content
String content = buildContent(records, holds);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected excpetion when the item being added to the hold
* does not exist.
*/
@SuppressWarnings("unchecked")
@Test
public void nodeRefDoesNotExist() throws Exception
{
// setup interactions
when(mockedNodeService.exists(eq(record))).thenReturn(false);
// build content
String content = buildContent(records, holds);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected exception when hold information is missing from
* sent JSON.
*/
@SuppressWarnings("unchecked")
@Test
public void holdMissingFromContent() throws Exception
{
// build content
String content = buildContent(records, null);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected exception when noderef information is missing
* from send JSON.
*/
@SuppressWarnings("unchecked")
@Test
public void nodeRefMissingFromContent() throws Exception
{
// build content
String content = buildContent(null, holds);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected exception when adding an item to something
* that isn't a hold.
*/
@SuppressWarnings("unchecked")
@Test
public void holdIsNotAHold() throws Exception
{
// build json content to send to server
List<NodeRef> notAHold = Collections.singletonList(recordFolder);
String content = buildContent(records, notAHold);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected exception when adding an item to a hold
* that isn't a record or record folder.
*/
@SuppressWarnings("unchecked")
@Test
public void nodeRefIsNotARecordOrRecordFolder() throws Exception
{
// build json content to send to server
List<NodeRef> notAHold = Collections.singletonList(recordFolder);
String content = buildContent(filePlanComponents, notAHold);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
}
package org.alfresco.module.org_alfresco_module_rm.script.hold;
import static org.alfresco.module.org_alfresco_module_rm.test.util.WebScriptExceptionMatcher.badRequest;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.List;
import org.alfresco.service.cmr.repository.NodeRef;
import org.junit.Test;
import org.springframework.extensions.webscripts.WebScriptException;
/**
* Base hold web script with content unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public abstract class BaseHoldWebScriptWithContentUnitTest extends BaseHoldWebScriptUnitTest
{
/**
* Helper method to build JSON content to send to hold webscripts.
*/
protected String buildContent(List<NodeRef> nodeRefs, List<NodeRef> holds)
{
StringBuilder builder = new StringBuilder(255);
builder.append("{");
if (nodeRefs != null)
{
builder.append("'nodeRefs':[");
boolean bFirst = true;
for (NodeRef nodeRef : nodeRefs)
{
if (!bFirst)
{
builder.append(",");
}
else
{
bFirst = false;
}
builder.append("'" + nodeRef.toString() + "'");
}
builder.append("]");
}
if (nodeRefs != null && holds != null)
{
builder.append(",");
}
if (holds != null)
{
builder.append("'holds':[");
boolean bFirst = true;
for (NodeRef hold : holds)
{
if (!bFirst)
{
builder.append(",");
}
else
{
bFirst = false;
}
builder.append("'" + hold.toString() + "'");
}
builder.append("]");
}
builder.append("}");
return builder.toString();
}
/**
* Test for expected exception when invalid JSON sent
*/
@SuppressWarnings("unchecked")
@Test
public void sendInvalidJSON() throws Exception
{
// invalid JSON
String content = "invalid JSON";
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected exception when one of the holds doesn't exist.
*/
@SuppressWarnings("unchecked")
@Test
public void holdDoesNotExist() throws Exception
{
// setup interactions
when(mockedNodeService.exists(eq(hold1NodeRef))).thenReturn(false);
// build content
String content = buildContent(records, holds);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected excpetion when the item being added to the hold
* does not exist.
*/
@SuppressWarnings("unchecked")
@Test
public void nodeRefDoesNotExist() throws Exception
{
// setup interactions
when(mockedNodeService.exists(eq(record))).thenReturn(false);
// build content
String content = buildContent(records, holds);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected exception when hold information is missing from
* sent JSON.
*/
@SuppressWarnings("unchecked")
@Test
public void holdMissingFromContent() throws Exception
{
// build content
String content = buildContent(records, null);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected exception when noderef information is missing
* from send JSON.
*/
@SuppressWarnings("unchecked")
@Test
public void nodeRefMissingFromContent() throws Exception
{
// build content
String content = buildContent(null, holds);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected exception when adding an item to something
* that isn't a hold.
*/
@SuppressWarnings("unchecked")
@Test
public void holdIsNotAHold() throws Exception
{
// build json content to send to server
List<NodeRef> notAHold = Collections.singletonList(recordFolder);
String content = buildContent(records, notAHold);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
/**
* Test for expected exception when adding an item to a hold
* that isn't a record or record folder.
*/
@SuppressWarnings("unchecked")
@Test
public void nodeRefIsNotARecordOrRecordFolder() throws Exception
{
// build json content to send to server
List<NodeRef> notAHold = Collections.singletonList(recordFolder);
String content = buildContent(filePlanComponents, notAHold);
// expected exception
exception.expect(WebScriptException.class);
exception.expect(badRequest());
// execute web script
executeWebScript(Collections.EMPTY_MAP, content);
}
}

View File

@@ -1,100 +1,100 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.script.hold;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import org.json.JSONObject;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
/**
* Hold ReST API POST implementation unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class HoldPostUnitTest extends BaseHoldWebScriptWithContentUnitTest
{
/** classpath location of ftl template for web script */
private static final String WEBSCRIPT_TEMPLATE = WEBSCRIPT_ROOT_RM + "hold.post.json.ftl";
/** HoldPost webscript instance */
protected @Spy @InjectMocks HoldPost webScript;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScript()
*/
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScriptTemplate()
*/
@Override
protected String getWebScriptTemplate()
{
return WEBSCRIPT_TEMPLATE;
}
/**
* Test that a record can be added to holds.
*/
@SuppressWarnings("unchecked")
@Test
public void addRecordToHolds() throws Exception
{
// build json to send to server
String content = buildContent(records, holds);
// execute web script
JSONObject json = executeJSONWebScript(Collections.EMPTY_MAP, content);
assertNotNull(json);
// verify that the record was added to the holds
verify(mockedHoldService, times(1)).addToHolds(holds, records);
}
/**
* Test that a record folder can be added to holds.
*/
@SuppressWarnings("unchecked")
@Test
public void addRecordFolderToHolds() throws Exception
{
// build json to send to server
String content = buildContent(recordFolders, holds);
// execute web script
JSONObject json = executeJSONWebScript(Collections.EMPTY_MAP, content);
assertNotNull(json);
// verify that the record was added to the holds
verify(mockedHoldService, times(1)).addToHolds(holds, recordFolders);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.script.hold;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import org.json.JSONObject;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
/**
* Hold ReST API POST implementation unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class HoldPostUnitTest extends BaseHoldWebScriptWithContentUnitTest
{
/** classpath location of ftl template for web script */
private static final String WEBSCRIPT_TEMPLATE = WEBSCRIPT_ROOT_RM + "hold.post.json.ftl";
/** HoldPost webscript instance */
protected @Spy @InjectMocks HoldPost webScript;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScript()
*/
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScriptTemplate()
*/
@Override
protected String getWebScriptTemplate()
{
return WEBSCRIPT_TEMPLATE;
}
/**
* Test that a record can be added to holds.
*/
@SuppressWarnings("unchecked")
@Test
public void addRecordToHolds() throws Exception
{
// build json to send to server
String content = buildContent(records, holds);
// execute web script
JSONObject json = executeJSONWebScript(Collections.EMPTY_MAP, content);
assertNotNull(json);
// verify that the record was added to the holds
verify(mockedHoldService, times(1)).addToHolds(holds, records);
}
/**
* Test that a record folder can be added to holds.
*/
@SuppressWarnings("unchecked")
@Test
public void addRecordFolderToHolds() throws Exception
{
// build json to send to server
String content = buildContent(recordFolders, holds);
// execute web script
JSONObject json = executeJSONWebScript(Collections.EMPTY_MAP, content);
assertNotNull(json);
// verify that the record was added to the holds
verify(mockedHoldService, times(1)).addToHolds(holds, recordFolders);
}
}

View File

@@ -1,100 +1,100 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.script.hold;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import org.json.JSONObject;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
/**
* Hold ReST API PUT implementation unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class HoldPutUnitTest extends BaseHoldWebScriptWithContentUnitTest
{
/** classpath location of ftl template for web script */
private static final String WEBSCRIPT_TEMPLATE = WEBSCRIPT_ROOT_RM + "hold.put.json.ftl";
/** HoldPut webscript instance */
protected @Spy @InjectMocks HoldPut webScript;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScript()
*/
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScriptTemplate()
*/
@Override
protected String getWebScriptTemplate()
{
return WEBSCRIPT_TEMPLATE;
}
/**
* Test that a record can be removed from holds.
*/
@SuppressWarnings("unchecked")
@Test
public void removeRecordFromHolds() throws Exception
{
// build json to send to server
String content = buildContent(records, holds);
// execute web script
JSONObject json = executeJSONWebScript(Collections.EMPTY_MAP, content);
assertNotNull(json);
// verify that the record was removed from holds
verify(mockedHoldService, times(1)).removeFromHolds(holds, records);
}
/**
* Test that a record folder can be removed from holds.
*/
@SuppressWarnings("unchecked")
@Test
public void removeRecordFolderFromHolds() throws Exception
{
// build json to send to server
String content = buildContent(recordFolders, holds);
// execute web script
JSONObject json = executeJSONWebScript(Collections.EMPTY_MAP, content);
assertNotNull(json);
// verify that the record was removed from holds
verify(mockedHoldService, times(1)).removeFromHolds(holds, recordFolders);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.script.hold;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import org.json.JSONObject;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
/**
* Hold ReST API PUT implementation unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class HoldPutUnitTest extends BaseHoldWebScriptWithContentUnitTest
{
/** classpath location of ftl template for web script */
private static final String WEBSCRIPT_TEMPLATE = WEBSCRIPT_ROOT_RM + "hold.put.json.ftl";
/** HoldPut webscript instance */
protected @Spy @InjectMocks HoldPut webScript;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScript()
*/
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScriptTemplate()
*/
@Override
protected String getWebScriptTemplate()
{
return WEBSCRIPT_TEMPLATE;
}
/**
* Test that a record can be removed from holds.
*/
@SuppressWarnings("unchecked")
@Test
public void removeRecordFromHolds() throws Exception
{
// build json to send to server
String content = buildContent(records, holds);
// execute web script
JSONObject json = executeJSONWebScript(Collections.EMPTY_MAP, content);
assertNotNull(json);
// verify that the record was removed from holds
verify(mockedHoldService, times(1)).removeFromHolds(holds, records);
}
/**
* Test that a record folder can be removed from holds.
*/
@SuppressWarnings("unchecked")
@Test
public void removeRecordFolderFromHolds() throws Exception
{
// build json to send to server
String content = buildContent(recordFolders, holds);
// execute web script
JSONObject json = executeJSONWebScript(Collections.EMPTY_MAP, content);
assertNotNull(json);
// verify that the record was removed from holds
verify(mockedHoldService, times(1)).removeFromHolds(holds, recordFolders);
}
}

View File

@@ -1,269 +1,269 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.script.hold;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.alfresco.module.org_alfresco_module_rm.test.util.WebScriptExceptionMatcher.fileNotFound;
import java.util.Collections;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.service.cmr.security.AccessStatus;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
import org.springframework.extensions.webscripts.WebScriptException;
/**
* Holds ReST API GET implementation unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class HoldsGetUnitTest extends BaseHoldWebScriptUnitTest
{
/** classpath location of ftl template for web script */
private static final String WEBSCRIPT_TEMPLATE = WEBSCRIPT_ROOT_RM + "holds.get.json.ftl";
/** HoldsGet webscript instance */
protected @Spy @InjectMocks HoldsGet webScript;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScript()
*/
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScriptTemplate()
*/
@Override
protected String getWebScriptTemplate()
{
return WEBSCRIPT_TEMPLATE;
}
/**
* Test the outcome of calling the web script with an invalid file plan
*/
@Test
public void invalidFilePlan() throws Exception
{
// setup web script parameters
Map<String, String> parameters = buildParameters
(
"store_type", filePlan.getStoreRef().getProtocol(),
"store_id", filePlan.getStoreRef().getIdentifier(),
"id", "imadethisup"
);
// setup expected exception
exception.expect(WebScriptException.class);
exception.expect(fileNotFound());
// execute web script
executeWebScript(parameters);
}
/**
* Test the outcome of calling the web script with no file plan specified
* and with no default file plan created.
*/
@SuppressWarnings("unchecked")
@Test
public void defaultFilePlanDoesNotExist() throws Exception
{
// setup expected exception
exception.expect(WebScriptException.class);
exception.expect(fileNotFound());
// execute web script
executeWebScript(Collections.EMPTY_MAP);
}
/**
* Test the successful retrieval of holds defined for a specified file
* plan.
*/
@Test
public void getHoldsForFilePlan() throws Exception
{
// setup interactions
doReturn(holds).when(mockedHoldService).getHolds(filePlan);
// setup web script parameters
Map<String, String> parameters = buildParameters
(
"store_type", filePlan.getStoreRef().getProtocol(),
"store_id", filePlan.getStoreRef().getIdentifier(),
"id", filePlan.getId()
);
// execute web script
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
// check the JSON result
testForBothHolds(json);
}
/**
* Test the retrieval of holds for the default file plan.
*/
@SuppressWarnings("unchecked")
@Test
public void getHoldsForDefaultFilePlan() throws Exception
{
// setup interactions
doReturn(holds).when(mockedHoldService).getHolds(filePlan);
doReturn(filePlan).when(mockedFilePlanService).getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
// execute web script
JSONObject json = executeJSONWebScript(Collections.EMPTY_MAP);
assertNotNull(json);
// check the JSON result
testForBothHolds(json);
}
/**
* Test the retrieval of holds that hold a specified node.
*/
@Test
public void getHoldsThatNodeRefIsHeldBy() throws Exception
{
// setup interactions
doReturn(holds).when(mockedHoldService).heldBy(record, true);
// setup web script parameters
Map<String, String> parameters = buildParameters
(
"store_type", filePlan.getStoreRef().getProtocol(),
"store_id", filePlan.getStoreRef().getIdentifier(),
"id", filePlan.getId(),
"itemNodeRef", record.toString()
);
// execute web script
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
// check the JSON result
testForBothHolds(json);
}
/**
* Test the retrieval of holds that a node is not held in.
*/
@Test
public void getHoldsThatNodeRefIsNotHeldBy() throws Exception
{
// setup interactions
doReturn(holds).when(mockedHoldService).heldBy(record, false);
// setup web script parameters
Map<String, String> parameters = buildParameters
(
"store_type", filePlan.getStoreRef().getProtocol(),
"store_id", filePlan.getStoreRef().getIdentifier(),
"id", filePlan.getId(),
"itemNodeRef", record.toString(),
"includedInHold", "false"
);
// execute web script
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
// check the JSON result
testForBothHolds(json);
}
public void getFileOnlyHolds() throws Exception
{
doReturn(AccessStatus.ALLOWED).when(mockedPermissionService).hasPermission(hold1NodeRef, RMPermissionModel.FILING);
doReturn(AccessStatus.DENIED).when(mockedPermissionService).hasPermission(hold2NodeRef, RMPermissionModel.FILING);
// setup web script parameters
Map<String, String> parameters = buildParameters
(
"store_type", filePlan.getStoreRef().getProtocol(),
"store_id", filePlan.getStoreRef().getIdentifier(),
"id", filePlan.getId(),
"itemNodeRef", record.toString(),
"includedInHold", "false",
"fileOnly", "true"
);
// execute web script
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
// check the JSON result
assertTrue(json.has("data"));
assertTrue(json.getJSONObject("data").has("holds"));
JSONArray jsonHolds = json.getJSONObject("data").getJSONArray("holds");
assertNotNull(jsonHolds);
assertEquals(1, jsonHolds.length());
JSONObject hold1 = jsonHolds.getJSONObject(0);
assertNotNull(hold1);
assertEquals("hold1", hold1.getString("name"));
assertEquals(hold1NodeRef.toString(), hold1.getString("nodeRef"));
}
/**
* Helper method to test JSON object for the presence of both test holds.
*
* @param json json result from web script
*/
private void testForBothHolds(JSONObject json) throws Exception
{
// check the JSON result
assertTrue(json.has("data"));
assertTrue(json.getJSONObject("data").has("holds"));
JSONArray jsonHolds = json.getJSONObject("data").getJSONArray("holds");
assertNotNull(jsonHolds);
assertEquals(2, jsonHolds.length());
JSONObject hold1 = jsonHolds.getJSONObject(0);
assertNotNull(hold1);
assertEquals("hold1", hold1.getString("name"));
assertEquals(hold1NodeRef.toString(), hold1.getString("nodeRef"));
JSONObject hold2 = jsonHolds.getJSONObject(1);
assertNotNull(hold2);
assertEquals("hold2", hold2.getString("name"));
assertEquals(hold2NodeRef.toString(), hold2.getString("nodeRef"));
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.script.hold;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.alfresco.module.org_alfresco_module_rm.test.util.WebScriptExceptionMatcher.fileNotFound;
import java.util.Collections;
import java.util.Map;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.service.cmr.security.AccessStatus;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
import org.springframework.extensions.webscripts.WebScriptException;
/**
* Holds ReST API GET implementation unit test.
*
* @author Roy Wetherall
* @since 2.2
*/
public class HoldsGetUnitTest extends BaseHoldWebScriptUnitTest
{
/** classpath location of ftl template for web script */
private static final String WEBSCRIPT_TEMPLATE = WEBSCRIPT_ROOT_RM + "holds.get.json.ftl";
/** HoldsGet webscript instance */
protected @Spy @InjectMocks HoldsGet webScript;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScript()
*/
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest#getWebScriptTemplate()
*/
@Override
protected String getWebScriptTemplate()
{
return WEBSCRIPT_TEMPLATE;
}
/**
* Test the outcome of calling the web script with an invalid file plan
*/
@Test
public void invalidFilePlan() throws Exception
{
// setup web script parameters
Map<String, String> parameters = buildParameters
(
"store_type", filePlan.getStoreRef().getProtocol(),
"store_id", filePlan.getStoreRef().getIdentifier(),
"id", "imadethisup"
);
// setup expected exception
exception.expect(WebScriptException.class);
exception.expect(fileNotFound());
// execute web script
executeWebScript(parameters);
}
/**
* Test the outcome of calling the web script with no file plan specified
* and with no default file plan created.
*/
@SuppressWarnings("unchecked")
@Test
public void defaultFilePlanDoesNotExist() throws Exception
{
// setup expected exception
exception.expect(WebScriptException.class);
exception.expect(fileNotFound());
// execute web script
executeWebScript(Collections.EMPTY_MAP);
}
/**
* Test the successful retrieval of holds defined for a specified file
* plan.
*/
@Test
public void getHoldsForFilePlan() throws Exception
{
// setup interactions
doReturn(holds).when(mockedHoldService).getHolds(filePlan);
// setup web script parameters
Map<String, String> parameters = buildParameters
(
"store_type", filePlan.getStoreRef().getProtocol(),
"store_id", filePlan.getStoreRef().getIdentifier(),
"id", filePlan.getId()
);
// execute web script
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
// check the JSON result
testForBothHolds(json);
}
/**
* Test the retrieval of holds for the default file plan.
*/
@SuppressWarnings("unchecked")
@Test
public void getHoldsForDefaultFilePlan() throws Exception
{
// setup interactions
doReturn(holds).when(mockedHoldService).getHolds(filePlan);
doReturn(filePlan).when(mockedFilePlanService).getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
// execute web script
JSONObject json = executeJSONWebScript(Collections.EMPTY_MAP);
assertNotNull(json);
// check the JSON result
testForBothHolds(json);
}
/**
* Test the retrieval of holds that hold a specified node.
*/
@Test
public void getHoldsThatNodeRefIsHeldBy() throws Exception
{
// setup interactions
doReturn(holds).when(mockedHoldService).heldBy(record, true);
// setup web script parameters
Map<String, String> parameters = buildParameters
(
"store_type", filePlan.getStoreRef().getProtocol(),
"store_id", filePlan.getStoreRef().getIdentifier(),
"id", filePlan.getId(),
"itemNodeRef", record.toString()
);
// execute web script
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
// check the JSON result
testForBothHolds(json);
}
/**
* Test the retrieval of holds that a node is not held in.
*/
@Test
public void getHoldsThatNodeRefIsNotHeldBy() throws Exception
{
// setup interactions
doReturn(holds).when(mockedHoldService).heldBy(record, false);
// setup web script parameters
Map<String, String> parameters = buildParameters
(
"store_type", filePlan.getStoreRef().getProtocol(),
"store_id", filePlan.getStoreRef().getIdentifier(),
"id", filePlan.getId(),
"itemNodeRef", record.toString(),
"includedInHold", "false"
);
// execute web script
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
// check the JSON result
testForBothHolds(json);
}
public void getFileOnlyHolds() throws Exception
{
doReturn(AccessStatus.ALLOWED).when(mockedPermissionService).hasPermission(hold1NodeRef, RMPermissionModel.FILING);
doReturn(AccessStatus.DENIED).when(mockedPermissionService).hasPermission(hold2NodeRef, RMPermissionModel.FILING);
// setup web script parameters
Map<String, String> parameters = buildParameters
(
"store_type", filePlan.getStoreRef().getProtocol(),
"store_id", filePlan.getStoreRef().getIdentifier(),
"id", filePlan.getId(),
"itemNodeRef", record.toString(),
"includedInHold", "false",
"fileOnly", "true"
);
// execute web script
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
// check the JSON result
assertTrue(json.has("data"));
assertTrue(json.getJSONObject("data").has("holds"));
JSONArray jsonHolds = json.getJSONObject("data").getJSONArray("holds");
assertNotNull(jsonHolds);
assertEquals(1, jsonHolds.length());
JSONObject hold1 = jsonHolds.getJSONObject(0);
assertNotNull(hold1);
assertEquals("hold1", hold1.getString("name"));
assertEquals(hold1NodeRef.toString(), hold1.getString("nodeRef"));
}
/**
* Helper method to test JSON object for the presence of both test holds.
*
* @param json json result from web script
*/
private void testForBothHolds(JSONObject json) throws Exception
{
// check the JSON result
assertTrue(json.has("data"));
assertTrue(json.getJSONObject("data").has("holds"));
JSONArray jsonHolds = json.getJSONObject("data").getJSONArray("holds");
assertNotNull(jsonHolds);
assertEquals(2, jsonHolds.length());
JSONObject hold1 = jsonHolds.getJSONObject(0);
assertNotNull(hold1);
assertEquals("hold1", hold1.getString("name"));
assertEquals(hold1NodeRef.toString(), hold1.getString("nodeRef"));
JSONObject hold2 = jsonHolds.getJSONObject(1);
assertNotNull(hold2);
assertEquals("hold2", hold2.getString("name"));
assertEquals(hold2NodeRef.toString(), hold2.getString("nodeRef"));
}
}

View File

@@ -1,440 +1,440 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.security;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.HashSet;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanComponentKind;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.security.permissions.impl.AccessPermissionImpl;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessPermission;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.OwnableService;
import org.alfresco.service.namespace.QName;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.verification.VerificationMode;
/**
* File plan permission service implementation unit test.
* <p>
* Primarily tests the file plan permission service interaction with the
* permission service.
*
* @author Roy Wetherall
* @since 2.2
*/
public class FilePlanPermissionServiceImplUnitTest extends BaseUnitTest
{
/** test authority */
protected static final String AUTHORITY = "anAuthority";
protected static final String AUTHORITY2 = "anOtherAuthority";
/** fileplan nodes */
protected NodeRef rootRecordCategory;
protected NodeRef recordCategory;
protected NodeRef newRecordFolder;
protected NodeRef newRecord;
/** unfiled nodes */
protected NodeRef unfiledRecordContainer;
protected NodeRef unfiledRecordFolder;
protected NodeRef unfiledRecordFolderChild;
protected NodeRef unfiledRecord;
/** held nodes */
protected NodeRef holdContainer;
protected NodeRef hold;
protected NodeRef heldRecord;
/** file plan permission service implementation */
@Spy @InjectMocks FilePlanPermissionServiceImpl filePlanPermissionService;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Override
public void before() throws Exception
{
super.before();
// initialize node's
unfiledRecordContainer = generateContainerNodeRef(TYPE_UNFILED_RECORD_CONTAINER);
unfiledRecordFolder = generateContainerNodeRef(TYPE_UNFILED_RECORD_FOLDER);
unfiledRecordFolderChild = generateContainerNodeRef(TYPE_UNFILED_RECORD_FOLDER);
unfiledRecord = generateRecord();
holdContainer = generateContainerNodeRef(TYPE_HOLD_CONTAINER);
hold = generateHoldNodeRef("my test hold");
heldRecord = generateRecord();
rootRecordCategory = generateContainerNodeRef(TYPE_RECORD_CATEGORY);
recordCategory = generateContainerNodeRef(TYPE_RECORD_CATEGORY);
newRecordFolder = generateRecordFolder();
newRecord = generateRecord();
// setup parent hierarchy
makePrimaryParentOf(filePlan, generateNodeRef(ContentModel.TYPE_FOLDER));
makePrimaryParentOf(rootRecordCategory, filePlan);
makePrimaryParentOf(recordCategory, rootRecordCategory);
makePrimaryParentOf(newRecordFolder, recordCategory);
makePrimaryParentOf(newRecord, newRecordFolder);
makePrimaryParentOf(unfiledRecordFolder, unfiledRecordContainer);
makePrimaryParentOf(unfiledRecordContainer, filePlan);
makePrimaryParentOf(hold, holdContainer);
makePrimaryParentOf(holdContainer, filePlan);
// setup child hierarchy
makeChildrenOf(filePlan, rootRecordCategory);
makeChildrenOf(rootRecordCategory, recordCategory);
makeChildrenOf(recordCategory, newRecordFolder);
makeChildrenOf(newRecordFolder, newRecord);
makeChildrenOf(unfiledRecordFolder, unfiledRecordFolderChild);
makeChildrenOf(unfiledRecordFolderChild, unfiledRecord);
makeChildrenOf(holdContainer, hold);
makeChildrenOf(hold, heldRecord);
doReturn(FilePlanComponentKind.FILE_PLAN).when(filePlanPermissionService).getFilePlanComponentKind(filePlan);
doReturn(FilePlanComponentKind.RECORD_CATEGORY).when(filePlanPermissionService).getFilePlanComponentKind(rootRecordCategory);
doReturn(FilePlanComponentKind.RECORD_CATEGORY).when(filePlanPermissionService).getFilePlanComponentKind(recordCategory);
doReturn(FilePlanComponentKind.RECORD_FOLDER).when(filePlanPermissionService).getFilePlanComponentKind(newRecordFolder);
doReturn(FilePlanComponentKind.RECORD).when(filePlanPermissionService).getFilePlanComponentKind(newRecord);
doReturn(FilePlanComponentKind.UNFILED_RECORD_FOLDER).when(filePlanPermissionService).getFilePlanComponentKind(unfiledRecordFolder);
doReturn(FilePlanComponentKind.UNFILED_RECORD_CONTAINER).when(filePlanPermissionService).getFilePlanComponentKind(unfiledRecordContainer);
doReturn(FilePlanComponentKind.RECORD).when(filePlanPermissionService).getFilePlanComponentKind(unfiledRecord);
doReturn(FilePlanComponentKind.HOLD_CONTAINER).when(filePlanPermissionService).getFilePlanComponentKind(holdContainer);
doReturn(FilePlanComponentKind.HOLD).when(filePlanPermissionService).getFilePlanComponentKind(hold);
}
/**
* Helper method to generate a container node ref of a perticular type.
*
* @param type type of node reference
* @return {@link NodeRef} node reference that behaves like a container of the type given.
*/
private NodeRef generateContainerNodeRef(QName type)
{
NodeRef nodeRef = generateNodeRef(type);
setupAsFilePlanComponent(nodeRef);
doReturn(true).when(filePlanPermissionService).isFilePlanContainer(nodeRef);
return nodeRef;
}
/**
* Set read permission on unfiled record folder.
*/
@Test
public void setReadPermissionOnUnfiledRecordFolder()
{
// set read permission on unfiled record folder
filePlanPermissionService.setPermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.READ_RECORDS);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.READ_RECORDS, true);
}
/**
* Set filling permission on unfiled record folder
*/
@Test
public void setReadAndFilePermissionOnUnfileRecordFolder()
{
// set read permission on unfiled record folder
filePlanPermissionService.setPermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.FILING);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.FILING, true);
}
/**
* Remove permission from unfiled record folders.
*/
@Test
public void deletePermissionFromUnfiledRecordFolder()
{
// delete read permission from unfiled record folder
filePlanPermissionService.deletePermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.READ_RECORDS);
// verify permission deleted on target node
verify(mockedPermissionService, times(1)).deletePermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.READ_RECORDS);
}
/**
* Set read permission on hold container
*/
@Test
public void setReadPermissionOnHoldContainer()
{
// set read permission on hold
filePlanPermissionService.setPermission(holdContainer, AUTHORITY, RMPermissionModel.READ_RECORDS);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(holdContainer, AUTHORITY, RMPermissionModel.READ_RECORDS, true);
}
/**
* Set filing permission on hold container
*/
@Test
public void setFilingPermissionOnHoldContainer()
{
// set read permission on hold
filePlanPermissionService.setPermission(holdContainer, AUTHORITY, RMPermissionModel.FILING);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(holdContainer, AUTHORITY, RMPermissionModel.FILING, true);
}
/**
* Set read permission on hold.
*/
@Test
public void setReadPermissionOnHold()
{
// set read permission on hold
filePlanPermissionService.setPermission(hold, AUTHORITY, RMPermissionModel.READ_RECORDS);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(hold, AUTHORITY, RMPermissionModel.READ_RECORDS, true);
}
/**
* Set filing permission on hold.
*/
@Test
public void setFilingPermissionOnHold()
{
// set filing permission on hold
filePlanPermissionService.setPermission(hold, AUTHORITY, RMPermissionModel.FILING);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(hold, AUTHORITY, RMPermissionModel.FILING, true);
}
/**
* Helper method to setup permissions on mock objects
*/
private void setupPermissions(NodeRef nodeRef)
{
Set<AccessPermission> perms = new HashSet<AccessPermission>(4);
// setup basic file and read for authorities
perms.add(new AccessPermissionImpl(RMPermissionModel.READ_RECORDS, AccessStatus.ALLOWED, AUTHORITY, 0));
perms.add(new AccessPermissionImpl(RMPermissionModel.FILING, AccessStatus.ALLOWED, AUTHORITY2, 1));
doReturn(perms).when(mockedPermissionService).getAllSetPermissions(nodeRef);
}
/**
* Helper to verify the core permissions have been initialized correctly
*/
private void verifyInitPermissions(NodeRef nodeRef, boolean isInherited)
{
verify(mockedPermissionService).getAllSetPermissions(nodeRef);
verify(mockedPermissionService).setInheritParentPermissions(nodeRef, isInherited);
verify(mockedPermissionService).clearPermission(nodeRef, null);
verify(mockedOwnableService).setOwner(nodeRef, OwnableService.NO_OWNER);
}
/**
* Helper to verify that permissions have been set correctly on the child
*
* @param parent parent node
* @param child child node
* @param read verification mode relating to setting read on the child
* @param filling verification mode relating to setting filling on the child
*/
private void verifyInitPermissions(NodeRef parent, NodeRef child, VerificationMode read, VerificationMode filling, boolean isParentFilePlan, boolean isInherited)
{
// verify the core permissions are set-up correctly
verifyInitPermissions(child, isInherited);
if (isParentFilePlan)
{
// verify the permissions came from the correct parent
verify(mockedPermissionService).getAllSetPermissions(parent);
// verify all the inherited permissions are set correctly (note read are not inherited from fileplan)
verify(mockedPermissionService, filling).setPermission(child, AUTHORITY2, RMPermissionModel.FILING, true);
verify(mockedPermissionService, read).setPermission(child, AUTHORITY, RMPermissionModel.READ_RECORDS, true);
}
}
/**
* Test the initialisation of permissions for a new root category
*/
@Test
public void initPermissionsForNewRootRecordCategory()
{
// setup permissions for file plan
setupPermissions(filePlan);
// setup permissions
filePlanPermissionService.setupRecordCategoryPermissions(rootRecordCategory);
// verify permission init
verifyInitPermissions(filePlan, rootRecordCategory, never(), times(1), true, false);
}
/**
* Test the initialisation of permissions for a new category
*/
@Test
public void initPermissionsForNewRecordCategory()
{
// setup permissions for parent
setupPermissions(rootRecordCategory);
// setup permissions
filePlanPermissionService.setupRecordCategoryPermissions(recordCategory);
// verify permission init
verifyInitPermissions(rootRecordCategory, recordCategory, times(1), times(1), false, true);
}
/**
* Test initialisation new record folder permissions
*/
@Test
public void initPermissionsForNewRecordFolder()
{
// setup permissions for parent
setupPermissions(recordCategory);
// setup permissions
filePlanPermissionService.setupPermissions(recordCategory, newRecordFolder);
// verify permission init
verifyInitPermissions(recordCategory, newRecordFolder, times(1), times(1), false, true);
}
/**
* Test setup of new record permissions
*/
@Test
public void initPermissionsForNewRecord()
{
// setup permissions for parent
setupPermissions(newRecordFolder);
// setup permissions for record
filePlanPermissionService.setupPermissions(newRecordFolder, newRecord);
// verify permission init
verifyInitPermissions(newRecordFolder, newRecord, times(1), times(1), false, true);
}
/**
* Test setup of permissions for new hold container
*/
@Test
public void initPermnissionsForNewHoldContainer()
{
// setup permissions for parent
setupPermissions(filePlan);
// setup permissions for record
filePlanPermissionService.setupPermissions(filePlan, holdContainer);
// verify permissions are set-up correctly
verifyInitPermissions(filePlan, holdContainer, times(1), times(1), false, true);
}
/**
* Test setup of permissions for new hold
*/
@Test
public void initPermissionsForNewHold()
{
// setup permissions for parent
setupPermissions(holdContainer);
// setup permissions for record
filePlanPermissionService.setupPermissions(holdContainer, hold);
// verify permissions are set-up correctly
verifyInitPermissions(holdContainer, hold, never(), times(1), false, false);
}
/**
* Test setup of permissions for new unfiled container
*/
@Test
public void initPermissionsForNewUnfiledContainer()
{
// setup permissions for parent
setupPermissions(filePlan);
// setup permissions for record
filePlanPermissionService.setupPermissions(filePlan, unfiledRecordContainer);
// verify permissions are set-up correctly
verifyInitPermissions(filePlan, unfiledRecordContainer, times(1), times(1), false, false);
}
/**
* Test setup of permissions for new unfiled record folder
*/
@Test
public void initPermissionsForNewUnfiledRecordFolder()
{
// setup permissions for parent
setupPermissions(unfiledRecordContainer);
// setup permissions for record
filePlanPermissionService.setupPermissions(unfiledRecordContainer, unfiledRecordFolder);
// verify permissions are set-up correctly
verifyInitPermissions(unfiledRecordContainer, unfiledRecordFolder, never(), times(1), false, true);
}
/**
* Test setup of permissions for new unfiled record
*/
@Test
public void initPermissionsForNewUnfiledRecord()
{
// setup permissions for parent
setupPermissions(unfiledRecordFolder);
// setup permissions for record
filePlanPermissionService.setupPermissions(unfiledRecordFolder, unfiledRecord);
// verify permission init
verifyInitPermissions(unfiledRecordFolder, unfiledRecord, times(1), times(1), false, true);
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.security;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.HashSet;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.capability.RMPermissionModel;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanComponentKind;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.security.permissions.impl.AccessPermissionImpl;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.security.AccessPermission;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.OwnableService;
import org.alfresco.service.namespace.QName;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.verification.VerificationMode;
/**
* File plan permission service implementation unit test.
* <p>
* Primarily tests the file plan permission service interaction with the
* permission service.
*
* @author Roy Wetherall
* @since 2.2
*/
public class FilePlanPermissionServiceImplUnitTest extends BaseUnitTest
{
/** test authority */
protected static final String AUTHORITY = "anAuthority";
protected static final String AUTHORITY2 = "anOtherAuthority";
/** fileplan nodes */
protected NodeRef rootRecordCategory;
protected NodeRef recordCategory;
protected NodeRef newRecordFolder;
protected NodeRef newRecord;
/** unfiled nodes */
protected NodeRef unfiledRecordContainer;
protected NodeRef unfiledRecordFolder;
protected NodeRef unfiledRecordFolderChild;
protected NodeRef unfiledRecord;
/** held nodes */
protected NodeRef holdContainer;
protected NodeRef hold;
protected NodeRef heldRecord;
/** file plan permission service implementation */
@Spy @InjectMocks FilePlanPermissionServiceImpl filePlanPermissionService;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@Override
public void before() throws Exception
{
super.before();
// initialize node's
unfiledRecordContainer = generateContainerNodeRef(TYPE_UNFILED_RECORD_CONTAINER);
unfiledRecordFolder = generateContainerNodeRef(TYPE_UNFILED_RECORD_FOLDER);
unfiledRecordFolderChild = generateContainerNodeRef(TYPE_UNFILED_RECORD_FOLDER);
unfiledRecord = generateRecord();
holdContainer = generateContainerNodeRef(TYPE_HOLD_CONTAINER);
hold = generateHoldNodeRef("my test hold");
heldRecord = generateRecord();
rootRecordCategory = generateContainerNodeRef(TYPE_RECORD_CATEGORY);
recordCategory = generateContainerNodeRef(TYPE_RECORD_CATEGORY);
newRecordFolder = generateRecordFolder();
newRecord = generateRecord();
// setup parent hierarchy
makePrimaryParentOf(filePlan, generateNodeRef(ContentModel.TYPE_FOLDER));
makePrimaryParentOf(rootRecordCategory, filePlan);
makePrimaryParentOf(recordCategory, rootRecordCategory);
makePrimaryParentOf(newRecordFolder, recordCategory);
makePrimaryParentOf(newRecord, newRecordFolder);
makePrimaryParentOf(unfiledRecordFolder, unfiledRecordContainer);
makePrimaryParentOf(unfiledRecordContainer, filePlan);
makePrimaryParentOf(hold, holdContainer);
makePrimaryParentOf(holdContainer, filePlan);
// setup child hierarchy
makeChildrenOf(filePlan, rootRecordCategory);
makeChildrenOf(rootRecordCategory, recordCategory);
makeChildrenOf(recordCategory, newRecordFolder);
makeChildrenOf(newRecordFolder, newRecord);
makeChildrenOf(unfiledRecordFolder, unfiledRecordFolderChild);
makeChildrenOf(unfiledRecordFolderChild, unfiledRecord);
makeChildrenOf(holdContainer, hold);
makeChildrenOf(hold, heldRecord);
doReturn(FilePlanComponentKind.FILE_PLAN).when(filePlanPermissionService).getFilePlanComponentKind(filePlan);
doReturn(FilePlanComponentKind.RECORD_CATEGORY).when(filePlanPermissionService).getFilePlanComponentKind(rootRecordCategory);
doReturn(FilePlanComponentKind.RECORD_CATEGORY).when(filePlanPermissionService).getFilePlanComponentKind(recordCategory);
doReturn(FilePlanComponentKind.RECORD_FOLDER).when(filePlanPermissionService).getFilePlanComponentKind(newRecordFolder);
doReturn(FilePlanComponentKind.RECORD).when(filePlanPermissionService).getFilePlanComponentKind(newRecord);
doReturn(FilePlanComponentKind.UNFILED_RECORD_FOLDER).when(filePlanPermissionService).getFilePlanComponentKind(unfiledRecordFolder);
doReturn(FilePlanComponentKind.UNFILED_RECORD_CONTAINER).when(filePlanPermissionService).getFilePlanComponentKind(unfiledRecordContainer);
doReturn(FilePlanComponentKind.RECORD).when(filePlanPermissionService).getFilePlanComponentKind(unfiledRecord);
doReturn(FilePlanComponentKind.HOLD_CONTAINER).when(filePlanPermissionService).getFilePlanComponentKind(holdContainer);
doReturn(FilePlanComponentKind.HOLD).when(filePlanPermissionService).getFilePlanComponentKind(hold);
}
/**
* Helper method to generate a container node ref of a perticular type.
*
* @param type type of node reference
* @return {@link NodeRef} node reference that behaves like a container of the type given.
*/
private NodeRef generateContainerNodeRef(QName type)
{
NodeRef nodeRef = generateNodeRef(type);
setupAsFilePlanComponent(nodeRef);
doReturn(true).when(filePlanPermissionService).isFilePlanContainer(nodeRef);
return nodeRef;
}
/**
* Set read permission on unfiled record folder.
*/
@Test
public void setReadPermissionOnUnfiledRecordFolder()
{
// set read permission on unfiled record folder
filePlanPermissionService.setPermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.READ_RECORDS);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.READ_RECORDS, true);
}
/**
* Set filling permission on unfiled record folder
*/
@Test
public void setReadAndFilePermissionOnUnfileRecordFolder()
{
// set read permission on unfiled record folder
filePlanPermissionService.setPermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.FILING);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.FILING, true);
}
/**
* Remove permission from unfiled record folders.
*/
@Test
public void deletePermissionFromUnfiledRecordFolder()
{
// delete read permission from unfiled record folder
filePlanPermissionService.deletePermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.READ_RECORDS);
// verify permission deleted on target node
verify(mockedPermissionService, times(1)).deletePermission(unfiledRecordFolder, AUTHORITY, RMPermissionModel.READ_RECORDS);
}
/**
* Set read permission on hold container
*/
@Test
public void setReadPermissionOnHoldContainer()
{
// set read permission on hold
filePlanPermissionService.setPermission(holdContainer, AUTHORITY, RMPermissionModel.READ_RECORDS);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(holdContainer, AUTHORITY, RMPermissionModel.READ_RECORDS, true);
}
/**
* Set filing permission on hold container
*/
@Test
public void setFilingPermissionOnHoldContainer()
{
// set read permission on hold
filePlanPermissionService.setPermission(holdContainer, AUTHORITY, RMPermissionModel.FILING);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(holdContainer, AUTHORITY, RMPermissionModel.FILING, true);
}
/**
* Set read permission on hold.
*/
@Test
public void setReadPermissionOnHold()
{
// set read permission on hold
filePlanPermissionService.setPermission(hold, AUTHORITY, RMPermissionModel.READ_RECORDS);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(hold, AUTHORITY, RMPermissionModel.READ_RECORDS, true);
}
/**
* Set filing permission on hold.
*/
@Test
public void setFilingPermissionOnHold()
{
// set filing permission on hold
filePlanPermissionService.setPermission(hold, AUTHORITY, RMPermissionModel.FILING);
// verify permission set on target node
verify(mockedPermissionService, times(1)).setPermission(hold, AUTHORITY, RMPermissionModel.FILING, true);
}
/**
* Helper method to setup permissions on mock objects
*/
private void setupPermissions(NodeRef nodeRef)
{
Set<AccessPermission> perms = new HashSet<AccessPermission>(4);
// setup basic file and read for authorities
perms.add(new AccessPermissionImpl(RMPermissionModel.READ_RECORDS, AccessStatus.ALLOWED, AUTHORITY, 0));
perms.add(new AccessPermissionImpl(RMPermissionModel.FILING, AccessStatus.ALLOWED, AUTHORITY2, 1));
doReturn(perms).when(mockedPermissionService).getAllSetPermissions(nodeRef);
}
/**
* Helper to verify the core permissions have been initialized correctly
*/
private void verifyInitPermissions(NodeRef nodeRef, boolean isInherited)
{
verify(mockedPermissionService).getAllSetPermissions(nodeRef);
verify(mockedPermissionService).setInheritParentPermissions(nodeRef, isInherited);
verify(mockedPermissionService).clearPermission(nodeRef, null);
verify(mockedOwnableService).setOwner(nodeRef, OwnableService.NO_OWNER);
}
/**
* Helper to verify that permissions have been set correctly on the child
*
* @param parent parent node
* @param child child node
* @param read verification mode relating to setting read on the child
* @param filling verification mode relating to setting filling on the child
*/
private void verifyInitPermissions(NodeRef parent, NodeRef child, VerificationMode read, VerificationMode filling, boolean isParentFilePlan, boolean isInherited)
{
// verify the core permissions are set-up correctly
verifyInitPermissions(child, isInherited);
if (isParentFilePlan)
{
// verify the permissions came from the correct parent
verify(mockedPermissionService).getAllSetPermissions(parent);
// verify all the inherited permissions are set correctly (note read are not inherited from fileplan)
verify(mockedPermissionService, filling).setPermission(child, AUTHORITY2, RMPermissionModel.FILING, true);
verify(mockedPermissionService, read).setPermission(child, AUTHORITY, RMPermissionModel.READ_RECORDS, true);
}
}
/**
* Test the initialisation of permissions for a new root category
*/
@Test
public void initPermissionsForNewRootRecordCategory()
{
// setup permissions for file plan
setupPermissions(filePlan);
// setup permissions
filePlanPermissionService.setupRecordCategoryPermissions(rootRecordCategory);
// verify permission init
verifyInitPermissions(filePlan, rootRecordCategory, never(), times(1), true, false);
}
/**
* Test the initialisation of permissions for a new category
*/
@Test
public void initPermissionsForNewRecordCategory()
{
// setup permissions for parent
setupPermissions(rootRecordCategory);
// setup permissions
filePlanPermissionService.setupRecordCategoryPermissions(recordCategory);
// verify permission init
verifyInitPermissions(rootRecordCategory, recordCategory, times(1), times(1), false, true);
}
/**
* Test initialisation new record folder permissions
*/
@Test
public void initPermissionsForNewRecordFolder()
{
// setup permissions for parent
setupPermissions(recordCategory);
// setup permissions
filePlanPermissionService.setupPermissions(recordCategory, newRecordFolder);
// verify permission init
verifyInitPermissions(recordCategory, newRecordFolder, times(1), times(1), false, true);
}
/**
* Test setup of new record permissions
*/
@Test
public void initPermissionsForNewRecord()
{
// setup permissions for parent
setupPermissions(newRecordFolder);
// setup permissions for record
filePlanPermissionService.setupPermissions(newRecordFolder, newRecord);
// verify permission init
verifyInitPermissions(newRecordFolder, newRecord, times(1), times(1), false, true);
}
/**
* Test setup of permissions for new hold container
*/
@Test
public void initPermnissionsForNewHoldContainer()
{
// setup permissions for parent
setupPermissions(filePlan);
// setup permissions for record
filePlanPermissionService.setupPermissions(filePlan, holdContainer);
// verify permissions are set-up correctly
verifyInitPermissions(filePlan, holdContainer, times(1), times(1), false, true);
}
/**
* Test setup of permissions for new hold
*/
@Test
public void initPermissionsForNewHold()
{
// setup permissions for parent
setupPermissions(holdContainer);
// setup permissions for record
filePlanPermissionService.setupPermissions(holdContainer, hold);
// verify permissions are set-up correctly
verifyInitPermissions(holdContainer, hold, never(), times(1), false, false);
}
/**
* Test setup of permissions for new unfiled container
*/
@Test
public void initPermissionsForNewUnfiledContainer()
{
// setup permissions for parent
setupPermissions(filePlan);
// setup permissions for record
filePlanPermissionService.setupPermissions(filePlan, unfiledRecordContainer);
// verify permissions are set-up correctly
verifyInitPermissions(filePlan, unfiledRecordContainer, times(1), times(1), false, false);
}
/**
* Test setup of permissions for new unfiled record folder
*/
@Test
public void initPermissionsForNewUnfiledRecordFolder()
{
// setup permissions for parent
setupPermissions(unfiledRecordContainer);
// setup permissions for record
filePlanPermissionService.setupPermissions(unfiledRecordContainer, unfiledRecordFolder);
// verify permissions are set-up correctly
verifyInitPermissions(unfiledRecordContainer, unfiledRecordFolder, never(), times(1), false, true);
}
/**
* Test setup of permissions for new unfiled record
*/
@Test
public void initPermissionsForNewUnfiledRecord()
{
// setup permissions for parent
setupPermissions(unfiledRecordFolder);
// setup permissions for record
filePlanPermissionService.setupPermissions(unfiledRecordFolder, unfiledRecord);
// verify permission init
verifyInitPermissions(unfiledRecordFolder, unfiledRecord, times(1), times(1), false, true);
}
}

View File

@@ -1,104 +1,104 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test;
import org.alfresco.module.org_alfresco_module_rm.action.dm.DeclareAsVersionRecordActionUnitTest;
import org.alfresco.module.org_alfresco_module_rm.action.impl.FileReportActionUnitTest;
import org.alfresco.module.org_alfresco_module_rm.action.impl.UnlinkFromActionUnitTest;
import org.alfresco.module.org_alfresco_module_rm.bootstrap.BootstrapImporterModuleComponentUnitTest;
import org.alfresco.module.org_alfresco_module_rm.bootstrap.RecordContributorsGroupBootstrapComponentUnitTest;
import org.alfresco.module.org_alfresco_module_rm.capability.RMEntryVoterUnitTest;
import org.alfresco.module.org_alfresco_module_rm.capability.declarative.condition.CapabilityDeclarativeConditionSuite;
import org.alfresco.module.org_alfresco_module_rm.capability.impl.EditNonRecordsMetadataCapabilityUnitTest;
import org.alfresco.module.org_alfresco_module_rm.forms.RecordsManagementTypeFormFilterUnitTest;
import org.alfresco.module.org_alfresco_module_rm.hold.HoldServiceImplUnitTest;
import org.alfresco.module.org_alfresco_module_rm.job.DispositionLifecycleJobExecuterUnitTest;
import org.alfresco.module.org_alfresco_module_rm.jscript.app.evaluator.FrozenEvaluatorUnitTest;
import org.alfresco.module.org_alfresco_module_rm.jscript.app.evaluator.TransferEvaluatorUnitTest;
import org.alfresco.module.org_alfresco_module_rm.model.compatibility.DictionaryBootstrapPostProcessorUnitTest;
import org.alfresco.module.org_alfresco_module_rm.patch.v22.RMv22RemoveInPlaceRolesFromAllPatchUnitTest;
import org.alfresco.module.org_alfresco_module_rm.record.RecordMetadataBootstrapUnitTest;
import org.alfresco.module.org_alfresco_module_rm.record.RecordServiceImplUnitTest;
import org.alfresco.module.org_alfresco_module_rm.recorded.version.config.RecordedVersionConfigGetTest;
import org.alfresco.module.org_alfresco_module_rm.recorded.version.config.RecordedVersionConfigPostTest;
import org.alfresco.module.org_alfresco_module_rm.script.hold.HoldPostUnitTest;
import org.alfresco.module.org_alfresco_module_rm.script.hold.HoldPutUnitTest;
import org.alfresco.module.org_alfresco_module_rm.script.hold.HoldsGetUnitTest;
import org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionServiceImplUnitTest;
import org.alfresco.repo.action.parameter.DateParameterProcessorUnitTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* All unit test suite.
*
* @author Roy Wetherall
* @since 2.2
*/
@RunWith(Suite.class)
@SuiteClasses(
{
RecordMetadataBootstrapUnitTest.class,
RecordsManagementTypeFormFilterUnitTest.class,
DispositionLifecycleJobExecuterUnitTest.class,
DictionaryBootstrapPostProcessorUnitTest.class,
DateParameterProcessorUnitTest.class,
RMEntryVoterUnitTest.class,
// services
RecordServiceImplUnitTest.class,
HoldServiceImplUnitTest.class,
// FilePlanPermissionServiceImplUnitTest.class, // removed because test unreliable on Bamboo
RecordableVersionServiceImplUnitTest.class,
// evaluators
TransferEvaluatorUnitTest.class,
FrozenEvaluatorUnitTest.class,
// capabilities
EditNonRecordsMetadataCapabilityUnitTest.class,
// web scripts
HoldsGetUnitTest.class,
HoldPostUnitTest.class,
HoldPutUnitTest.class,
// action implementations
FileReportActionUnitTest.class,
UnlinkFromActionUnitTest.class,
DeclareAsVersionRecordActionUnitTest.class,
// patches
RMv22RemoveInPlaceRolesFromAllPatchUnitTest.class,
// recorded version config
RecordedVersionConfigGetTest.class,
RecordedVersionConfigPostTest.class,
// bootstrap
BootstrapImporterModuleComponentUnitTest.class,
RecordContributorsGroupBootstrapComponentUnitTest.class,
// suites by package
CapabilityDeclarativeConditionSuite.class
})
public class AllUnitTestSuite
{
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test;
import org.alfresco.module.org_alfresco_module_rm.action.dm.DeclareAsVersionRecordActionUnitTest;
import org.alfresco.module.org_alfresco_module_rm.action.impl.FileReportActionUnitTest;
import org.alfresco.module.org_alfresco_module_rm.action.impl.UnlinkFromActionUnitTest;
import org.alfresco.module.org_alfresco_module_rm.bootstrap.BootstrapImporterModuleComponentUnitTest;
import org.alfresco.module.org_alfresco_module_rm.bootstrap.RecordContributorsGroupBootstrapComponentUnitTest;
import org.alfresco.module.org_alfresco_module_rm.capability.RMEntryVoterUnitTest;
import org.alfresco.module.org_alfresco_module_rm.capability.declarative.condition.CapabilityDeclarativeConditionSuite;
import org.alfresco.module.org_alfresco_module_rm.capability.impl.EditNonRecordsMetadataCapabilityUnitTest;
import org.alfresco.module.org_alfresco_module_rm.forms.RecordsManagementTypeFormFilterUnitTest;
import org.alfresco.module.org_alfresco_module_rm.hold.HoldServiceImplUnitTest;
import org.alfresco.module.org_alfresco_module_rm.job.DispositionLifecycleJobExecuterUnitTest;
import org.alfresco.module.org_alfresco_module_rm.jscript.app.evaluator.FrozenEvaluatorUnitTest;
import org.alfresco.module.org_alfresco_module_rm.jscript.app.evaluator.TransferEvaluatorUnitTest;
import org.alfresco.module.org_alfresco_module_rm.model.compatibility.DictionaryBootstrapPostProcessorUnitTest;
import org.alfresco.module.org_alfresco_module_rm.patch.v22.RMv22RemoveInPlaceRolesFromAllPatchUnitTest;
import org.alfresco.module.org_alfresco_module_rm.record.RecordMetadataBootstrapUnitTest;
import org.alfresco.module.org_alfresco_module_rm.record.RecordServiceImplUnitTest;
import org.alfresco.module.org_alfresco_module_rm.recorded.version.config.RecordedVersionConfigGetTest;
import org.alfresco.module.org_alfresco_module_rm.recorded.version.config.RecordedVersionConfigPostTest;
import org.alfresco.module.org_alfresco_module_rm.script.hold.HoldPostUnitTest;
import org.alfresco.module.org_alfresco_module_rm.script.hold.HoldPutUnitTest;
import org.alfresco.module.org_alfresco_module_rm.script.hold.HoldsGetUnitTest;
import org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionServiceImplUnitTest;
import org.alfresco.repo.action.parameter.DateParameterProcessorUnitTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* All unit test suite.
*
* @author Roy Wetherall
* @since 2.2
*/
@RunWith(Suite.class)
@SuiteClasses(
{
RecordMetadataBootstrapUnitTest.class,
RecordsManagementTypeFormFilterUnitTest.class,
DispositionLifecycleJobExecuterUnitTest.class,
DictionaryBootstrapPostProcessorUnitTest.class,
DateParameterProcessorUnitTest.class,
RMEntryVoterUnitTest.class,
// services
RecordServiceImplUnitTest.class,
HoldServiceImplUnitTest.class,
// FilePlanPermissionServiceImplUnitTest.class, // removed because test unreliable on Bamboo
RecordableVersionServiceImplUnitTest.class,
// evaluators
TransferEvaluatorUnitTest.class,
FrozenEvaluatorUnitTest.class,
// capabilities
EditNonRecordsMetadataCapabilityUnitTest.class,
// web scripts
HoldsGetUnitTest.class,
HoldPostUnitTest.class,
HoldPutUnitTest.class,
// action implementations
FileReportActionUnitTest.class,
UnlinkFromActionUnitTest.class,
DeclareAsVersionRecordActionUnitTest.class,
// patches
RMv22RemoveInPlaceRolesFromAllPatchUnitTest.class,
// recorded version config
RecordedVersionConfigGetTest.class,
RecordedVersionConfigPostTest.class,
// bootstrap
BootstrapImporterModuleComponentUnitTest.class,
RecordContributorsGroupBootstrapComponentUnitTest.class,
// suites by package
CapabilityDeclarativeConditionSuite.class
})
public class AllUnitTestSuite
{
}

View File

@@ -1,130 +1,130 @@
/*
* #%L
* Alfresco Records Management Module
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* -
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
* -
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* -
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* -
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
import java.util.UUID;
import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.GUID;
/**
* Utilities helpful when mocking Alfresco constructs.
*
* @author Roy Wetherall
* @since 2.4.a
*/
public class AlfMock
{
/**
* Helper to generate random text value suitable for a property
* value or node name
*/
public static String generateText()
{
return UUID.randomUUID().toString();
}
/**
* Helper method to generate a qname.
*/
public static QName generateQName()
{
return generateQName(GUID.generate());
}
/**
* Helper method to generate a qname.
*/
public static QName generateQName(String uri)
{
return QName.createQName(uri, GUID.generate());
}
/**
* Helper method to generate a node reference.
*
* @return {@link NodeRef} node reference that behaves like a node that exists in the spaces store
*/
public static NodeRef generateNodeRef(NodeService mockedNodeService)
{
return generateNodeRef(mockedNodeService, null);
}
/**
* Helper method to generate a node reference of a particular type.
*
* @param type content type qualified name
* @return {@link NodeRef} node reference that behaves like a node that exists in the spaces store with
* the content type provided
*/
public static NodeRef generateNodeRef(NodeService mockedNodeService, QName type)
{
return generateNodeRef(mockedNodeService, type, true);
}
/**
* Helper method to generate a cm:content node reference with a given name.
*
* @param name content name
* @return NodeRef node reference
*/
public static NodeRef generateCmContent(NodeService mockedNodeService, String name)
{
NodeRef nodeRef = generateNodeRef(mockedNodeService, ContentModel.TYPE_CONTENT, true);
doReturn(name).when(mockedNodeService).getProperty(nodeRef, ContentModel.PROP_NAME);
return nodeRef;
}
/**
* Helper method to generate a node reference of a particular type with a given existence characteristic.
*
* @param type content type qualified name
* @param exists indicates whether this node should behave like a node that exists or not
* @return {@link NodeRef} node reference that behaves like a node that exists (or not) in the spaces store with
* the content type provided
*/
public static NodeRef generateNodeRef(NodeService mockedNodeService, QName type, boolean exists)
{
NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate());
when(mockedNodeService.exists(eq(nodeRef))).thenReturn(exists);
if (type != null)
{
when(mockedNodeService.getType(eq(nodeRef))).thenReturn(type);
}
return nodeRef;
}
}
/*
* #%L
* Alfresco Records Management Module
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* -
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
* -
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* -
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* -
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
import java.util.UUID;
import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.GUID;
/**
* Utilities helpful when mocking Alfresco constructs.
*
* @author Roy Wetherall
* @since 2.4.a
*/
public class AlfMock
{
/**
* Helper to generate random text value suitable for a property
* value or node name
*/
public static String generateText()
{
return UUID.randomUUID().toString();
}
/**
* Helper method to generate a qname.
*/
public static QName generateQName()
{
return generateQName(GUID.generate());
}
/**
* Helper method to generate a qname.
*/
public static QName generateQName(String uri)
{
return QName.createQName(uri, GUID.generate());
}
/**
* Helper method to generate a node reference.
*
* @return {@link NodeRef} node reference that behaves like a node that exists in the spaces store
*/
public static NodeRef generateNodeRef(NodeService mockedNodeService)
{
return generateNodeRef(mockedNodeService, null);
}
/**
* Helper method to generate a node reference of a particular type.
*
* @param type content type qualified name
* @return {@link NodeRef} node reference that behaves like a node that exists in the spaces store with
* the content type provided
*/
public static NodeRef generateNodeRef(NodeService mockedNodeService, QName type)
{
return generateNodeRef(mockedNodeService, type, true);
}
/**
* Helper method to generate a cm:content node reference with a given name.
*
* @param name content name
* @return NodeRef node reference
*/
public static NodeRef generateCmContent(NodeService mockedNodeService, String name)
{
NodeRef nodeRef = generateNodeRef(mockedNodeService, ContentModel.TYPE_CONTENT, true);
doReturn(name).when(mockedNodeService).getProperty(nodeRef, ContentModel.PROP_NAME);
return nodeRef;
}
/**
* Helper method to generate a node reference of a particular type with a given existence characteristic.
*
* @param type content type qualified name
* @param exists indicates whether this node should behave like a node that exists or not
* @return {@link NodeRef} node reference that behaves like a node that exists (or not) in the spaces store with
* the content type provided
*/
public static NodeRef generateNodeRef(NodeService mockedNodeService, QName type, boolean exists)
{
NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate());
when(mockedNodeService.exists(eq(nodeRef))).thenReturn(exists);
if (type != null)
{
when(mockedNodeService.getType(eq(nodeRef))).thenReturn(type);
}
return nodeRef;
}
}

View File

@@ -1,443 +1,443 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
import org.alfresco.module.org_alfresco_module_rm.audit.RecordsManagementAuditService;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionService;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.module.org_alfresco_module_rm.freeze.FreezeService;
import org.alfresco.module.org_alfresco_module_rm.hold.HoldService;
import org.alfresco.module.org_alfresco_module_rm.identifier.IdentifierService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.model.rma.type.CmObjectType;
import org.alfresco.module.org_alfresco_module_rm.model.security.ModelSecurityService;
import org.alfresco.module.org_alfresco_module_rm.record.RecordService;
import org.alfresco.module.org_alfresco_module_rm.recordableversion.RecordableVersionConfigService;
import org.alfresco.module.org_alfresco_module_rm.recordfolder.RecordFolderService;
import org.alfresco.module.org_alfresco_module_rm.report.ReportService;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedSecurityService;
import org.alfresco.module.org_alfresco_module_rm.util.AlfrescoTransactionSupport;
import org.alfresco.module.org_alfresco_module_rm.util.AuthenticationUtil;
import org.alfresco.module.org_alfresco_module_rm.util.TransactionalResourceHelper;
import org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionService;
import org.alfresco.repo.policy.BehaviourFilter;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.security.permissions.impl.ExtendedPermissionService;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.CopyService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.OwnableService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.QNamePattern;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.util.GUID;
import org.alfresco.util.collections.CollectionUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.context.ApplicationContext;
/**
* Base unit test.
* <p>
* Contains core and records management service mocks ready for injection. Helper methods
* provide an easy way to build RM or Alfresco constructs for use in tests.
*
* @author Roy Wetherall
* @since 2.2
*/
public class BaseUnitTest implements RecordsManagementModel, ContentModel
{
protected NodeRef filePlanComponent;
protected NodeRef filePlan;
protected NodeRef recordFolder;
protected NodeRef record;
/** core service mocks */
@Mock(name="nodeService") protected NodeService mockedNodeService;
@Mock(name="dictionaryService") protected DictionaryService mockedDictionaryService;
@Mock(name="namespaceService") protected NamespaceService mockedNamespaceService;
@Mock(name="identifierService") protected IdentifierService mockedIdentifierService;
@Mock(name="permissionService") protected PermissionService mockedPermissionService;
@Mock(name="ownableService") protected OwnableService mockedOwnableService;
@Mock(name="searchService") protected SearchService mockedSearchService;
@Mock(name="retryingTransactionHelper") protected RetryingTransactionHelper mockedRetryingTransactionHelper;
@Mock(name="authorityService") protected AuthorityService mockedAuthorityService;
@Mock(name="policyComponent") protected PolicyComponent mockedPolicyComponent;
@Mock(name="copyService") protected CopyService mockedCopyService;
@Mock(name="fileFolderService") protected FileFolderService mockedFileFolderService;
@Mock(name="modelSecurityService") protected ModelSecurityService mockedModelSecurityService;
/** rm service mocks */
@Mock(name="filePlanService") protected FilePlanService mockedFilePlanService;
@Mock(name="recordFolderService") protected RecordFolderService mockedRecordFolderService;
@Mock(name="recordService") protected RecordService mockedRecordService;
@Mock(name="holdService") protected HoldService mockedHoldService;
@Mock(name="recordsManagementActionService") protected RecordsManagementActionService mockedRecordsManagementActionService;
@Mock(name="reportService") protected ReportService mockedReportService;
@Mock(name="filePlanRoleService") protected FilePlanRoleService mockedFilePlanRoleService;
@Mock(name="recordsManagementAuditService") protected RecordsManagementAuditService mockedRecordsManagementAuditService;
@Mock(name="policyBehaviourFilter") protected BehaviourFilter mockedBehaviourFilter;
@Mock(name="authenticationUtil") protected AuthenticationUtil mockedAuthenticationUtil;
@Mock(name="extendedPermissionService") protected ExtendedPermissionService mockedExtendedPermissionService;
@Mock(name="extendedSecurityService") protected ExtendedSecurityService mockedExtendedSecurityService;
@Mock(name="recordableVersionConfigService") protected RecordableVersionConfigService mockedRecordableVersionConfigService;
@Mock(name="cmObjectType") protected CmObjectType mockedCmObjectType;
@Mock(name="recordableVersionService") protected RecordableVersionService mockedRecordableVersionService;
@Mock(name="transactionalResourceHelper") protected TransactionalResourceHelper mockedTransactionalResourceHelper;
@Mock(name="alfrescoTransactionSupport") protected AlfrescoTransactionSupport mockedAlfrescoTransactionSupport;
@Mock(name="freezeService") protected FreezeService mockedFreezeService;
@Mock(name="dispositionService") protected DispositionService mockedDispositionService;
/** application context mock */
@Mock(name="applicationContext") protected ApplicationContext mockedApplicationContext;
/** expected exception rule */
@Rule
public ExpectedException exception = ExpectedException.none();
/**
* Test method setup
*/
@SuppressWarnings("unchecked")
@Before
public void before() throws Exception
{
MockitoAnnotations.initMocks(this);
// setup application context
doReturn(mockedNodeService).when(mockedApplicationContext).getBean("dbNodeService");
// setup retrying transaction helper
Answer<Object> doInTransactionAnswer = new Answer<Object>()
{
@SuppressWarnings("rawtypes")
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
RetryingTransactionCallback callback = (RetryingTransactionCallback)invocation.getArguments()[0];
return callback.execute();
}
};
doAnswer(doInTransactionAnswer).when(mockedRetryingTransactionHelper).doInTransaction(any(RetryingTransactionCallback.class));
// setup mocked authentication util
setupAuthenticationUtilMock();
// setup file plan
filePlan = generateNodeRef(TYPE_FILE_PLAN);
setupAsFilePlanComponent(filePlan);
doReturn(true).when(mockedFilePlanService).isFilePlan(filePlan);
// setup basic file plan component
filePlanComponent = generateNodeRef();
setupAsFilePlanComponent(filePlanComponent);
// setup namespace service
doReturn(RM_URI).when(mockedNamespaceService).getNamespaceURI(RM_PREFIX);
doReturn(CollectionUtils.unmodifiableSet(RM_PREFIX)).when(mockedNamespaceService).getPrefixes(RM_URI);
// setup record folder and record
recordFolder = generateRecordFolder();
record = generateRecord();
// set record as child of record folder
List<ChildAssociationRef> result = new ArrayList<ChildAssociationRef>(1);
result.add(new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, recordFolder, generateQName(), record, true, 1));
doReturn(result).when(mockedNodeService).getChildAssocs(eq(recordFolder), eq(ContentModel.ASSOC_CONTAINS), any(QNamePattern.class));
doReturn(result).when(mockedNodeService).getParentAssocs(record);
doReturn(Collections.singletonList(recordFolder)).when(mockedRecordFolderService).getRecordFolders(record);
doReturn(Collections.singletonList(record)).when(mockedRecordService).getRecords(recordFolder);
}
/**
* Setup authentication util mock
*/
@SuppressWarnings("unchecked")
private void setupAuthenticationUtilMock()
{
// just do the work
doAnswer(new Answer<Object>()
{
@SuppressWarnings("rawtypes")
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
RunAsWork work = (RunAsWork)invocation.getArguments()[0];
return work.doWork();
}
}).when(mockedAuthenticationUtil).runAsSystem(any(RunAsWork.class));
// just do the work
doAnswer(new Answer<Object>()
{
@SuppressWarnings("rawtypes")
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
RunAsWork work = (RunAsWork)invocation.getArguments()[0];
return work.doWork();
}
}).when(mockedAuthenticationUtil).runAs(any(RunAsWork.class), anyString());
// assume admin
doReturn("admin").when(mockedAuthenticationUtil).getAdminUserName();
doReturn("admin").when(mockedAuthenticationUtil).getFullyAuthenticatedUser();
}
/**
* Helper to generate random text value suitable for a property
* value or node name
*/
protected String generateText()
{
return UUID.randomUUID().toString();
}
/**
* Helper method to generate a qname.
*
* @return QName qualified name
*/
protected static QName generateQName()
{
return QName.createQName(RM_URI, GUID.generate());
}
/**
* Helper method to generate hold reference
*
* @param name hold name
* @return {@link NodeRef} node reference that will behave like a hold
*/
protected NodeRef generateHoldNodeRef(String name)
{
NodeRef hold = generateNodeRef(TYPE_HOLD);
doReturn(name).when(mockedNodeService).getProperty(hold, ContentModel.PROP_NAME);
doReturn(true).when(mockedHoldService).isHold(hold);
return hold;
}
/**
* Helper method to generate record folder reference
*
* @return {@link NodeRef} node reference that will behave like a record folder
*/
protected NodeRef generateRecordFolder()
{
NodeRef recordFolder = generateNodeRef(TYPE_RECORD_FOLDER);
setupAsFilePlanComponent(recordFolder);
doReturn(true).when(mockedRecordFolderService).isRecordFolder(recordFolder);
return recordFolder;
}
/**
* Helper method to generate a record node reference.
*
* @return {@link NodeRef} node reference that will behave like a record or type cm:content
*/
protected NodeRef generateRecord()
{
NodeRef record = generateNodeRef(ContentModel.TYPE_CONTENT);
setupAsFilePlanComponent(record);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_RECORD);
doReturn(true).when(mockedRecordService).isRecord(record);
return record;
}
/**
* Helper method to setup a node reference as a file plan component.
*
* @param nodeRef {@link NodeRef} node reference that will now behave like a file plan component
*/
protected void setupAsFilePlanComponent(NodeRef nodeRef)
{
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, ASPECT_FILE_PLAN_COMPONENT);
doReturn(true).when(mockedFilePlanService).isFilePlanComponent(nodeRef);
doReturn(filePlan).when(mockedFilePlanService).getFilePlan(nodeRef);
doReturn(filePlan).when(mockedNodeService).getProperty(nodeRef, PROP_ROOT_NODEREF);
}
/**
* Helper method to generate a node reference.
*
* @return {@link NodeRef} node reference that behaves like a node that exists in the spaces store
*/
protected NodeRef generateNodeRef()
{
return generateNodeRef(null);
}
/**
* Helper method to generate a node reference of a particular type.
*
* @param type content type qualified name
* @return {@link NodeRef} node reference that behaves like a node that exists in the spaces store with
* the content type provided
*/
protected NodeRef generateNodeRef(QName type)
{
return generateNodeRef(type, true);
}
/**
* Helper method to generate a cm:content node reference with a given name.
*
* @param name content name
* @return NodeRef node reference
*/
protected NodeRef generateCmContent(String name)
{
NodeRef nodeRef = generateNodeRef(ContentModel.TYPE_CONTENT, true);
doReturn(name).when(mockedNodeService).getProperty(nodeRef, ContentModel.PROP_NAME);
return nodeRef;
}
/**
* Helper method to generate a node reference of a particular type with a given existence characteristic.
*
* @param type content type qualified name
* @param exists indicates whether this node should behave like a node that exists or not
* @return {@link NodeRef} node reference that behaves like a node that exists (or not) in the spaces store with
* the content type provided
*/
protected NodeRef generateNodeRef(QName type, boolean exists)
{
NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate());
when(mockedNodeService.exists(eq(nodeRef))).thenReturn(exists);
if (type != null)
{
when(mockedNodeService.getType(eq(nodeRef))).thenReturn(type);
}
return nodeRef;
}
/**
* Helper method to generate a mocked child association reference.
*
* @param parent parent node (optional)
* @param child child node (optional)
* @return {@link ChildAssociationRef} mocked to return the parent and child nodes
*/
protected ChildAssociationRef generateChildAssociationRef(NodeRef parent, NodeRef child)
{
ChildAssociationRef mockedChildAssociationRef = mock(ChildAssociationRef.class);
if (parent != null)
{
doReturn(parent).when(mockedChildAssociationRef).getParentRef();
}
if (child != null)
{
doReturn(child).when(mockedChildAssociationRef).getChildRef();
}
return mockedChildAssociationRef;
}
/**
* Helper method to make one node the primary parent of the other.
* <p>
* Assumes the cm:contains assoc type.
*
* @param child
* @param parent
*/
protected void makePrimaryParentOf(NodeRef child, NodeRef parent)
{
makePrimaryParentOf(child, parent, ContentModel.ASSOC_CONTAINS, generateQName());
}
protected void makePrimaryParentOf(NodeRef child, NodeRef parent, QName assocType, QName assocName)
{
makePrimaryParentOf(child, parent, assocType, assocName, mockedNodeService);
}
protected void makePrimaryParentOf(NodeRef child, NodeRef parent, QName assocType, QName assocName, NodeService mockedNodeService)
{
doReturn(new ChildAssociationRef(assocType, parent, assocName, child))
.when(mockedNodeService)
.getPrimaryParent(child);
}
/**
* Helper method to make a number of nodes children of another.
* <p>
* Assumes the cm:contains assoc type.
*
* @param parent
* @param children
*/
protected void makeChildrenOf(NodeRef parent, NodeRef ... children)
{
List<ChildAssociationRef> assocs = new ArrayList<ChildAssociationRef>(children.length);
for (NodeRef child : children)
{
assocs.add(new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, parent, generateQName(), child));
doReturn(assocs).when(mockedNodeService).getParentAssocs(child);
}
doReturn(assocs).when(mockedNodeService).getChildAssocs(parent, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
}
@SuppressWarnings("unchecked")
protected <T> List<T> buildList(T ... values)
{
List<T> result = new ArrayList<T>(values.length);
for (T value : values)
{
result.add(value);
}
return result;
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionService;
import org.alfresco.module.org_alfresco_module_rm.audit.RecordsManagementAuditService;
import org.alfresco.module.org_alfresco_module_rm.disposition.DispositionService;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.module.org_alfresco_module_rm.freeze.FreezeService;
import org.alfresco.module.org_alfresco_module_rm.hold.HoldService;
import org.alfresco.module.org_alfresco_module_rm.identifier.IdentifierService;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.model.rma.type.CmObjectType;
import org.alfresco.module.org_alfresco_module_rm.model.security.ModelSecurityService;
import org.alfresco.module.org_alfresco_module_rm.record.RecordService;
import org.alfresco.module.org_alfresco_module_rm.recordableversion.RecordableVersionConfigService;
import org.alfresco.module.org_alfresco_module_rm.recordfolder.RecordFolderService;
import org.alfresco.module.org_alfresco_module_rm.report.ReportService;
import org.alfresco.module.org_alfresco_module_rm.role.FilePlanRoleService;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedSecurityService;
import org.alfresco.module.org_alfresco_module_rm.util.AlfrescoTransactionSupport;
import org.alfresco.module.org_alfresco_module_rm.util.AuthenticationUtil;
import org.alfresco.module.org_alfresco_module_rm.util.TransactionalResourceHelper;
import org.alfresco.module.org_alfresco_module_rm.version.RecordableVersionService;
import org.alfresco.repo.policy.BehaviourFilter;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.security.permissions.impl.ExtendedPermissionService;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.CopyService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.OwnableService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.QNamePattern;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.util.GUID;
import org.alfresco.util.collections.CollectionUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.context.ApplicationContext;
/**
* Base unit test.
* <p>
* Contains core and records management service mocks ready for injection. Helper methods
* provide an easy way to build RM or Alfresco constructs for use in tests.
*
* @author Roy Wetherall
* @since 2.2
*/
public class BaseUnitTest implements RecordsManagementModel, ContentModel
{
protected NodeRef filePlanComponent;
protected NodeRef filePlan;
protected NodeRef recordFolder;
protected NodeRef record;
/** core service mocks */
@Mock(name="nodeService") protected NodeService mockedNodeService;
@Mock(name="dictionaryService") protected DictionaryService mockedDictionaryService;
@Mock(name="namespaceService") protected NamespaceService mockedNamespaceService;
@Mock(name="identifierService") protected IdentifierService mockedIdentifierService;
@Mock(name="permissionService") protected PermissionService mockedPermissionService;
@Mock(name="ownableService") protected OwnableService mockedOwnableService;
@Mock(name="searchService") protected SearchService mockedSearchService;
@Mock(name="retryingTransactionHelper") protected RetryingTransactionHelper mockedRetryingTransactionHelper;
@Mock(name="authorityService") protected AuthorityService mockedAuthorityService;
@Mock(name="policyComponent") protected PolicyComponent mockedPolicyComponent;
@Mock(name="copyService") protected CopyService mockedCopyService;
@Mock(name="fileFolderService") protected FileFolderService mockedFileFolderService;
@Mock(name="modelSecurityService") protected ModelSecurityService mockedModelSecurityService;
/** rm service mocks */
@Mock(name="filePlanService") protected FilePlanService mockedFilePlanService;
@Mock(name="recordFolderService") protected RecordFolderService mockedRecordFolderService;
@Mock(name="recordService") protected RecordService mockedRecordService;
@Mock(name="holdService") protected HoldService mockedHoldService;
@Mock(name="recordsManagementActionService") protected RecordsManagementActionService mockedRecordsManagementActionService;
@Mock(name="reportService") protected ReportService mockedReportService;
@Mock(name="filePlanRoleService") protected FilePlanRoleService mockedFilePlanRoleService;
@Mock(name="recordsManagementAuditService") protected RecordsManagementAuditService mockedRecordsManagementAuditService;
@Mock(name="policyBehaviourFilter") protected BehaviourFilter mockedBehaviourFilter;
@Mock(name="authenticationUtil") protected AuthenticationUtil mockedAuthenticationUtil;
@Mock(name="extendedPermissionService") protected ExtendedPermissionService mockedExtendedPermissionService;
@Mock(name="extendedSecurityService") protected ExtendedSecurityService mockedExtendedSecurityService;
@Mock(name="recordableVersionConfigService") protected RecordableVersionConfigService mockedRecordableVersionConfigService;
@Mock(name="cmObjectType") protected CmObjectType mockedCmObjectType;
@Mock(name="recordableVersionService") protected RecordableVersionService mockedRecordableVersionService;
@Mock(name="transactionalResourceHelper") protected TransactionalResourceHelper mockedTransactionalResourceHelper;
@Mock(name="alfrescoTransactionSupport") protected AlfrescoTransactionSupport mockedAlfrescoTransactionSupport;
@Mock(name="freezeService") protected FreezeService mockedFreezeService;
@Mock(name="dispositionService") protected DispositionService mockedDispositionService;
/** application context mock */
@Mock(name="applicationContext") protected ApplicationContext mockedApplicationContext;
/** expected exception rule */
@Rule
public ExpectedException exception = ExpectedException.none();
/**
* Test method setup
*/
@SuppressWarnings("unchecked")
@Before
public void before() throws Exception
{
MockitoAnnotations.initMocks(this);
// setup application context
doReturn(mockedNodeService).when(mockedApplicationContext).getBean("dbNodeService");
// setup retrying transaction helper
Answer<Object> doInTransactionAnswer = new Answer<Object>()
{
@SuppressWarnings("rawtypes")
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
RetryingTransactionCallback callback = (RetryingTransactionCallback)invocation.getArguments()[0];
return callback.execute();
}
};
doAnswer(doInTransactionAnswer).when(mockedRetryingTransactionHelper).doInTransaction(any(RetryingTransactionCallback.class));
// setup mocked authentication util
setupAuthenticationUtilMock();
// setup file plan
filePlan = generateNodeRef(TYPE_FILE_PLAN);
setupAsFilePlanComponent(filePlan);
doReturn(true).when(mockedFilePlanService).isFilePlan(filePlan);
// setup basic file plan component
filePlanComponent = generateNodeRef();
setupAsFilePlanComponent(filePlanComponent);
// setup namespace service
doReturn(RM_URI).when(mockedNamespaceService).getNamespaceURI(RM_PREFIX);
doReturn(CollectionUtils.unmodifiableSet(RM_PREFIX)).when(mockedNamespaceService).getPrefixes(RM_URI);
// setup record folder and record
recordFolder = generateRecordFolder();
record = generateRecord();
// set record as child of record folder
List<ChildAssociationRef> result = new ArrayList<ChildAssociationRef>(1);
result.add(new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, recordFolder, generateQName(), record, true, 1));
doReturn(result).when(mockedNodeService).getChildAssocs(eq(recordFolder), eq(ContentModel.ASSOC_CONTAINS), any(QNamePattern.class));
doReturn(result).when(mockedNodeService).getParentAssocs(record);
doReturn(Collections.singletonList(recordFolder)).when(mockedRecordFolderService).getRecordFolders(record);
doReturn(Collections.singletonList(record)).when(mockedRecordService).getRecords(recordFolder);
}
/**
* Setup authentication util mock
*/
@SuppressWarnings("unchecked")
private void setupAuthenticationUtilMock()
{
// just do the work
doAnswer(new Answer<Object>()
{
@SuppressWarnings("rawtypes")
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
RunAsWork work = (RunAsWork)invocation.getArguments()[0];
return work.doWork();
}
}).when(mockedAuthenticationUtil).runAsSystem(any(RunAsWork.class));
// just do the work
doAnswer(new Answer<Object>()
{
@SuppressWarnings("rawtypes")
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
RunAsWork work = (RunAsWork)invocation.getArguments()[0];
return work.doWork();
}
}).when(mockedAuthenticationUtil).runAs(any(RunAsWork.class), anyString());
// assume admin
doReturn("admin").when(mockedAuthenticationUtil).getAdminUserName();
doReturn("admin").when(mockedAuthenticationUtil).getFullyAuthenticatedUser();
}
/**
* Helper to generate random text value suitable for a property
* value or node name
*/
protected String generateText()
{
return UUID.randomUUID().toString();
}
/**
* Helper method to generate a qname.
*
* @return QName qualified name
*/
protected static QName generateQName()
{
return QName.createQName(RM_URI, GUID.generate());
}
/**
* Helper method to generate hold reference
*
* @param name hold name
* @return {@link NodeRef} node reference that will behave like a hold
*/
protected NodeRef generateHoldNodeRef(String name)
{
NodeRef hold = generateNodeRef(TYPE_HOLD);
doReturn(name).when(mockedNodeService).getProperty(hold, ContentModel.PROP_NAME);
doReturn(true).when(mockedHoldService).isHold(hold);
return hold;
}
/**
* Helper method to generate record folder reference
*
* @return {@link NodeRef} node reference that will behave like a record folder
*/
protected NodeRef generateRecordFolder()
{
NodeRef recordFolder = generateNodeRef(TYPE_RECORD_FOLDER);
setupAsFilePlanComponent(recordFolder);
doReturn(true).when(mockedRecordFolderService).isRecordFolder(recordFolder);
return recordFolder;
}
/**
* Helper method to generate a record node reference.
*
* @return {@link NodeRef} node reference that will behave like a record or type cm:content
*/
protected NodeRef generateRecord()
{
NodeRef record = generateNodeRef(ContentModel.TYPE_CONTENT);
setupAsFilePlanComponent(record);
doReturn(true).when(mockedNodeService).hasAspect(record, ASPECT_RECORD);
doReturn(true).when(mockedRecordService).isRecord(record);
return record;
}
/**
* Helper method to setup a node reference as a file plan component.
*
* @param nodeRef {@link NodeRef} node reference that will now behave like a file plan component
*/
protected void setupAsFilePlanComponent(NodeRef nodeRef)
{
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, ASPECT_FILE_PLAN_COMPONENT);
doReturn(true).when(mockedFilePlanService).isFilePlanComponent(nodeRef);
doReturn(filePlan).when(mockedFilePlanService).getFilePlan(nodeRef);
doReturn(filePlan).when(mockedNodeService).getProperty(nodeRef, PROP_ROOT_NODEREF);
}
/**
* Helper method to generate a node reference.
*
* @return {@link NodeRef} node reference that behaves like a node that exists in the spaces store
*/
protected NodeRef generateNodeRef()
{
return generateNodeRef(null);
}
/**
* Helper method to generate a node reference of a particular type.
*
* @param type content type qualified name
* @return {@link NodeRef} node reference that behaves like a node that exists in the spaces store with
* the content type provided
*/
protected NodeRef generateNodeRef(QName type)
{
return generateNodeRef(type, true);
}
/**
* Helper method to generate a cm:content node reference with a given name.
*
* @param name content name
* @return NodeRef node reference
*/
protected NodeRef generateCmContent(String name)
{
NodeRef nodeRef = generateNodeRef(ContentModel.TYPE_CONTENT, true);
doReturn(name).when(mockedNodeService).getProperty(nodeRef, ContentModel.PROP_NAME);
return nodeRef;
}
/**
* Helper method to generate a node reference of a particular type with a given existence characteristic.
*
* @param type content type qualified name
* @param exists indicates whether this node should behave like a node that exists or not
* @return {@link NodeRef} node reference that behaves like a node that exists (or not) in the spaces store with
* the content type provided
*/
protected NodeRef generateNodeRef(QName type, boolean exists)
{
NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate());
when(mockedNodeService.exists(eq(nodeRef))).thenReturn(exists);
if (type != null)
{
when(mockedNodeService.getType(eq(nodeRef))).thenReturn(type);
}
return nodeRef;
}
/**
* Helper method to generate a mocked child association reference.
*
* @param parent parent node (optional)
* @param child child node (optional)
* @return {@link ChildAssociationRef} mocked to return the parent and child nodes
*/
protected ChildAssociationRef generateChildAssociationRef(NodeRef parent, NodeRef child)
{
ChildAssociationRef mockedChildAssociationRef = mock(ChildAssociationRef.class);
if (parent != null)
{
doReturn(parent).when(mockedChildAssociationRef).getParentRef();
}
if (child != null)
{
doReturn(child).when(mockedChildAssociationRef).getChildRef();
}
return mockedChildAssociationRef;
}
/**
* Helper method to make one node the primary parent of the other.
* <p>
* Assumes the cm:contains assoc type.
*
* @param child
* @param parent
*/
protected void makePrimaryParentOf(NodeRef child, NodeRef parent)
{
makePrimaryParentOf(child, parent, ContentModel.ASSOC_CONTAINS, generateQName());
}
protected void makePrimaryParentOf(NodeRef child, NodeRef parent, QName assocType, QName assocName)
{
makePrimaryParentOf(child, parent, assocType, assocName, mockedNodeService);
}
protected void makePrimaryParentOf(NodeRef child, NodeRef parent, QName assocType, QName assocName, NodeService mockedNodeService)
{
doReturn(new ChildAssociationRef(assocType, parent, assocName, child))
.when(mockedNodeService)
.getPrimaryParent(child);
}
/**
* Helper method to make a number of nodes children of another.
* <p>
* Assumes the cm:contains assoc type.
*
* @param parent
* @param children
*/
protected void makeChildrenOf(NodeRef parent, NodeRef ... children)
{
List<ChildAssociationRef> assocs = new ArrayList<ChildAssociationRef>(children.length);
for (NodeRef child : children)
{
assocs.add(new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, parent, generateQName(), child));
doReturn(assocs).when(mockedNodeService).getParentAssocs(child);
}
doReturn(assocs).when(mockedNodeService).getChildAssocs(parent, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
}
@SuppressWarnings("unchecked")
protected <T> List<T> buildList(T ... values)
{
List<T> result = new ArrayList<T>(values.length);
for (T value : values)
{
result.add(value);
}
return result;
}
}

View File

@@ -1,269 +1,269 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.extensions.surf.util.Content;
import org.springframework.extensions.webscripts.Container;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
import org.springframework.extensions.webscripts.Description;
import org.springframework.extensions.webscripts.Description.RequiredCache;
import org.springframework.extensions.webscripts.DescriptionExtension;
import org.springframework.extensions.webscripts.FormatRegistry;
import org.springframework.extensions.webscripts.Match;
import org.springframework.extensions.webscripts.ScriptProcessorRegistry;
import org.springframework.extensions.webscripts.SearchPath;
import org.springframework.extensions.webscripts.TemplateProcessorRegistry;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;
import org.springframework.extensions.webscripts.json.JSONUtils;
import org.springframework.extensions.webscripts.processor.FTLTemplateProcessor;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.TemplateLoader;
/**
* Base Web Script Unit Test.
* <p>
* Provides helper methods that mock the nessesery classes needed to execute
* a Java backed webscript that implements DeclarativeWebScript.
* <p>
* Note that execution of java script controllers is not currently supported.
*
* @author Roy Wetherall
* @since 2.2
*/
public abstract class BaseWebScriptUnitTest extends BaseUnitTest
{
/** web script root folder for RM webscripts */
protected static final String WEBSCRIPT_ROOT_RM = "alfresco/templates/webscripts/org/alfresco/rma/";
/**
* @return declarative webscript
*/
protected abstract DeclarativeWebScript getWebScript();
/**
* @return classpath location of webscript template
*/
protected abstract String getWebScriptTemplate();
/**
* Helper method to build a map of web script parameter values
* mimicking those provided on the URL
*
* @param values
* @return
*/
protected Map<String, String> buildParameters(String ... values)
{
Map<String, String> result = new HashMap<String, String>(values.length/2);
for (int i = 0; i < values.length; i=i+2)
{
String key = values[i];
String value = values[i+1];
result.put(key, value);
}
return result;
}
/**
*
* @param parameters
* @return
* @throws Exception
*/
protected JSONObject executeJSONWebScript(Map<String, String> parameters) throws Exception
{
return executeJSONWebScript(parameters, null);
}
/**
* Execute web script and convert result into a JSON object.
*
* @param parameters map of all parameter values
* @return {@link JSONObject} result, parsed into a JSON object
*/
protected JSONObject executeJSONWebScript(Map<String, String> parameters, String content) throws Exception
{
String result = executeWebScript(parameters, content);
return new JSONObject(result);
}
/**
*
* @param parameters
* @return
* @throws Exception
*/
protected String executeWebScript(Map<String, String> parameters) throws Exception
{
return executeWebScript( parameters, null);
}
/**
* Execute web script and return result as a string.
*
* @param parameters map of all parameter values
* @return {@link String} result of web script
*/
protected String executeWebScript(Map<String, String> parameters, String content) throws Exception
{
DeclarativeWebScript webScript = getWebScript();
String template = getWebScriptTemplate();
// initialise webscript
webScript.init(getMockedContainer(template), getMockedDescription());
// execute webscript
WebScriptResponse mockedResponse = getMockedWebScriptResponse();
webScript.execute(getMockedWebScriptRequest(webScript, parameters, content), mockedResponse);
// return results
return mockedResponse.getWriter().toString();
}
/**
* Helper method to get the mocked web script request.
*
* @param webScript declarative web script
* @param parameters web script parameter values
* @return {@link WebScriptRequest} mocked web script request
*/
@SuppressWarnings("rawtypes")
protected WebScriptRequest getMockedWebScriptRequest(DeclarativeWebScript webScript, final Map<String, String> parameters, String content) throws Exception
{
Match match = new Match(null, parameters, null, webScript);
org.springframework.extensions.webscripts.Runtime mockedRuntime = mock(org.springframework.extensions.webscripts.Runtime.class);
WebScriptRequest mockedRequest = mock(WebScriptRequest.class);
doReturn(match).when(mockedRequest).getServiceMatch();
doReturn(mockedRuntime).when(mockedRequest).getRuntime();
if (content != null && !content.isEmpty())
{
Content mockedContent = mock(Content.class);
doReturn(content).when(mockedContent).getContent();
doReturn(mockedContent).when(mockedRequest).getContent();
}
String [] paramNames = (String[])parameters.keySet().toArray(new String[parameters.size()]);
doReturn(paramNames).when(mockedRequest).getParameterNames();
doAnswer(new Answer()
{
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
String paramName = (String)invocation.getArguments()[0];
return parameters.get(paramName);
}
}).when(mockedRequest).getParameter(anyString());
doReturn(new String[0]).when(mockedRequest).getHeaderNames();
doReturn("json").when(mockedRequest).getFormat();
return mockedRequest;
}
/**
* Helper method to get mocked web script response
*
* @return {@link WebScriptResponse} mocked web script response
*/
protected WebScriptResponse getMockedWebScriptResponse() throws Exception
{
WebScriptResponse mockedResponse = mock(WebScriptResponse.class);
StringWriter writer = new StringWriter();
doReturn(writer).when(mockedResponse).getWriter();
return mockedResponse;
}
/**
* Helper method to get mocked container object.
*
* @param template classpath location of webscripts ftl template
* @return {@link Container} mocked container
*/
protected Container getMockedContainer(String template) throws Exception
{
FormatRegistry mockedFormatRegistry = mock(FormatRegistry.class);
doReturn("application/json").when(mockedFormatRegistry).getMimeType(anyString(), anyString());
ScriptProcessorRegistry mockedScriptProcessorRegistry = mock(ScriptProcessorRegistry.class);
doReturn(null).when(mockedScriptProcessorRegistry).findValidScriptPath(anyString());
TemplateProcessorRegistry mockedTemplateProcessorRegistry = mock(TemplateProcessorRegistry.class);
doReturn(template).when(mockedTemplateProcessorRegistry).findValidTemplatePath(anyString());
FTLTemplateProcessor ftlTemplateProcessor = new FTLTemplateProcessor()
{
@Override
protected TemplateLoader getTemplateLoader()
{
return new ClassTemplateLoader(getClass(), "/");
}
};
ftlTemplateProcessor.init();
doReturn(ftlTemplateProcessor).when(mockedTemplateProcessorRegistry).getTemplateProcessor(anyString());
Container mockedContainer = mock(Container.class);
doReturn(mockedFormatRegistry).when(mockedContainer).getFormatRegistry();
doReturn(mockedScriptProcessorRegistry).when(mockedContainer).getScriptProcessorRegistry();
doReturn(mockedTemplateProcessorRegistry).when(mockedContainer).getTemplateProcessorRegistry();
Map<String, Object> containerTemplateParameters = new HashMap<String, Object>(5);
containerTemplateParameters.put("jsonUtils", new JSONUtils());
doReturn(containerTemplateParameters).when(mockedContainer).getTemplateParameters();
SearchPath mockedSearchPath = mock(SearchPath.class);
doReturn(false).when(mockedSearchPath).hasDocument(anyString());
doReturn(mockedSearchPath).when(mockedContainer).getSearchPath();
// setup description
Description mockDescription = mock(Description.class);
doReturn(mock(RequiredCache.class)).when(mockDescription).getRequiredCache();
return mockedContainer;
}
/**
* Helper method to get mocked description class
*
* @return {@link DescriptionExtension} mocked description class
*/
protected Description getMockedDescription()
{
Description mockedDescription = mock(Description.class);
doReturn(mock(RequiredCache.class)).when(mockedDescription).getRequiredCache();
return mockedDescription;
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.test.util;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.extensions.surf.util.Content;
import org.springframework.extensions.webscripts.Container;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
import org.springframework.extensions.webscripts.Description;
import org.springframework.extensions.webscripts.Description.RequiredCache;
import org.springframework.extensions.webscripts.DescriptionExtension;
import org.springframework.extensions.webscripts.FormatRegistry;
import org.springframework.extensions.webscripts.Match;
import org.springframework.extensions.webscripts.ScriptProcessorRegistry;
import org.springframework.extensions.webscripts.SearchPath;
import org.springframework.extensions.webscripts.TemplateProcessorRegistry;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;
import org.springframework.extensions.webscripts.json.JSONUtils;
import org.springframework.extensions.webscripts.processor.FTLTemplateProcessor;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.TemplateLoader;
/**
* Base Web Script Unit Test.
* <p>
* Provides helper methods that mock the nessesery classes needed to execute
* a Java backed webscript that implements DeclarativeWebScript.
* <p>
* Note that execution of java script controllers is not currently supported.
*
* @author Roy Wetherall
* @since 2.2
*/
public abstract class BaseWebScriptUnitTest extends BaseUnitTest
{
/** web script root folder for RM webscripts */
protected static final String WEBSCRIPT_ROOT_RM = "alfresco/templates/webscripts/org/alfresco/rma/";
/**
* @return declarative webscript
*/
protected abstract DeclarativeWebScript getWebScript();
/**
* @return classpath location of webscript template
*/
protected abstract String getWebScriptTemplate();
/**
* Helper method to build a map of web script parameter values
* mimicking those provided on the URL
*
* @param values
* @return
*/
protected Map<String, String> buildParameters(String ... values)
{
Map<String, String> result = new HashMap<String, String>(values.length/2);
for (int i = 0; i < values.length; i=i+2)
{
String key = values[i];
String value = values[i+1];
result.put(key, value);
}
return result;
}
/**
*
* @param parameters
* @return
* @throws Exception
*/
protected JSONObject executeJSONWebScript(Map<String, String> parameters) throws Exception
{
return executeJSONWebScript(parameters, null);
}
/**
* Execute web script and convert result into a JSON object.
*
* @param parameters map of all parameter values
* @return {@link JSONObject} result, parsed into a JSON object
*/
protected JSONObject executeJSONWebScript(Map<String, String> parameters, String content) throws Exception
{
String result = executeWebScript(parameters, content);
return new JSONObject(result);
}
/**
*
* @param parameters
* @return
* @throws Exception
*/
protected String executeWebScript(Map<String, String> parameters) throws Exception
{
return executeWebScript( parameters, null);
}
/**
* Execute web script and return result as a string.
*
* @param parameters map of all parameter values
* @return {@link String} result of web script
*/
protected String executeWebScript(Map<String, String> parameters, String content) throws Exception
{
DeclarativeWebScript webScript = getWebScript();
String template = getWebScriptTemplate();
// initialise webscript
webScript.init(getMockedContainer(template), getMockedDescription());
// execute webscript
WebScriptResponse mockedResponse = getMockedWebScriptResponse();
webScript.execute(getMockedWebScriptRequest(webScript, parameters, content), mockedResponse);
// return results
return mockedResponse.getWriter().toString();
}
/**
* Helper method to get the mocked web script request.
*
* @param webScript declarative web script
* @param parameters web script parameter values
* @return {@link WebScriptRequest} mocked web script request
*/
@SuppressWarnings("rawtypes")
protected WebScriptRequest getMockedWebScriptRequest(DeclarativeWebScript webScript, final Map<String, String> parameters, String content) throws Exception
{
Match match = new Match(null, parameters, null, webScript);
org.springframework.extensions.webscripts.Runtime mockedRuntime = mock(org.springframework.extensions.webscripts.Runtime.class);
WebScriptRequest mockedRequest = mock(WebScriptRequest.class);
doReturn(match).when(mockedRequest).getServiceMatch();
doReturn(mockedRuntime).when(mockedRequest).getRuntime();
if (content != null && !content.isEmpty())
{
Content mockedContent = mock(Content.class);
doReturn(content).when(mockedContent).getContent();
doReturn(mockedContent).when(mockedRequest).getContent();
}
String [] paramNames = (String[])parameters.keySet().toArray(new String[parameters.size()]);
doReturn(paramNames).when(mockedRequest).getParameterNames();
doAnswer(new Answer()
{
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
String paramName = (String)invocation.getArguments()[0];
return parameters.get(paramName);
}
}).when(mockedRequest).getParameter(anyString());
doReturn(new String[0]).when(mockedRequest).getHeaderNames();
doReturn("json").when(mockedRequest).getFormat();
return mockedRequest;
}
/**
* Helper method to get mocked web script response
*
* @return {@link WebScriptResponse} mocked web script response
*/
protected WebScriptResponse getMockedWebScriptResponse() throws Exception
{
WebScriptResponse mockedResponse = mock(WebScriptResponse.class);
StringWriter writer = new StringWriter();
doReturn(writer).when(mockedResponse).getWriter();
return mockedResponse;
}
/**
* Helper method to get mocked container object.
*
* @param template classpath location of webscripts ftl template
* @return {@link Container} mocked container
*/
protected Container getMockedContainer(String template) throws Exception
{
FormatRegistry mockedFormatRegistry = mock(FormatRegistry.class);
doReturn("application/json").when(mockedFormatRegistry).getMimeType(anyString(), anyString());
ScriptProcessorRegistry mockedScriptProcessorRegistry = mock(ScriptProcessorRegistry.class);
doReturn(null).when(mockedScriptProcessorRegistry).findValidScriptPath(anyString());
TemplateProcessorRegistry mockedTemplateProcessorRegistry = mock(TemplateProcessorRegistry.class);
doReturn(template).when(mockedTemplateProcessorRegistry).findValidTemplatePath(anyString());
FTLTemplateProcessor ftlTemplateProcessor = new FTLTemplateProcessor()
{
@Override
protected TemplateLoader getTemplateLoader()
{
return new ClassTemplateLoader(getClass(), "/");
}
};
ftlTemplateProcessor.init();
doReturn(ftlTemplateProcessor).when(mockedTemplateProcessorRegistry).getTemplateProcessor(anyString());
Container mockedContainer = mock(Container.class);
doReturn(mockedFormatRegistry).when(mockedContainer).getFormatRegistry();
doReturn(mockedScriptProcessorRegistry).when(mockedContainer).getScriptProcessorRegistry();
doReturn(mockedTemplateProcessorRegistry).when(mockedContainer).getTemplateProcessorRegistry();
Map<String, Object> containerTemplateParameters = new HashMap<String, Object>(5);
containerTemplateParameters.put("jsonUtils", new JSONUtils());
doReturn(containerTemplateParameters).when(mockedContainer).getTemplateParameters();
SearchPath mockedSearchPath = mock(SearchPath.class);
doReturn(false).when(mockedSearchPath).hasDocument(anyString());
doReturn(mockedSearchPath).when(mockedContainer).getSearchPath();
// setup description
Description mockDescription = mock(Description.class);
doReturn(mock(RequiredCache.class)).when(mockDescription).getRequiredCache();
return mockedContainer;
}
/**
* Helper method to get mocked description class
*
* @return {@link DescriptionExtension} mocked description class
*/
protected Description getMockedDescription()
{
Description mockedDescription = mock(Description.class);
doReturn(mock(RequiredCache.class)).when(mockedDescription).getRequiredCache();
return mockedDescription;
}
}

View File

@@ -1,80 +1,80 @@
package org.alfresco.module.org_alfresco_module_rm.test.util;
import org.junit.internal.matchers.TypeSafeMatcher;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptException;
/**
* Web script exception matcher.
* <p>
* Allows use to check whether the raised web script exception has the correct
* status number or not.
*
* @author Roy Wetherall
* @since 2.2
*/
@SuppressWarnings("deprecation")
public class WebScriptExceptionMatcher extends TypeSafeMatcher<WebScriptException>
{
/**
* Helper method to create a matcher for the file not found (404)
* exception status.
*
* @return {@link WebScriptExceptionMatcher}
*/
public static WebScriptExceptionMatcher fileNotFound()
{
return new WebScriptExceptionMatcher(Status.STATUS_NOT_FOUND);
}
/**
* Helper method to create a matcher for the bad request status (400)
* exception status.
*
* @return {@link WebScriptExceptionMatcher}
*/
public static WebScriptExceptionMatcher badRequest()
{
return new WebScriptExceptionMatcher(Status.STATUS_BAD_REQUEST);
}
/** expected status */
public int expectedStatus;
/** actual status */
public int actualStatus;
/**
* Constructor
*
* @param expectedStatus expected status
*/
public WebScriptExceptionMatcher(int expectedStatus)
{
this.expectedStatus = expectedStatus;
}
/**
* Determines if the expected outcome matches the actual
* outcome.
*
* @return true if matches, false otherwise
*/
@Override
public boolean matchesSafely(WebScriptException exception)
{
actualStatus = exception.getStatus();
return (actualStatus == expectedStatus);
}
/**
* Describe unexpected outcome.
*/
@Override
public void describeTo(org.hamcrest.Description description)
{
description.appendValue(actualStatus)
.appendText(" was found instead of ")
.appendValue(expectedStatus);
}
package org.alfresco.module.org_alfresco_module_rm.test.util;
import org.junit.internal.matchers.TypeSafeMatcher;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptException;
/**
* Web script exception matcher.
* <p>
* Allows use to check whether the raised web script exception has the correct
* status number or not.
*
* @author Roy Wetherall
* @since 2.2
*/
@SuppressWarnings("deprecation")
public class WebScriptExceptionMatcher extends TypeSafeMatcher<WebScriptException>
{
/**
* Helper method to create a matcher for the file not found (404)
* exception status.
*
* @return {@link WebScriptExceptionMatcher}
*/
public static WebScriptExceptionMatcher fileNotFound()
{
return new WebScriptExceptionMatcher(Status.STATUS_NOT_FOUND);
}
/**
* Helper method to create a matcher for the bad request status (400)
* exception status.
*
* @return {@link WebScriptExceptionMatcher}
*/
public static WebScriptExceptionMatcher badRequest()
{
return new WebScriptExceptionMatcher(Status.STATUS_BAD_REQUEST);
}
/** expected status */
public int expectedStatus;
/** actual status */
public int actualStatus;
/**
* Constructor
*
* @param expectedStatus expected status
*/
public WebScriptExceptionMatcher(int expectedStatus)
{
this.expectedStatus = expectedStatus;
}
/**
* Determines if the expected outcome matches the actual
* outcome.
*
* @return true if matches, false otherwise
*/
@Override
public boolean matchesSafely(WebScriptException exception)
{
actualStatus = exception.getStatus();
return (actualStatus == expectedStatus);
}
/**
* Describe unexpected outcome.
*/
@Override
public void describeTo(org.hamcrest.Description description)
{
description.appendValue(actualStatus)
.appendText(" was found instead of ")
.appendValue(expectedStatus);
}
}

View File

@@ -1,498 +1,498 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.version;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.version.Version2Model;
import org.alfresco.repo.version.VersionModel;
import org.alfresco.repo.version.common.VersionImpl;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.version.Version;
import org.alfresco.service.cmr.version.VersionType;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
/**
* Recordable version service implementation unit test.
*
* @author Roy Wetherall
* @since 2.3
*/
public class RecordableVersionServiceImplUnitTest extends BaseUnitTest
{
/** versioned content name */
private static final String CONTENT_NAME = "test.txt";
/** versioned node reference */
private NodeRef nodeRef;
private NodeRef record;
private NodeRef unfiledRecordContainer;
private NodeRef version;
/** mocked version properties */
private Map<String, Serializable> versionProperties;
/** mocked services */
private @Mock(name="dbNodeService") NodeService mockedDbNodeService;
/** recordable version service */
private @InjectMocks @Spy TestRecordableVersionServiceImpl recordableVersionService;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@SuppressWarnings("unchecked")
@Override
public void before() throws Exception
{
super.before();
nodeRef = generateCmContent(CONTENT_NAME);
doReturn(123l).when(mockedNodeService).getProperty(nodeRef, ContentModel.PROP_NODE_DBID);
versionProperties = new HashMap<String, Serializable>(5);
recordableVersionService.initialise();
doReturn(generateChildAssociationRef(null, generateNodeRef(Version2Model.TYPE_QNAME_VERSION_HISTORY)))
.when(mockedDbNodeService).createNode(any(NodeRef.class),
any(QName.class),
any(QName.class),
eq(Version2Model.TYPE_QNAME_VERSION_HISTORY),
anyMap());
doReturn(generateChildAssociationRef(null, generateNodeRef(TYPE_CONTENT)))
.when(mockedDbNodeService).createNode(any(NodeRef.class),
any(QName.class),
any(QName.class),
eq(TYPE_CONTENT),
anyMap());
doReturn(filePlan).when(mockedFilePlanService).getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
doReturn(unfiledRecordContainer).when(mockedFilePlanService).getUnfiledContainer(any(NodeRef.class));
record = generateCmContent(CONTENT_NAME);
FileInfo mockedFileInfo = mock(FileInfo.class);
doReturn(record).when(mockedFileInfo).getNodeRef();
doReturn(mockedFileInfo).when(mockedFileFolderService).copy(any(NodeRef.class),
any(NodeRef.class),
any(String.class));
version = generateNodeRef(TYPE_CONTENT);
doReturn(generateChildAssociationRef(null, version)).when(mockedDbNodeService).createNode(
any(NodeRef.class),
eq(Version2Model.CHILD_QNAME_VERSIONS),
any(QName.class),
eq(TYPE_CONTENT),
anyMap());
}
/**
* Given that the node has no recordable version aspect
* When I create a version
* Then version service creates a normal version.
*/
@Test
public void noAspect() throws Exception
{
// setup given conditions
doReturn(false).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then a normal version is created
verifyNormalVersion();
}
/**
* Given that the node has a recordable version policy of null
* When I create a version
* Then the version service creates a normal version.
*/
@Test
public void policyNull() throws Exception
{
// setup given conditions
doReturn(false).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(null).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then a normal version is created
verifyNormalVersion();
}
/**
* Given that the node has a recordable version policy of NONE
* When I create a version
* Then the version service creates a normal version.
*/
@Test
public void policyNone() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.NONE.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then a normal version is created
verifyNormalVersion();
}
/**
* Given that the node has a recordable version policy of ALL
* When I create a MINOR version then
* the version service creates a recorded version
*/
@Test
public void policyAllVersionMinor() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.ALL.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(1)).createRecordFromCopy(filePlan, nodeRef);
}
/**
* Helper method that verified that a recorded version was not created.
*/
@SuppressWarnings("unchecked")
private void verifyNormalVersion() throws Exception
{
// verify no interactions
verify(mockedFilePlanService, never()).getUnfiledContainer(any(NodeRef.class));
verify(mockedFileFolderService, never()).copy(eq(nodeRef),
eq(unfiledRecordContainer),
anyString());
// then the version is created
verify(mockedDbNodeService, times(1)).createNode(any(NodeRef.class),
eq(Version2Model.CHILD_QNAME_VERSIONS),
any(QName.class),
eq(TYPE_CONTENT),
anyMap());
verify(mockedNodeService, times(1)).addAspect(eq(version), eq(Version2Model.ASPECT_VERSION), anyMap());
verify(mockedNodeService, never()).addAspect(eq(version), eq(RecordableVersionModel.PROP_RECORD_NODE_REF), anyMap());
}
/**
* Given that the node has a recordable version policy of ALL
* When I create a MAJOR version then
* the version service creates a recorded version
*/
@Test
public void policyAllVersionMajor() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.ALL.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(1)).createRecordFromCopy(filePlan, nodeRef);
}
/**
* Given that the node has a recordable version policy of MAJOR_ONLY
* When I create a MINOR version then
* the version service creates a normal version
*/
@Test
public void policyMajorOnlyVersionMinor() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.MAJOR_ONLY.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then a normal version is created
verifyNormalVersion();
}
/**
* Given that the node has a recordable version policy of MAJOR_ONLY
* When I create a MAJOR version then
* the version service creates a recorded version
*/
@Test
public void policyMajorOnlyVersionMajor() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.MAJOR_ONLY.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(1)).createRecordFromCopy(filePlan, nodeRef);
}
/**
* Given that the node has a valid recordable version policy
* And there is no file plan
* When I create a new version
* Then an exception should be thrown to indicate that there is no file plan
*/
@Test
public void noFilePlan() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.MAJOR_ONLY.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
doReturn(null).when(mockedFilePlanService).getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
// expected exception
exception.expect(AlfrescoRuntimeException.class);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
}
/**
* Given that the node has a valid recordable version policy
* And that I set a specific file plan in the version properties
* When I create a new version
* Then the recorded version should be directed to the specified file plan, not the default file plan
*/
@Test
public void filePlanSpecifiedWithPolicy() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.MAJOR_ONLY.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
// specify the file plan
NodeRef anotherFilePlan = generateNodeRef(TYPE_FILE_PLAN);
versionProperties.put(RecordableVersionServiceImpl.KEY_FILE_PLAN, anotherFilePlan);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(0)).createRecordFromCopy(filePlan, nodeRef);
}
/**
* Given that the node has specifically indicated that a recorded version should be created
* And that I set a specific file plan in the version properties
* When I create a new version
* Then the recorded version should be directed to the specified file plan, not the default file plan
*/
@Test
public void filePlanSpecifiedNoPolicy() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
versionProperties.put(RecordableVersionServiceImpl.KEY_RECORDABLE_VERSION, true);
// specify the file plan
NodeRef anotherFilePlan = generateNodeRef(TYPE_FILE_PLAN);
versionProperties.put(RecordableVersionServiceImpl.KEY_FILE_PLAN, anotherFilePlan);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(0)).createRecordFromCopy(filePlan, nodeRef);
}
@Test
public void adHocRecordedVersionNoPolicy() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
versionProperties.put(RecordableVersionServiceImpl.KEY_RECORDABLE_VERSION, true);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(1)).createRecordFromCopy(filePlan, nodeRef);
}
@Test
public void adHocRecordedVersionOverridePolicy() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.MAJOR_ONLY.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
versionProperties.put(RecordableVersionServiceImpl.KEY_RECORDABLE_VERSION, true);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(1)).createRecordFromCopy(filePlan, nodeRef);
}
/**
* Given that a node is not versionable
* When I try and create a record from the latest version
* Then nothing will happen, because there is not version to record
*/
@Test
public void notVersionableCreateRecordFromVersion()
{
// content node is not versionable
doReturn(false).when(mockedNodeService).hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE);
// create record from version
recordableVersionService.createRecordFromLatestVersion(filePlan, nodeRef);
// nothing happens
verify(mockedRecordService, never()).createRecordFromCopy(eq(filePlan), any(NodeRef.class));
}
/**
* Given that a nodes last version is recorded
* When I try and create a record from the latest version
* Then nothing will happen, because the latest version is already recorded
*/
@Test
public void alreadyRecordedCreateRecordFromVersion()
{
// latest version is already recorded
Version mockedVersion = mock(VersionImpl.class);
doReturn(Collections.singletonMap(RecordableVersionServiceImpl.PROP_VERSION_RECORD, generateNodeRef())).when(mockedVersion).getVersionProperties();
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(mockedVersion).when(recordableVersionService).getCurrentVersion(nodeRef);
// create record from version
recordableVersionService.createRecordFromLatestVersion(filePlan, nodeRef);
// nothing happens
verify(mockedRecordService, never()).createRecordFromCopy(eq(filePlan), any(NodeRef.class));
}
/**
* Given that a nodes last version is not recorded
* When I try to create a record from the latest version
* Then the latest version is marked as record and a new record version is created to store the version state
*/
@SuppressWarnings("unchecked")
@Test
public void notRecordedCreateRecordFromVersion()
{
// latest version is not recorded
Version mockedVersion = mock(VersionImpl.class);
NodeRef versionNodeRef = generateNodeRef();
doReturn(Collections.emptyMap()).when(mockedVersion).getVersionProperties();
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE);
// version history
NodeRef versionHistoryNodeRef = generateNodeRef();
doReturn(versionHistoryNodeRef).when(mockedDbNodeService).getChildByName(any(NodeRef.class), eq(Version2Model.CHILD_QNAME_VERSION_HISTORIES), any(String.class));
// version number
doReturn(mockedVersion).when(recordableVersionService).getCurrentVersion(nodeRef);
doReturn(versionNodeRef).when(recordableVersionService).convertNodeRef(any(NodeRef.class));
makePrimaryParentOf(versionNodeRef, versionHistoryNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "something-0"), mockedDbNodeService);
// created version
NodeRef newVersionNodeRef = generateNodeRef();
doReturn(generateChildAssociationRef(versionHistoryNodeRef, newVersionNodeRef)).when(mockedDbNodeService).createNode(
eq(versionHistoryNodeRef),
eq(Version2Model.CHILD_QNAME_VERSIONS),
any(QName.class),
any(QName.class),
any(Map.class));
// created record
NodeRef newRecordNodeRef = generateNodeRef();
doReturn(newRecordNodeRef).when(mockedRecordService).createRecordFromContent(
eq(filePlan),
any(String.class),
any(QName.class),
any(Map.class),
any(ContentReader.class));
// create record from version
recordableVersionService.createRecordFromLatestVersion(filePlan, nodeRef);
// verify that the version is converted to a recorded version
verify(mockedRecordService, times(1)).createRecordFromContent(
eq(filePlan),
any(String.class),
any(QName.class),
any(Map.class),
any(ContentReader.class));
verify(mockedDbNodeService, times(1)).deleteNode(any(NodeRef.class));
verify(mockedDbNodeService, times(1)).createNode(
eq(versionHistoryNodeRef),
eq(Version2Model.CHILD_QNAME_VERSIONS),
any(QName.class),
any(QName.class),
any(Map.class));
verify(mockedNodeService, times(1)).addAspect(eq(newVersionNodeRef), eq(Version2Model.ASPECT_VERSION), any(Map.class));
verify(mockedNodeService, times(1)).addAspect(
newVersionNodeRef,
RecordableVersionModel.ASPECT_RECORDED_VERSION,
Collections.singletonMap(RecordableVersionModel.PROP_RECORD_NODE_REF, (Serializable)newRecordNodeRef));
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.version;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.module.org_alfresco_module_rm.fileplan.FilePlanService;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest;
import org.alfresco.repo.version.Version2Model;
import org.alfresco.repo.version.VersionModel;
import org.alfresco.repo.version.common.VersionImpl;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.version.Version;
import org.alfresco.service.cmr.version.VersionType;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
/**
* Recordable version service implementation unit test.
*
* @author Roy Wetherall
* @since 2.3
*/
public class RecordableVersionServiceImplUnitTest extends BaseUnitTest
{
/** versioned content name */
private static final String CONTENT_NAME = "test.txt";
/** versioned node reference */
private NodeRef nodeRef;
private NodeRef record;
private NodeRef unfiledRecordContainer;
private NodeRef version;
/** mocked version properties */
private Map<String, Serializable> versionProperties;
/** mocked services */
private @Mock(name="dbNodeService") NodeService mockedDbNodeService;
/** recordable version service */
private @InjectMocks @Spy TestRecordableVersionServiceImpl recordableVersionService;
/**
* @see org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest#before()
*/
@SuppressWarnings("unchecked")
@Override
public void before() throws Exception
{
super.before();
nodeRef = generateCmContent(CONTENT_NAME);
doReturn(123l).when(mockedNodeService).getProperty(nodeRef, ContentModel.PROP_NODE_DBID);
versionProperties = new HashMap<String, Serializable>(5);
recordableVersionService.initialise();
doReturn(generateChildAssociationRef(null, generateNodeRef(Version2Model.TYPE_QNAME_VERSION_HISTORY)))
.when(mockedDbNodeService).createNode(any(NodeRef.class),
any(QName.class),
any(QName.class),
eq(Version2Model.TYPE_QNAME_VERSION_HISTORY),
anyMap());
doReturn(generateChildAssociationRef(null, generateNodeRef(TYPE_CONTENT)))
.when(mockedDbNodeService).createNode(any(NodeRef.class),
any(QName.class),
any(QName.class),
eq(TYPE_CONTENT),
anyMap());
doReturn(filePlan).when(mockedFilePlanService).getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
doReturn(unfiledRecordContainer).when(mockedFilePlanService).getUnfiledContainer(any(NodeRef.class));
record = generateCmContent(CONTENT_NAME);
FileInfo mockedFileInfo = mock(FileInfo.class);
doReturn(record).when(mockedFileInfo).getNodeRef();
doReturn(mockedFileInfo).when(mockedFileFolderService).copy(any(NodeRef.class),
any(NodeRef.class),
any(String.class));
version = generateNodeRef(TYPE_CONTENT);
doReturn(generateChildAssociationRef(null, version)).when(mockedDbNodeService).createNode(
any(NodeRef.class),
eq(Version2Model.CHILD_QNAME_VERSIONS),
any(QName.class),
eq(TYPE_CONTENT),
anyMap());
}
/**
* Given that the node has no recordable version aspect
* When I create a version
* Then version service creates a normal version.
*/
@Test
public void noAspect() throws Exception
{
// setup given conditions
doReturn(false).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then a normal version is created
verifyNormalVersion();
}
/**
* Given that the node has a recordable version policy of null
* When I create a version
* Then the version service creates a normal version.
*/
@Test
public void policyNull() throws Exception
{
// setup given conditions
doReturn(false).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(null).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then a normal version is created
verifyNormalVersion();
}
/**
* Given that the node has a recordable version policy of NONE
* When I create a version
* Then the version service creates a normal version.
*/
@Test
public void policyNone() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.NONE.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then a normal version is created
verifyNormalVersion();
}
/**
* Given that the node has a recordable version policy of ALL
* When I create a MINOR version then
* the version service creates a recorded version
*/
@Test
public void policyAllVersionMinor() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.ALL.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(1)).createRecordFromCopy(filePlan, nodeRef);
}
/**
* Helper method that verified that a recorded version was not created.
*/
@SuppressWarnings("unchecked")
private void verifyNormalVersion() throws Exception
{
// verify no interactions
verify(mockedFilePlanService, never()).getUnfiledContainer(any(NodeRef.class));
verify(mockedFileFolderService, never()).copy(eq(nodeRef),
eq(unfiledRecordContainer),
anyString());
// then the version is created
verify(mockedDbNodeService, times(1)).createNode(any(NodeRef.class),
eq(Version2Model.CHILD_QNAME_VERSIONS),
any(QName.class),
eq(TYPE_CONTENT),
anyMap());
verify(mockedNodeService, times(1)).addAspect(eq(version), eq(Version2Model.ASPECT_VERSION), anyMap());
verify(mockedNodeService, never()).addAspect(eq(version), eq(RecordableVersionModel.PROP_RECORD_NODE_REF), anyMap());
}
/**
* Given that the node has a recordable version policy of ALL
* When I create a MAJOR version then
* the version service creates a recorded version
*/
@Test
public void policyAllVersionMajor() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.ALL.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(1)).createRecordFromCopy(filePlan, nodeRef);
}
/**
* Given that the node has a recordable version policy of MAJOR_ONLY
* When I create a MINOR version then
* the version service creates a normal version
*/
@Test
public void policyMajorOnlyVersionMinor() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.MAJOR_ONLY.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then a normal version is created
verifyNormalVersion();
}
/**
* Given that the node has a recordable version policy of MAJOR_ONLY
* When I create a MAJOR version then
* the version service creates a recorded version
*/
@Test
public void policyMajorOnlyVersionMajor() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.MAJOR_ONLY.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(1)).createRecordFromCopy(filePlan, nodeRef);
}
/**
* Given that the node has a valid recordable version policy
* And there is no file plan
* When I create a new version
* Then an exception should be thrown to indicate that there is no file plan
*/
@Test
public void noFilePlan() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.MAJOR_ONLY.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
doReturn(null).when(mockedFilePlanService).getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
// expected exception
exception.expect(AlfrescoRuntimeException.class);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
}
/**
* Given that the node has a valid recordable version policy
* And that I set a specific file plan in the version properties
* When I create a new version
* Then the recorded version should be directed to the specified file plan, not the default file plan
*/
@Test
public void filePlanSpecifiedWithPolicy() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.MAJOR_ONLY.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
// specify the file plan
NodeRef anotherFilePlan = generateNodeRef(TYPE_FILE_PLAN);
versionProperties.put(RecordableVersionServiceImpl.KEY_FILE_PLAN, anotherFilePlan);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(0)).createRecordFromCopy(filePlan, nodeRef);
}
/**
* Given that the node has specifically indicated that a recorded version should be created
* And that I set a specific file plan in the version properties
* When I create a new version
* Then the recorded version should be directed to the specified file plan, not the default file plan
*/
@Test
public void filePlanSpecifiedNoPolicy() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
versionProperties.put(RecordableVersionServiceImpl.KEY_RECORDABLE_VERSION, true);
// specify the file plan
NodeRef anotherFilePlan = generateNodeRef(TYPE_FILE_PLAN);
versionProperties.put(RecordableVersionServiceImpl.KEY_FILE_PLAN, anotherFilePlan);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(0)).createRecordFromCopy(filePlan, nodeRef);
}
@Test
public void adHocRecordedVersionNoPolicy() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
versionProperties.put(RecordableVersionServiceImpl.KEY_RECORDABLE_VERSION, true);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(1)).createRecordFromCopy(filePlan, nodeRef);
}
@Test
public void adHocRecordedVersionOverridePolicy() throws Exception
{
// setup given conditions
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, RecordableVersionModel.ASPECT_VERSIONABLE);
doReturn(RecordableVersionPolicy.MAJOR_ONLY.toString()).when(mockedNodeService).getProperty(nodeRef, RecordableVersionModel.PROP_RECORDABLE_VERSION_POLICY);
versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
versionProperties.put(RecordableVersionServiceImpl.KEY_RECORDABLE_VERSION, true);
// when version is created
recordableVersionService.createVersion(nodeRef, versionProperties);
// then the recorded version is created
verify(mockedRecordService, times(1)).createRecordFromCopy(filePlan, nodeRef);
}
/**
* Given that a node is not versionable
* When I try and create a record from the latest version
* Then nothing will happen, because there is not version to record
*/
@Test
public void notVersionableCreateRecordFromVersion()
{
// content node is not versionable
doReturn(false).when(mockedNodeService).hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE);
// create record from version
recordableVersionService.createRecordFromLatestVersion(filePlan, nodeRef);
// nothing happens
verify(mockedRecordService, never()).createRecordFromCopy(eq(filePlan), any(NodeRef.class));
}
/**
* Given that a nodes last version is recorded
* When I try and create a record from the latest version
* Then nothing will happen, because the latest version is already recorded
*/
@Test
public void alreadyRecordedCreateRecordFromVersion()
{
// latest version is already recorded
Version mockedVersion = mock(VersionImpl.class);
doReturn(Collections.singletonMap(RecordableVersionServiceImpl.PROP_VERSION_RECORD, generateNodeRef())).when(mockedVersion).getVersionProperties();
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE);
doReturn(mockedVersion).when(recordableVersionService).getCurrentVersion(nodeRef);
// create record from version
recordableVersionService.createRecordFromLatestVersion(filePlan, nodeRef);
// nothing happens
verify(mockedRecordService, never()).createRecordFromCopy(eq(filePlan), any(NodeRef.class));
}
/**
* Given that a nodes last version is not recorded
* When I try to create a record from the latest version
* Then the latest version is marked as record and a new record version is created to store the version state
*/
@SuppressWarnings("unchecked")
@Test
public void notRecordedCreateRecordFromVersion()
{
// latest version is not recorded
Version mockedVersion = mock(VersionImpl.class);
NodeRef versionNodeRef = generateNodeRef();
doReturn(Collections.emptyMap()).when(mockedVersion).getVersionProperties();
doReturn(true).when(mockedNodeService).hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE);
// version history
NodeRef versionHistoryNodeRef = generateNodeRef();
doReturn(versionHistoryNodeRef).when(mockedDbNodeService).getChildByName(any(NodeRef.class), eq(Version2Model.CHILD_QNAME_VERSION_HISTORIES), any(String.class));
// version number
doReturn(mockedVersion).when(recordableVersionService).getCurrentVersion(nodeRef);
doReturn(versionNodeRef).when(recordableVersionService).convertNodeRef(any(NodeRef.class));
makePrimaryParentOf(versionNodeRef, versionHistoryNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "something-0"), mockedDbNodeService);
// created version
NodeRef newVersionNodeRef = generateNodeRef();
doReturn(generateChildAssociationRef(versionHistoryNodeRef, newVersionNodeRef)).when(mockedDbNodeService).createNode(
eq(versionHistoryNodeRef),
eq(Version2Model.CHILD_QNAME_VERSIONS),
any(QName.class),
any(QName.class),
any(Map.class));
// created record
NodeRef newRecordNodeRef = generateNodeRef();
doReturn(newRecordNodeRef).when(mockedRecordService).createRecordFromContent(
eq(filePlan),
any(String.class),
any(QName.class),
any(Map.class),
any(ContentReader.class));
// create record from version
recordableVersionService.createRecordFromLatestVersion(filePlan, nodeRef);
// verify that the version is converted to a recorded version
verify(mockedRecordService, times(1)).createRecordFromContent(
eq(filePlan),
any(String.class),
any(QName.class),
any(Map.class),
any(ContentReader.class));
verify(mockedDbNodeService, times(1)).deleteNode(any(NodeRef.class));
verify(mockedDbNodeService, times(1)).createNode(
eq(versionHistoryNodeRef),
eq(Version2Model.CHILD_QNAME_VERSIONS),
any(QName.class),
any(QName.class),
any(Map.class));
verify(mockedNodeService, times(1)).addAspect(eq(newVersionNodeRef), eq(Version2Model.ASPECT_VERSION), any(Map.class));
verify(mockedNodeService, times(1)).addAspect(
newVersionNodeRef,
RecordableVersionModel.ASPECT_RECORDED_VERSION,
Collections.singletonMap(RecordableVersionModel.PROP_RECORD_NODE_REF, (Serializable)newRecordNodeRef));
}
}

View File

@@ -1,62 +1,62 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.version;
import java.io.Serializable;
import java.util.Map;
import org.alfresco.repo.policy.PolicyScope;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.version.Version;
import org.alfresco.service.namespace.QName;
/**
* Helper class to help with the unit testing of RecordableVersionServiceImpl.
*
* @author Roy Wetherall
* @since 2.3
*/
public class TestRecordableVersionServiceImpl extends RecordableVersionServiceImpl
{
@Override
protected void invokeBeforeCreateVersion(NodeRef nodeRef)
{
}
@Override
protected void invokeAfterCreateVersion(NodeRef nodeRef, Version version)
{
}
@Override
protected void invokeAfterVersionRevert(NodeRef nodeRef, Version version)
{
}
@Override
protected void invokeOnCreateVersion(NodeRef nodeRef, Map<String, Serializable> versionProperties,PolicyScope nodeDetails)
{
}
@Override
protected String invokeCalculateVersionLabel(QName classRef, Version preceedingVersion, int versionNumber, Map<String, Serializable> versionProperties)
{
return "1.1";
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.module.org_alfresco_module_rm.version;
import java.io.Serializable;
import java.util.Map;
import org.alfresco.repo.policy.PolicyScope;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.version.Version;
import org.alfresco.service.namespace.QName;
/**
* Helper class to help with the unit testing of RecordableVersionServiceImpl.
*
* @author Roy Wetherall
* @since 2.3
*/
public class TestRecordableVersionServiceImpl extends RecordableVersionServiceImpl
{
@Override
protected void invokeBeforeCreateVersion(NodeRef nodeRef)
{
}
@Override
protected void invokeAfterCreateVersion(NodeRef nodeRef, Version version)
{
}
@Override
protected void invokeAfterVersionRevert(NodeRef nodeRef, Version version)
{
}
@Override
protected void invokeOnCreateVersion(NodeRef nodeRef, Map<String, Serializable> versionProperties,PolicyScope nodeDetails)
{
}
@Override
protected String invokeCalculateVersionLabel(QName classRef, Version preceedingVersion, int versionNumber, Map<String, Serializable> versionProperties)
{
return "1.1";
}
}

View File

@@ -1,122 +1,122 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.action.parameter;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the DateParameterProcessor
*
* @author Mark Hibbins
* @since 2.2
*/
public class DateParameterProcessorUnitTest
{
private DateParameterProcessor dateParameterProcessor;
@Before
public void setUp() throws Exception
{
this.dateParameterProcessor = new DateParameterProcessor();
this.dateParameterProcessor.setName("date");
}
@Test
public void testGetSubstitutionSuggestions_01()
{
List<String> suggestions = this.dateParameterProcessor.getSubstitutionSuggestions("date");
assertTrue(suggestions.contains("date.day.short"));
assertTrue(suggestions.contains("date.day"));
assertTrue(suggestions.contains("date.day.long"));
assertTrue(suggestions.contains("date.day.number"));
assertTrue(suggestions.contains("date.day.month"));
assertTrue(suggestions.contains("date.day.year"));
assertTrue(suggestions.contains("date.month.short"));
assertTrue(suggestions.contains("date.month"));
assertTrue(suggestions.contains("date.month.long"));
assertTrue(suggestions.contains("date.month.number"));
assertEquals(10, suggestions.size());
}
@Test
public void testGetSubstitutionSuggestions_02()
{
List<String> suggestions = this.dateParameterProcessor.getSubstitutionSuggestions("dat");
assertTrue(suggestions.contains("date.day.short"));
assertTrue(suggestions.contains("date.day"));
assertTrue(suggestions.contains("date.day.long"));
assertTrue(suggestions.contains("date.day.number"));
assertTrue(suggestions.contains("date.day.month"));
assertTrue(suggestions.contains("date.day.year"));
assertTrue(suggestions.contains("date.month.short"));
assertTrue(suggestions.contains("date.month"));
assertTrue(suggestions.contains("date.month.long"));
assertTrue(suggestions.contains("date.month.number"));
assertEquals(10, suggestions.size());
}
@Test
public void testGetSubstitutionSuggestions_03()
{
List<String> suggestions = this.dateParameterProcessor.getSubstitutionSuggestions("at");
assertTrue(suggestions.contains("date.day.short"));
assertTrue(suggestions.contains("date.day"));
assertTrue(suggestions.contains("date.day.long"));
assertTrue(suggestions.contains("date.day.number"));
assertTrue(suggestions.contains("date.day.month"));
assertTrue(suggestions.contains("date.day.year"));
assertTrue(suggestions.contains("date.month.short"));
assertTrue(suggestions.contains("date.month"));
assertTrue(suggestions.contains("date.month.long"));
assertTrue(suggestions.contains("date.month.number"));
assertEquals(10, suggestions.size());
}
@Test
public void testGetSubstitutionSuggestions_05()
{
List<String> suggestions = this.dateParameterProcessor.getSubstitutionSuggestions("ay");
assertTrue(suggestions.contains("date.day.short"));
assertTrue(suggestions.contains("date.day"));
assertTrue(suggestions.contains("date.day.long"));
assertTrue(suggestions.contains("date.day.number"));
assertTrue(suggestions.contains("date.day.month"));
assertTrue(suggestions.contains("date.day.year"));
assertEquals(6, suggestions.size());
}
@Test
public void testGetSubstitutionSuggestions_06()
{
List<String> suggestions = this.dateParameterProcessor.getSubstitutionSuggestions("on");
assertTrue(suggestions.contains("date.day.long"));
assertTrue(suggestions.contains("date.month.short"));
assertTrue(suggestions.contains("date.month"));
assertTrue(suggestions.contains("date.month.long"));
assertTrue(suggestions.contains("date.month.number"));
assertTrue(suggestions.contains("date.year.long"));
assertTrue(suggestions.contains("date.day.month"));
assertEquals(7, suggestions.size());
}
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.action.parameter;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the DateParameterProcessor
*
* @author Mark Hibbins
* @since 2.2
*/
public class DateParameterProcessorUnitTest
{
private DateParameterProcessor dateParameterProcessor;
@Before
public void setUp() throws Exception
{
this.dateParameterProcessor = new DateParameterProcessor();
this.dateParameterProcessor.setName("date");
}
@Test
public void testGetSubstitutionSuggestions_01()
{
List<String> suggestions = this.dateParameterProcessor.getSubstitutionSuggestions("date");
assertTrue(suggestions.contains("date.day.short"));
assertTrue(suggestions.contains("date.day"));
assertTrue(suggestions.contains("date.day.long"));
assertTrue(suggestions.contains("date.day.number"));
assertTrue(suggestions.contains("date.day.month"));
assertTrue(suggestions.contains("date.day.year"));
assertTrue(suggestions.contains("date.month.short"));
assertTrue(suggestions.contains("date.month"));
assertTrue(suggestions.contains("date.month.long"));
assertTrue(suggestions.contains("date.month.number"));
assertEquals(10, suggestions.size());
}
@Test
public void testGetSubstitutionSuggestions_02()
{
List<String> suggestions = this.dateParameterProcessor.getSubstitutionSuggestions("dat");
assertTrue(suggestions.contains("date.day.short"));
assertTrue(suggestions.contains("date.day"));
assertTrue(suggestions.contains("date.day.long"));
assertTrue(suggestions.contains("date.day.number"));
assertTrue(suggestions.contains("date.day.month"));
assertTrue(suggestions.contains("date.day.year"));
assertTrue(suggestions.contains("date.month.short"));
assertTrue(suggestions.contains("date.month"));
assertTrue(suggestions.contains("date.month.long"));
assertTrue(suggestions.contains("date.month.number"));
assertEquals(10, suggestions.size());
}
@Test
public void testGetSubstitutionSuggestions_03()
{
List<String> suggestions = this.dateParameterProcessor.getSubstitutionSuggestions("at");
assertTrue(suggestions.contains("date.day.short"));
assertTrue(suggestions.contains("date.day"));
assertTrue(suggestions.contains("date.day.long"));
assertTrue(suggestions.contains("date.day.number"));
assertTrue(suggestions.contains("date.day.month"));
assertTrue(suggestions.contains("date.day.year"));
assertTrue(suggestions.contains("date.month.short"));
assertTrue(suggestions.contains("date.month"));
assertTrue(suggestions.contains("date.month.long"));
assertTrue(suggestions.contains("date.month.number"));
assertEquals(10, suggestions.size());
}
@Test
public void testGetSubstitutionSuggestions_05()
{
List<String> suggestions = this.dateParameterProcessor.getSubstitutionSuggestions("ay");
assertTrue(suggestions.contains("date.day.short"));
assertTrue(suggestions.contains("date.day"));
assertTrue(suggestions.contains("date.day.long"));
assertTrue(suggestions.contains("date.day.number"));
assertTrue(suggestions.contains("date.day.month"));
assertTrue(suggestions.contains("date.day.year"));
assertEquals(6, suggestions.size());
}
@Test
public void testGetSubstitutionSuggestions_06()
{
List<String> suggestions = this.dateParameterProcessor.getSubstitutionSuggestions("on");
assertTrue(suggestions.contains("date.day.long"));
assertTrue(suggestions.contains("date.month.short"));
assertTrue(suggestions.contains("date.month"));
assertTrue(suggestions.contains("date.month.long"));
assertTrue(suggestions.contains("date.month.number"));
assertTrue(suggestions.contains("date.year.long"));
assertTrue(suggestions.contains("date.day.month"));
assertEquals(7, suggestions.size());
}
}

View File

@@ -1,392 +1,392 @@
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.web.scripts.roles;
import static java.util.Collections.emptyMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedReaderDynamicAuthority;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedSecurityService;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedWriterDynamicAuthority;
import org.alfresco.module.org_alfresco_module_rm.test.util.AlfMock;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest;
import org.alfresco.repo.domain.node.NodeDAO;
import org.alfresco.repo.domain.patch.PatchDAO;
import org.alfresco.repo.domain.qname.QNameDAO;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.Pair;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
/**
* DynamicAuthoritiesGet Unit Test
*
* @author Silviu Dinuta
*/
@SuppressWarnings("deprecation")
public class DynamicAuthoritiesGetUnitTest extends BaseWebScriptUnitTest implements RecordsManagementModel
{
/** test data */
private static final Long ASPECT_ID = 123l;
private static final QName ASPECT = AlfMock.generateQName();
/** mocks */
@Mock
private PatchDAO mockedPatchDAO;
@Mock
private NodeDAO mockedNodeDAO;
@Mock
private QNameDAO mockedQnameDAO;
@Mock
private NodeService mockedNodeService;
@Mock
private PermissionService mockedPermissionService;
@Mock
private ExtendedSecurityService mockedExtendedSecurityService;
@Mock
private TransactionService mockedTransactionService;
@Mock
private RetryingTransactionHelper mockedRetryingTransactionHelper;
/** test component */
@InjectMocks
private DynamicAuthoritiesGet webScript;
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
@Override
protected String getWebScriptTemplate()
{
return "alfresco/templates/webscripts/org/alfresco/repository/roles/rm-dynamicauthorities.get.json.ftl";
}
/**
* Before test
*/
@SuppressWarnings("unchecked")
@Before
public void before()
{
MockitoAnnotations.initMocks(this);
webScript.setNodeService(mockedNodeService);
webScript.setPermissionService(mockedPermissionService);
webScript.setExtendedSecurityService(mockedExtendedSecurityService);
// setup retrying transaction helper
Answer<Object> doInTransactionAnswer = new Answer<Object>()
{
@SuppressWarnings("rawtypes")
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
RetryingTransactionCallback callback = (RetryingTransactionCallback) invocation.getArguments()[0];
return callback.execute();
}
};
doAnswer(doInTransactionAnswer).when(mockedRetryingTransactionHelper)
.<Object> doInTransaction(any(RetryingTransactionCallback.class), anyBoolean(), anyBoolean());
when(mockedTransactionService.getRetryingTransactionHelper()).thenReturn(mockedRetryingTransactionHelper);
// max node id
when(mockedPatchDAO.getMaxAdmNodeID()).thenReturn(500000L);
// aspect
when(mockedQnameDAO.getQName(ASPECT_EXTENDED_SECURITY)).thenReturn(new Pair<Long, QName>(ASPECT_ID, ASPECT));
}
/**
* Given that there are no nodes with the extended security aspect When the action is executed Nothing happens
* @throws Exception
*/
@SuppressWarnings({ "unchecked" })
@Test
public void noNodesWithExtendedSecurity() throws Exception
{
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(Collections.emptyList());
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "3");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
// Check the JSON result using Jackson to allow easy equality testing.
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 0 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(mockedNodeService, never()).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, never()).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, never()).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, never()).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, never()).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, never()).set(any(NodeRef.class), any(Set.class), any(Set.class));
}
/**
* Given that there are records with the extended security aspect When the action is executed Then the aspect is
* removed And the dynamic authorities permissions are cleared And extended security is set via the updated API
* @throws Exception
*/
@SuppressWarnings("unchecked")
@Test
public void recordsWithExtendedSecurityAspect() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<Long, NodeRef>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(true);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 3 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, times(3)).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, times(3)).set(any(NodeRef.class), any(Set.class), any(Set.class));
}
/**
* Given that there are non-records with the extended security aspect When the web script is executed Then the aspect is
* removed And the dynamic authorities permissions are cleared
* @throws Exception
*/
@SuppressWarnings("unchecked")
@Test
public void nonRecordsWithExtendedSecurityAspect() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<Long, NodeRef>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(false);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 3 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, times(3)).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, never()).set(any(NodeRef.class), any(Set.class), any(Set.class));
}
@Test
public void missingBatchSizeParameter() throws Exception
{
JSONObject json = executeJSONWebScript(emptyMap());
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"failed\",\"message\":\"Parameter batchsize is mandatory\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void invalidBatchSizeParameter() throws Exception
{
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "dd");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"failed\",\"message\":\"Parameter batchsize is invalid.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void batchSizeShouldBeGraterThanZero() throws Exception
{
when(mockedQnameDAO.getQName(ASPECT_EXTENDED_SECURITY)).thenReturn(null);
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "0");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"failed\",\"message\":\"Parameter batchsize should be a number greater than 0.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void extendedSecurityAspectNotCreated() throws Exception
{
when(mockedQnameDAO.getQName(ASPECT_EXTENDED_SECURITY)).thenReturn(null);
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "3");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"There where no records to be processed.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void processAllRecordsWhenMaxProcessedRecordsIsZero() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l,4l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<Long, NodeRef>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(false);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "0");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 4 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void whenMaxProcessedRecordsIsMissingItDefaultsToBatchSize() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l, 4l, 5l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<Long, NodeRef>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(false);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed first 4 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
/*
* Copyright (C) 2005-2014 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.web.scripts.roles;
import static java.util.Collections.emptyMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import org.alfresco.module.org_alfresco_module_rm.model.RecordsManagementModel;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedReaderDynamicAuthority;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedSecurityService;
import org.alfresco.module.org_alfresco_module_rm.security.ExtendedWriterDynamicAuthority;
import org.alfresco.module.org_alfresco_module_rm.test.util.AlfMock;
import org.alfresco.module.org_alfresco_module_rm.test.util.BaseWebScriptUnitTest;
import org.alfresco.repo.domain.node.NodeDAO;
import org.alfresco.repo.domain.patch.PatchDAO;
import org.alfresco.repo.domain.qname.QNameDAO;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.Pair;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
/**
* DynamicAuthoritiesGet Unit Test
*
* @author Silviu Dinuta
*/
@SuppressWarnings("deprecation")
public class DynamicAuthoritiesGetUnitTest extends BaseWebScriptUnitTest implements RecordsManagementModel
{
/** test data */
private static final Long ASPECT_ID = 123l;
private static final QName ASPECT = AlfMock.generateQName();
/** mocks */
@Mock
private PatchDAO mockedPatchDAO;
@Mock
private NodeDAO mockedNodeDAO;
@Mock
private QNameDAO mockedQnameDAO;
@Mock
private NodeService mockedNodeService;
@Mock
private PermissionService mockedPermissionService;
@Mock
private ExtendedSecurityService mockedExtendedSecurityService;
@Mock
private TransactionService mockedTransactionService;
@Mock
private RetryingTransactionHelper mockedRetryingTransactionHelper;
/** test component */
@InjectMocks
private DynamicAuthoritiesGet webScript;
@Override
protected DeclarativeWebScript getWebScript()
{
return webScript;
}
@Override
protected String getWebScriptTemplate()
{
return "alfresco/templates/webscripts/org/alfresco/repository/roles/rm-dynamicauthorities.get.json.ftl";
}
/**
* Before test
*/
@SuppressWarnings("unchecked")
@Before
public void before()
{
MockitoAnnotations.initMocks(this);
webScript.setNodeService(mockedNodeService);
webScript.setPermissionService(mockedPermissionService);
webScript.setExtendedSecurityService(mockedExtendedSecurityService);
// setup retrying transaction helper
Answer<Object> doInTransactionAnswer = new Answer<Object>()
{
@SuppressWarnings("rawtypes")
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
RetryingTransactionCallback callback = (RetryingTransactionCallback) invocation.getArguments()[0];
return callback.execute();
}
};
doAnswer(doInTransactionAnswer).when(mockedRetryingTransactionHelper)
.<Object> doInTransaction(any(RetryingTransactionCallback.class), anyBoolean(), anyBoolean());
when(mockedTransactionService.getRetryingTransactionHelper()).thenReturn(mockedRetryingTransactionHelper);
// max node id
when(mockedPatchDAO.getMaxAdmNodeID()).thenReturn(500000L);
// aspect
when(mockedQnameDAO.getQName(ASPECT_EXTENDED_SECURITY)).thenReturn(new Pair<Long, QName>(ASPECT_ID, ASPECT));
}
/**
* Given that there are no nodes with the extended security aspect When the action is executed Nothing happens
* @throws Exception
*/
@SuppressWarnings({ "unchecked" })
@Test
public void noNodesWithExtendedSecurity() throws Exception
{
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(Collections.emptyList());
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "3");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
// Check the JSON result using Jackson to allow easy equality testing.
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 0 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(mockedNodeService, never()).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, never()).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, never()).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, never()).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, never()).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, never()).set(any(NodeRef.class), any(Set.class), any(Set.class));
}
/**
* Given that there are records with the extended security aspect When the action is executed Then the aspect is
* removed And the dynamic authorities permissions are cleared And extended security is set via the updated API
* @throws Exception
*/
@SuppressWarnings("unchecked")
@Test
public void recordsWithExtendedSecurityAspect() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<Long, NodeRef>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(true);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 3 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, times(3)).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, times(3)).set(any(NodeRef.class), any(Set.class), any(Set.class));
}
/**
* Given that there are non-records with the extended security aspect When the web script is executed Then the aspect is
* removed And the dynamic authorities permissions are cleared
* @throws Exception
*/
@SuppressWarnings("unchecked")
@Test
public void nonRecordsWithExtendedSecurityAspect() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<Long, NodeRef>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(false);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 3 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_READERS));
verify(mockedNodeService, times(3)).getProperty(any(NodeRef.class), eq(PROP_WRITERS));
verify(mockedNodeService, times(3)).removeAspect(any(NodeRef.class), eq(ASPECT_EXTENDED_SECURITY));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedReaderDynamicAuthority.EXTENDED_READER));
verify(mockedPermissionService, times(3)).clearPermission(any(NodeRef.class),
eq(ExtendedWriterDynamicAuthority.EXTENDED_WRITER));
verify(mockedExtendedSecurityService, never()).set(any(NodeRef.class), any(Set.class), any(Set.class));
}
@Test
public void missingBatchSizeParameter() throws Exception
{
JSONObject json = executeJSONWebScript(emptyMap());
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"failed\",\"message\":\"Parameter batchsize is mandatory\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void invalidBatchSizeParameter() throws Exception
{
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "dd");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"failed\",\"message\":\"Parameter batchsize is invalid.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void batchSizeShouldBeGraterThanZero() throws Exception
{
when(mockedQnameDAO.getQName(ASPECT_EXTENDED_SECURITY)).thenReturn(null);
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "0");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"failed\",\"message\":\"Parameter batchsize should be a number greater than 0.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void extendedSecurityAspectNotCreated() throws Exception
{
when(mockedQnameDAO.getQName(ASPECT_EXTENDED_SECURITY)).thenReturn(null);
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "3");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"There where no records to be processed.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void processAllRecordsWhenMaxProcessedRecordsIsZero() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l,4l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<Long, NodeRef>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(false);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "10", "maxProcessedRecords", "0");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed 4 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
@Test
public void whenMaxProcessedRecordsIsMissingItDefaultsToBatchSize() throws Exception
{
List<Long> ids = Stream.of(1l, 2l, 3l, 4l, 5l).collect(Collectors.toList());
when(mockedPatchDAO.getNodesByAspectQNameId(eq(ASPECT_ID), anyLong(), anyLong()))
.thenReturn(ids)
.thenReturn(Collections.emptyList());
ids.stream().forEach((i) -> {
NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
when(mockedNodeDAO.getNodePair(i)).thenReturn(new Pair<Long, NodeRef>(i, nodeRef));
when(mockedNodeService.hasAspect(nodeRef, ASPECT_RECORD)).thenReturn(false);
when(mockedNodeService.getProperty(nodeRef, PROP_READERS))
.thenReturn((Serializable) Collections.emptyMap());
when(mockedNodeService.getProperty(nodeRef, PROP_WRITERS))
.thenReturn((Serializable) Collections.emptyMap());
});
// Set up parameters.
Map<String, String> parameters = ImmutableMap.of("batchsize", "4");
JSONObject json = executeJSONWebScript(parameters);
assertNotNull(json);
String actualJSONString = json.toString();
ObjectMapper mapper = new ObjectMapper();
String expectedJSONString = "{\"responsestatus\":\"success\",\"message\":\"Processed first 4 records.\"}";
assertEquals(mapper.readTree(expectedJSONString), mapper.readTree(actualJSONString));
}
}