1 package org.collectionspace.services.client.test;
3 import java.util.ArrayList;
4 import java.util.HashMap;
8 import javax.ws.rs.core.Response;
9 import org.apache.http.HttpStatus;
11 import org.collectionspace.services.client.AbstractCommonListUtils;
12 import org.collectionspace.services.client.AuthorityClient;
13 import org.collectionspace.services.client.CollectionSpaceClient;
14 import org.collectionspace.services.client.PayloadInputPart;
15 import org.collectionspace.services.client.PayloadOutputPart;
16 import org.collectionspace.services.client.PoxPayloadIn;
17 import org.collectionspace.services.client.PoxPayloadOut;
18 import org.collectionspace.services.client.RelationClient;
19 import org.collectionspace.services.client.XmlTools;
20 import org.collectionspace.services.client.workflow.WorkflowClient;
21 import org.collectionspace.services.description.ServiceDescription;
22 import org.collectionspace.services.jaxb.AbstractCommonList;
23 import org.collectionspace.services.relation.RelationsCommon;
24 import org.collectionspace.services.relation.RelationshipType;
26 import org.dom4j.Document;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import org.testng.Assert;
30 import org.testng.annotations.Test;
36 * @param <AUTHORITY_COMMON_TYPE>
37 * @param <AUTHORITY_ITEM_TYPE>
39 * All CRUD related authority test classes should extend this class.
42 public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHORITY_ITEM_TYPE>
43 extends AbstractPoxServiceTestImpl<AbstractCommonList, AUTHORITY_COMMON_TYPE> {
45 private final Logger logger = LoggerFactory.getLogger(AbstractAuthorityServiceTest.class);
47 protected String knownResourceShortIdentifer = null;
48 protected static final String READITEMS_SHORT_IDENTIFIER = "resourceWithItems" + random.nextInt(1000);
49 protected String knownAuthorityWithItems = null;
50 protected String knownAuthorityWithItemsIdentifier = null;
52 protected static final String SAS_IDENTIFIER = "SAS";
53 protected static final String SAS_WITH_RELATIONS = "_RELATIONS_";
55 private static final int SAS_ITEMLIST_SIZE = 5;
57 protected String knownSASAuthorityResourceId = null;
58 protected String knownSASAuthorityResourceShortId = null;
59 protected List<String> knownSASItemIdentifiersList = new ArrayList<String>();
60 protected String knownSASItemResourceId = null;
61 protected HashMap<String, String> allSASResourceItemIdsCreated = new HashMap<String, String>(); /* itemURN, parentURN */;
63 protected String knownResourceRefName = null;
64 protected String knownItemResourceId = null;
65 protected String knownItemResourceShortIdentifer = null;
66 protected int nItemsToCreateInList = 5;
67 protected String TEST_SHORTID = "johnWayneActor";
69 protected String knownSASAuthorityResourceWithRelationsId = null;
70 protected String knownSASAuthorityResourceWithRelationsShortId = null;
73 * Abstract methods that subclasses must override/implement
80 public abstract void authorityTests(String testName);
88 abstract protected String createItemInAuthority(AuthorityClient client, String vcsid, String shortId);
93 * @param authorityItem
96 protected abstract AUTHORITY_ITEM_TYPE updateItemInstance(final AUTHORITY_ITEM_TYPE authorityItem);
104 protected abstract void compareUpdatedItemInstances(AUTHORITY_ITEM_TYPE original,
105 AUTHORITY_ITEM_TYPE updated,
106 boolean compareRevNumbers) throws Exception;
114 protected void compareUpdatedItemInstances(AUTHORITY_ITEM_TYPE original,
115 AUTHORITY_ITEM_TYPE updated) throws Exception {
116 compareUpdatedItemInstances(original, updated, false);
122 * @param shortIdentifer
124 protected void setKnownItemResource(String id, String shortIdentifer ) {
125 knownItemResourceId = id;
126 knownItemResourceShortIdentifer = shortIdentifer;
132 * @param shortIdentifer
135 protected void setKnownResource(String id, String shortIdentifer,
137 knownResourceId = id;
138 knownResourceShortIdentifer = shortIdentifer;
139 knownResourceRefName = refName;
146 protected String getSASAuthorityIdentifier() {
147 return this.getKnowResourceIdentifier() + SAS_IDENTIFIER;
154 protected String getSASAuthorityWithRelationsIdentifier() {
155 return this.getKnowResourceIdentifier() + SAS_WITH_RELATIONS + SAS_IDENTIFIER;
163 protected String getUrnIdentifier(String shortId) {
164 return String.format("urn:cspace:name(%s)", shortId);
168 * Sets up create tests.
170 protected void setupSync() {
171 testExpectedStatusCode = this.STATUS_OK;
172 testRequestType = ServiceRequestType.SYNC;
173 testSetup(testExpectedStatusCode, testRequestType);
177 * Gets a client to the SAS (Shared Authority Server)
181 protected AuthorityClient getSASClientInstance() {
182 return (AuthorityClient) this.getClientInstance(CollectionSpaceClient.SAS_CLIENT_PROPERTIES_FILENAME);
186 * Returns the root URL for a service.
188 * This URL consists of a base URL for all services, followed by
189 * a path component for the owning vocabulary, followed by the
190 * path component for the items.
192 * @return The root URL for a service.
194 protected String getItemServiceRootURL(String parentResourceIdentifier) {
195 return getResourceURL(parentResourceIdentifier) + "/" + getServicePathItemsComponent();
199 * Returns the URL of a specific resource managed by a service, and
200 * designated by an identifier (such as a universally unique ID, or UUID).
202 * @param resourceIdentifier An identifier (such as a UUID) for a resource.
204 * @return The URL of a specific resource managed by a service.
206 protected String getItemResourceURL(String parentResourceIdentifier, String resourceIdentifier) {
207 return getItemServiceRootURL(parentResourceIdentifier) + "/" + resourceIdentifier;
211 * For authorities we override this method so we can save the shortid.
214 protected String createWithIdentifier(String testName, String identifier) throws Exception {
215 String csid = createResource(testName, identifier);
216 // Store the ID returned from the first resource created
217 // for additional tests below.
218 if (getKnowResourceId() == null) {
219 setKnownResource(csid, identifier /*shortId*/, null /*refname*/ );
220 if (logger.isDebugEnabled()) {
221 logger.debug(testName + ": Setting knownResourceId=" + getKnowResourceId());
228 @Test(dependsOnMethods = {"readItem", "CRUDTests"})
229 public void testItemSubmitRequest() {
231 // Expected status code: 200 OK
232 final int EXPECTED_STATUS = Response.Status.OK.getStatusCode();
234 // Submit the request to the service and store the response.
235 String method = ServiceRequestType.READ.httpMethodName();
236 String url = getItemResourceURL(knownResourceId, knownItemResourceId);
237 int statusCode = submitRequest(method, url);
239 // Check the status code of the response: does it match
240 // the expected response(s)?
241 if (logger.isDebugEnabled()) {
242 logger.debug("testItemSubmitRequest: url=" + url
243 + " status=" + statusCode);
245 Assert.assertEquals(statusCode, EXPECTED_STATUS);
249 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
250 dependsOnMethods = {"readItem"})
251 public void verifyIgnoredUpdateWithInAuthority(String testName) throws Exception {
255 // Submit the request to the service and store the response.
256 AuthorityClient client = (AuthorityClient)this.getClientInstance();
257 Response res = client.readItem(knownResourceId, knownItemResourceId);
258 AUTHORITY_ITEM_TYPE vitem = null;
260 int statusCode = res.getStatus();
262 // Check the status code of the response: does it match
263 // the expected response(s)?
264 if (logger.isDebugEnabled()) {
265 logger.debug(testName + " read authority:" + knownResourceId + "/Item:"
266 + knownItemResourceId + " status = " + statusCode);
268 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
269 invalidStatusCodeMessage(testRequestType, statusCode));
270 Assert.assertEquals(statusCode, Response.Status.OK.getStatusCode());
272 vitem = extractItemCommonPartValue(res);
273 Assert.assertNotNull(vitem);
274 // Try to Update with new parent vocab (use self, for test).
275 Assert.assertEquals(client.getInAuthority(vitem), knownResourceId,
276 "VocabularyItem inAuthority does not match knownResourceId.");
277 client.setInAuthority(vitem, knownItemResourceId);
283 // Submit the updated resource to the service and store the response.
284 PoxPayloadOut output = this.createItemRequestTypeInstance(vitem);
285 res = client.updateItem(knownResourceId, knownItemResourceId, output);
287 int statusCode = res.getStatus();
289 // Check the status code of the response: does it match the expected response(s)?
290 if (logger.isDebugEnabled()) {
291 logger.debug(testName + ": status = " + statusCode);
293 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
294 invalidStatusCodeMessage(testRequestType, statusCode));
295 Assert.assertEquals(statusCode, testExpectedStatusCode);
300 res = client.readItem(knownResourceId, knownItemResourceId);
302 // Retrieve the updated resource and verify that the parent did not change
303 AUTHORITY_ITEM_TYPE updatedVocabularyItem = extractItemCommonPartValue(res);
304 Assert.assertNotNull(updatedVocabularyItem);
306 // Verify that the updated resource received the correct data.
307 Assert.assertEquals(client.getInAuthority(updatedVocabularyItem),
309 "VocabularyItem allowed update to the parent (inAuthority).");
315 @Test(dataProvider = "testName", dependsOnMethods = {"CRUDTests"})
316 public void createItem(String testName) {
320 String newID = createItemInAuthority((AuthorityClient) getClientInstance(), knownResourceId, getTestAuthorityItemShortId());
322 // Store the ID returned from the first item resource created
323 // for additional tests below.
324 if (knownItemResourceId == null) {
325 knownItemResourceId = newID;
326 if (null != testName && logger.isDebugEnabled()) {
327 logger.debug(testName + ": knownItemResourceId=" + knownItemResourceId);
333 * Sync the local with the SAS
336 @Test(dataProvider = "testName", dependsOnMethods = {"createSASItemList", "CRUDTests"})
337 public void syncWithSAS(String testName) throws Exception {
339 // First check to see if the authority supports synchronization.
341 AuthorityClient client = (AuthorityClient) this.getClientInstance();
342 if (client.supportsSync() == false) {
343 return; // Exit the test since this authority doesn't support synchronization
347 // Create an empty instance of the authority, so we can sync items with it. We're
348 // using the short ID of the SAS authority. The short ID of the local and the SAS will (must) be the same.
350 String localAuthorityId = null;
352 localAuthorityId = createResource(client, testName, knownSASAuthorityResourceShortId, false);
353 } catch (Exception e) {
354 Assert.assertNotNull(localAuthorityId);
358 // Now we can try to sync the SAS authority with the local one we just created.
361 Response response = client.syncByName(knownSASAuthorityResourceShortId); // Notice we're using the Short ID (short ID is the same on the local and SAS)
363 int statusCode = response.getStatus();
364 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
365 invalidStatusCodeMessage(testRequestType, statusCode));
366 Assert.assertEquals(statusCode, testExpectedStatusCode);
372 // Check to see if the parent authority (local) is in the "Replicated" state.
375 response = client.readByName(knownSASAuthorityResourceShortId); // Notice we're using the Short ID (short ID is the same on the local and SAS)
377 int statusCode = response.getStatus();
378 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
379 invalidStatusCodeMessage(testRequestType, statusCode));
380 Assert.assertEquals(statusCode, testExpectedStatusCode);
381 String workflowState = this.extractAuthorityWorkflowState(response);
382 Assert.assertTrue(workflowState.contains(WorkflowClient.WORKFLOWSTATE_REPLICATED)); // After a sync, the parent should be in the "Replicated" state
390 * Check to make sure the sync with the SAS returned the correct number of items as well as items
391 * with the correct short IDs.
394 @Test(dataProvider = "testName", dependsOnMethods = {"syncWithSAS", "CRUDTests"})
395 public void veryifySyncWithSAS(String testName) {
397 // First check to see if we support sync.
399 AuthorityClient client = (AuthorityClient) getClientInstance();
400 if (client.supportsSync() == false) {
401 return; // Exit the test since this authority doesn't support synchronization
407 // Submit the request to the service and store the response.
409 res = client.readItemListForNamedAuthority(knownSASAuthorityResourceShortId, null, null);
412 int statusCode = res.getStatus();
414 // Check the status code of the response: does it match
415 // the expected response(s)?
416 if (logger.isDebugEnabled()) {
417 logger.debug(" " + testName + ": status = " + statusCode);
419 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
420 invalidStatusCodeMessage(testRequestType, statusCode));
421 Assert.assertEquals(statusCode, testExpectedStatusCode);
423 AbstractCommonList list = res.readEntity(AbstractCommonList.class);
424 List<AbstractCommonList.ListItem> items = list.getListItem();
425 int nItemsReturned = items.size();
426 long nItemsTotal = list.getTotalItems();
427 if (logger.isDebugEnabled()) {
428 logger.debug(" " + testName + ": Expected "
429 + nItemsToCreateInList + " items; got: " + nItemsReturned + " of: " + nItemsTotal);
431 Assert.assertEquals(nItemsTotal, SAS_ITEMLIST_SIZE);
433 // Verify that each of our local items has a corresponding remote item
435 for (AbstractCommonList.ListItem item : items) {
436 String shortId = AbstractCommonListUtils.ListItemGetElementValue(
437 item, AuthorityClient.SHORT_IDENTIFIER);
438 Assert.assertTrue(knownSASItemIdentifiersList.contains(shortId)); // The local short ID should be in SAS list
440 String workflowState = AbstractCommonListUtils.ListItemGetElementValue(
441 item, CollectionSpaceClient.COLLECTIONSPACE_CORE_WORKFLOWSTATE);
442 Assert.assertTrue(workflowState.contains(WorkflowClient.WORKFLOWSTATE_REPLICATED)); // Workflow state must show up in a "replicated" state
444 String refName = AbstractCommonListUtils.ListItemGetElementValue(
445 item, AuthorityClient.REF_NAME);
446 Assert.assertTrue((refName != null), "Item refName is null or not set in the item list!");
447 String termDisplayName = AbstractCommonListUtils.ListItemGetElementValue(item,
448 AuthorityClient.TERM_DISPLAY_NAME);
449 String vocabDisplayName = AbstractCommonListUtils.ListItemGetElementValue(item,
450 AuthorityClient.VOCAB_DISPLAY_NAME);
451 // One of these names needs to be set.
452 Assert.assertTrue(!(termDisplayName == null && vocabDisplayName == null), "The item's display name is null or not set in the item list!");
455 if(logger.isTraceEnabled()){
456 AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName);
464 * SAS - Create a new authority on the SAS server.
467 @Test(dataProvider = "testName", dependsOnMethods = {"createItem", "CRUDTests"})
468 public void createSASAuthority(String testName) {
470 // First check to see if the authority supports synchronization.
472 AuthorityClient client = (AuthorityClient) this.getClientInstance();
473 if (client.supportsSync() == false) {
474 return; // Exit the test since this authority doesn't support synchronization
481 String newID = createResource(getSASClientInstance(), testName, getSASAuthorityIdentifier(), true);
482 knownSASAuthorityResourceId = newID;
483 knownSASAuthorityResourceShortId = getShortId(getSASClientInstance(), knownSASAuthorityResourceId);
484 if (logger.isDebugEnabled()) {
485 String.format("Created SAS authority '%s' with CSID=%s.", getSASAuthorityIdentifier(), newID);
487 } catch (Exception e) {
488 logger.info(String.format("Failed to create SAS authority '%s'.", getSASAuthorityIdentifier()));
492 @Test(dataProvider = "testName", dependsOnMethods = {"deleteLocalItemWithSync", "CRUDTests"})
493 public void createSASAuthorityWithRelations(String testName) {
495 // First check to see if the authority supports synchronization.
497 AuthorityClient client = (AuthorityClient) getClientInstance();
498 if (client.supportsSync() == false) {
499 return; // Exit the test since this authority doesn't support synchronization
505 // Create a new authority on the remote server
508 String newID = createResource(getSASClientInstance(), testName, getSASAuthorityWithRelationsIdentifier(), true);
509 knownSASAuthorityResourceWithRelationsId = newID;
510 knownSASAuthorityResourceWithRelationsShortId = getShortId(getSASClientInstance(), knownSASAuthorityResourceWithRelationsId);
511 } catch (Exception e) {
512 logger.info(String.format("Failed to create SAS authority with relations '%s'.", getSASAuthorityWithRelationsIdentifier()));
515 // Add three items to the remote authority
517 String continentShortId = "Continent" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
518 String continentCSID = createItemInAuthority(getSASClientInstance(), knownSASAuthorityResourceWithRelationsId, continentShortId);
519 this.allSASResourceItemIdsCreated.put(this.getUrnIdentifier(continentShortId), getUrnIdentifier(getSASAuthorityWithRelationsIdentifier()));
521 String countryShortId = "Country" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
522 String countryCSID = createItemInAuthority(getSASClientInstance(), knownSASAuthorityResourceWithRelationsId, countryShortId);
523 this.allSASResourceItemIdsCreated.put(this.getUrnIdentifier(countryShortId), getUrnIdentifier(getSASAuthorityWithRelationsIdentifier()));
525 String cityShortId = "City" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
526 String cityCSID = createItemInAuthority(getSASClientInstance(), knownSASAuthorityResourceWithRelationsId, cityShortId);
527 this.allSASResourceItemIdsCreated.put(this.getUrnIdentifier(cityShortId), getUrnIdentifier(getSASAuthorityWithRelationsIdentifier()));
529 // Create a set of hierarchical relationships between the items
531 ServiceDescription serviceDescription = client.getServiceDescription();
532 final String authorityItemDocumentType = serviceDescription == null ? "unknown" : serviceDescription.getSubresourceDocumentType();
534 RelationsCommon relationCommon = new RelationsCommon();
535 relationCommon.setSubjectCsid(countryCSID);
536 relationCommon.setSubjectDocumentType(authorityItemDocumentType);
537 relationCommon.setObjectCsid(continentCSID);
538 relationCommon.setObjectDocumentType(authorityItemDocumentType);
539 relationCommon.setRelationshipType(RelationshipType.HAS_BROADER.value());
540 relationCommon.setPredicateDisplayName(RelationshipType.HAS_BROADER.value());
542 RelationClient relationClient = new RelationClient(CollectionSpaceClient.SAS_CLIENT_PROPERTIES_FILENAME); // Get a Relation service client to the SAS
543 PoxPayloadOut payloadOut = relationClient.createRequestTypeInstance(relationCommon);
544 Response res = relationClient.create(payloadOut);
545 if (res.getStatus() != HttpStatus.SC_CREATED) {
546 logger.error("Could not create Relationship.");
552 * SAS - Create an item in the SAS authority on the SAS server.
555 @Test(dataProvider = "testName", dependsOnMethods = {"createSASAuthority", "CRUDTests"})
556 public void createSASItemList(String testName) {
558 // First check to see if the authority supports synchronization.
560 AuthorityClient client = (AuthorityClient) this.getClientInstance();
561 if (client.supportsSync() == false) {
562 return; // Exit the test since this authority doesn't support synchronization
568 for (int i = 0; i < SAS_ITEMLIST_SIZE; i++) {
569 String shortId = "SassyActor" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
570 String newID = createItemInAuthority(getSASClientInstance(), knownSASAuthorityResourceId, shortId);
572 // Store the ID returned from the first item resource created
573 // for additional tests below.
574 if (knownSASItemResourceId == null) {
575 knownSASItemResourceId = newID;
576 if (null != testName && logger.isDebugEnabled()) {
577 logger.debug(testName + ": knownSASItemResourceId=" + knownSASItemResourceId);
581 knownSASItemIdentifiersList.add(shortId);
584 // Keep track of the SAS authority items we create, so we can delete them from
585 // the *local* authority after we perform a sync operation. We need to keep track
586 // of the URN (not the CSID) since the CSIDs will differ on the SAS vs local.
588 this.allSASResourceItemIdsCreated.put(this.getUrnIdentifier(shortId), getUrnIdentifier(knownSASAuthorityResourceShortId));
593 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
594 dependsOnMethods = {"createItem"})
595 public void createItemList(String testName) throws Exception {
596 knownAuthorityWithItems = createResource(testName, READITEMS_SHORT_IDENTIFIER);
597 knownAuthorityWithItemsIdentifier = getShortId(knownAuthorityWithItems);
598 for (int j = 0; j < nItemsToCreateInList; j++) {
599 createItemInAuthority((AuthorityClient) getClientInstance(), knownAuthorityWithItems, this.getTestAuthorityItemShortId(true));
603 private String getShortId(AuthorityClient client, String authorityCsid) throws Exception {
604 String result = null;
606 // Submit the request to the service and store the response.
607 Response res = client.read(authorityCsid);
609 int statusCode = res.getStatus();
610 result = this.extractAuthorityShortId(res);
618 private String getShortId(String authorityCsid) throws Exception {
619 AuthorityClient client = (AuthorityClient) getClientInstance();
620 return getShortId(client, authorityCsid);
626 * @param testName the test name
627 * @throws Exception the exception
629 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
630 dependsOnMethods = {"CRUDTests"})
631 public void readByName(String testName) throws Exception {
635 // Submit the request to the service and store the response.
636 AuthorityClient client = (AuthorityClient) this.getClientInstance();
637 Response res = client.readByName(getKnowResourceIdentifier());
639 int statusCode = res.getStatus();
641 // Check the status code of the response: does it match
642 // the expected response(s)?
643 if (logger.isDebugEnabled()) {
644 logger.debug(testName + ": status = " + statusCode);
646 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
647 invalidStatusCodeMessage(testRequestType, statusCode));
648 Assert.assertEquals(statusCode, testExpectedStatusCode);
650 AUTHORITY_COMMON_TYPE commonPart = extractCommonPartValue(res);
651 Assert.assertNotNull(commonPart);
658 * Extracts the common part item from a service's item payload.
664 public AUTHORITY_ITEM_TYPE extractItemCommonPartValue(Response res) throws Exception {
665 AUTHORITY_ITEM_TYPE result = null;
667 AuthorityClient client = (AuthorityClient) getClientInstance();
668 PayloadInputPart payloadInputPart = extractPart(res, client.getItemCommonPartName());
669 if (payloadInputPart != null) {
670 result = (AUTHORITY_ITEM_TYPE) payloadInputPart.getBody();
672 Assert.assertNotNull(result,
673 "Part or body of part " + client.getCommonPartName() + " was unexpectedly null.");
680 * Extracts the short ID from a service request payload
686 protected String extractAuthorityShortId(Response res) throws Exception {
687 String result = null;
689 PoxPayloadIn input = new PoxPayloadIn((String)res.readEntity(getEntityResponseType()));
690 Document document = input.getDOMDocument();
691 result = XmlTools.getElementValue(document, "//" + AuthorityClient.SHORT_IDENTIFIER);
697 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
698 dependsOnMethods = {"readItem"})
699 public void readItemNonExistent(String testName) {
701 setupReadNonExistent();
703 // Submit the request to the service and store the response.
704 AuthorityClient client = (AuthorityClient) getClientInstance();
705 Response res = client.readItem(knownResourceId, NON_EXISTENT_ID);
707 int statusCode = res.getStatus();
709 // Check the status code of the response: does it match
710 // the expected response(s)?
711 if (logger.isDebugEnabled()) {
712 logger.debug(testName + ": status = " + statusCode);
714 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
715 invalidStatusCodeMessage(testRequestType, statusCode));
716 Assert.assertEquals(statusCode, testExpectedStatusCode);
722 @Test(dataProvider = "testName",
723 dependsOnMethods = {"createItem"})
724 public void readItem(String testName) throws Exception {
728 // Submit the request to the service and store the response.
729 AuthorityClient client = (AuthorityClient) getClientInstance();
730 Response res = client.readItem(knownResourceId, knownItemResourceId);
732 int statusCode = res.getStatus();
734 // Check the status code of the response: does it match
735 // the expected response(s)?
736 if (logger.isDebugEnabled()) {
737 logger.debug(testName + ": status = " + statusCode);
739 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
740 invalidStatusCodeMessage(testRequestType, statusCode));
741 Assert.assertEquals(statusCode, testExpectedStatusCode);
743 AUTHORITY_ITEM_TYPE itemCommonPart = extractItemCommonPartValue(res);
744 Assert.assertNotNull(itemCommonPart);
745 Assert.assertEquals(client.getInAuthority(itemCommonPart), knownResourceId);
746 verifyReadItemInstance(itemCommonPart);
752 protected abstract void verifyReadItemInstance(AUTHORITY_ITEM_TYPE item) throws Exception;
754 @Test(dataProvider = "testName",
755 dependsOnMethods = {"testItemSubmitRequest", "updateItem", "verifyIgnoredUpdateWithInAuthority"})
756 public void deleteItem(String testName) throws Exception {
760 // Submit the request to the service and store the response.
761 AuthorityClient client = (AuthorityClient) getClientInstance();
762 Response res = client.deleteItem(knownResourceId, knownItemResourceId);
765 statusCode = res.getStatus();
770 // Check the status code of the response: does it match
771 // the expected response(s)?
772 if (logger.isDebugEnabled()) {
773 logger.debug("delete: status = " + statusCode);
775 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
776 invalidStatusCodeMessage(testRequestType, statusCode));
777 Assert.assertEquals(statusCode, testExpectedStatusCode);
780 protected void readItemListInt(String vcsid, String shortId, String testName) {
784 // Submit the request to the service and store the response.
785 AuthorityClient client = (AuthorityClient) getClientInstance();
788 res = client.readItemList(vcsid, null, null);
789 } else if (shortId != null) {
790 res = client.readItemListForNamedAuthority(shortId, null, null);
792 Assert.fail("Internal Error: readItemList both vcsid and shortId are null!");
795 int statusCode = res.getStatus();
797 // Check the status code of the response: does it match
798 // the expected response(s)?
799 if (logger.isDebugEnabled()) {
800 logger.debug(" " + testName + ": status = " + statusCode);
802 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
803 invalidStatusCodeMessage(testRequestType, statusCode));
804 Assert.assertEquals(statusCode, testExpectedStatusCode);
806 AbstractCommonList list = res.readEntity(AbstractCommonList.class);
807 List<AbstractCommonList.ListItem> items = list.getListItem();
808 int nItemsReturned = items.size();
809 long nItemsTotal = list.getTotalItems();
810 if (logger.isDebugEnabled()) {
811 logger.debug(" " + testName + ": Expected "
812 + nItemsToCreateInList + " items; got: " + nItemsReturned + " of: " + nItemsTotal);
814 Assert.assertEquals(nItemsTotal, nItemsToCreateInList);
816 for (AbstractCommonList.ListItem item : items) {
817 String refName = AbstractCommonListUtils.ListItemGetElementValue(
818 item, AuthorityClient.REF_NAME);
819 Assert.assertTrue((refName != null), "Item refName is null or not set in the item list!");
820 String termDisplayName = AbstractCommonListUtils.ListItemGetElementValue(item,
821 AuthorityClient.TERM_DISPLAY_NAME);
822 String vocabDisplayName = AbstractCommonListUtils.ListItemGetElementValue(item,
823 AuthorityClient.VOCAB_DISPLAY_NAME);
824 // One of these names needs to be set.
825 Assert.assertTrue(!(termDisplayName == null && vocabDisplayName == null), "The item's display name is null or not set in the item list!");
828 if(logger.isTraceEnabled()){
829 AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName);
836 @Test(dataProvider = "testName", dependsOnMethods = {"createItemList"})
837 public void readItemList(String testName) {
838 readItemListInt(knownAuthorityWithItems, null, testName);
841 @Test(dataProvider = "testName", dependsOnMethods = {"readItemList"})
842 public void readItemListByName(String testName) {
843 readItemListInt(null, knownAuthorityWithItemsIdentifier, testName);
846 @Test(dataProvider = "testName",
847 dependsOnMethods = {"deleteItem"})
848 public void deleteNonExistentItem(String testName) {
850 setupDeleteNonExistent();
852 // Submit the request to the service and store the response.
853 AuthorityClient client = (AuthorityClient) getClientInstance();
854 Response res = client.deleteItem(knownResourceId, NON_EXISTENT_ID);
857 statusCode = res.getStatus();
862 // Check the status code of the response: does it match
863 // the expected response(s)?
864 if (logger.isDebugEnabled()) {
865 logger.debug(testName + ": status = " + statusCode);
867 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
868 invalidStatusCodeMessage(testRequestType, statusCode));
869 Assert.assertEquals(statusCode, testExpectedStatusCode);
872 protected String getServicePathItemsComponent() {
873 return AuthorityClient.ITEMS;
876 public PoxPayloadOut createItemRequestTypeInstance(AUTHORITY_ITEM_TYPE itemTypeInstance) {
877 PoxPayloadOut result = null;
879 AuthorityClient client = (AuthorityClient) getClientInstance();
880 PoxPayloadOut payloadOut = new PoxPayloadOut(this.getServicePathItemsComponent());
881 PayloadOutputPart part = payloadOut.addPart(client.getItemCommonPartName(), itemTypeInstance);
888 * Update an Authority item.
893 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
894 dependsOnMethods = {"readItem", "CRUDTests", "verifyIgnoredUpdateWithInAuthority"})
895 public void updateItem(String testName) throws Exception {
898 AUTHORITY_ITEM_TYPE theUpdate = null;
900 // Retrieve the contents of a resource to update.
901 AuthorityClient client = (AuthorityClient)this.getClientInstance();
902 Response res = client.readItem(knownResourceId, knownItemResourceId);
904 if (logger.isDebugEnabled()) {
905 logger.debug(testName + ": read status = " + res.getStatus());
907 Assert.assertEquals(res.getStatus(), testExpectedStatusCode);
909 if (logger.isDebugEnabled()) {
910 logger.debug("got Authority item to update with ID: "
911 + knownItemResourceId
912 + " in authority: " + knownResourceId);
914 AUTHORITY_ITEM_TYPE authorityItem = extractItemCommonPartValue(res);
915 Assert.assertNotNull(authorityItem);
917 // Update the contents of this resource.
918 theUpdate = updateItemInstance(authorityItem);
919 if (logger.isDebugEnabled()) {
920 logger.debug("\n\nTo be updated fields: CSID = " + knownItemResourceId + "\n"
921 + objectAsXmlString(theUpdate));
927 // Submit the updated resource to the service and store the response.
928 PoxPayloadOut output = this.createItemRequestTypeInstance(theUpdate);
929 res = client.updateItem(knownResourceId, knownItemResourceId, output);
931 int statusCode = res.getStatus();
933 // Check the status code of the response: does it match the expected response(s)?
934 if (logger.isDebugEnabled()) {
935 logger.debug("updateItem: status = " + statusCode);
937 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
938 invalidStatusCodeMessage(testRequestType, statusCode));
939 Assert.assertEquals(statusCode, testExpectedStatusCode);
941 // Retrieve the updated resource and verify that its contents exist.
942 AUTHORITY_ITEM_TYPE updatedVocabularyItem = extractItemCommonPartValue(res);
943 Assert.assertNotNull(updatedVocabularyItem);
945 compareUpdatedItemInstances(theUpdate, updatedVocabularyItem);
951 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
952 dependsOnMethods = {"updateLocalItemWithSync", "CRUDTests"})
953 public void deleteLocalItemWithSync(String testName) throws Exception {
954 final int itemIndexToDelete = 1;
956 // First check to see if we support sync.
958 AuthorityClient client = (AuthorityClient) getClientInstance();
959 if (client.supportsSync() == false) {
960 return; // Exit the test since this authority doesn't support synchronization
963 // Perform test setup for a DELETE.
965 AUTHORITY_ITEM_TYPE theUpdate = null;
967 // Delete an item from the SAS server
968 AuthorityClient sasClient = (AuthorityClient) this.getSASClientInstance();
969 Response res = sasClient.deleteNamedItemInNamedAuthority(knownSASAuthorityResourceShortId, knownSASItemIdentifiersList.get(itemIndexToDelete));
971 Assert.assertEquals(res.getStatus(), testExpectedStatusCode);
976 // Synchronize the local item's parent authority and verify the delete we just made
977 // to the SAS takes place locally after the sync -i.e., the local item should be deleted as well.
979 AuthorityClient localClient = (AuthorityClient) this.getClientInstance();
980 Response response = localClient.syncByName(knownSASAuthorityResourceShortId); // Notice we're using the Short ID (short ID is the same on the local and SAS)
982 int statusCode = response.getStatus();
983 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), invalidStatusCodeMessage(testRequestType, statusCode));
984 Assert.assertEquals(statusCode, testExpectedStatusCode);
989 // Verify that the local item has been deleted.
990 setupReadNonExistent();
991 res = localClient.readNamedItemInNamedAuthority(knownSASAuthorityResourceShortId, knownSASItemIdentifiersList.get(itemIndexToDelete));
993 Assert.assertEquals(res.getStatus(), testExpectedStatusCode);
994 knownSASItemIdentifiersList.remove(0); // remove it from our known set now that we've deleted it
1001 * We create a new item on the SAS, perform a sync with the local authority, and verify the local authority contains a copy
1004 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
1005 dependsOnMethods = {"veryifySyncWithSAS", "CRUDTests"})
1006 public void updateLocalItemWithSync(String testName) throws Exception {
1008 // First check to see if we support sync.
1010 AuthorityClient client = (AuthorityClient) getClientInstance();
1011 if (client.supportsSync() == false) {
1012 return; // Exit the test since this authority doesn't support synchronization
1017 AUTHORITY_ITEM_TYPE theUpdate = null;
1019 // Retrieve the contents of a shared authority item that we're going to update.
1020 AUTHORITY_ITEM_TYPE sasAuthorityItem = null;
1021 AuthorityClient sasClient = (AuthorityClient) this.getSASClientInstance();
1022 Response res = sasClient.readNamedItemInNamedAuthority(knownSASAuthorityResourceShortId, knownSASItemIdentifiersList.get(0));
1024 if (logger.isDebugEnabled()) {
1025 logger.debug(testName + ": read status = " + res.getStatus());
1027 Assert.assertEquals(res.getStatus(), testExpectedStatusCode);
1029 sasAuthorityItem = extractItemCommonPartValue(res); // This is a SAS authority item
1030 Assert.assertNotNull(sasAuthorityItem);
1035 // Update the contents of this authority item so we can post an UPDATE to the server
1036 theUpdate = updateItemInstance(sasAuthorityItem);
1038 // Submit the updated authority item and check the response.
1039 PoxPayloadOut output = this.createItemRequestTypeInstance(theUpdate);
1040 res = sasClient.updateNamedItemInNamedAuthority(knownSASAuthorityResourceShortId, knownSASItemIdentifiersList.get(0), output);
1041 AUTHORITY_ITEM_TYPE updatedSASAuthorityItem = null;
1043 int statusCode = res.getStatus();
1045 // Check the status code of the response: does it match the expected response(s)?
1046 if (logger.isDebugEnabled()) {
1047 logger.debug("updateItem: status = " + statusCode);
1049 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
1050 invalidStatusCodeMessage(testRequestType, statusCode));
1051 Assert.assertEquals(statusCode, testExpectedStatusCode);
1053 // Retrieve the updated authority item and verify that its contents exist.
1054 updatedSASAuthorityItem = extractItemCommonPartValue(res);
1055 Assert.assertNotNull(updatedSASAuthorityItem);
1057 compareUpdatedItemInstances(theUpdate, updatedSASAuthorityItem);
1062 // Synchronize the local item's parent authority and verify the update we just made
1063 // to the SAS item appears locally after the sync
1065 AuthorityClient localClient = (AuthorityClient) this.getClientInstance();
1066 Response response = localClient.syncByName(knownSASAuthorityResourceShortId); // Notice we're using the Short ID (short ID is the same on the local and SAS)
1068 int statusCode = response.getStatus();
1069 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), invalidStatusCodeMessage(testRequestType, statusCode));
1070 Assert.assertEquals(statusCode, testExpectedStatusCode);
1076 res = localClient.readNamedItemInNamedAuthority(knownSASAuthorityResourceShortId, knownSASItemIdentifiersList.get(0));
1078 Assert.assertEquals(res.getStatus(), testExpectedStatusCode);
1079 AUTHORITY_ITEM_TYPE syncedAuthorityItem = extractItemCommonPartValue(res);
1080 Assert.assertNotNull(syncedAuthorityItem);
1081 compareUpdatedItemInstances(syncedAuthorityItem, updatedSASAuthorityItem);
1087 protected abstract PoxPayloadOut createNonExistenceItemInstance(String commonPartName, String identifier);
1090 * @see org.collectionspace.services.client.test.ServiceTest#updateNonExistent(java.lang.String)
1092 @Test(dataProvider = "testName",
1093 dependsOnMethods = {"create", "update", "updateNonExistent"})
1094 public void updateNonExistentItem(String testName) throws Exception {
1096 setupUpdateNonExistent();
1098 // Submit the request to the service and store the response.
1099 // Note: The ID used in this 'create' call may be arbitrary.
1100 // The only relevant ID may be the one used in update(), below.
1101 AuthorityClient client = (AuthorityClient)this.getClientInstance();
1102 PoxPayloadOut multipart = createNonExistenceItemInstance(client.getItemCommonPartName(), NON_EXISTENT_ID);
1103 Response res = client.updateItem(knownResourceId, NON_EXISTENT_ID, multipart);
1105 int statusCode = res.getStatus();
1107 // Check the status code of the response: does it match
1108 // the expected response(s)?
1109 if (logger.isDebugEnabled()) {
1110 logger.debug(testName + ": status = " + statusCode);
1112 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
1113 invalidStatusCodeMessage(testRequestType, statusCode));
1114 Assert.assertEquals(statusCode, testExpectedStatusCode);
1121 // Methods to persuade TestNG to follow the correct test dependency path
1124 @Test(dataProvider = "testName",
1125 dependsOnMethods = {"createItem"})
1126 public void baseAuthorityTests(String testName) {
1127 // Do nothing. Here just to setup a test dependency chain.
1131 * For convenience and terseness, this test method is the base of the test execution dependency chain. Other test methods may
1132 * refer to this method in their @Test annotation declarations.
1135 @Test(dataProvider = "testName",
1136 dependsOnMethods = {
1137 "org.collectionspace.services.client.test.AbstractServiceTestImpl.baseCRUDTests"})
1138 public void CRUDTests(String testName) {
1139 // TODO Auto-generated method stub
1143 public void cleanUp() {
1144 String noTest = System.getProperty("noTestCleanup");
1145 if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
1146 if (logger.isDebugEnabled()) {
1147 logger.debug("Skipping Cleanup phase ...");
1152 AuthorityClient client = (AuthorityClient) this.getClientInstance();
1153 String parentResourceId;
1154 String itemResourceId;
1156 // Clean up all authority item resources.
1158 for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
1159 itemResourceId = entry.getKey();
1160 parentResourceId = entry.getValue();
1161 Response response = client.deleteItem(parentResourceId, itemResourceId);
1163 int status = response.getStatus();
1164 if (status != Response.Status.OK.getStatusCode()) {
1165 logger.debug(String.format("Could not deleted authority item '%s' in authority '%s'.",
1166 itemResourceId, parentResourceId));
1173 // Clean up authority items that were the result of a sync with the SAS
1174 // all the IDs are URN (not CSIDs). The URNs work for the local items as well
1175 // as the SAS items.
1177 for (Map.Entry<String, String> entry : allSASResourceItemIdsCreated.entrySet()) {
1178 itemResourceId = entry.getKey();
1179 parentResourceId = entry.getValue();
1180 // Note: Any non-success responses from the delete operation
1181 // below are ignored and not reported.
1182 client.deleteItem(parentResourceId, itemResourceId).close();
1185 // Clean up authority items on the SAS using the SAS client.
1187 client = (AuthorityClient) this.getSASClientInstance();
1188 for (Map.Entry<String, String> entry : allSASResourceItemIdsCreated.entrySet()) {
1189 itemResourceId = entry.getKey();
1190 parentResourceId = entry.getValue();
1191 client.deleteItem(parentResourceId, itemResourceId).close();
1194 // Finally, call out superclass's cleanUp method to deleted the local authorities
1198 // Call out superclass's cleanUp method to delete the SAS authorities
1200 super.cleanUp(client);
1203 protected String getTestAuthorityItemShortId() {
1204 return getTestAuthorityItemShortId(false);
1207 protected String getTestAuthorityItemShortId(boolean makeUnique) {
1208 String result = TEST_SHORTID;
1210 if (makeUnique == true) {
1211 result = result + System.currentTimeMillis() + Math.abs(random.nextInt());