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 (c)) 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;
29 import javax.ws.rs.core.Response;
31 import org.collectionspace.services.PersonJAXBSchema;
32 import org.collectionspace.services.client.CollectionSpaceClient;
33 import org.collectionspace.services.client.PersonAuthorityClient;
34 import org.collectionspace.services.client.PersonAuthorityClientUtils;
35 import org.collectionspace.services.jaxb.AbstractCommonList;
36 import org.collectionspace.services.person.PersonsCommonList;
38 import org.jboss.resteasy.client.ClientResponse;
39 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.testng.Assert;
43 import org.testng.annotations.AfterClass;
44 import org.testng.annotations.BeforeClass;
45 import org.testng.annotations.Test;
48 * VocabularyServiceTest, carries out tests against a
49 * deployed and running Vocabulary Service.
51 * $LastChangedRevision: 753 $
52 * $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed, 23 Sep 2009) $
54 public class PersonAuthorityServicePerfTest extends BaseServiceTest {
56 private final String CLASS_NAME = PersonAuthorityServicePerfTest.class.getName();
57 private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
59 // Instance variables specific to this test.
60 final String SERVICE_PATH_COMPONENT = "personauthorities";
61 final String ITEM_SERVICE_PATH_COMPONENT = "items";
62 private String authId = null;
63 private String authRefName = null;
64 private List<String> allItemIdsCreated = new ArrayList<String>();
65 private String[] firstNames = {
67 "George","Geoff","Georgia",
68 "John","Johanna","Jon",
69 "Patrick","Patty","Patrik"};
70 private String[] firstNameSuffixes = {
71 "1","2","3","4","5","6","7","8","9","0"};
72 private String[] lastNames = {
73 "Axis","Black","Cobbler",
74 "Dunne","England","France",
75 "Goldsmith","Hart","Indy",
76 "Jones","Kohn","Lark",
77 "Maven","Newhart","Overdunne",
78 "Plaxo","Queen","Roberts",
79 "Smith","Tate","Underdunne",
80 "Vicious","Waits","Xavier",
83 // Keep these two arrays in sync!!!
84 private String[] partialTerms = {"Ann","John","Patty2"};
85 private int[] nMatches = {
86 4*lastNames.length*firstNameSuffixes.length, // Johanna too!
87 lastNames.length*firstNameSuffixes.length,
89 private int shortTestLimit = 2; // Just use first three items in suffix and last name arrays
90 private int[] nMatchesShort = {
91 4*shortTestLimit*shortTestLimit, // Johanna too!
92 shortTestLimit*shortTestLimit,
94 private boolean runFullTest = false;
97 * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
100 protected CollectionSpaceClient getClientInstance() {
101 return new PersonAuthorityClient();
105 * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
108 protected AbstractCommonList getAbstractCommonList(
109 ClientResponse<AbstractCommonList> response) {
110 return response.getEntity(PersonsCommonList.class);
114 public void setup() {
117 } catch (Exception e) {
118 Assert.fail("Could not create new Authority for search tests.", e);
121 long startTime = System.currentTimeMillis();
123 long stopTime = System.currentTimeMillis();
124 double runTime = (stopTime - startTime)/1000.0;
125 logger.info("Created {} items in {} seconds.",
126 allItemIdsCreated.size(), runTime);
127 } catch (Exception e) {
128 Assert.fail("Could not create new item in Authority for search tests.", e);
132 // ---------------------------------------------------------------
133 // Utilities: setup routines for search tests
134 // ---------------------------------------------------------------
136 public void createAuthority() throws Exception {
138 String testName = "createAuthority";
141 int expectedStatusCode = Response.Status.CREATED.getStatusCode();
142 ServiceRequestType requestType = ServiceRequestType.CREATE;
143 testSetup(expectedStatusCode, requestType);
145 // Submit the request to the service and store the response.
146 PersonAuthorityClient client = new PersonAuthorityClient();
147 String shortId = "perfTestPersons";
148 String displayName = "Perf Test Person Auth";
149 String baseRefName = PersonAuthorityClientUtils.createPersonAuthRefName(shortId, null);
150 MultipartOutput multipart =
151 PersonAuthorityClientUtils.createPersonAuthorityInstance(
152 displayName, shortId, client.getCommonPartName());
155 ClientResponse<Response> res = client.create(multipart);
157 int statusCode = res.getStatus();
158 // Check the status code of the response: does it match
159 // the expected response(s)?
160 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
161 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
162 Assert.assertEquals(statusCode, this.EXPECTED_STATUS_CODE);
163 newID = PersonAuthorityClientUtils.extractId(res);
164 logger.info("{}: succeeded.", testName);
166 res.releaseConnection();
168 // Store the refname from the first resource created
169 // for additional tests below.
170 authRefName = baseRefName;
171 // Store the ID returned from the first resource created
172 // for additional tests below.
177 * Creates an item in the authority, used for partial term matching tests.
179 * @param authorityCsid The CSID of the Authority in which the term will be created.
180 * @param authRefName The refName of the Authority in which the term will be created.
182 private void createItem(String firstName, String lastName, PersonAuthorityClient client )
185 int expectedStatusCode = Response.Status.CREATED.getStatusCode();
186 ServiceRequestType requestType = ServiceRequestType.CREATE;
187 testSetup(expectedStatusCode, requestType);
190 client = new PersonAuthorityClient();
193 // Submit the request to the service and store the response.
194 Map<String, String> personMap = new HashMap<String,String>();
196 // Fill the property map
198 String shortId = firstName+lastName;
199 personMap.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId );
200 personMap.put(PersonJAXBSchema.DISPLAY_NAME_COMPUTED, "true");
201 personMap.put(PersonJAXBSchema.FORE_NAME, firstName);
202 personMap.put(PersonJAXBSchema.SUR_NAME, lastName);
203 Map<String, List<String>> personRepeatablesMap = new HashMap<String, List<String>>();
204 MultipartOutput multipart =
205 PersonAuthorityClientUtils.createPersonInstance(authId, authRefName,
206 personMap, personRepeatablesMap, client.getItemCommonPartName() );
209 ClientResponse<Response> res = client.createItem(authId, multipart);
211 int statusCode = res.getStatus();
212 // Check the status code of the response: does it match
213 // the expected response(s)?
214 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
215 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
216 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
218 newID = PersonAuthorityClientUtils.extractId(res);
220 res.releaseConnection();
223 // Store the IDs from any item resources created
224 // by tests, along with the IDs of their parents, so these items
225 // can be deleted after all tests have been run.
226 allItemIdsCreated.add(newID);
229 private void createItems()
231 PersonAuthorityClient client = new PersonAuthorityClient();
232 String fullTest = System.getProperty("runFullItemsTest");
233 runFullTest = Boolean.TRUE.toString().equalsIgnoreCase(fullTest);
234 int maxSuff = shortTestLimit;
235 int maxLN = shortTestLimit;
237 logger.debug("Creating full items set ...");
238 maxSuff = firstNameSuffixes.length;
239 maxLN = lastNames.length;
241 logger.debug("Creating short items set ...");
243 for(String fname:firstNames) {
244 for( int iSuff=0; iSuff<maxSuff; iSuff++ ) {
245 String fns = firstNameSuffixes[iSuff];
246 for( int iLN=0; iLN<maxLN; iLN++ ) {
247 String lname = lastNames[iLN];
248 createItem(fname+fns, lname, null);
252 logger.debug("createItems created {} items.", allItemIdsCreated.size());
256 * Reads an item list by partial term.
258 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
259 public void partialTermMatch(String testName) {
260 if (logger.isDebugEnabled()) {
261 logger.debug(testBanner(testName, CLASS_NAME));
263 for(int i=0; i<partialTerms.length; i++) {
264 long startTime = System.currentTimeMillis();
265 int numMatchesFound = readItemListWithFilters(testName, authId,
266 partialTerms[i], null);
267 Assert.assertEquals(numMatchesFound, (runFullTest?nMatches[i]:nMatchesShort[i]),
268 "Did not get expected number of partial term matches for "+partialTerms[i]);
269 long stopTime = System.currentTimeMillis();
270 double runTime = (stopTime - startTime)/1000.0;
271 if(logger.isInfoEnabled()){
272 logger.info("Got: "+numMatchesFound+
273 " matches for: \""+partialTerms[i]+"\" in "+
274 runTime+" seconds.");
280 * Reads an item list by partial term or keywords, given an authority and a term.
281 * Only one of partialTerm or keywords should be specified.
282 * If both are specified, keywords will be ignored.
284 * @param testName Calling test name
285 * @param authorityCsid The CSID of the authority within which partial term matching
287 * @param partialTerm A partial term to match item resources.
288 * @param partialTerm A keyword list to match item resources.
289 * @return The number of item resources matched by the partial term.
291 private int readItemListWithFilters(String testName,
292 String authorityCsid, String partialTerm, String keywords) {
295 int expectedStatusCode = Response.Status.OK.getStatusCode();
296 ServiceRequestType requestType = ServiceRequestType.READ_LIST;
297 testSetup(expectedStatusCode, requestType);
299 // Submit the request to the service and store the response.
300 PersonAuthorityClient client = new PersonAuthorityClient();
301 ClientResponse<PersonsCommonList> res = null;
302 if (authorityCsid != null) {
303 res = client.readItemList(authorityCsid, partialTerm, keywords);
305 Assert.fail(testName+" passed null csid!");
307 PersonsCommonList list = null;
309 int statusCode = res.getStatus();
310 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
311 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
312 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
314 list = res.getEntity();
316 res.releaseConnection();
319 List<PersonsCommonList.PersonListItem> items = list.getPersonListItem();
320 return (int)list.getTotalItems();
322 // ---------------------------------------------------------------
323 // Utility methods used by tests above
324 // ---------------------------------------------------------------
326 public String getServicePathComponent() {
327 return SERVICE_PATH_COMPONENT;
331 * Deletes all resources created by tests, after all tests have been run.
333 * This cleanup method will always be run, even if one or more tests fail.
334 * For this reason, it attempts to remove all resources created
335 * at any point during testing, even if some of those resources
336 * may be expected to be deleted by certain tests.
338 @AfterClass(alwaysRun=true)
339 public void cleanUp() {
340 String noTest = System.getProperty("noTestCleanup");
341 if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
342 if (logger.isDebugEnabled()) {
343 logger.debug("Skipping Cleanup phase ...");
347 // Note: Any non-success responses from the delete operations
348 // below are ignored and not reported.
349 PersonAuthorityClient client = new PersonAuthorityClient();
350 // Clean up item resources.
351 for (String itemId : allItemIdsCreated) {
352 client.deleteItem(authId, itemId).releaseConnection();
354 client.delete(authId).releaseConnection();