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 /** The PERSO n_ authorit y_ name. */
72 final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
74 /** The known resource ref name. */
75 private String knownResourceRefName = null;
77 /** The known auth resource id. */
78 private String knownAuthResourceId = null;
80 /** The known item id. */
81 private String knownItemId = null;
83 /** The all resource ids created. */
84 private List<String> allResourceIdsCreated = new ArrayList<String>();
86 /** The all item resource ids created. */
87 private Map<String, String> allItemResourceIdsCreated =
88 new HashMap<String, String>();
90 /** The person ids created. */
91 private List<String> personIdsCreated = new ArrayList<String>();
93 /** The person auth csid. */
94 private String personAuthCSID = null;
96 /** The organization contact person ref name. */
97 private String organizationContactPersonRefName = null;
99 /** The number of authorityreferences expected. */
100 private final int NUM_AUTH_REFS_EXPECTED = 1;
103 * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
106 protected CollectionSpaceClient getClientInstance() {
107 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
111 * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
114 protected AbstractCommonList getAbstractCommonList(
115 ClientResponse<AbstractCommonList> response) {
116 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
119 // ---------------------------------------------------------------
120 // CRUD tests : CREATE tests
121 // ---------------------------------------------------------------
124 * Creates the with auth refs.
126 * @param testName the test name
127 * @throws Exception the exception
129 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
130 public void createWithAuthRefs(String testName) throws Exception {
132 if (logger.isDebugEnabled()) {
133 logger.debug(testBanner(testName, CLASS_NAME));
135 testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
137 // Create a new Organization Authority resource.
138 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
139 String identifier = createIdentifier();
140 String displayName = "TestOrgAuth-" + identifier;
141 boolean createWithDisplayName = false;
142 knownResourceRefName =
143 OrgAuthorityClientUtils.createOrgAuthRefName(displayName, createWithDisplayName);
144 MultipartOutput multipart =
145 OrgAuthorityClientUtils.createOrgAuthorityInstance(
146 displayName, knownResourceRefName, orgAuthClient.getCommonPartName());
148 // Submit the request to the service and store the response.
149 ClientResponse<Response> res = orgAuthClient.create(multipart);
151 int statusCode = res.getStatus();
152 // Check the status code of the response: does it match
153 // the expected response(s)?
156 // Does it fall within the set of valid status codes?
157 // Does it exactly match the expected status code?
158 if(logger.isDebugEnabled()){
159 logger.debug(testName + ": status = " + statusCode);
161 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
162 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
163 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
165 // Store the IDs from every resource created by tests,
166 // so they can be deleted after tests have been run.
167 knownAuthResourceId = extractId(res);
169 res.releaseConnection();
171 allResourceIdsCreated.add(knownAuthResourceId);
173 // Create all the person refs and entities
176 // Initialize values for a new Organization item, to be created within
177 // the newly-created Organization Authority resource.
179 // One or more fields in the Organization item record will
180 // contain references to Persons, via their refNames, as
181 // per the initialization(s) below.
182 Map<String, String> testOrgMap = new HashMap<String,String>();
183 testOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
184 "Test Organization-" + identifier);
185 testOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Test Organization Name");
186 testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
187 testOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, organizationContactPersonRefName);
189 // Finishing creating the new Organization item, then
190 // submit the request to the service and store the response.
191 knownItemId = OrgAuthorityClientUtils.createItemInAuthority(
192 knownAuthResourceId, knownResourceRefName, testOrgMap, orgAuthClient);
194 // Store the IDs from every item created by tests,
195 // so they can be deleted after tests have been run.
196 allItemResourceIdsCreated.put(knownItemId, knownAuthResourceId);
200 * Creates the person refs.
202 protected void createPersonRefs() {
203 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
204 // Create a temporary PersonAuthority resource, and its corresponding
205 // refName by which it can be identified.
207 PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
208 MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
209 PERSON_AUTHORITY_NAME, authRefName, personAuthClient.getCommonPartName());
211 ClientResponse<Response> res = personAuthClient.create(multipart);
213 int statusCode = res.getStatus();
214 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
215 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
216 Assert.assertEquals(statusCode, STATUS_CREATED);
217 personAuthCSID = extractId(res);
219 res.releaseConnection();
222 // Create a temporary Person resource, and its corresponding refName
223 // by which it can be identified.
224 organizationContactPersonRefName =
225 PersonAuthorityClientUtils.createPersonRefName(authRefName, "Charlie Orgcontact", true);
226 personIdsCreated.add(createPerson("Charlie", "Orgcontact", organizationContactPersonRefName));
231 * Creates the person.
233 * @param firstName the first name
234 * @param surName the sur name
235 * @param refName the ref name
238 protected String createPerson(String firstName, String surName, String refName ) {
239 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
240 Map<String, String> personInfo = new HashMap<String,String>();
241 personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
242 personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
243 MultipartOutput multipart =
244 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
245 refName, personInfo, personAuthClient.getItemCommonPartName());
247 String result = null;
248 ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
250 int statusCode = res.getStatus();
252 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
253 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
254 Assert.assertEquals(statusCode, STATUS_CREATED);
255 result = extractId(res);
257 res.releaseConnection();
265 * Read and check auth refs.
267 * @param testName the test name
268 * @throws Exception the exception
270 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
271 dependsOnMethods = {"createWithAuthRefs"})
272 public void readAndCheckAuthRefs(String testName) throws Exception {
274 if (logger.isDebugEnabled()) {
275 logger.debug(testBanner(testName, CLASS_NAME));
278 testSetup(STATUS_OK, ServiceRequestType.READ);
280 // Submit the request to the service and store the response.
281 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
282 ClientResponse<MultipartInput> res =
283 orgAuthClient.readItem(knownAuthResourceId, knownItemId);
284 int statusCode = res.getStatus();
286 // Check the status code of the response: does it match
287 // the expected response(s)?
288 if(logger.isDebugEnabled()){
289 logger.debug(testName + ".read: status = " + statusCode);
291 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
292 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
293 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
295 MultipartInput input = (MultipartInput) res.getEntity();
296 OrganizationsCommon organization = (OrganizationsCommon) extractPart(input,
297 orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
298 Assert.assertNotNull(organization);
299 if(logger.isDebugEnabled()){
300 logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
302 // Check one or more of the authority fields in the Organization item
303 Assert.assertEquals(organization.getContactName(), organizationContactPersonRefName);
305 // Get the auth refs and check them
306 // FIXME - need to create this method in the client
307 // and get the ID for the organization item
308 ClientResponse<AuthorityRefList> res2 =
309 orgAuthClient.getItemAuthorityRefs(knownAuthResourceId, knownItemId);
310 statusCode = res2.getStatus();
312 if(logger.isDebugEnabled()){
313 logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
315 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
316 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
317 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
318 AuthorityRefList list = res2.getEntity();
320 // Optionally output additional data about list members for debugging.
321 boolean iterateThroughList = true;
322 if(iterateThroughList && logger.isDebugEnabled()){
323 List<AuthorityRefList.AuthorityRefItem> items =
324 list.getAuthorityRefItem();
326 for(AuthorityRefList.AuthorityRefItem item : items){
327 logger.debug(testName + ": list-item[" + i + "] Field:" +
328 item.getSourceField() + "=" +
329 item.getItemDisplayName());
330 logger.debug(testName + ": list-item[" + i + "] refName=" +
332 logger.debug(testName + ": list-item[" + i + "] URI=" +
336 Assert.assertEquals(i, NUM_AUTH_REFS_EXPECTED, "Did not find all authrefs!");
340 // ---------------------------------------------------------------
341 // Cleanup of resources created during testing
342 // ---------------------------------------------------------------
345 * Deletes all resources created by tests, after all tests have been run.
347 * This cleanup method will always be run, even if one or more tests fail.
348 * For this reason, it attempts to remove all resources created
349 * at any point during testing, even if some of those resources
350 * may be expected to be deleted by certain tests.
352 @AfterClass(alwaysRun=true)
353 public void cleanUp() {
354 String noTest = System.getProperty("noTestCleanup");
355 if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
356 if (logger.isDebugEnabled()) {
357 logger.debug("Skipping Cleanup phase ...");
361 if (logger.isDebugEnabled()) {
362 logger.debug("Cleaning up temporary resources created for testing ...");
364 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
365 // Delete Person resource(s) (before PersonAuthority resources).
366 for (String resourceId : personIdsCreated) {
367 // Note: Any non-success responses are ignored and not reported.
368 personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
370 // Delete PersonAuthority resource(s).
371 // Note: Any non-success response is ignored and not reported.
372 personAuthClient.delete(personAuthCSID).releaseConnection();
374 String parentResourceId;
375 String itemResourceId;
376 OrgAuthorityClient client = new OrgAuthorityClient();
377 // Clean up item resources.
378 for (Map.Entry<String, String> entry : allItemResourceIdsCreated.entrySet()) {
379 itemResourceId = entry.getKey();
380 parentResourceId = entry.getValue();
381 // Note: Any non-success responses from the delete operation
382 // below are ignored and not reported.
383 client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
386 // Clean up parent resources.
387 for (String resourceId : allResourceIdsCreated) {
388 // Note: Any non-success responses from the delete operation
389 // below are ignored and not reported.
390 client.delete(resourceId).releaseConnection();
394 // ---------------------------------------------------------------
395 // Utility methods used by tests above
396 // ---------------------------------------------------------------
398 * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
401 public String getServicePathComponent() {
402 return SERVICE_PATH_COMPONENT;
406 * Creates the org authority instance.
408 * @param identifier the identifier
409 * @return the multipart output
411 private MultipartOutput createOrgAuthorityInstance(String identifier) {
412 String displayName = "displayName-" + identifier;
413 String refName = OrgAuthorityClientUtils.createOrgAuthRefName(displayName, true);
414 return OrgAuthorityClientUtils.createOrgAuthorityInstance(
415 displayName, refName,
416 new OrgAuthorityClient().getCommonPartName());