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.account.client.test;
25 import java.util.Collection;
26 import java.util.Hashtable;
27 import java.util.List;
28 import java.lang.UnsupportedOperationException;
30 import org.collectionspace.services.account.AccountsCommon;
31 import org.collectionspace.services.account.AccountsCommonList;
32 import org.collectionspace.services.account.AccountListItem;
33 import org.collectionspace.services.authorization.AccountRole;
34 import org.collectionspace.services.authorization.AccountValue;
35 import org.collectionspace.services.authorization.Role;
36 import org.collectionspace.services.authorization.RoleValue;
37 import org.collectionspace.services.client.AccountClient;
38 import org.collectionspace.services.client.AccountFactory;
39 import org.collectionspace.services.client.AccountRoleClient;
40 import org.collectionspace.services.client.AccountRoleFactory;
41 import org.collectionspace.services.client.CollectionSpaceClient;
42 import org.collectionspace.services.client.RoleClient;
43 import org.collectionspace.services.client.RoleFactory;
44 import org.collectionspace.services.client.test.AbstractServiceTestImpl;
45 import org.collectionspace.services.client.test.ServiceRequestType;
47 import javax.ws.rs.core.Response;
49 import org.jboss.resteasy.client.ClientResponse;
50 import org.testng.Assert;
51 import org.testng.annotations.Test;
52 import org.testng.annotations.AfterClass;
53 import org.testng.annotations.BeforeClass;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * AccountServiceTest, carries out tests against a
59 * deployed and running Account, Role and AccountRole Services.
61 * $LastChangedRevision: 917 $
62 * $LastChangedDate: 2009-11-06 12:20:28 -0800 (Fri, 06 Nov 2009) $
64 public class AccountRoleServiceTest extends AbstractServiceTestImpl<AccountRole, AccountRole, AccountRole, AccountRole> {
66 /** The Constant logger. */
67 private final static String CLASS_NAME = AccountRoleServiceTest.class.getName();
68 private final static Logger logger = LoggerFactory.getLogger(CLASS_NAME);
69 // Instance variables specific to this test.
70 private String prebuiltAdminCSID = null;
71 private String prebuiltAdminUserId = "admin@core.collectionspace.org";
72 /** The all resource ids created. */
73 /** The acc values. */
74 private Hashtable<String, AccountValue> accValues = new Hashtable<String, AccountValue>();
75 /** The role values. */
76 private Hashtable<String, RoleValue> roleValues = new Hashtable<String, RoleValue>();
78 * This method is called only by the parent class, AbstractServiceTestImpl
82 * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
85 protected String getServicePathComponent() {
86 return new AccountRoleClient().getServicePathComponent();
90 * The entity type expected from the JAX-RS Response object
92 public Class<AccountRole> getEntityResponseType() {
93 return AccountRole.class;
99 @BeforeClass(alwaysRun = true)
100 public void seedData() {
101 String userId = "acc-role-user1";
102 String accId = createAccount(userId, "acc-role-user1-test@cspace.org");
103 AccountValue ava = new AccountValue();
104 ava.setScreenName(userId);
105 ava.setUserId(userId);
106 ava.setAccountId(accId);
107 accValues.put(ava.getScreenName(), ava);
109 String userId2 = "acc-role-user2";
110 String coAccId = createAccount(userId2, "acc-role-user2-test@cspace.org");
111 AccountValue avc = new AccountValue();
112 avc.setScreenName(userId2);
113 avc.setUserId(userId2);
114 avc.setAccountId(coAccId);
115 accValues.put(avc.getScreenName(), avc);
117 String rn1 = "ROLE_CO1";
118 String r1RoleId = createRole(rn1);
119 RoleValue rv1 = new RoleValue();
120 rv1.setRoleId(r1RoleId);
121 rv1.setRoleName(rn1);
122 roleValues.put(rv1.getRoleName(), rv1);
124 String rn2 = "ROLE_CO2";
125 String r2RoleId = createRole(rn2);
126 RoleValue rv2 = new RoleValue();
127 rv2.setRoleId(r2RoleId);
128 rv2.setRoleName(rn2);
129 roleValues.put(rv2.getRoleName(), rv2);
133 * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
136 protected CollectionSpaceClient getClientInstance() {
137 return new AccountRoleClient();
140 // ---------------------------------------------------------------
141 // CRUD tests : CREATE tests
142 // ---------------------------------------------------------------
145 public void createList(String testName) throws Exception {
146 // Do nothing. We do not support list creation in this test yet.
150 protected AccountRole createInstance(String commonPartName,
152 AccountRole result = null;
154 // Use a known Account to associate the AccountRole instance to
155 AccountValue av = accValues.get("acc-role-user1");
156 AccountRole accRole = createAccountRoleInstance(av,
157 roleValues.values(), true, true);
164 public void create(String testName) throws Exception {
166 AccountValue av = accValues.get("acc-role-user1");
167 AccountRole accRole = createAccountRoleInstance(av,
168 roleValues.values(), true, true);
169 AccountRoleClient client = new AccountRoleClient();
170 ClientResponse<Response> res = client.create(av.getAccountId(), accRole);
172 assertStatusCode(res, testName);
173 knownResourceId = av.getAccountId();
174 if (logger.isDebugEnabled()) {
175 logger.debug(testName + ": Created an AccountRole instance for account with knownResourceId="
180 res.releaseConnection();
185 // ---------------------------------------------------------------
186 // CRUD tests : READ tests
187 // ---------------------------------------------------------------
189 @Test(dataProvider = "testName",
190 dependsOnMethods = {"CRUDTests"})
191 public void readNoRelationship(String testName) throws Exception {
195 // Submit the request to the service and store the response.
196 AccountRoleClient client = new AccountRoleClient();
197 ClientResponse<AccountRole> res = client.read(
198 accValues.get("acc-role-user2").getAccountId());
200 // Check the status code of the response: does it match
201 // the expected response(s)?
202 assertStatusCode(res, testName);
203 AccountRole output = res.getEntity();
204 if(logger.isDebugEnabled()) {
205 org.collectionspace.services.authorization.ObjectFactory objectFactory = new org.collectionspace.services.authorization.ObjectFactory();
206 String sOutput = objectAsXmlString(objectFactory.createAccountRole(output), AccountRole.class);
207 logger.debug(testName + " received " + sOutput);
211 res.releaseConnection();
217 * In this test, for setup, we associate both test roles ("ROLE_CO1", "ROLE_CO2") with the test account "acc-role-user2".
218 * After we've performed this setup, our call to "/role/{csid}/accountroles" should contain an AccountRole that has
219 * a list of 1 account -the test user account we associated during setup.
221 @Test(dataProvider = "testName",
222 dependsOnMethods = {"CRUDTests"})
223 public void readRoleAccounts(String testName) throws Exception {
225 * Setup a temp local scope for local variables that we need to create the AccountRole for
226 * the setup of the read tests.
229 // Associate "acc-role-user2" with all the roles.
230 AccountValue av = accValues.get("acc-role-user2");
231 AccountRole accRole = createAccountRoleInstance(av,
232 roleValues.values(), true, true);
233 AccountRoleClient client = new AccountRoleClient();
235 ClientResponse<Response> res = client.create(av.getAccountId(), accRole);
237 assertStatusCode(res, testName);
240 res.releaseConnection();
246 // Now read the list of accounts associated with the role "ROLE_CO1".
247 // There should be just the "acc-role-user2" account.
249 RoleClient roleClient = new RoleClient();
251 // Submit the request to the service and store the response.
253 ClientResponse<AccountRole> res = roleClient.readRoleAccounts(
254 roleValues.get("ROLE_CO1").getRoleId());
256 // Check the status code of the response: does it match
257 // the expected response(s)?
258 assertStatusCode(res, testName);
259 AccountRole output = res.getEntity();
261 // Now verify that the role has 2 accounts associate to it.
262 Assert.assertEquals(output.getAccount().size(), 1);
263 String sOutput = objectAsXmlString(output, AccountRole.class);
264 if(logger.isDebugEnabled()) {
265 logger.debug(testName + " received " + sOutput);
269 res.releaseConnection();
274 // ---------------------------------------------------------------
275 // CRUD tests : READ_LIST tests
276 // ---------------------------------------------------------------
280 public void readList(String testName) throws Exception {
282 // There is no such thing as a list of AccountRole resources
287 public void readPaginatedList(String testName) throws Exception {
289 // There is no such thing as a list of AccountRole resources
295 // ---------------------------------------------------------------
296 // CRUD tests : UPDATE tests
297 // ---------------------------------------------------------------
301 public void update(String testName) throws Exception {
303 // AccountRole entities cannot be updated. You must delete and recreate them
308 @Test(dataProvider = "testName",
309 dependsOnMethods = {"CRUDTests"})
310 public void updateNonExistent(String testName) throws Exception {
312 // AccountRole entities cannot be updated. You must delete and recreate them
316 // ---------------------------------------------------------------
317 // CRUD tests : DELETE tests
318 // ---------------------------------------------------------------
322 public void delete(String testName) throws Exception {
324 // First, lookup the known account and delete all of its role relationships
326 AccountRoleClient client = new AccountRoleClient();
328 ClientResponse<AccountRole> readResponse = client.read(
329 accValues.get("acc-role-user1").getAccountId());
330 AccountRole toDelete = null;
332 assertStatusCode(readResponse, testName);
333 toDelete = readResponse.getEntity();
334 Assert.assertNotNull(toDelete);
336 if (readResponse != null) {
337 readResponse.releaseConnection();
342 ClientResponse<Response> res = client.delete(
343 toDelete.getAccount().get(0).getAccountId(), toDelete); // delete form #1
345 assertStatusCode(readResponse, testName);
348 res.releaseConnection();
352 // Recreate 'acc-role-user1' account and roles for the next test
357 // Lookup a known account and delete all of its role relationships again
360 readResponse = client.read(
361 accValues.get("acc-role-user1").getAccountId());
364 toDelete = readResponse.getEntity();
366 if (readResponse != null) {
367 readResponse.releaseConnection();
372 Response deleteRes = client.delete(toDelete.getAccount().get(0).getAccountId()); // delete form #2
374 int statusCode = deleteRes.getStatus();
375 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
376 invalidStatusCodeMessage(testRequestType, statusCode));
377 Assert.assertEquals(statusCode, testExpectedStatusCode);
383 @Test(dataProvider = "testName",
384 dependsOnMethods = {"CRUDTests"})
385 public void deleteLockedAccount(String testName) throws Exception {
386 findPrebuiltAdminAccount();
389 testExpectedStatusCode = Response.Status.FORBIDDEN.getStatusCode();
390 testRequestType = ServiceRequestType.DELETE;
391 testSetup(testExpectedStatusCode, testRequestType);
393 AccountRoleClient client = new AccountRoleClient();
394 Response res = client.delete(prebuiltAdminCSID);
396 int statusCode = res.getStatus();
397 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
398 invalidStatusCodeMessage(testRequestType, statusCode));
399 Assert.assertEquals(statusCode, testExpectedStatusCode);
408 // Tests with expected failure outcomes
412 public void deleteNonExistent(String testName) throws Exception {
413 //ignoring this test as the service side returns 200 now even if it does
414 //not find a record in the db
416 //FIXME: REM - 1/9/2012, need to find out why a 200 status code is returned and fix this.
419 // ---------------------------------------------------------------
421 // ---------------------------------------------------------------
424 public void searchWorkflowDeleted(String testName) throws Exception {
425 // Fixme: null test for now, overriding test in base class
428 // ---------------------------------------------------------------
429 // Utility methods used by tests above
430 // ---------------------------------------------------------------
433 * Creates the account role instance.
437 * @param usePermId the use perm id
438 * @param useRoleId the use role id
439 * @return the account role
441 static public AccountRole createAccountRoleInstance(AccountValue pv,
442 Collection<RoleValue> rvs,
446 AccountRole accRole = AccountRoleFactory.createAccountRoleInstance(
447 pv, rvs, usePermId, useRoleId);
449 if (logger.isDebugEnabled()) {
450 logger.debug("to be created, accRole common");
451 org.collectionspace.services.authorization.ObjectFactory objectFactory = new org.collectionspace.services.authorization.ObjectFactory();
452 logger.debug(objectAsXmlString(objectFactory.createAccountRole(accRole), AccountRole.class));
460 @AfterClass(alwaysRun = true)
462 public void cleanUp() {
466 String noTest = System.getProperty("noTestCleanup");
467 if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
468 if (logger.isDebugEnabled()) {
469 logger.debug("Skipping Cleanup phase ...");
473 if (logger.isDebugEnabled()) {
474 logger.debug("Cleaning up temporary resources created for testing ...");
477 for (AccountValue pv : accValues.values()) {
478 deleteAccount(pv.getAccountId());
481 for (RoleValue rv : roleValues.values()) {
482 deleteRole(rv.getRoleId());
487 * Creates the account.
489 * @param userName the user name
490 * @param email the email
493 private String createAccount(String userName, String email) {
494 AccountClient accClient = new AccountClient();
495 AccountsCommon account = AccountFactory.createAccountInstance(
496 userName, userName, userName, email, accClient.getTenantId(),
497 true, false, true, true);
498 String result = null;
501 ClientResponse<Response> res = accClient.create(account);
503 assertStatusCode(res, "CreateAccount");
504 result = extractId(res);
507 res.releaseConnection();
514 private void findPrebuiltAdminAccount() {
515 // Search for the prebuilt admin user and then hold its CSID
516 if (prebuiltAdminCSID == null) {
518 AccountClient client = new AccountClient();
519 ClientResponse<AccountsCommonList> res =
520 client.readSearchList(null, this.prebuiltAdminUserId, null);
522 assertStatusCode(res, "findPrebuiltAdminAccount");
523 AccountsCommonList list = res.getEntity();
524 List<AccountListItem> items = list.getAccountListItem();
525 Assert.assertEquals(1, items.size(), "Found more than one Admin account!");
526 AccountListItem item = items.get(0);
527 prebuiltAdminCSID = item.getCsid();
528 if (logger.isDebugEnabled()) {
529 logger.debug("Found Admin Account with ID: " + prebuiltAdminCSID);
533 res.releaseConnection();
542 * @param accId the acc id
544 private void deleteAccount(String accId) {
545 AccountClient accClient = new AccountClient();
547 Response res = accClient.delete(accId);
549 assertStatusCode(res, "DeleteAccount");
560 * @param roleName the role name
563 private String createRole(String roleName) {
564 String result = null;
566 RoleClient roleClient = new RoleClient();
567 Role role = RoleFactory.createRoleInstance(roleName,
568 roleName, //the display name
569 "role for " + roleName, true);
571 ClientResponse<Response> res = roleClient.create(role);
573 assertStatusCode(res, "CreateRole");
574 result = extractId(res);
577 res.releaseConnection();
587 * @param roleId the role id
589 private void deleteRole(String roleId) {
591 RoleClient roleClient = new RoleClient();
592 Response res = roleClient.delete(roleId);
594 assertStatusCode(res, "DeleteRole");
603 protected String getServiceName() {
604 // AccountRoles service is a sub-service of the Account service, so we return Account's service name
605 return AccountClient.SERVICE_NAME;
609 * For convenience and terseness, this test method is the base of the test execution dependency chain. Other test methods may
610 * refer to this method in their @Test annotation declarations.
613 @Test(dataProvider = "testName",
615 "org.collectionspace.services.client.test.AbstractServiceTestImpl.baseCRUDTests"})
616 public void CRUDTests(String testName) {
617 // Do nothing. Simply here to for a TestNG execution order for our tests
621 protected AccountRole updateInstance(AccountRole commonPartObject) {
623 // AccountRole entities cannot be updated. You must delete and recreate them
629 protected void compareReadInstances(AccountRole original, AccountRole updated)
631 // FIXME: Should add field checks here.
635 protected void compareUpdatedInstances(AccountRole original,
636 AccountRole updated) throws Exception {
638 // AccountRole entities cannot be updated. You must delete and recreate them
643 protected Class<AccountRole> getCommonListType() {
644 return AccountRole.class;
648 protected long getSizeOfList(AccountRole list) {
649 // TODO Auto-generated method stub
650 throw new UnsupportedOperationException("Method getSizeOfList() is not implemented because this service does not support lists.");