2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright © 2009 Regents of the University of California
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 package org.collectionspace.services.client.test;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
30 import javax.ws.rs.core.MediaType;
31 import javax.ws.rs.core.Response;
33 import org.collectionspace.services.PersonJAXBSchema;
34 import org.collectionspace.services.client.CollectionSpaceClient;
35 import org.collectionspace.services.client.MovementClient;
36 import org.collectionspace.services.client.PersonAuthorityClient;
37 import org.collectionspace.services.client.PersonAuthorityClientUtils;
38 import org.collectionspace.services.client.PayloadInputPart;
39 import org.collectionspace.services.client.PayloadOutputPart;
40 import org.collectionspace.services.client.PoxPayloadIn;
41 import org.collectionspace.services.client.PoxPayloadOut;
42 import org.collectionspace.services.common.authorityref.AuthorityRefList;
43 import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils;
44 import org.collectionspace.services.jaxb.AbstractCommonList;
45 import org.collectionspace.services.movement.MovementsCommon;
47 import org.jboss.resteasy.client.ClientResponse;
49 import org.testng.Assert;
50 import org.testng.annotations.AfterClass;
51 import org.testng.annotations.Test;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * MovementAuthRefsTest, carries out Authority References tests against a
58 * deployed and running Movement Service.
60 * $LastChangedRevision$
63 public class MovementAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
65 private final String CLASS_NAME = MovementAuthRefsTest.class.getName();
66 private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
67 final String SERVICE_NAME = "movements";
68 final String SERVICE_PATH_COMPONENT = "movements";
70 // Instance variables specific to this test.
71 final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
72 private List<String> movementIdsCreated = new ArrayList<String>();
73 private List<String> personIdsCreated = new ArrayList<String>();
74 private String personAuthCSID = null;
75 private String movementContactRefName = null;
77 // FIXME: Can add 'current location' and 'normal location'
78 // as authRefs to tests below, and increase the
79 // number of expected authRefs to 3.
80 private final int NUM_AUTH_REFS_EXPECTED = 1;
83 * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
86 protected CollectionSpaceClient getClientInstance() {
87 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
91 * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
94 protected AbstractCommonList getCommonList(
95 ClientResponse<AbstractCommonList> response) {
96 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
99 // ---------------------------------------------------------------
100 // CRUD tests : CREATE tests
101 // ---------------------------------------------------------------
103 @Test(dataProvider="testName")
104 public void createWithAuthRefs(String testName) throws Exception {
105 testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
107 // Submit the request to the service and store the response.
108 String identifier = createIdentifier();
110 // Create all the person refs and entities
113 // Create a new Movement resource.
115 // One or more fields in this resource will be PersonAuthority
116 // references, and will refer to Person resources by their refNames.
117 MovementClient movementClient = new MovementClient();
118 PoxPayloadOut multipart = createMovementInstance(
119 "movementReferenceNumber-" + identifier,
120 GregorianCalendarDateTimeUtils.timestampUTC(),
121 movementContactRefName);
122 ClientResponse<Response> res = movementClient.create(multipart);
123 int statusCode = res.getStatus();
125 // Check the status code of the response: does it match
126 // the expected response(s)?
129 // Does it fall within the set of valid status codes?
130 // Does it exactly match the expected status code?
131 if(logger.isDebugEnabled()){
132 logger.debug(testName + ": status = " + statusCode);
134 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
135 invalidStatusCodeMessage(testRequestType, statusCode));
136 Assert.assertEquals(statusCode, testExpectedStatusCode);
138 // Store the ID returned from the first resource created
139 // for additional tests below.
140 if (knownResourceId == null){
141 knownResourceId = extractId(res);
142 if (logger.isDebugEnabled()) {
143 logger.debug(testName + ": knownResourceId=" + knownResourceId);
147 // Store the IDs from every resource created by tests,
148 // so they can be deleted after tests have been run.
149 movementIdsCreated.add(extractId(res));
152 protected void createPersonRefs(){
154 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
155 // Create a temporary PersonAuthority resource, and its corresponding
156 // refName by which it can be identified.
157 PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
158 PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
159 ClientResponse<Response> res = personAuthClient.create(multipart);
160 int statusCode = res.getStatus();
162 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
163 invalidStatusCodeMessage(testRequestType, statusCode));
164 Assert.assertEquals(statusCode, STATUS_CREATED);
165 personAuthCSID = extractId(res);
167 String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
169 // Create temporary Person resources, and their corresponding refNames
170 // by which they can be identified.
171 String csid = createPerson("Melvin", "MovementContact", "melvinMovementContact", authRefName);
172 personIdsCreated.add(csid);
173 movementContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
176 protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
177 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
178 Map<String, String> personInfo = new HashMap<String,String>();
179 personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
180 personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
181 personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
182 PoxPayloadOut multipart =
183 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
184 authRefName, personInfo, null, personAuthClient.getItemCommonPartName());
185 ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
186 int statusCode = res.getStatus();
188 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
189 invalidStatusCodeMessage(testRequestType, statusCode));
190 Assert.assertEquals(statusCode, STATUS_CREATED);
191 return extractId(res);
195 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
196 dependsOnMethods = {"createWithAuthRefs"})
197 public void readAndCheckAuthRefs(String testName) throws Exception {
199 testSetup(STATUS_OK, ServiceRequestType.READ);
201 // Submit the request to the service and store the response.
202 MovementClient movementClient = new MovementClient();
203 ClientResponse<String> res = movementClient.read(knownResourceId);
204 MovementsCommon movementCommon = null;
206 assertStatusCode(res, testName);
207 // Extract and return the common part of the record.
208 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
209 PayloadInputPart payloadInputPart = input.getPart(movementClient.getCommonPartName());
210 if (payloadInputPart != null) {
211 movementCommon = (MovementsCommon) payloadInputPart.getBody();
213 Assert.assertNotNull(movementCommon);
214 if(logger.isDebugEnabled()){
215 logger.debug(objectAsXmlString(movementCommon, MovementsCommon.class));
219 res.releaseConnection();
222 // Check a couple of fields
224 Assert.assertEquals(movementCommon.getMovementContact(), movementContactRefName);
226 // Get the auth refs and check them
227 ClientResponse<AuthorityRefList> res2 = movementClient.getAuthorityRefs(knownResourceId);
228 AuthorityRefList list = null;
230 assertStatusCode(res2, testName);
231 list = res2.getEntity();
234 res2.releaseConnection();
238 List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
239 int numAuthRefsFound = items.size();
240 if(logger.isDebugEnabled()){
241 logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
242 " authority references, found " + numAuthRefsFound);
244 Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
245 "Did not find all expected authority references! " +
246 "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
248 // Optionally output additional data about list members for debugging.
249 boolean iterateThroughList = true;
250 if(iterateThroughList && logger.isDebugEnabled()){
252 for(AuthorityRefList.AuthorityRefItem item : items){
253 logger.debug(testName + ": list-item[" + i + "] Field:" +
254 item.getSourceField() + "= " +
255 item.getAuthDisplayName() +
256 item.getItemDisplayName());
257 logger.debug(testName + ": list-item[" + i + "] refName=" +
259 logger.debug(testName + ": list-item[" + i + "] URI=" +
267 // ---------------------------------------------------------------
268 // Cleanup of resources created during testing
269 // ---------------------------------------------------------------
272 * Deletes all resources created by tests, after all tests have been run.
274 * This cleanup method will always be run, even if one or more tests fail.
275 * For this reason, it attempts to remove all resources created
276 * at any point during testing, even if some of those resources
277 * may be expected to be deleted by certain tests.
279 @AfterClass(alwaysRun=true)
280 public void cleanUp() {
281 String noTest = System.getProperty("noTestCleanup");
282 if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
283 if (logger.isDebugEnabled()) {
284 logger.debug("Skipping Cleanup phase ...");
288 if (logger.isDebugEnabled()) {
289 logger.debug("Cleaning up temporary resources created for testing ...");
291 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
292 // Delete Person resource(s) (before PersonAuthority resources).
293 for (String resourceId : personIdsCreated) {
294 // Note: Any non-success responses are ignored and not reported.
295 personAuthClient.deleteItem(personAuthCSID, resourceId);
297 // Delete PersonAuthority resource(s).
298 // Note: Any non-success response is ignored and not reported.
299 if (personAuthCSID != null) {
300 personAuthClient.delete(personAuthCSID);
302 // Delete Movement resource(s).
303 MovementClient movementClient = new MovementClient();
304 for (String resourceId : movementIdsCreated) {
305 // Note: Any non-success responses are ignored and not reported.
306 movementClient.delete(resourceId);
310 // ---------------------------------------------------------------
311 // Utility methods used by tests above
312 // ---------------------------------------------------------------
315 protected String getServiceName() {
320 public String getServicePathComponent() {
321 return SERVICE_PATH_COMPONENT;
324 private PoxPayloadOut createMovementInstance(String movementReferenceNumber,
326 String movementContact) {
327 MovementsCommon movementCommon = new MovementsCommon();
328 movementCommon.setMovementReferenceNumber(movementReferenceNumber);
329 movementCommon.setLocationDate(locationDate);
330 movementCommon.setMovementContact(movementContact);
331 PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
332 PayloadOutputPart commonPart =
333 multipart.addPart(movementCommon, MediaType.APPLICATION_XML_TYPE);
334 commonPart.setLabel(new MovementClient().getCommonPartName());
336 if(logger.isDebugEnabled()){
337 logger.debug("to be created, movement common");
338 logger.debug(objectAsXmlString(movementCommon, MovementsCommon.class));