]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
e006e29f4476d76173f34ae0a63562b700b2842b
[tmp/jakarta-migration.git] /
1 /**
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:
5  *
6  * http://www.collectionspace.org
7  * http://wiki.collectionspace.org
8  *
9  * Copyright © 2009 Regents of the University of California
10  *
11  * Licensed under the Educational Community License (ECL), Version 2.0.
12  * You may not use this file except in compliance with this License.
13  *
14  * You may obtain a copy of the ECL 2.0 License at
15  * https://source.collectionspace.org/collection-space/LICENSE.txt
16  *
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.
22  */
23 package org.collectionspace.services.account.client.test;
24
25 import java.util.Collection;
26 import java.util.Hashtable;
27 import java.util.List;
28
29 import org.collectionspace.services.account.AccountsCommon;
30 import org.collectionspace.services.account.AccountsCommonList;
31 import org.collectionspace.services.account.AccountListItem;
32 import org.collectionspace.services.authorization.AccountRole;
33 import org.collectionspace.services.authorization.AccountValue;
34 import org.collectionspace.services.authorization.Role;
35 import org.collectionspace.services.authorization.RoleValue;
36 import org.collectionspace.services.client.AccountClient;
37 import org.collectionspace.services.client.AccountFactory;
38 import org.collectionspace.services.client.AccountRoleClient;
39 import org.collectionspace.services.client.AccountRoleFactory;
40 import org.collectionspace.services.client.CollectionSpaceClient;
41 import org.collectionspace.services.client.RoleClient;
42 import org.collectionspace.services.client.RoleFactory;
43 import org.collectionspace.services.client.test.AbstractServiceTestImpl;
44 import org.collectionspace.services.client.test.ServiceRequestType;
45
46 import javax.ws.rs.core.Response;
47 import org.jboss.resteasy.client.ClientResponse;
48
49 import org.testng.Assert;
50 import org.testng.annotations.Test;
51 import org.testng.annotations.AfterClass;
52 import org.testng.annotations.BeforeClass;
53
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  * AccountServiceTest, carries out tests against a
59  * deployed and running Account, Role and AccountRole Services.
60  * 
61  * $LastChangedRevision: 917 $
62  * $LastChangedDate: 2009-11-06 12:20:28 -0800 (Fri, 06 Nov 2009) $
63  */
64 public class AccountRoleServiceTest extends AbstractServiceTestImpl<AccountRole, AccountRole, AccountRole, AccountRole> {
65
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>();
77     /*
78      * This method is called only by the parent class, AbstractServiceTestImpl
79      */
80
81     /* (non-Javadoc)
82      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
83      */
84     @Override
85     protected String getServicePathComponent() {
86         return new AccountRoleClient().getServicePathComponent();
87     }
88
89     /**
90      * Seed data.
91      */
92     @BeforeClass(alwaysRun = true)
93     public void seedData() {
94         String userId = "acc-role-user1";
95         String accId = createAccount(userId, "acc-role-user1-test@cspace.org");
96         AccountValue ava = new AccountValue();
97         ava.setScreenName(userId);
98         ava.setUserId(userId);
99         ava.setAccountId(accId);
100         accValues.put(ava.getScreenName(), ava);
101
102         String userId2 = "acc-role-user2";
103         String coAccId = createAccount(userId2, "acc-role-user2-test@cspace.org");
104         AccountValue avc = new AccountValue();
105         avc.setScreenName(userId2);
106         avc.setUserId(userId2);
107         avc.setAccountId(coAccId);
108         accValues.put(avc.getScreenName(), avc);
109
110         String rn1 = "ROLE_CO1";
111         String r1RoleId = createRole(rn1);
112         RoleValue rv1 = new RoleValue();
113         rv1.setRoleId(r1RoleId);
114         rv1.setRoleName(rn1);
115         roleValues.put(rv1.getRoleName(), rv1);
116
117         String rn2 = "ROLE_CO2";
118         String r2RoleId = createRole(rn2);
119         RoleValue rv2 = new RoleValue();
120         rv2.setRoleId(r2RoleId);
121         rv2.setRoleName(rn2);
122         roleValues.put(rv2.getRoleName(), rv2);
123     }
124
125     /* (non-Javadoc)
126      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
127      */
128     @Override
129     protected CollectionSpaceClient getClientInstance() {
130         return new AccountRoleClient();
131     }
132
133     // ---------------------------------------------------------------
134     // CRUD tests : CREATE tests
135     // ---------------------------------------------------------------
136     // Success outcomes
137     
138     public void createList(String testName) throws Exception {
139         // Do nothing.  We do not support list creation in this test yet.
140     }
141     
142         @Override
143         protected AccountRole createInstance(String commonPartName,
144                         String identifier) {
145                 AccountRole result = null;
146                 
147         // Use a known Account to associate the AccountRole instance to
148         AccountValue av = accValues.get("acc-role-user1");
149         AccountRole accRole = createAccountRoleInstance(av,
150                 roleValues.values(), true, true);
151         
152         result = accRole;
153         return result;
154         }
155         
156         @Override
157         public void create(String testName) throws Exception {
158                 setupCreate();
159         AccountValue av = accValues.get("acc-role-user1");
160         AccountRole accRole = createAccountRoleInstance(av,
161                 roleValues.values(), true, true);
162         AccountRoleClient client = new AccountRoleClient();
163         ClientResponse<Response> res = client.create(av.getAccountId(), accRole);
164         try {
165                 assertStatusCode(res, testName);
166             knownResourceId = av.getAccountId();
167             if (logger.isDebugEnabled()) {
168                 logger.debug(testName + ": Created an AccountRole instance for account with knownResourceId="
169                                 + knownResourceId);
170             }
171         } finally {
172                 if (res != null) {
173                         res.releaseConnection();
174                 }
175         }
176         }
177
178     // ---------------------------------------------------------------
179     // CRUD tests : READ tests
180     // ---------------------------------------------------------------
181
182     @Test(dataProvider = "testName",
183                 dependsOnMethods = {"CRUDTests"})
184     public void readNoRelationship(String testName) throws Exception {
185         // Perform setup.
186         setupRead();
187
188         // Submit the request to the service and store the response.
189         AccountRoleClient client = new AccountRoleClient();
190         ClientResponse<AccountRole> res = client.read(
191                 accValues.get("acc-role-user2").getAccountId());
192         try {
193             // Check the status code of the response: does it match
194             // the expected response(s)?
195             assertStatusCode(res, testName);
196             AccountRole output = res.getEntity();
197             if(logger.isDebugEnabled()) {
198                 org.collectionspace.services.authorization.ObjectFactory objectFactory = new org.collectionspace.services.authorization.ObjectFactory();
199                 String sOutput = objectAsXmlString(objectFactory.createAccountRole(output), AccountRole.class);
200                 logger.debug(testName + " received " + sOutput);
201             }
202         } finally {
203                 if (res != null) {
204                         res.releaseConnection();
205                 }
206         }
207     }
208     
209     /*
210      * In this test, for setup, we associate both test roles ("ROLE_CO1", "ROLE_CO2") with the test account "acc-role-user2".
211      * After we've performed this setup, our call to "/role/{csid}/accountroles" should contain an AccountRole that has
212      * a list of 1 account -the test user account we associated during setup.
213      */
214     @Test(dataProvider = "testName",
215             dependsOnMethods = {"CRUDTests"})
216     public void readRoleAccounts(String testName) throws Exception {
217                 /*
218                  * Setup a temp local scope for local variables that we need to create the AccountRole for
219                  * the setup of the read tests.
220                  */
221         {
222                 // Associate "acc-role-user2" with all the roles.
223                 AccountValue av = accValues.get("acc-role-user2");
224                 AccountRole accRole = createAccountRoleInstance(av,
225                         roleValues.values(), true, true);
226                 AccountRoleClient client = new AccountRoleClient();
227                 setupCreate();          
228                 ClientResponse<Response> res = client.create(av.getAccountId(), accRole);
229                 try {
230                         assertStatusCode(res, testName);
231                 } finally {
232                         if (res != null) {
233                                 res.releaseConnection();
234                         }
235                 }
236         }
237
238         //
239         // Now read the list of accounts associated with the role "ROLE_CO1".
240         // There should be just the "acc-role-user2" account.
241         //
242         RoleClient roleClient = new RoleClient();
243         
244         // Submit the request to the service and store the response.
245         setupRead();        
246         ClientResponse<AccountRole> res = roleClient.readRoleAccounts(
247                         roleValues.get("ROLE_CO1").getRoleId());
248         try {
249             // Check the status code of the response: does it match
250             // the expected response(s)?
251             assertStatusCode(res, testName);
252             AccountRole output = res.getEntity();
253             
254             // Now verify that the role has 2 accounts associate to it.
255             Assert.assertEquals(output.getAccount().size(), 1);
256             String sOutput = objectAsXmlString(output, AccountRole.class);
257             if(logger.isDebugEnabled()) {
258                 logger.debug(testName + " received " + sOutput);
259             }
260         } finally {
261                 if (res != null) {
262                 res.releaseConnection();
263             }
264         }
265     }    
266
267     // ---------------------------------------------------------------
268     // CRUD tests : READ_LIST tests
269     // ---------------------------------------------------------------
270     // Success outcomes
271
272     @Override
273     public void readList(String testName) throws Exception {
274         //
275         // There is no such thing as a list of AccountRole resources
276         //
277     }
278     
279     @Override
280     public void readPaginatedList(String testName) throws Exception {
281         //
282         // There is no such thing as a list of AccountRole resources
283         //
284     }    
285
286     // Failure outcomes
287     // None at present.
288     // ---------------------------------------------------------------
289     // CRUD tests : UPDATE tests
290     // ---------------------------------------------------------------
291     // Success outcomes
292
293     @Override
294     public void update(String testName) throws Exception {
295         //
296         // AccountRole entities cannot be updated.  You must delete and recreate them
297         //
298     }
299
300     @Override
301     @Test(dataProvider = "testName",
302         dependsOnMethods = {"CRUDTests"})
303     public void updateNonExistent(String testName) throws Exception {
304         //
305         // AccountRole entities cannot be updated.  You must delete and recreate them
306         //
307     }
308
309     // ---------------------------------------------------------------
310     // CRUD tests : DELETE tests
311     // ---------------------------------------------------------------
312     // Success outcomes
313     
314     @Override
315     public void delete(String testName) throws Exception {
316         //
317         // First, lookup the known account and delete all of its role relationships
318         //
319         AccountRoleClient client = new AccountRoleClient();
320         setupRead();        
321         ClientResponse<AccountRole> readResponse = client.read(
322                 accValues.get("acc-role-user1").getAccountId());
323         AccountRole toDelete = null;
324         try {
325                 assertStatusCode(readResponse, testName);
326                 toDelete = readResponse.getEntity();
327                 Assert.assertNotNull(toDelete);
328         } finally {
329                 if (readResponse != null) {
330                         readResponse.releaseConnection();
331                 }
332         }
333
334         setupDelete();                
335         ClientResponse<Response> res = client.delete(
336                 toDelete.getAccount().get(0).getAccountId(), toDelete); // delete form #1
337         try {
338                 assertStatusCode(readResponse, testName);
339         } finally {
340                 if (res != null) {
341                         res.releaseConnection();
342                 }
343         }
344         //
345         // Recreate 'acc-role-user1' account and roles for the next test
346         //
347         create(testName);
348                 
349         //
350         // Lookup a known account and delete all of its role relationships again
351         //
352         setupRead();
353         readResponse = client.read(
354                         accValues.get("acc-role-user1").getAccountId());
355         toDelete = null;
356         try {
357                 toDelete = readResponse.getEntity();
358         } finally {
359                 if (readResponse != null) {
360                         readResponse.releaseConnection();
361                 }
362         }
363
364         setupDelete();        
365         res = client.delete(toDelete.getAccount().get(0).getAccountId()); // delete form #2
366         try {
367             int statusCode = res.getStatus();
368             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
369                     invalidStatusCodeMessage(testRequestType, statusCode));
370             Assert.assertEquals(statusCode, testExpectedStatusCode);
371         } finally {
372             res.releaseConnection();
373         }
374     }
375
376     @Test(dataProvider = "testName",
377             dependsOnMethods = {"CRUDTests"})
378         public void deleteLockedAccount(String testName) throws Exception {
379         findPrebuiltAdminAccount();
380
381         // Perform setup.
382         testExpectedStatusCode = Response.Status.FORBIDDEN.getStatusCode();
383         testRequestType = ServiceRequestType.DELETE;
384         testSetup(testExpectedStatusCode, testRequestType);
385
386         AccountRoleClient client = new AccountRoleClient();
387         ClientResponse<Response> res = client.delete(prebuiltAdminCSID);
388         try {
389                 int statusCode = res.getStatus();
390                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
391                                 invalidStatusCodeMessage(testRequestType, statusCode));
392                 Assert.assertEquals(statusCode, testExpectedStatusCode);
393         } finally {
394                 if (res != null) {
395                         res.releaseConnection();
396                 }
397         }
398     }
399
400     //
401     // Tests with expected failure outcomes
402     //
403
404     @Override
405     public void deleteNonExistent(String testName) throws Exception {
406         //ignoring this test as the service side returns 200 now even if it does
407         //not find a record in the db
408         
409         //FIXME: REM - 1/9/2012, need to find out why a 200 status code is returned and fix this.
410     }
411     
412     // ---------------------------------------------------------------
413     // Search tests
414     // ---------------------------------------------------------------
415     
416     @Override
417     public void searchWorkflowDeleted(String testName) throws Exception {
418         // Fixme: null test for now, overriding test in base class
419     }    
420
421     // ---------------------------------------------------------------
422     // Utility methods used by tests above
423     // ---------------------------------------------------------------
424
425     /**
426      * Creates the account role instance.
427      *
428      * @param av the av
429      * @param rvs the rvs
430      * @param usePermId the use perm id
431      * @param useRoleId the use role id
432      * @return the account role
433      */
434     static public AccountRole createAccountRoleInstance(AccountValue pv,
435             Collection<RoleValue> rvs,
436             boolean usePermId,
437             boolean useRoleId) {
438
439         AccountRole accRole = AccountRoleFactory.createAccountRoleInstance(
440                 pv, rvs, usePermId, useRoleId);
441
442         if (logger.isDebugEnabled()) {
443             logger.debug("to be created, accRole common");
444             org.collectionspace.services.authorization.ObjectFactory objectFactory = new org.collectionspace.services.authorization.ObjectFactory();
445             logger.debug(objectAsXmlString(objectFactory.createAccountRole(accRole), AccountRole.class));
446         }
447         return accRole;
448     }
449
450     /**
451      * Clean up.
452      */
453     @AfterClass(alwaysRun = true)
454     @Override
455     public void cleanUp() {
456
457         setupDelete();
458
459         String noTest = System.getProperty("noTestCleanup");
460         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
461             if (logger.isDebugEnabled()) {
462                 logger.debug("Skipping Cleanup phase ...");
463             }
464             return;
465         }
466         if (logger.isDebugEnabled()) {
467             logger.debug("Cleaning up temporary resources created for testing ...");
468         }
469
470         for (AccountValue pv : accValues.values()) {
471             deleteAccount(pv.getAccountId());
472         }
473
474         for (RoleValue rv : roleValues.values()) {
475             deleteRole(rv.getRoleId());
476         }
477     }
478
479     /**
480      * Creates the account.
481      *
482      * @param userName the user name
483      * @param email the email
484      * @return the string
485      */
486     private String createAccount(String userName, String email) {
487         AccountClient accClient = new AccountClient();
488         AccountsCommon account = AccountFactory.createAccountInstance(
489                 userName, userName, userName, email, accClient.getTenantId(),
490                 true, false, true, true);
491         String result = null;
492         
493         setupCreate();
494         ClientResponse<Response> res = accClient.create(account);
495         try {
496                 assertStatusCode(res, "CreateAccount");
497                 result = extractId(res);
498         } finally {
499                 if (res != null) {
500                         res.releaseConnection();
501                 }
502         }
503
504         return result;
505     }
506
507     private void findPrebuiltAdminAccount() {
508         // Search for the prebuilt admin user and then hold its CSID
509         if (prebuiltAdminCSID == null) {
510             setupReadList();
511             AccountClient client = new AccountClient();
512             ClientResponse<AccountsCommonList> res =
513                     client.readSearchList(null, this.prebuiltAdminUserId, null);
514             try {
515                     assertStatusCode(res, "findPrebuiltAdminAccount");
516                     AccountsCommonList list = res.getEntity();
517                     List<AccountListItem> items = list.getAccountListItem();
518                     Assert.assertEquals(1, items.size(), "Found more than one Admin account!");
519                     AccountListItem item = items.get(0);
520                     prebuiltAdminCSID = item.getCsid();
521                     if (logger.isDebugEnabled()) {
522                         logger.debug("Found Admin Account with ID: " + prebuiltAdminCSID);
523                     }
524             } finally {
525                 if (res != null) {
526                     res.releaseConnection();
527                 }               
528             }
529         }
530     }
531     
532     /**
533      * Delete account.
534      *
535      * @param accId the acc id
536      */
537     private void deleteAccount(String accId) {
538         AccountClient accClient = new AccountClient();
539         setupDelete();
540         ClientResponse<Response> res = accClient.delete(accId);
541         try {
542                 assertStatusCode(res, "DeleteAccount");
543         } finally {
544                 if (res != null) {
545                         res.releaseConnection();
546                 }
547         }
548     }
549
550     /**
551      * Creates the role.
552      *
553      * @param roleName the role name
554      * @return the string
555      */
556     private String createRole(String roleName) {
557         String result = null;
558         
559         RoleClient roleClient = new RoleClient();
560         Role role = RoleFactory.createRoleInstance(roleName,
561                         roleName, //the display name
562                 "role for " + roleName, true);
563         setupCreate();
564         ClientResponse<Response> res = roleClient.create(role);
565         try {
566                 assertStatusCode(res, "CreateRole");
567                 result = extractId(res);
568         } finally {
569                 if (res != null) {
570                         res.releaseConnection();
571                 }
572         }
573         
574         return result;
575     }
576
577     /**
578      * Delete role.
579      *
580      * @param roleId the role id
581      */
582     private void deleteRole(String roleId) {
583         setupDelete();
584         RoleClient roleClient = new RoleClient();
585         ClientResponse<Response> res = roleClient.delete(roleId);
586         try {
587                 assertStatusCode(res, "DeleteRole");
588         } finally {
589                 if (res != null) {
590                         res.releaseConnection();
591                 }
592         }
593     }
594
595         @Override
596         protected String getServiceName() {
597                 // AccountRoles service is a sub-service of the Account service, so we return Account's service name
598                 return AccountClient.SERVICE_NAME;
599         }
600
601     /*
602      * For convenience and terseness, this test method is the base of the test execution dependency chain.  Other test methods may
603      * refer to this method in their @Test annotation declarations.
604      */
605     @Override
606     @Test(dataProvider = "testName",
607                 dependsOnMethods = {
608                         "org.collectionspace.services.client.test.AbstractServiceTestImpl.baseCRUDTests"})    
609     public void CRUDTests(String testName) {
610         // Do nothing.  Simply here to for a TestNG execution order for our tests
611     }
612
613         @Override
614         protected AccountRole updateInstance(AccountRole commonPartObject) {
615         //
616         // AccountRole entities cannot be updated.  You must delete and recreate them
617         //
618                 return null;
619         }
620
621         @Override
622         protected void compareReadInstances(AccountRole original, AccountRole updated)
623                         throws Exception {
624                 // FIXME: Should add field checks here.
625         }
626
627         @Override
628         protected void compareUpdatedInstances(AccountRole original,
629                         AccountRole updated) throws Exception {
630         //
631         // AccountRole entities cannot be updated.  You must delete and recreate them
632         //
633         }
634
635         @Override
636         protected Class<AccountRole> getCommonListType() {
637                 return AccountRole.class;
638         }
639 }