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.text.Collator;
26 import java.util.ArrayList;
27 import java.util.Comparator;
28 import java.util.List;
29 import java.util.Locale;
30 import javax.ws.rs.core.MediaType;
31 import javax.ws.rs.core.Response;
33 import org.collectionspace.services.MovementJAXBSchema;
34 import org.collectionspace.services.client.CollectionSpaceClient;
35 import org.collectionspace.services.client.MovementClient;
36 import org.collectionspace.services.movement.MovementsCommon;
37 import org.collectionspace.services.movement.MovementsCommonList;
38 import org.collectionspace.services.jaxb.AbstractCommonList;
40 import org.jboss.resteasy.client.ClientResponse;
41 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
42 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
43 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
45 import org.testng.Assert;
46 import org.testng.annotations.AfterClass;
47 import org.testng.annotations.DataProvider;
48 import org.testng.annotations.Test;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * MovementSortByTest, tests sorting of summary lists by fields
55 * of various datatypes.
57 * $LastChangedRevision: 2562 $
58 * $LastChangedDate: 2010-06-22 23:26:51 -0700 (Tue, 22 Jun 2010) $
60 public class MovementSortByTest extends BaseServiceTest {
62 private final String CLASS_NAME = MovementSortByTest.class.getName();
63 private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
65 // Instance variables specific to this test.
66 final String DELIMITER_SCHEMA_AND_FIELD = ":";
67 final String KEYWORD_DESCENDING_SEARCH = "DESC";
68 final String SERVICE_PATH_COMPONENT = "movements";
69 final String TEST_SPECIFIC_KEYWORD = "msotebstpfscn";
70 private List<String> movementIdsCreated = new ArrayList<String>();
73 * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
76 protected CollectionSpaceClient getClientInstance() {
77 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
81 * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
84 protected AbstractCommonList getAbstractCommonList(
85 ClientResponse<AbstractCommonList> response) {
86 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
89 // ---------------------------------------------------------------
91 // ---------------------------------------------------------------
96 * Tests whether a list of records, sorted by a String field in
97 * ascending order, is returned in the expected order.
99 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
100 dependsOnMethods = {"createList"})
101 public void sortByStringFieldAscending(String testName) throws Exception {
103 if (logger.isDebugEnabled()) {
104 logger.debug(testBanner(testName, CLASS_NAME));
107 String sortFieldName = qualifySortFieldName(MovementJAXBSchema.MOVEMENT_NOTE);
108 if (logger.isDebugEnabled()) {
109 logger.debug("Sorting on field name=" + sortFieldName);
111 MovementsCommonList list = readSortedList(sortFieldName);
112 List<MovementsCommonList.MovementListItem> items =
113 list.getMovementListItem();
115 String[] values = new String[100];
116 Collator usEnglishCollator = Collator.getInstance(Locale.US);
118 for (MovementsCommonList.MovementListItem item : items) {
119 // Because movementNote is not currently a summary field
120 // (returned in summary list items), we will need to verify
121 // sort order by retrieving full records, using the
122 // IDs provided in the summary list items. amd then retriving
123 // the value of that field from each of those records.
124 MovementsCommon movement = read(item.getCsid());
125 values[i] = movement.getMovementNote();
126 if (logger.isDebugEnabled()) {
127 logger.debug("list-item[" + i + "] movementNote=" + values[i]);
129 // Verify that the value of the specified field in the current record
130 // is equal to or greater than its value in the previous record,
131 // using a locale-specific collator.
133 // (Note: when used with certain text, this test case could potentially
134 // reflect inconsistencies, if any, between Java's collator and the
135 // collator used for ordering by the database. To help avoid this,
136 // it might be useful to keep test strings fairly generic.)
138 Assert.assertTrue(usEnglishCollator.compare(values[i], values[i - 1]) >= 0);
146 * Tests whether a list of records, obtained by a keyword search, and
147 * sorted by a String field in ascending order, is returned in the expected order.
149 * This verifies that summary list results from keyword searches, in
150 * addition to 'read list' requests, can be returned in sorted order.
152 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
153 dependsOnMethods = {"createList"})
154 public void sortKeywordSearchResultsByStringFieldAscending(String testName) throws Exception {
156 if (logger.isDebugEnabled()) {
157 logger.debug(testBanner(testName, CLASS_NAME));
160 String sortFieldName = qualifySortFieldName(MovementJAXBSchema.MOVEMENT_NOTE);
161 if (logger.isDebugEnabled()) {
162 logger.debug("Sorting on field name=" + sortFieldName);
164 MovementsCommonList list = keywordSearchSortedBy(TEST_SPECIFIC_KEYWORD, sortFieldName);
165 List<MovementsCommonList.MovementListItem> items =
166 list.getMovementListItem();
168 String[] values = new String[100];
169 Collator usEnglishCollator = Collator.getInstance(Locale.US);
171 for (MovementsCommonList.MovementListItem item : items) {
172 // Because movementNote is not currently a summary field
173 // (returned in summary list items), we will need to verify
174 // sort order by retrieving full records, using the
175 // IDs provided in the summary list items. amd then retriving
176 // the value of that field from each of those records.
177 MovementsCommon movement = read(item.getCsid());
178 values[i] = movement.getMovementNote();
179 if (logger.isDebugEnabled()) {
180 logger.debug("list-item[" + i + "] movementNote=" + values[i]);
182 // Verify that the value of the specified field in the current record
183 // is equal to or greater than its value in the previous record,
184 // using a locale-specific collator.
186 // (Note: when used with certain text, this test case could potentially
187 // reflect inconsistencies, if any, between Java's collator and the
188 // collator used for ordering by the database. To help avoid this,
189 // it might be useful to keep test strings fairly generic.)
191 Assert.assertTrue(usEnglishCollator.compare(values[i], values[i - 1]) >= 0);
199 * Tests whether a list of records, sorted by a String field in
200 * descending order, is returned in the expected order.
202 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
203 dependsOnMethods = {"createList"})
204 public void sortByStringFieldDescending(String testName) throws Exception {
206 if (logger.isDebugEnabled()) {
207 logger.debug(testBanner(testName, CLASS_NAME));
210 String sortFieldName =
211 asDescendingSort(qualifySortFieldName(MovementJAXBSchema.MOVEMENT_NOTE));
212 if (logger.isDebugEnabled()) {
213 logger.debug("Sorting on field name=" + sortFieldName);
215 MovementsCommonList list = readSortedList(sortFieldName);
216 List<MovementsCommonList.MovementListItem> items =
217 list.getMovementListItem();
219 String[] values = new String[100];
220 Collator usEnglishCollator = Collator.getInstance(Locale.US);
222 for (MovementsCommonList.MovementListItem item : items) {
223 // Because movementNote is not currently a summary field
224 // (returned in summary list items), we will need to verify
225 // sort order by retrieving full records, using the
226 // IDs provided in the summary list items. amd then retriving
227 // the value of that field from each of those records.
228 MovementsCommon movement = read(item.getCsid());
229 values[i] = movement.getMovementNote();
230 if (logger.isDebugEnabled()) {
231 logger.debug("list-item[" + i + "] movementNote=" + values[i]);
233 // Verify that the value of the specified field in the current record
234 // is less than or equal to than its value in the previous record,
235 // using a locale-specific collator.
237 // (Note: when used with certain text, this test case could potentially
238 // reflect inconsistencies, if any, between Java's collator and the
239 // collator used for ordering by the database. To help avoid this,
240 // it might be useful to keep test strings fairly generic.)
242 Assert.assertTrue(usEnglishCollator.compare(values[i], values[i - 1]) <= 0);
250 * Tests whether a list of records, sorted by a dateTime field in
251 * ascending order, is returned in the expected order.
253 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
254 dependsOnMethods = {"createList"})
255 public void sortByDateTimeFieldAscending(String testName) throws Exception {
257 if (logger.isDebugEnabled()) {
258 logger.debug(testBanner(testName, CLASS_NAME));
261 String sortFieldName = qualifySortFieldName(MovementJAXBSchema.LOCATION_DATE);
262 if (logger.isDebugEnabled()) {
263 logger.debug("Sorting on field name=" + sortFieldName);
265 MovementsCommonList list = readSortedList(sortFieldName);
266 List<MovementsCommonList.MovementListItem> items =
267 list.getMovementListItem();
269 String[] values = new String[100];
270 Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
272 for (MovementsCommonList.MovementListItem item : items) {
273 values[i] = item.getLocationDate();
274 if (logger.isDebugEnabled()) {
275 logger.debug("list-item[" + i + "] locationDate=" + values[i]);
277 // Verify that the value of the specified field in the current record
278 // is equal to or greater than its value in the previous record.
280 Assert.assertTrue(comparator.compare(values[i], values[i - 1]) >= 0);
287 * Tests whether a list of records, sorted by a dateTime field in
288 * descending order, is returned in the expected order.
290 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
291 dependsOnMethods = {"createList"})
292 public void sortByDateTimeFieldDescending(String testName) throws Exception {
294 if (logger.isDebugEnabled()) {
295 logger.debug(testBanner(testName, CLASS_NAME));
298 String sortFieldName =
299 asDescendingSort(qualifySortFieldName(MovementJAXBSchema.LOCATION_DATE));
300 if (logger.isDebugEnabled()) {
301 logger.debug("Sorting on field name=" + sortFieldName);
303 MovementsCommonList list = readSortedList(sortFieldName);
304 List<MovementsCommonList.MovementListItem> items =
305 list.getMovementListItem();
307 String[] values = new String[100];
308 Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
310 for (MovementsCommonList.MovementListItem item : items) {
311 values[i] = item.getLocationDate();
312 if (logger.isDebugEnabled()) {
313 logger.debug("list-item[" + i + "] locationDate=" + values[i]);
315 // Verify that the value of the specified field in the current record
316 // is less than or equal to its value in the previous record.
318 Assert.assertTrue(comparator.compare(values[i], values[i - 1]) <= 1);
325 * Tests whether a request to sort by an empty field name is handled
326 * as expected: the query parameter is simply ignored, and a list
327 * of records is returned, unsorted, with a success result.
329 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
330 public void sortWithEmptySortFieldName(String testName) throws Exception {
332 if (logger.isDebugEnabled()) {
333 logger.debug(testBanner(testName, CLASS_NAME));
335 testSetup(STATUS_OK, ServiceRequestType.READ);
337 // Submit the request to the service and store the response.
338 MovementClient client = new MovementClient();
339 final String EMPTY_SORT_FIELD_NAME = "";
340 ClientResponse<MovementsCommonList> res =
341 client.readListSortedBy(EMPTY_SORT_FIELD_NAME);
342 int statusCode = res.getStatus();
344 // Check the status code of the response: does it match
345 // the expected response(s)?
346 if (logger.isDebugEnabled()) {
347 logger.debug(testName + ": status = " + statusCode);
349 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
350 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
351 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
358 * Tests whether a request to sort by an unqualified field name is
359 * handled as expected. The field name provided in this test is valid,
360 * but has not been qualified by being prefixed by a schema name and delimiter.
362 @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
363 public void sortWithUnqualifiedFieldName(String testName) throws Exception {
365 if (logger.isDebugEnabled()) {
366 logger.debug(testBanner(testName, CLASS_NAME));
368 // FIXME: Ultimately, this should return a BAD_REQUEST status.
369 testSetup(STATUS_INTERNAL_SERVER_ERROR, ServiceRequestType.READ);
371 // Submit the request to the service and store the response.
372 MovementClient client = new MovementClient();
373 ClientResponse<MovementsCommonList> res =
374 client.readListSortedBy(MovementJAXBSchema.LOCATION_DATE);
375 int statusCode = res.getStatus();
377 // Check the status code of the response: does it match
378 // the expected response(s)?
379 if (logger.isDebugEnabled()) {
380 logger.debug(testName + ": status = " + statusCode);
382 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
383 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
384 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
389 * Tests whether a request to sort by a malformed field name is
390 * handled as expected.
393 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
394 public void sortWithMalformedFieldName(String testName) throws Exception {
396 // FIXME: Implement this stub method.
398 // FIXME: Consider splitting this test into various tests, with
399 // different malformed field name formats that might confuse parsers
400 // and/or validation code.
402 // FIXME: Consider fixing DocumentFilter.setSortOrder() to return
403 // an error response to this test case, then revise this test case
404 // to expect that response.
409 // ---------------------------------------------------------------
410 // Cleanup of resources created during testing
411 // ---------------------------------------------------------------
413 * Deletes all resources created by tests, after all tests have been run.
415 * This cleanup method will always be run, even if one or more tests fail.
416 * For this reason, it attempts to remove all resources created
417 * at any point during testing, even if some of those resources
418 * may be expected to be deleted by certain tests.
420 @AfterClass(alwaysRun = true)
421 public void cleanUp() {
422 String noTest = System.getProperty("noTestCleanup");
423 if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
424 if (logger.isDebugEnabled()) {
425 logger.debug("Skipping Cleanup phase ...");
429 if (logger.isDebugEnabled()) {
430 logger.debug("Cleaning up temporary resources created for testing ...");
432 // Delete all Movement resource(s) created during this test.
433 MovementClient movementClient = new MovementClient();
434 for (String resourceId : movementIdsCreated) {
435 // Note: Any non-success responses are ignored and not reported.
436 movementClient.delete(resourceId);
440 // ---------------------------------------------------------------
441 // Utility methods used by tests above
442 // ---------------------------------------------------------------
445 public String getServicePathComponent() {
446 return SERVICE_PATH_COMPONENT;
449 private String getCommonSchemaName() {
450 // FIXME: While this convention - appending a suffix to the name of
451 // the service's first unique URL path component - works, it would
452 // be preferable to get the common schema name from configuration.
453 return getServicePathComponent() + "_" + "common";
456 public String qualifySortFieldName(String fieldName) {
457 return getCommonSchemaName() + DELIMITER_SCHEMA_AND_FIELD + fieldName;
460 public String asDescendingSort(String qualifiedFieldName) {
461 return qualifiedFieldName + " " + KEYWORD_DESCENDING_SEARCH;
465 * A data provider that provides a set of unsorted values, which are
466 * to be used in populating (seeding) values in test records.
468 * Data elements provided for each test record consist of:
469 * * An integer, reflecting expected sort order.
470 * * US English text, to populate the value of a free text (String) field.
471 * * An ISO 8601 timestamp, to populate the value of a calendar date (dateTime) field.
473 @DataProvider(name = "unsortedValues")
474 public Object[][] unsortedValues() {
475 // Add a test record-specific string so we have the option of
476 // constraining tests to only test records, in list or search results.
477 final String TEST_RECORD_SPECIFIC_STRING = CLASS_NAME + " " + TEST_SPECIFIC_KEYWORD;
478 return new Object[][]{
479 {1, "Aardvark and plumeria. " + TEST_RECORD_SPECIFIC_STRING, "2009-01-29T00:00:05Z"},
480 {4, "Bat fling off wall. " + TEST_RECORD_SPECIFIC_STRING, "2010-08-30T00:00:00Z"},
481 {2, "Aardvarks and plumeria. " + TEST_RECORD_SPECIFIC_STRING, "2009-01-29T08:00:00Z"},
482 {5, "Zounds! " + TEST_RECORD_SPECIFIC_STRING, "2010-08-31T00:00:00Z"},
483 {3, "Bat flies off ball. " + TEST_RECORD_SPECIFIC_STRING, "2009-05-29T00:00:00Z"}
487 @Test(dataProvider = "unsortedValues")
488 public void createList(int expectedSortOrder, String movementNote,
489 String locationDate) throws Exception {
491 String testName = "createList";
492 if (logger.isDebugEnabled()) {
493 logger.debug(testBanner(testName, CLASS_NAME));
495 testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
497 // Create each unsorted record provided by the data provider.
498 create(movementNote, locationDate);
501 private void create(String movementNote, String locationDate) throws Exception {
503 String testName = "create";
504 testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
506 // Submit the request to the service and store the response.
507 MovementClient client = new MovementClient();
508 MultipartOutput multipart = createMovementInstance(createIdentifier(),
509 movementNote, locationDate);
510 ClientResponse<Response> res = client.create(multipart);
511 int statusCode = res.getStatus();
513 // Check the status code of the response: does it match
514 // the expected response(s)?
517 // Does it fall within the set of valid status codes?
518 // Does it exactly match the expected status code?
519 if (logger.isDebugEnabled()) {
520 logger.debug(testName + ": status = " + statusCode);
522 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
523 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
524 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
526 // Store the IDs from every resource created by tests,
527 // so they can be deleted after tests have been run.
528 movementIdsCreated.add(extractId(res));
531 private MovementsCommon read(String csid) throws Exception {
533 String testName = "read";
534 testSetup(STATUS_OK, ServiceRequestType.READ);
536 // Submit the request to the service and store the response.
537 MovementClient client = new MovementClient();
538 ClientResponse<MultipartInput> res = client.read(csid);
539 int statusCode = res.getStatus();
541 // Check the status code of the response: does it match
542 // the expected response(s)?
543 if (logger.isDebugEnabled()) {
544 logger.debug(testName + ": status = " + statusCode);
546 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
547 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
548 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
550 // Extract and return the common part of the record.
551 MultipartInput input = (MultipartInput) res.getEntity();
552 MovementsCommon movement = (MovementsCommon) extractPart(input,
553 client.getCommonPartName(), MovementsCommon.class);
558 private MultipartOutput createMovementInstance(
559 String movementReferenceNumber,
561 String locationDate) {
562 MovementsCommon movement = new MovementsCommon();
563 movement.setMovementReferenceNumber(movementReferenceNumber);
564 movement.setMovementNote(movementNote);
565 movement.setLocationDate(locationDate);
566 MultipartOutput multipart = new MultipartOutput();
567 OutputPart commonPart =
568 multipart.addPart(movement, MediaType.APPLICATION_XML_TYPE);
569 commonPart.getHeaders().add("label", new MovementClient().getCommonPartName());
571 if (logger.isDebugEnabled()) {
572 logger.debug("to be created, movement common");
573 logger.debug(objectAsXmlString(movement, MovementsCommon.class));
579 private MovementsCommonList readSortedList(String sortFieldName) throws Exception {
581 String testName = "readSortedList";
582 testSetup(STATUS_OK, ServiceRequestType.READ);
584 // Submit the request to the service and store the response.
585 MovementClient client = new MovementClient();
587 ClientResponse<MovementsCommonList> res =
588 client.readListSortedBy(sortFieldName);
589 MovementsCommonList list = res.getEntity();
590 int statusCode = res.getStatus();
592 // Check the status code of the response: does it match
593 // the expected response(s)?
594 if (logger.isDebugEnabled()) {
595 logger.debug(testName + ": status = " + statusCode);
597 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
598 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
599 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
605 private MovementsCommonList keywordSearchSortedBy(String keywords,
606 String sortFieldName) throws Exception {
608 String testName = "keywordSearchSortedBy";
609 testSetup(STATUS_OK, ServiceRequestType.READ);
611 // Submit the request to the service and store the response.
612 MovementClient client = new MovementClient();
614 ClientResponse<MovementsCommonList> res =
615 client.keywordSearchSortedBy(keywords, sortFieldName);
616 MovementsCommonList list = res.getEntity();
617 int statusCode = res.getStatus();
619 // Check the status code of the response: does it match
620 // the expected response(s)?
621 if (logger.isDebugEnabled()) {
622 logger.debug(testName + ": status = " + statusCode);
624 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
625 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
626 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);