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");
198 testOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, organizationContactPersonRefName);
199 testOrgMap.put(OrganizationJAXBSchema.SUB_BODY, subBodyRefName);
201 // Finishing creating the new Organization item, then
202 // submit the request to the service and store the response.
203 knownItemResourceId = OrgAuthorityClientUtils.createItemInAuthority(
204 knownResourceId, knownResourceRefName, testOrgMap, orgAuthClient);
206 // Store the IDs from every item created by tests,
207 // so they can be deleted after tests have been run.
208 allItemResourceIdsCreated.put(knownItemResourceId, knownResourceId);
212 * Creates the person refs.
214 protected void createPersonRefs() {
215 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
216 // Create a temporary PersonAuthority resource, and its corresponding
217 // refName by which it can be identified.
218 MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
219 PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, 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 String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
234 // Create temporary Person resources, and their corresponding refNames
235 // by which they can be identified.
236 String csid = createPerson("Charlie", "Orgcontact", "charlieOrgcontact", authRefName);
237 personIdsCreated.add(csid);
238 organizationContactPersonRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
242 * Creates the person.
244 * @param firstName the first name
245 * @param surName the sur name
250 protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
251 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
252 Map<String, String> personInfo = new HashMap<String,String>();
253 personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
254 personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
255 personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
256 MultipartOutput multipart =
257 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
258 authRefName, personInfo, personAuthClient.getItemCommonPartName());
260 String result = null;
261 ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
263 int statusCode = res.getStatus();
265 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
266 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
267 Assert.assertEquals(statusCode, STATUS_CREATED);
268 result = extractId(res);
270 res.releaseConnection();
276 private void createSubBodyOrgRefs() {
277 // Create a temporary sub-body Organization resource, and its corresponding refName
278 // by which it can be identified.
280 // This sub-body Organization resource will be created in the same
281 // Organization authority as its parent Organization resource.
283 String subBodyResourceId = createSubBodyOrganization("Test SubBody Organization");
284 allItemResourceIdsCreated.put(subBodyResourceId, knownResourceId);
285 subBodyRefName = OrgAuthorityClientUtils.getOrgRefName(knownResourceId, subBodyResourceId, null);
288 protected String createSubBodyOrganization(String subBodyName) {
289 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
290 Map<String, String> subBodyOrgMap = new HashMap<String,String>();
291 String shortId = createIdentifier();
292 subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId );
293 subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
294 subBodyName + "-" + shortId);
295 subBodyOrgMap.put(OrganizationJAXBSchema.LONG_NAME, subBodyName + " Long Name");
296 subBodyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, subBodyName + " Founding Place");
297 MultipartOutput multipart =
298 OrgAuthorityClientUtils.createOrganizationInstance(knownResourceId,
299 knownResourceRefName, subBodyOrgMap, orgAuthClient.getItemCommonPartName());
301 String result = null;
302 ClientResponse<Response> res = orgAuthClient.createItem(knownResourceId, multipart);
304 int statusCode = res.getStatus();
305 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
306 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
307 Assert.assertEquals(statusCode, STATUS_CREATED);
308 result = extractId(res);
310 res.releaseConnection();
318 * Read and check auth refs.
320 * @param testName the test name
321 * @throws Exception the exception
323 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
324 dependsOnMethods = {"createWithAuthRefs"})
325 public void readAndCheckAuthRefs(String testName) throws Exception {
327 if (logger.isDebugEnabled()) {
328 logger.debug(testBanner(testName, CLASS_NAME));
331 testSetup(STATUS_OK, ServiceRequestType.READ);
333 // Submit the request to the service and store the response.
334 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
335 ClientResponse<MultipartInput> res =
336 orgAuthClient.readItem(knownResourceId, knownItemResourceId);
337 int statusCode = res.getStatus();
339 // Check the status code of the response: does it match
340 // the expected response(s)?
341 if(logger.isDebugEnabled()){
342 logger.debug(testName + ".read: status = " + statusCode);
344 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
345 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
346 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
348 MultipartInput input = (MultipartInput) res.getEntity();
349 OrganizationsCommon organization = (OrganizationsCommon) extractPart(input,
350 orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
351 Assert.assertNotNull(organization);
352 if(logger.isDebugEnabled()){
353 logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
355 // Check one or more of the authority fields in the Organization item
356 Assert.assertEquals(organization.getContactName(), organizationContactPersonRefName);
357 Assert.assertEquals(organization.getSubBody(), subBodyRefName);
359 // Get the auth refs and check them
360 // FIXME - need to create this method in the client
361 // and get the ID for the organization item
362 ClientResponse<AuthorityRefList> res2 =
363 orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
364 statusCode = res2.getStatus();
366 if(logger.isDebugEnabled()){
367 logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
369 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
370 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
371 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
372 AuthorityRefList list = res2.getEntity();
374 List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
375 int numAuthRefsFound = items.size();
376 if(logger.isDebugEnabled()){
377 logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
378 " authority references, found " + numAuthRefsFound);
380 Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
381 "Did not find all expected authority references! " +
382 "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
384 // Optionally output additional data about list members for debugging.
385 boolean iterateThroughList = true;
386 if(iterateThroughList && logger.isDebugEnabled()){
388 for(AuthorityRefList.AuthorityRefItem item : items){
389 logger.debug(testName + ": list-item[" + i + "] Field:" +
390 item.getSourceField() + "=" +
391 item.getItemDisplayName());
392 logger.debug(testName + ": list-item[" + i + "] refName=" +
394 logger.debug(testName + ": list-item[" + i + "] URI=" +
401 // ---------------------------------------------------------------
402 // Cleanup of resources created during testing
403 // ---------------------------------------------------------------
406 * Deletes all resources created by tests, after all tests have been run.
408 * This cleanup method will always be run, even if one or more tests fail.
409 * For this reason, it attempts to remove all resources created
410 * at any point during testing, even if some of those resources
411 * may be expected to be deleted by certain tests.
413 @AfterClass(alwaysRun=true)
414 public void cleanUp() {
415 String noTest = System.getProperty("noTestCleanup");
416 if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
417 if (logger.isDebugEnabled()) {
418 logger.debug("Skipping Cleanup phase ...");
422 if (logger.isDebugEnabled()) {
423 logger.debug("Cleaning up temporary resources created for testing ...");
425 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
426 // Delete Person resource(s) (before PersonAuthority resources).
427 for (String resourceId : personIdsCreated) {
428 // Note: Any non-success responses are ignored and not reported.
429 personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
431 // Delete PersonAuthority resource(s).
432 // Note: Any non-success response is ignored and not reported.
433 if(personAuthCSID!=null) {
434 personAuthClient.delete(personAuthCSID).releaseConnection();
437 String parentResourceId;
438 String itemResourceId;
439 OrgAuthorityClient client = new OrgAuthorityClient();
440 // Clean up item resources.
441 for (Map.Entry<String, String> entry : allItemResourceIdsCreated.entrySet()) {
442 itemResourceId = entry.getKey();
443 parentResourceId = entry.getValue();
444 // Note: Any non-success responses from the delete operation
445 // below are ignored and not reported.
446 client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
449 // Clean up parent resources.
450 for (String resourceId : allResourceIdsCreated) {
451 // Note: Any non-success responses from the delete operation
452 // below are ignored and not reported.
453 client.delete(resourceId).releaseConnection();
457 // ---------------------------------------------------------------
458 // Utility methods used by tests above
459 // ---------------------------------------------------------------
461 * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
464 public String getServicePathComponent() {
465 return SERVICE_PATH_COMPONENT;