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.PersonJAXBSchema;
33 import org.collectionspace.services.client.CollectionSpaceClient;
34 import org.collectionspace.services.client.LoanoutClient;
35 import org.collectionspace.services.client.PayloadOutputPart;
36 import org.collectionspace.services.client.PersonAuthorityClient;
37 import org.collectionspace.services.client.PersonAuthorityClientUtils;
38 import org.collectionspace.services.client.PoxPayloadIn;
39 import org.collectionspace.services.client.PoxPayloadOut;
40 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
42 import org.collectionspace.services.jaxb.AbstractCommonList;
43 import org.collectionspace.services.loanout.LoansoutCommon;
44 import org.collectionspace.services.person.PersonTermGroup;
45 import org.testng.Assert;
46 import org.testng.annotations.AfterClass;
47 import org.testng.annotations.Test;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * LoanoutAuthRefsTest, carries out Authority References tests against a
53 * deployed and running Loanout (aka Loans Out) Service.
55 * $LastChangedRevision$
58 public class LoanoutAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
60 private final String CLASS_NAME = LoanoutAuthRefsTest.class.getName();
61 private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
63 // Instance variables specific to this test.
64 final String SERVICE_NAME = "loansout";
65 final String SERVICE_PATH_COMPONENT = "loansout";
66 final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
67 private String knownResourceId = null;
68 private List<String> loanoutIdsCreated = new ArrayList<String>();
69 private List<String> personIdsCreated = new ArrayList<String>();
70 private String personAuthCSID = null;
71 private String borrowerRefName = null;
72 private String borrowersContactRefName = null;
73 private String lendersAuthorizerRefName = null;
74 private String lendersContactRefName = null;
76 // FIXME: Can add 'borrower' - likely to be an organization
77 // authority - as an authRef to tests below, and increase the
78 // number of expected authRefs to 4.
79 private final int NUM_AUTH_REFS_EXPECTED = 4;
81 private final static String CURRENT_DATE_UTC =
82 GregorianCalendarDateTimeUtils.currentDateUTC();
85 * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
88 protected CollectionSpaceClient getClientInstance() {
89 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
93 protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
94 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
98 * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
101 protected AbstractCommonList getCommonList(Response response) {
102 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
105 // ---------------------------------------------------------------
106 // CRUD tests : CREATE tests
107 // ---------------------------------------------------------------
109 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
110 public void createWithAuthRefs(String testName) throws Exception {
111 testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
113 // Submit the request to the service and store the response.
114 String identifier = createIdentifier();
116 // Create all the person refs and entities
119 // Create a new Loans In resource.
121 // One or more fields in this resource will be PersonAuthority
122 // references, and will refer to Person resources by their refNames.
123 LoanoutClient loanoutClient = new LoanoutClient();
124 PoxPayloadOut multipart = createLoanoutInstance(
125 "loanOutNumber-" + identifier,
128 borrowersContactRefName,
129 lendersAuthorizerRefName,
130 lendersContactRefName);
132 Response res = loanoutClient.create(multipart);
134 int statusCode = res.getStatus();
136 // Check the status code of the response: does it match
137 // the expected response(s)?
140 // Does it fall within the set of valid status codes?
141 // Does it exactly match the expected status code?
142 if(logger.isDebugEnabled()){
143 logger.debug(testName + ": status = " + statusCode);
145 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
146 invalidStatusCodeMessage(testRequestType, statusCode));
147 Assert.assertEquals(statusCode, testExpectedStatusCode);
148 newId = extractId(res);
149 Assert.assertNotNull(newId, "Could not create a new LoanOut record.");
154 // Store the ID returned from the first resource created
155 // for additional tests below.
156 if (knownResourceId == null){
157 knownResourceId = newId;
158 if (logger.isDebugEnabled()) {
159 logger.debug(testName + ": knownResourceId=" + knownResourceId);
163 // Store the IDs from every resource created by tests,
164 // so they can be deleted after tests have been run.
165 loanoutIdsCreated.add(newId);
168 protected void createPersonRefs() throws Exception{
170 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
171 // Create a temporary PersonAuthority resource, and its corresponding
172 // refName by which it can be identified.
173 PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
174 PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
175 Response res = personAuthClient.create(multipart);
177 int statusCode = res.getStatus();
178 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
179 invalidStatusCodeMessage(testRequestType, statusCode));
180 Assert.assertEquals(statusCode, STATUS_CREATED);
181 personAuthCSID = extractId(res);
186 String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
188 // Create temporary Person resources, and their corresponding refNames
189 // by which they can be identified.
191 String csid = createPerson("Betty", "Borrower", "bettyBorrower", authRefName);
192 personIdsCreated.add(csid);
193 borrowerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
195 csid = createPerson("Bradley", "BorrowersContact", "bradleyBorrowersContact", authRefName);
196 personIdsCreated.add(csid);
197 borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
199 csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
200 personIdsCreated.add(csid);
201 lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
203 csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
204 personIdsCreated.add(csid);
205 lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
208 protected String createPerson(String firstName, String surName, String shortId, String authRefName ) throws Exception {
209 String result = null;
211 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
212 Map<String, String> personInfo = new HashMap<String,String>();
213 personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
214 personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
215 personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId + random.nextInt(1000)); // avoid short ID conflicts with pass test session records that never got cleaned up
216 List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
217 PersonTermGroup term = new PersonTermGroup();
218 String termName = firstName + " " + surName;
219 term.setTermDisplayName(termName);
220 term.setTermName(termName);
221 personTerms.add(term);
222 PoxPayloadOut multipart =
223 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
224 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
225 Response res = personAuthClient.createItem(personAuthCSID, multipart);
227 int statusCode = res.getStatus();
229 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
230 invalidStatusCodeMessage(testRequestType, statusCode));
231 Assert.assertEquals(statusCode, STATUS_CREATED);
232 result = extractId(res);
241 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
242 dependsOnMethods = {"createWithAuthRefs"})
243 public void readAndCheckAuthRefs(String testName) throws Exception {
245 testSetup(STATUS_OK, ServiceRequestType.READ);
247 // Submit the request to the service and store the response.
248 LoanoutClient loanoutClient = new LoanoutClient();
249 Response res = loanoutClient.read(knownResourceId);
250 LoansoutCommon loanoutCommon = null;
252 assertStatusCode(res, testName);
253 // Extract the common part from the response.
254 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
255 loanoutCommon = (LoansoutCommon) extractPart(input,
256 loanoutClient.getCommonPartName(), LoansoutCommon.class);
257 Assert.assertNotNull(loanoutCommon);
258 if(logger.isDebugEnabled()){
259 logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
267 // Check a couple of fields
268 Assert.assertEquals(loanoutCommon.getBorrower(), borrowerRefName);
269 Assert.assertEquals(loanoutCommon.getBorrowersContact(), borrowersContactRefName);
270 Assert.assertEquals(loanoutCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
271 Assert.assertEquals(loanoutCommon.getLendersContact(), lendersContactRefName);
273 // Get the auth refs and check them
274 Response res2 = loanoutClient.getAuthorityRefs(knownResourceId);
275 AuthorityRefList list = null;
277 assertStatusCode(res2, testName);
278 list = res2.readEntity(AuthorityRefList.class);
285 List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
286 int numAuthRefsFound = items.size();
287 if(logger.isDebugEnabled()){
288 logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
289 " authority references, found " + numAuthRefsFound);
291 Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
292 "Did not find all expected authority references! " +
293 "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
295 // Optionally output additional data about list members for debugging.
296 boolean iterateThroughList = true;
297 if(iterateThroughList && logger.isDebugEnabled()){
299 for(AuthorityRefList.AuthorityRefItem item : items){
300 logger.debug(testName + ": list-item[" + i + "] Field:" +
301 item.getSourceField() + "= " +
302 item.getAuthDisplayName() +
303 item.getItemDisplayName());
304 logger.debug(testName + ": list-item[" + i + "] refName=" +
306 logger.debug(testName + ": list-item[" + i + "] URI=" +
314 // ---------------------------------------------------------------
315 // Cleanup of resources created during testing
316 // ---------------------------------------------------------------
319 * Deletes all resources created by tests, after all tests have been run.
321 * This cleanup method will always be run, even if one or more tests fail.
322 * For this reason, it attempts to remove all resources created
323 * at any point during testing, even if some of those resources
324 * may be expected to be deleted by certain tests.
327 @AfterClass(alwaysRun=true)
328 public void cleanUp() throws Exception {
329 String noTest = System.getProperty("noTestCleanup");
330 if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
331 if (logger.isDebugEnabled()) {
332 logger.debug("Skipping Cleanup phase ...");
336 if (logger.isDebugEnabled()) {
337 logger.debug("Cleaning up temporary resources created for testing ...");
339 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
340 // Delete Person resource(s) (before PersonAuthority resources).
341 for (String resourceId : personIdsCreated) {
342 // Note: Any non-success responses are ignored and not reported.
343 personAuthClient.deleteItem(personAuthCSID, resourceId).close();
345 // Delete PersonAuthority resource(s).
346 // Note: Any non-success response is ignored and not reported.
347 if (personAuthCSID != null) {
348 personAuthClient.delete(personAuthCSID).close();
349 // Delete Loans In resource(s).
350 LoanoutClient loanoutClient = new LoanoutClient();
351 for (String resourceId : loanoutIdsCreated) {
352 // Note: Any non-success responses are ignored and not reported.
353 loanoutClient.delete(resourceId).close();
358 // ---------------------------------------------------------------
359 // Utility methods used by tests above
360 // ---------------------------------------------------------------
361 public String getServiceName() {
366 public String getServicePathComponent() {
367 return SERVICE_PATH_COMPONENT;
370 private PoxPayloadOut createLoanoutInstance(String loanoutNumber,
373 String borrowersContact,
374 String lendersAuthorizer,
375 String lendersContact) throws Exception {
376 LoansoutCommon loanoutCommon = new LoansoutCommon();
377 loanoutCommon.setLoanOutNumber(loanoutNumber);
378 loanoutCommon.setLoanReturnDate(returnDate);
379 loanoutCommon.setBorrower(borrower);
380 loanoutCommon.setBorrowersContact(borrowersContact);
381 loanoutCommon.setLendersAuthorizer(lendersAuthorizer);
382 loanoutCommon.setLendersContact(lendersContact);
384 PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
385 PayloadOutputPart commonPart =
386 multipart.addPart(new LoanoutClient().getCommonPartName(), loanoutCommon);
388 if(logger.isDebugEnabled()){
389 logger.debug("to be created, loanout common");
390 logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
397 protected Class<AbstractCommonList> getCommonListType() {
398 // TODO Auto-generated method stub