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.Response;
32 import org.collectionspace.services.OrganizationJAXBSchema;
33 import org.collectionspace.services.PersonJAXBSchema;
34 import org.collectionspace.services.client.CollectionSpaceClient;
35 import org.collectionspace.services.client.OrgAuthorityClient;
36 import org.collectionspace.services.client.OrgAuthorityClientUtils;
37 import org.collectionspace.services.client.PersonAuthorityClient;
38 import org.collectionspace.services.client.PersonAuthorityClientUtils;
39 import org.collectionspace.services.common.authorityref.AuthorityRefList;
40 import org.collectionspace.services.jaxb.AbstractCommonList;
41 import org.collectionspace.services.organization.OrganizationsCommon;
43 import org.jboss.resteasy.client.ClientResponse;
45 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
46 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
47 import org.testng.Assert;
48 import org.testng.annotations.AfterClass;
49 import org.testng.annotations.Test;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * LoaninAuthRefsTest, carries out Authority References tests against a
56 * deployed and running Loanin (aka Loans In) Service.
58 * $LastChangedRevision: 1327 $
59 * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
61 public class OrgAuthorityAuthRefsTest extends BaseServiceTest {
64 private final String CLASS_NAME = OrgAuthorityAuthRefsTest.class.getName();
65 private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
67 // Instance variables specific to this test.
68 /** The SERVIC e_ pat h_ component. */
69 final String SERVICE_PATH_COMPONENT = "orgauthorities";
71 // Temporary Person and Organization Authority names, used for test purposes.
72 final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
73 final String ORG_AUTHORITY_NAME = "TestOrgAuth";
75 /** The known resource ref name. */
76 private String knownResourceRefName = null;
78 /** The known auth resource id. */
79 private String knownAuthResourceId = null;
81 /** The known item id. */
82 private String knownItemId = null;
84 /** The all resource ids created. */
85 private List<String> allResourceIdsCreated = new ArrayList<String>();
87 /** The all item resource ids created. */
88 private Map<String, String> allItemResourceIdsCreated =
89 new HashMap<String, String>();
91 /** The person ids created. */
92 private List<String> personIdsCreated = new ArrayList<String>();
94 // CSID for the instance of the test Person authority
95 // created during testing.
96 private String personAuthCSID = null;
98 /** The organization contact person ref name. */
99 private String organizationContactPersonRefName = null;
101 // The refName of an Organization item that represents
102 // the sub-body organization of a second Organization item.
103 private String subBodyRefName = null;
105 /** The number of authorityreferences expected. */
106 private final int NUM_AUTH_REFS_EXPECTED = 2;
109 * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
112 protected CollectionSpaceClient getClientInstance() {
113 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
117 * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
120 protected AbstractCommonList getAbstractCommonList(
121 ClientResponse<AbstractCommonList> response) {
122 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
125 // ---------------------------------------------------------------
126 // CRUD tests : CREATE tests
127 // ---------------------------------------------------------------
130 * Creates the with auth refs.
132 * @param testName the test name
133 * @throws Exception the exception
135 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
136 public void createWithAuthRefs(String testName) throws Exception {
138 if (logger.isDebugEnabled()) {
139 logger.debug(testBanner(testName, CLASS_NAME));
141 testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
143 // Create a new Organization Authority resource.
144 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
145 String identifier = createIdentifier();
146 String displayName = "TestOrgAuth-" + identifier;
147 boolean createWithDisplayName = false;
148 knownResourceRefName =
149 OrgAuthorityClientUtils.createOrgAuthRefName(displayName, createWithDisplayName);
150 MultipartOutput multipart =
151 OrgAuthorityClientUtils.createOrgAuthorityInstance(
152 displayName, knownResourceRefName, orgAuthClient.getCommonPartName());
154 // Submit the request to the service and store the response.
155 ClientResponse<Response> res = orgAuthClient.create(multipart);
157 int statusCode = res.getStatus();
158 // Check the status code of the response: does it match
159 // the expected response(s)?
162 // Does it fall within the set of valid status codes?
163 // Does it exactly match the expected status code?
164 if(logger.isDebugEnabled()){
165 logger.debug(testName + ": status = " + statusCode);
167 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
168 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
169 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
171 // Store the IDs from every resource created by tests,
172 // so they can be deleted after tests have been run.
173 knownAuthResourceId = extractId(res);
175 res.releaseConnection();
177 allResourceIdsCreated.add(knownAuthResourceId);
179 // Create all the person refs and entities
182 // Create all the organization sub-body refs and entities
183 createSubBodyOrgRefs();
185 // Initialize values for a new Organization item, to be created within
186 // the newly-created Organization Authority resource.
188 // One or more fields in the Organization item record will
189 // contain references to Persons, via their refNames, as
190 // per the initialization(s) below.
191 Map<String, String> testOrgMap = new HashMap<String,String>();
192 testOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
193 "Test Organization-" + identifier);
194 testOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Test Organization Name");
195 testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
196 testOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, organizationContactPersonRefName);
197 testOrgMap.put(OrganizationJAXBSchema.SUB_BODY, subBodyRefName);
199 // Finishing creating the new Organization item, then
200 // submit the request to the service and store the response.
201 knownItemId = OrgAuthorityClientUtils.createItemInAuthority(
202 knownAuthResourceId, knownResourceRefName, testOrgMap, orgAuthClient);
204 // Store the IDs from every item created by tests,
205 // so they can be deleted after tests have been run.
206 allItemResourceIdsCreated.put(knownItemId, knownAuthResourceId);
210 * Creates the person refs.
212 protected void createPersonRefs() {
213 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
214 // Create a temporary PersonAuthority resource, and its corresponding
215 // refName by which it can be identified.
216 String personAuthRefName =
217 PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
218 MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
219 PERSON_AUTHORITY_NAME, personAuthRefName, personAuthClient.getCommonPartName());
221 ClientResponse<Response> res = personAuthClient.create(multipart);
223 int statusCode = res.getStatus();
224 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
225 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
226 Assert.assertEquals(statusCode, STATUS_CREATED);
227 personAuthCSID = extractId(res);
229 res.releaseConnection();
232 // Create a temporary Person resource, and its corresponding refName
233 // by which it can be identified.
234 organizationContactPersonRefName =
235 PersonAuthorityClientUtils.createPersonRefName(personAuthRefName, "Charlie Orgcontact", true);
236 personIdsCreated.add(createPerson("Charlie", "Orgcontact", organizationContactPersonRefName));
241 * Creates the person.
243 * @param firstName the first name
244 * @param surName the sur name
245 * @param refName the ref name
248 protected String createPerson(String firstName, String surName, String refName ) {
249 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
250 Map<String, String> personInfo = new HashMap<String,String>();
251 personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
252 personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
253 MultipartOutput multipart =
254 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
255 refName, personInfo, personAuthClient.getItemCommonPartName());
257 String result = null;
258 ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
260 int statusCode = res.getStatus();
262 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
263 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
264 Assert.assertEquals(statusCode, STATUS_CREATED);
265 result = extractId(res);
267 res.releaseConnection();
273 private void createSubBodyOrgRefs() {
274 // Create a temporary sub-body Organization resource, and its corresponding refName
275 // by which it can be identified.
277 // This sub-body Organization resource will be created in the same
278 // Organization authority as its parent Organization resource.
280 String subBodyResourceId = createSubBodyOrganization("Test SubBody Organization", subBodyRefName);
281 allItemResourceIdsCreated.put(subBodyResourceId, knownAuthResourceId);
284 protected String createSubBodyOrganization(String subBodyName, String refName) {
285 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
286 Map<String, String> subBodyOrgMap = new HashMap<String,String>();
287 subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
288 subBodyName + "-" + createIdentifier());
289 subBodyOrgMap.put(OrganizationJAXBSchema.LONG_NAME, subBodyName + " Long Name");
290 subBodyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, subBodyName + " Founding Place");
291 String subBodyDisplayName = OrgAuthorityClientUtils.createDisplayName(subBodyOrgMap);
293 OrgAuthorityClientUtils.createOrganizationRefName(knownResourceRefName, subBodyDisplayName, true);
294 MultipartOutput multipart =
295 OrgAuthorityClientUtils.createOrganizationInstance(knownAuthResourceId,
296 subBodyRefName, subBodyOrgMap, orgAuthClient.getItemCommonPartName());
298 String result = null;
299 ClientResponse<Response> res = orgAuthClient.createItem(knownAuthResourceId, multipart);
301 int statusCode = res.getStatus();
302 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
303 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
304 Assert.assertEquals(statusCode, STATUS_CREATED);
305 result = extractId(res);
307 res.releaseConnection();
315 * Read and check auth refs.
317 * @param testName the test name
318 * @throws Exception the exception
320 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
321 dependsOnMethods = {"createWithAuthRefs"})
322 public void readAndCheckAuthRefs(String testName) throws Exception {
324 if (logger.isDebugEnabled()) {
325 logger.debug(testBanner(testName, CLASS_NAME));
328 testSetup(STATUS_OK, ServiceRequestType.READ);
330 // Submit the request to the service and store the response.
331 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
332 ClientResponse<MultipartInput> res =
333 orgAuthClient.readItem(knownAuthResourceId, knownItemId);
334 int statusCode = res.getStatus();
336 // Check the status code of the response: does it match
337 // the expected response(s)?
338 if(logger.isDebugEnabled()){
339 logger.debug(testName + ".read: status = " + statusCode);
341 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
342 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
343 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
345 MultipartInput input = (MultipartInput) res.getEntity();
346 OrganizationsCommon organization = (OrganizationsCommon) extractPart(input,
347 orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
348 Assert.assertNotNull(organization);
349 if(logger.isDebugEnabled()){
350 logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
352 // Check one or more of the authority fields in the Organization item
353 Assert.assertEquals(organization.getContactName(), organizationContactPersonRefName);
354 Assert.assertEquals(organization.getSubBody(), subBodyRefName);
356 // Get the auth refs and check them
357 // FIXME - need to create this method in the client
358 // and get the ID for the organization item
359 ClientResponse<AuthorityRefList> res2 =
360 orgAuthClient.getItemAuthorityRefs(knownAuthResourceId, knownItemId);
361 statusCode = res2.getStatus();
363 if(logger.isDebugEnabled()){
364 logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
366 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
367 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
368 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
369 AuthorityRefList list = res2.getEntity();
371 List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
372 int numAuthRefsFound = items.size();
373 if(logger.isDebugEnabled()){
374 logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
375 " authority references, found " + numAuthRefsFound);
377 Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
378 "Did not find all expected authority references! " +
379 "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
381 // Optionally output additional data about list members for debugging.
382 boolean iterateThroughList = true;
383 if(iterateThroughList && logger.isDebugEnabled()){
385 for(AuthorityRefList.AuthorityRefItem item : items){
386 logger.debug(testName + ": list-item[" + i + "] Field:" +
387 item.getSourceField() + "=" +
388 item.getItemDisplayName());
389 logger.debug(testName + ": list-item[" + i + "] refName=" +
391 logger.debug(testName + ": list-item[" + i + "] URI=" +
398 // ---------------------------------------------------------------
399 // Cleanup of resources created during testing
400 // ---------------------------------------------------------------
403 * Deletes all resources created by tests, after all tests have been run.
405 * This cleanup method will always be run, even if one or more tests fail.
406 * For this reason, it attempts to remove all resources created
407 * at any point during testing, even if some of those resources
408 * may be expected to be deleted by certain tests.
410 @AfterClass(alwaysRun=true)
411 public void cleanUp() {
412 String noTest = System.getProperty("noTestCleanup");
413 if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
414 if (logger.isDebugEnabled()) {
415 logger.debug("Skipping Cleanup phase ...");
419 if (logger.isDebugEnabled()) {
420 logger.debug("Cleaning up temporary resources created for testing ...");
422 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
423 // Delete Person resource(s) (before PersonAuthority resources).
424 for (String resourceId : personIdsCreated) {
425 // Note: Any non-success responses are ignored and not reported.
426 personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
428 // Delete PersonAuthority resource(s).
429 // Note: Any non-success response is ignored and not reported.
430 personAuthClient.delete(personAuthCSID).releaseConnection();
432 String parentResourceId;
433 String itemResourceId;
434 OrgAuthorityClient client = new OrgAuthorityClient();
435 // Clean up item resources.
436 for (Map.Entry<String, String> entry : allItemResourceIdsCreated.entrySet()) {
437 itemResourceId = entry.getKey();
438 parentResourceId = entry.getValue();
439 // Note: Any non-success responses from the delete operation
440 // below are ignored and not reported.
441 client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
444 // Clean up parent resources.
445 for (String resourceId : allResourceIdsCreated) {
446 // Note: Any non-success responses from the delete operation
447 // below are ignored and not reported.
448 client.delete(resourceId).releaseConnection();
452 // ---------------------------------------------------------------
453 // Utility methods used by tests above
454 // ---------------------------------------------------------------
456 * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
459 public String getServicePathComponent() {
460 return SERVICE_PATH_COMPONENT;
464 * Creates the org authority instance.
466 * @param identifier the identifier
467 * @return the multipart output
469 private MultipartOutput createOrgAuthorityInstance(String identifier) {
470 String displayName = "displayName-" + identifier;
471 String refName = OrgAuthorityClientUtils.createOrgAuthRefName(displayName, true);
472 return OrgAuthorityClientUtils.createOrgAuthorityInstance(
473 displayName, refName,
474 new OrgAuthorityClient().getCommonPartName());