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 final String SERVICE_PATH_COMPONENT = "orgauthorities";
69 final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
70 final String ORG_AUTHORITY_NAME = "TestOrgAuth";
73 private String knownResourceId = null;
74 private String knownResourceRefName = null;
76 /** The known item id. */
77 private String knownItemResourceId = null;
79 /** The all resource ids created. */
80 private List<String> allResourceIdsCreated = new ArrayList<String>();
82 /** The all item resource ids created. */
83 private Map<String, String> allItemResourceIdsCreated =
84 new HashMap<String, String>();
86 /** The person ids created. */
87 private List<String> personIdsCreated = new ArrayList<String>();
89 // CSID for the instance of the test Person authority
90 // created during testing.
91 private String personAuthCSID = null;
93 /** The organization contact person ref name. */
94 private String organizationContactPersonRefName = null;
96 // The refName of an Organization item that represents
97 // the sub-body organization of a second Organization item.
98 private String subBodyRefName = null;
100 /** The number of authorityreferences expected. */
101 private final int NUM_AUTH_REFS_EXPECTED = 2;
103 protected void setKnownResource( String id, String refName ) {
104 knownResourceId = id;
105 knownResourceRefName = refName;
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 shortId = createIdentifier();
146 String displayName = "TestOrgAuth-" + shortId;
147 String baseRefName = OrgAuthorityClientUtils.createOrgAuthRefName(shortId, null);
148 MultipartOutput multipart =
149 OrgAuthorityClientUtils.createOrgAuthorityInstance(
150 displayName, shortId, orgAuthClient.getCommonPartName());
152 // Submit the request to the service and store the response.
153 ClientResponse<Response> res = orgAuthClient.create(multipart);
155 int statusCode = res.getStatus();
156 // Check the status code of the response: does it match
157 // the expected response(s)?
160 // Does it fall within the set of valid status codes?
161 // Does it exactly match the expected status code?
162 if(logger.isDebugEnabled()){
163 logger.debug(testName + ": status = " + statusCode);
165 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
166 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
167 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
169 // Store the IDs from every resource created by tests,
170 // so they can be deleted after tests have been run.
171 String newId = extractId(res);
172 if (knownResourceId == null){
173 setKnownResource( newId, baseRefName );
175 allResourceIdsCreated.add(newId);
177 res.releaseConnection();
180 // Create all the person refs and entities
183 // Create all the organization sub-body refs and entities
184 createSubBodyOrgRefs();
186 // Initialize values for a new Organization item, to be created within
187 // the newly-created Organization Authority resource.
189 // One or more fields in the Organization item record will
190 // contain references to Persons, via their refNames, as
191 // per the initialization(s) below.
192 Map<String, String> testOrgMap = new HashMap<String,String>();
193 testOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
194 testOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
195 "Test Organization-" + shortId);
196 testOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Test Organization Name");
197 testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
199 Map<String, List<String>> testOrgRepeatablesMap = new HashMap<String,List<String>>();
200 List<String> testOrgContactNames = new ArrayList<String>();
201 testOrgContactNames.add(organizationContactPersonRefName);
202 testOrgRepeatablesMap.put(OrganizationJAXBSchema.CONTACT_NAMES, testOrgContactNames);
203 List<String> testOrgSubBodies = new ArrayList<String>();
204 testOrgSubBodies.add(subBodyRefName);
205 testOrgRepeatablesMap.put(OrganizationJAXBSchema.SUB_BODIES, testOrgSubBodies);
207 // Finishing creating the new Organization item, then
208 // submit the request to the service and store the response.
209 knownItemResourceId = OrgAuthorityClientUtils.createItemInAuthority(
210 knownResourceId, knownResourceRefName, testOrgMap,
211 testOrgRepeatablesMap, orgAuthClient);
213 // Store the IDs from every item created by tests,
214 // so they can be deleted after tests have been run.
215 allItemResourceIdsCreated.put(knownItemResourceId, knownResourceId);
219 * Creates the person refs.
221 protected void createPersonRefs() {
222 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
223 // Create a temporary PersonAuthority resource, and its corresponding
224 // refName by which it can be identified.
225 MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
226 PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
228 ClientResponse<Response> res = personAuthClient.create(multipart);
230 int statusCode = res.getStatus();
231 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
232 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
233 Assert.assertEquals(statusCode, STATUS_CREATED);
234 personAuthCSID = extractId(res);
236 res.releaseConnection();
239 String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
241 // Create temporary Person resources, and their corresponding refNames
242 // by which they can be identified.
243 String csid = createPerson("Charlie", "Orgcontact", "charlieOrgcontact", authRefName);
244 personIdsCreated.add(csid);
245 organizationContactPersonRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
249 * Creates the person.
251 * @param firstName the first name
252 * @param surName the sur name
257 protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
258 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
259 Map<String, String> personInfo = new HashMap<String,String>();
260 personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
261 personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
262 personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
263 MultipartOutput multipart =
264 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
265 authRefName, personInfo, personAuthClient.getItemCommonPartName());
267 String result = null;
268 ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
270 int statusCode = res.getStatus();
272 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
273 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
274 Assert.assertEquals(statusCode, STATUS_CREATED);
275 result = extractId(res);
277 res.releaseConnection();
283 private void createSubBodyOrgRefs() {
284 // Create a temporary sub-body Organization resource, and its corresponding refName
285 // by which it can be identified.
287 // This sub-body Organization resource will be created in the same
288 // Organization authority as its parent Organization resource.
290 String subBodyResourceId = createSubBodyOrganization("Test SubBody Organization");
291 allItemResourceIdsCreated.put(subBodyResourceId, knownResourceId);
292 subBodyRefName = OrgAuthorityClientUtils.getOrgRefName(knownResourceId, subBodyResourceId, null);
295 protected String createSubBodyOrganization(String subBodyName) {
296 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
297 Map<String, String> subBodyOrgMap = new HashMap<String,String>();
298 String shortId = createIdentifier();
299 subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId );
300 subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
301 subBodyName + "-" + shortId);
302 subBodyOrgMap.put(OrganizationJAXBSchema.LONG_NAME, subBodyName + " Long Name");
303 subBodyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, subBodyName + " Founding Place");
304 MultipartOutput multipart =
305 OrgAuthorityClientUtils.createOrganizationInstance(
306 knownResourceRefName, subBodyOrgMap, orgAuthClient.getItemCommonPartName());
308 String result = null;
309 ClientResponse<Response> res = orgAuthClient.createItem(knownResourceId, multipart);
311 int statusCode = res.getStatus();
312 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
313 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
314 Assert.assertEquals(statusCode, STATUS_CREATED);
315 result = extractId(res);
317 res.releaseConnection();
325 * Read and check auth refs.
327 * @param testName the test name
328 * @throws Exception the exception
330 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
331 dependsOnMethods = {"createWithAuthRefs"})
332 public void readAndCheckAuthRefs(String testName) throws Exception {
334 if (logger.isDebugEnabled()) {
335 logger.debug(testBanner(testName, CLASS_NAME));
338 testSetup(STATUS_OK, ServiceRequestType.READ);
340 // Submit the request to the service and store the response.
341 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
342 ClientResponse<MultipartInput> res =
343 orgAuthClient.readItem(knownResourceId, knownItemResourceId);
344 int statusCode = res.getStatus();
346 // Check the status code of the response: does it match
347 // the expected response(s)?
348 if(logger.isDebugEnabled()){
349 logger.debug(testName + ".read: status = " + statusCode);
351 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
352 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
353 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
355 MultipartInput input = (MultipartInput) res.getEntity();
356 OrganizationsCommon organization = (OrganizationsCommon) extractPart(input,
357 orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
358 Assert.assertNotNull(organization);
359 if(logger.isDebugEnabled()){
360 logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
362 // Check one or more of the authority fields in the Organization item
363 Assert.assertEquals(organization.getContactNames().getContactName().get(0),
364 organizationContactPersonRefName);
365 Assert.assertEquals(organization.getSubBodies().getSubBody().get(0),
368 // Get the auth refs and check them
369 // FIXME - need to create this method in the client
370 // and get the ID for the organization item
371 ClientResponse<AuthorityRefList> res2 =
372 orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
373 statusCode = res2.getStatus();
375 if(logger.isDebugEnabled()){
376 logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
378 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
379 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
380 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
381 AuthorityRefList list = res2.getEntity();
383 List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
384 int numAuthRefsFound = items.size();
385 if(logger.isDebugEnabled()){
386 logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
387 " authority references, found " + numAuthRefsFound);
389 Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
390 "Did not find all expected authority references! " +
391 "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
393 // Optionally output additional data about list members for debugging.
394 boolean iterateThroughList = true;
395 if(iterateThroughList && logger.isDebugEnabled()){
397 for(AuthorityRefList.AuthorityRefItem item : items){
398 logger.debug(testName + ": list-item[" + i + "] Field:" +
399 item.getSourceField() + "=" +
400 item.getItemDisplayName());
401 logger.debug(testName + ": list-item[" + i + "] refName=" +
403 logger.debug(testName + ": list-item[" + i + "] URI=" +
410 // ---------------------------------------------------------------
411 // Cleanup of resources created during testing
412 // ---------------------------------------------------------------
415 * Deletes all resources created by tests, after all tests have been run.
417 * This cleanup method will always be run, even if one or more tests fail.
418 * For this reason, it attempts to remove all resources created
419 * at any point during testing, even if some of those resources
420 * may be expected to be deleted by certain tests.
422 @AfterClass(alwaysRun=true)
423 public void cleanUp() {
424 String noTest = System.getProperty("noTestCleanup");
425 if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
426 if (logger.isDebugEnabled()) {
427 logger.debug("Skipping Cleanup phase ...");
431 if (logger.isDebugEnabled()) {
432 logger.debug("Cleaning up temporary resources created for testing ...");
434 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
435 // Delete Person resource(s) (before PersonAuthority resources).
436 for (String resourceId : personIdsCreated) {
437 // Note: Any non-success responses are ignored and not reported.
438 personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
440 // Delete PersonAuthority resource(s).
441 // Note: Any non-success response is ignored and not reported.
442 if(personAuthCSID!=null) {
443 personAuthClient.delete(personAuthCSID).releaseConnection();
446 String parentResourceId;
447 String itemResourceId;
448 OrgAuthorityClient client = new OrgAuthorityClient();
449 // Clean up item resources.
450 for (Map.Entry<String, String> entry : allItemResourceIdsCreated.entrySet()) {
451 itemResourceId = entry.getKey();
452 parentResourceId = entry.getValue();
453 // Note: Any non-success responses from the delete operation
454 // below are ignored and not reported.
455 client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
458 // Clean up parent resources.
459 for (String resourceId : allResourceIdsCreated) {
460 // Note: Any non-success responses from the delete operation
461 // below are ignored and not reported.
462 client.delete(resourceId).releaseConnection();
466 // ---------------------------------------------------------------
467 // Utility methods used by tests above
468 // ---------------------------------------------------------------
470 * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
473 public String getServicePathComponent() {
474 return SERVICE_PATH_COMPONENT;