]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
79340c43d970a174b4782a7aba6312cb7a9f2580
[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 import java.lang.UnsupportedOperationException;
29
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;
46
47 import javax.ws.rs.core.Response;
48
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;
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      * The entity type expected from the JAX-RS Response object
91      */
92     public Class<AccountRole> getEntityResponseType() {
93         return AccountRole.class;
94     }
95
96     /**
97      * Seed data.
98      */
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);
108
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);
116
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);
123
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);
130     }
131
132     /* (non-Javadoc)
133      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
134      */
135     @Override
136     protected CollectionSpaceClient getClientInstance() {
137         return new AccountRoleClient();
138     }
139
140     // ---------------------------------------------------------------
141     // CRUD tests : CREATE tests
142     // ---------------------------------------------------------------
143     // Success outcomes
144     
145     public void createList(String testName) throws Exception {
146         // Do nothing.  We do not support list creation in this test yet.
147     }
148     
149         @Override
150         protected AccountRole createInstance(String commonPartName,
151                         String identifier) {
152                 AccountRole result = null;
153                 
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);
158         
159         result = accRole;
160         return result;
161         }
162         
163         @Override
164         public void create(String testName) throws Exception {
165                 setupCreate();
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);
171         try {
172                 assertStatusCode(res, testName);
173             knownResourceId = av.getAccountId();
174             if (logger.isDebugEnabled()) {
175                 logger.debug(testName + ": Created an AccountRole instance for account with knownResourceId="
176                                 + knownResourceId);
177             }
178         } finally {
179                 if (res != null) {
180                         res.releaseConnection();
181                 }
182         }
183         }
184
185     // ---------------------------------------------------------------
186     // CRUD tests : READ tests
187     // ---------------------------------------------------------------
188
189     @Test(dataProvider = "testName",
190                 dependsOnMethods = {"CRUDTests"})
191     public void readNoRelationship(String testName) throws Exception {
192         // Perform setup.
193         setupRead();
194
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());
199         try {
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);
208             }
209         } finally {
210                 if (res != null) {
211                         res.releaseConnection();
212                 }
213         }
214     }
215     
216     /*
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.
220      */
221     @Test(dataProvider = "testName",
222             dependsOnMethods = {"CRUDTests"})
223     public void readRoleAccounts(String testName) throws Exception {
224                 /*
225                  * Setup a temp local scope for local variables that we need to create the AccountRole for
226                  * the setup of the read tests.
227                  */
228         {
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();
234                 setupCreate();          
235                 ClientResponse<Response> res = client.create(av.getAccountId(), accRole);
236                 try {
237                         assertStatusCode(res, testName);
238                 } finally {
239                         if (res != null) {
240                                 res.releaseConnection();
241                         }
242                 }
243         }
244
245         //
246         // Now read the list of accounts associated with the role "ROLE_CO1".
247         // There should be just the "acc-role-user2" account.
248         //
249         RoleClient roleClient = new RoleClient();
250         
251         // Submit the request to the service and store the response.
252         setupRead();        
253         ClientResponse<AccountRole> res = roleClient.readRoleAccounts(
254                         roleValues.get("ROLE_CO1").getRoleId());
255         try {
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();
260             
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);
266             }
267         } finally {
268                 if (res != null) {
269                 res.releaseConnection();
270             }
271         }
272     }    
273
274     // ---------------------------------------------------------------
275     // CRUD tests : READ_LIST tests
276     // ---------------------------------------------------------------
277     // Success outcomes
278
279     @Override
280     public void readList(String testName) throws Exception {
281         //
282         // There is no such thing as a list of AccountRole resources
283         //
284     }
285     
286     @Override
287     public void readPaginatedList(String testName) throws Exception {
288         //
289         // There is no such thing as a list of AccountRole resources
290         //
291     }    
292
293     // Failure outcomes
294     // None at present.
295     // ---------------------------------------------------------------
296     // CRUD tests : UPDATE tests
297     // ---------------------------------------------------------------
298     // Success outcomes
299
300     @Override
301     public void update(String testName) throws Exception {
302         //
303         // AccountRole entities cannot be updated.  You must delete and recreate them
304         //
305     }
306
307     @Override
308     @Test(dataProvider = "testName",
309         dependsOnMethods = {"CRUDTests"})
310     public void updateNonExistent(String testName) throws Exception {
311         //
312         // AccountRole entities cannot be updated.  You must delete and recreate them
313         //
314     }
315
316     // ---------------------------------------------------------------
317     // CRUD tests : DELETE tests
318     // ---------------------------------------------------------------
319     // Success outcomes
320     
321     @Override
322     public void delete(String testName) throws Exception {
323         //
324         // First, lookup the known account and delete all of its role relationships
325         //
326         AccountRoleClient client = new AccountRoleClient();
327         setupRead();        
328         ClientResponse<AccountRole> readResponse = client.read(
329                 accValues.get("acc-role-user1").getAccountId());
330         AccountRole toDelete = null;
331         try {
332                 assertStatusCode(readResponse, testName);
333                 toDelete = readResponse.getEntity();
334                 Assert.assertNotNull(toDelete);
335         } finally {
336                 if (readResponse != null) {
337                         readResponse.releaseConnection();
338                 }
339         }
340
341         setupDelete();                
342         ClientResponse<Response> res = client.delete(
343                 toDelete.getAccount().get(0).getAccountId(), toDelete); // delete form #1
344         try {
345                 assertStatusCode(readResponse, testName);
346         } finally {
347                 if (res != null) {
348                         res.releaseConnection();
349                 }
350         }
351         //
352         // Recreate 'acc-role-user1' account and roles for the next test
353         //
354         create(testName);
355                 
356         //
357         // Lookup a known account and delete all of its role relationships again
358         //
359         setupRead();
360         readResponse = client.read(
361                         accValues.get("acc-role-user1").getAccountId());
362         toDelete = null;
363         try {
364                 toDelete = readResponse.getEntity();
365         } finally {
366                 if (readResponse != null) {
367                         readResponse.releaseConnection();
368                 }
369         }
370
371         setupDelete();        
372         Response deleteRes = client.delete(toDelete.getAccount().get(0).getAccountId()); // delete form #2
373         try {
374             int statusCode = deleteRes.getStatus();
375             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
376                     invalidStatusCodeMessage(testRequestType, statusCode));
377             Assert.assertEquals(statusCode, testExpectedStatusCode);
378         } finally {
379                 deleteRes.close();
380         }
381     }
382
383     @Test(dataProvider = "testName",
384             dependsOnMethods = {"CRUDTests"})
385         public void deleteLockedAccount(String testName) throws Exception {
386         findPrebuiltAdminAccount();
387
388         // Perform setup.
389         testExpectedStatusCode = Response.Status.FORBIDDEN.getStatusCode();
390         testRequestType = ServiceRequestType.DELETE;
391         testSetup(testExpectedStatusCode, testRequestType);
392
393         AccountRoleClient client = new AccountRoleClient();
394         Response res = client.delete(prebuiltAdminCSID);
395         try {
396                 int statusCode = res.getStatus();
397                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
398                                 invalidStatusCodeMessage(testRequestType, statusCode));
399                 Assert.assertEquals(statusCode, testExpectedStatusCode);
400         } finally {
401                 if (res != null) {
402                         res.close();
403                 }
404         }
405     }
406
407     //
408     // Tests with expected failure outcomes
409     //
410
411     @Override
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
415         
416         //FIXME: REM - 1/9/2012, need to find out why a 200 status code is returned and fix this.
417     }
418     
419     // ---------------------------------------------------------------
420     // Search tests
421     // ---------------------------------------------------------------
422     
423     @Override
424     public void searchWorkflowDeleted(String testName) throws Exception {
425         // Fixme: null test for now, overriding test in base class
426     }    
427
428     // ---------------------------------------------------------------
429     // Utility methods used by tests above
430     // ---------------------------------------------------------------
431
432     /**
433      * Creates the account role instance.
434      *
435      * @param av the av
436      * @param rvs the rvs
437      * @param usePermId the use perm id
438      * @param useRoleId the use role id
439      * @return the account role
440      */
441     static public AccountRole createAccountRoleInstance(AccountValue pv,
442             Collection<RoleValue> rvs,
443             boolean usePermId,
444             boolean useRoleId) {
445
446         AccountRole accRole = AccountRoleFactory.createAccountRoleInstance(
447                 pv, rvs, usePermId, useRoleId);
448
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));
453         }
454         return accRole;
455     }
456
457     /**
458      * Clean up.
459      */
460     @AfterClass(alwaysRun = true)
461     @Override
462     public void cleanUp() {
463
464         setupDelete();
465
466         String noTest = System.getProperty("noTestCleanup");
467         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
468             if (logger.isDebugEnabled()) {
469                 logger.debug("Skipping Cleanup phase ...");
470             }
471             return;
472         }
473         if (logger.isDebugEnabled()) {
474             logger.debug("Cleaning up temporary resources created for testing ...");
475         }
476
477         for (AccountValue pv : accValues.values()) {
478             deleteAccount(pv.getAccountId());
479         }
480
481         for (RoleValue rv : roleValues.values()) {
482             deleteRole(rv.getRoleId());
483         }
484     }
485
486     /**
487      * Creates the account.
488      *
489      * @param userName the user name
490      * @param email the email
491      * @return the string
492      */
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;
499         
500         setupCreate();
501         ClientResponse<Response> res = accClient.create(account);
502         try {
503                 assertStatusCode(res, "CreateAccount");
504                 result = extractId(res);
505         } finally {
506                 if (res != null) {
507                         res.releaseConnection();
508                 }
509         }
510
511         return result;
512     }
513
514     private void findPrebuiltAdminAccount() {
515         // Search for the prebuilt admin user and then hold its CSID
516         if (prebuiltAdminCSID == null) {
517             setupReadList();
518             AccountClient client = new AccountClient();
519             ClientResponse<AccountsCommonList> res =
520                     client.readSearchList(null, this.prebuiltAdminUserId, null);
521             try {
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);
530                     }
531             } finally {
532                 if (res != null) {
533                     res.releaseConnection();
534                 }               
535             }
536         }
537     }
538     
539     /**
540      * Delete account.
541      *
542      * @param accId the acc id
543      */
544     private void deleteAccount(String accId) {
545         AccountClient accClient = new AccountClient();
546         setupDelete();
547         Response res = accClient.delete(accId);
548         try {
549                 assertStatusCode(res, "DeleteAccount");
550         } finally {
551                 if (res != null) {
552                         res.close();
553                 }
554         }
555     }
556
557     /**
558      * Creates the role.
559      *
560      * @param roleName the role name
561      * @return the string
562      */
563     private String createRole(String roleName) {
564         String result = null;
565         
566         RoleClient roleClient = new RoleClient();
567         Role role = RoleFactory.createRoleInstance(roleName,
568                         roleName, //the display name
569                 "role for " + roleName, true);
570         setupCreate();
571         ClientResponse<Response> res = roleClient.create(role);
572         try {
573                 assertStatusCode(res, "CreateRole");
574                 result = extractId(res);
575         } finally {
576                 if (res != null) {
577                         res.releaseConnection();
578                 }
579         }
580         
581         return result;
582     }
583
584     /**
585      * Delete role.
586      *
587      * @param roleId the role id
588      */
589     private void deleteRole(String roleId) {
590         setupDelete();
591         RoleClient roleClient = new RoleClient();
592         Response res = roleClient.delete(roleId);
593         try {
594                 assertStatusCode(res, "DeleteRole");
595         } finally {
596                 if (res != null) {
597                         res.close();
598                 }
599         }
600     }
601
602         @Override
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;
606         }
607
608     /*
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.
611      */
612     @Override
613     @Test(dataProvider = "testName",
614                 dependsOnMethods = {
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
618     }
619
620         @Override
621         protected AccountRole updateInstance(AccountRole commonPartObject) {
622         //
623         // AccountRole entities cannot be updated.  You must delete and recreate them
624         //
625                 return null;
626         }
627
628         @Override
629         protected void compareReadInstances(AccountRole original, AccountRole updated)
630                         throws Exception {
631                 // FIXME: Should add field checks here.
632         }
633
634         @Override
635         protected void compareUpdatedInstances(AccountRole original,
636                         AccountRole updated) throws Exception {
637         //
638         // AccountRole entities cannot be updated.  You must delete and recreate them
639         //
640         }
641
642         @Override
643         protected Class<AccountRole> getCommonListType() {
644                 return AccountRole.class;
645         }
646
647         @Override
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.");
651         }
652 }