Standardise user admin unit tests
authorMathieu Baudier <mbaudier@argeo.org>
Thu, 8 Sep 2016 10:58:15 +0000 (10:58 +0000)
committerMathieu Baudier <mbaudier@argeo.org>
Thu, 8 Sep 2016 10:58:15 +0000 (10:58 +0000)
git-svn-id: https://svn.argeo.org/commons/trunk@9104 4cfe0d0a-d680-48aa-b62c-e0a02a3f76cc

org.argeo.security.core/build.properties
org.argeo.security.core/ext/test/log4j.properties
org.argeo.security.core/ext/test/org/argeo/osgi/useradmin/BasicTestConstants.java
org.argeo.security.core/ext/test/org/argeo/osgi/useradmin/LdifUserAdminTest.java
org.argeo.security.core/src/org/argeo/osgi/useradmin/AbstractUserDirectory.java
org.argeo.security.core/src/org/argeo/osgi/useradmin/LdifUserAdmin.java
org.argeo.security.core/src/org/argeo/osgi/useradmin/UserDirectory.java

index 6fa156125f5d6f395cdb3de16ff3f8e355f65664..af03ba43ba18f646885f4214a2abdc4b4a1c7bcc 100644 (file)
@@ -4,4 +4,5 @@ additional.bundles = org.junit,\
                      org.slf4j.commons.logging,\
                      org.slf4j.api,\
                      org.slf4j.log4j12,\
-                     org.apache.log4j
+                     org.apache.log4j,\
+                     bitronix.tm
index b33daa9db7747a1b628d1ce14ba993dbce72e66a..ef735668bad0e5bdace65bcb7c039e97edd840dd 100644 (file)
@@ -1,7 +1,7 @@
 log4j.rootLogger=WARN, console
 
 ## Levels
-log4j.logger.org.argeo=DEBUG
+log4j.logger.org.argeo=TRACE
 
 log4j.logger.org.hibernate=WARN
 
index 5bf1b5b0f2f417b561092ca78f8b7c5e5feaf386..98b8bc96d21544e990b27eacf36498f561ab29c7 100644 (file)
@@ -1,8 +1,9 @@
 package org.argeo.osgi.useradmin;
 
 interface BasicTestConstants {
-       final static String ROOT_USER_DN = "uid=root,ou=users,dc=example,dc=com";
-       final static String DEMO_USER_DN = "uid=demo,ou=users,dc=example,dc=com";
-       final static String ADMIN_GROUP_DN = "cn=admin,ou=groups,dc=example,dc=com";
-       final static String EDITORS_GROUP_DN = "cn=editors,ou=groups,dc=example,dc=com";
+       String BASE_DN = "dc=example,dc=com";
+       String ROOT_USER_DN = "uid=root,ou=users," + BASE_DN;
+       String DEMO_USER_DN = "uid=demo,ou=users," + BASE_DN;
+       String ADMIN_GROUP_DN = "cn=admin,ou=groups," + BASE_DN;
+       String EDITORS_GROUP_DN = "cn=editors,ou=groups," + BASE_DN;
 }
index c8bc583ed322b96c34c80eab76744d3a6537dc4a..d2e3f6290894cd4decf674b3ce9c3b128b48baa4 100644 (file)
@@ -2,10 +2,16 @@ package org.argeo.osgi.useradmin;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.InputStream;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.Arrays;
+import java.util.Dictionary;
+import java.util.Hashtable;
 import java.util.List;
-
-import junit.framework.TestCase;
+import java.util.UUID;
 
 import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.codec.digest.DigestUtils;
@@ -15,23 +21,41 @@ import org.osgi.service.useradmin.Group;
 import org.osgi.service.useradmin.Role;
 import org.osgi.service.useradmin.User;
 
+import bitronix.tm.BitronixTransactionManager;
+import bitronix.tm.TransactionManagerServices;
+import bitronix.tm.resource.ehcache.EhCacheXAResourceProducer;
+import junit.framework.TestCase;
+
 public class LdifUserAdminTest extends TestCase implements BasicTestConstants {
+       private AbstractUserDirectory userAdmin;
+       private BitronixTransactionManager tm;
+
+       @SuppressWarnings("unchecked")
+       public void testEdition() throws Exception {
+               User demoUser = (User) userAdmin.getRole(DEMO_USER_DN);
+               assertNotNull(demoUser);
+
+               tm.begin();
+               String newName = "demo";
+               demoUser.getProperties().put("cn", newName);
+               assertEquals(newName, demoUser.getProperties().get("cn"));
+               tm.commit();
+               assertEquals(newName, demoUser.getProperties().get("cn"));
+
+               tm.begin();
+               userAdmin.removeRole(DEMO_USER_DN);
+               tm.commit();
 
-       public void testBasicUserAdmin() throws Exception {
-               // read
-               LdifUserAdmin initialUserAdmin = new LdifUserAdmin(getClass()
-                               .getResourceAsStream("basic.ldif"));
-               // write
-               ByteArrayOutputStream out = new ByteArrayOutputStream();
-               initialUserAdmin.save(out);
-               byte[] arr = out.toByteArray();
-               initialUserAdmin.destroy();
-               IOUtils.closeQuietly(out);
-               String written = new String(arr);
-               System.out.print(written);
-               ByteArrayInputStream in = new ByteArrayInputStream(arr);
-               LdifUserAdmin userAdmin = new LdifUserAdmin(in);
+               // check data
+               Role[] search = userAdmin.getRoles("(objectclass=inetOrgPerson)");
+               assertEquals(1, search.length);
+               Group editorGroup = (Group) userAdmin.getRole(EDITORS_GROUP_DN);
+               assertNotNull(editorGroup);
+               Role[] members = editorGroup.getMembers();
+               assertEquals(1, members.length);
+       }
 
+       public void testRetrieve() throws Exception {
                // users
                User rootUser = (User) userAdmin.getRole(ROOT_USER_DN);
                assertNotNull(rootUser);
@@ -63,13 +87,9 @@ public class LdifUserAdminTest extends TestCase implements BasicTestConstants {
                assertEquals("root@localhost", rootUser.getProperties().get("mail"));
 
                // credentials
-               byte[] hashedPassword = ("{SHA}" + Base64
-                               .encodeBase64String(DigestUtils.sha1("demo".getBytes())))
-                               .getBytes();
-               assertTrue(rootUser.hasCredential(LdifName.userPassword.name(),
-                               hashedPassword));
-               assertTrue(demoUser.hasCredential(LdifName.userPassword.name(),
-                               hashedPassword));
+               byte[] hashedPassword = ("{SHA}" + Base64.encodeBase64String(DigestUtils.sha1("demo".getBytes()))).getBytes();
+               assertTrue(rootUser.hasCredential(LdifName.userPassword.name(), hashedPassword));
+               assertTrue(demoUser.hasCredential(LdifName.userPassword.name(), hashedPassword));
 
                // search
                Role[] search = userAdmin.getRoles(null);
@@ -81,4 +101,71 @@ public class LdifUserAdminTest extends TestCase implements BasicTestConstants {
                search = userAdmin.getRoles("(&(objectclass=inetOrgPerson)(uid=demo))");
                assertEquals(1, search.length);
        }
+
+       public void testReadWriteRead() throws Exception {
+               if (userAdmin instanceof LdifUserAdmin) {
+                       Dictionary<String, Object> props = userAdmin.getProperties();
+                       ByteArrayOutputStream out = new ByteArrayOutputStream();
+                       ((LdifUserAdmin) userAdmin).save(out);
+                       byte[] arr = out.toByteArray();
+                       IOUtils.closeQuietly(out);
+                       userAdmin.destroy();
+                       String written = new String(arr);
+                       System.out.print(written);
+                       try (ByteArrayInputStream in = new ByteArrayInputStream(arr)) {
+                               userAdmin = new LdifUserAdmin(props);
+                               ((LdifUserAdmin) userAdmin).load(in);
+                       }
+                       Role[] search = userAdmin.getRoles(null);
+                       assertEquals(4, search.length);
+               } else {
+                       // test not relevant for LDAP
+               }
+       }
+
+       @Override
+       protected void setUp() throws Exception {
+               Path tempDir = Files.createTempDirectory(getClass().getName());
+               URI uri;
+               String uriProp = System.getProperty("argeo.useradmin.uri");
+               if (uriProp != null)
+                       uri = new URI(uriProp);
+               else {
+                       tempDir.toFile().deleteOnExit();
+                       Path ldifPath = tempDir.resolve(BASE_DN + ".ldif");
+                       try (InputStream in = getClass().getResource("basic.ldif").openStream()) {
+                               Files.copy(in, ldifPath);
+                       }
+                       uri = ldifPath.toUri();
+               }
+
+               Dictionary<String, Object> props = new Hashtable<>();
+               props.put(UserAdminConf.uri.name(), uri.toString());
+               props.put(UserAdminConf.baseDn.name(), BASE_DN);
+               props.put(UserAdminConf.userBase.name(), "ou=users");
+               props.put(UserAdminConf.groupBase.name(), "ou=groups");
+               if (uri.getScheme().startsWith("ldap"))
+                       userAdmin = new LdapUserAdmin(props);
+               else
+                       userAdmin = new LdifUserAdmin(props);
+               userAdmin.init();
+
+               bitronix.tm.Configuration tmConf = TransactionManagerServices.getConfiguration();
+               tmConf.setServerId(UUID.randomUUID().toString());
+               tmConf.setLogPart1Filename(new File(tempDir.toFile(), "btm1.tlog").getAbsolutePath());
+               tmConf.setLogPart2Filename(new File(tempDir.toFile(), "btm2.tlog").getAbsolutePath());
+               tm = TransactionManagerServices.getTransactionManager();
+               EhCacheXAResourceProducer.registerXAResource(UserDirectory.class.getName(), userAdmin.getXaResource());
+
+               userAdmin.setTransactionManager(tm);
+       }
+
+       @Override
+       protected void tearDown() throws Exception {
+               EhCacheXAResourceProducer.unregisterXAResource(UserDirectory.class.getName(), userAdmin.getXaResource());
+               tm.shutdown();
+               if (userAdmin != null)
+                       userAdmin.destroy();
+       }
+
 }
index 121fb3500480b955447d47fa2be0053e971d66c5..48d657c2e21d00620a65920cd7e33972c68dc5d3 100644 (file)
@@ -392,7 +392,7 @@ abstract class AbstractUserDirectory implements UserAdmin, UserDirectory {
                return groupObjectClass;
        }
 
-       public Dictionary<String, ?> getProperties() {
+       public Dictionary<String, Object> getProperties() {
                return properties;
        }
 
index 366c32fa0da5edf1e41fae8518706ba0a5742f04..e83186f22676286a28144c0e9cded18823f73f4c 100644 (file)
@@ -71,16 +71,13 @@ public class LdifUserAdmin extends AbstractUserDirectory {
 
        public void save() {
                if (getUri() == null)
-                       throw new UserDirectoryException(
-                                       "Cannot save LDIF user admin: no URI is set");
+                       throw new UserDirectoryException("Cannot save LDIF user admin: no URI is set");
                if (isReadOnly())
-                       throw new UserDirectoryException("Cannot save LDIF user admin: "
-                                       + getUri() + " is read-only");
+                       throw new UserDirectoryException("Cannot save LDIF user admin: " + getUri() + " is read-only");
                try (FileOutputStream out = new FileOutputStream(new File(getUri()))) {
                        save(out);
                } catch (IOException e) {
-                       throw new UserDirectoryException("Cannot save user admin to "
-                                       + getUri(), e);
+                       throw new UserDirectoryException("Cannot save user admin to " + getUri(), e);
                }
        }
 
@@ -111,14 +108,12 @@ public class LdifUserAdmin extends AbstractUserDirectory {
                                while (ids.hasMoreElements()) {
                                        String id = ids.nextElement().toLowerCase();
                                        if (lowerCase.contains(id))
-                                               throw new UserDirectoryException(key
-                                                               + " has duplicate id " + id);
+                                               throw new UserDirectoryException(key + " has duplicate id " + id);
                                        lowerCase.add(id);
                                }
 
                                // analyse object classes
-                               NamingEnumeration<?> objectClasses = attributes.get(
-                                               objectClass.name()).getAll();
+                               NamingEnumeration<?> objectClasses = attributes.get(objectClass.name()).getAll();
                                // System.out.println(key);
                                objectClasses: while (objectClasses.hasMore()) {
                                        String objectClass = objectClasses.next().toString();
@@ -133,12 +128,13 @@ public class LdifUserAdmin extends AbstractUserDirectory {
                                }
                        }
                } catch (Exception e) {
-                       throw new UserDirectoryException(
-                                       "Cannot load user admin service from LDIF", e);
+                       throw new UserDirectoryException("Cannot load user admin service from LDIF", e);
                }
        }
 
        public void destroy() {
+               if (users == null || groups == null)
+                       throw new UserDirectoryException("User directory " + getBaseDn() + " is already destroyed");
                users.clear();
                users = null;
                groups.clear();
@@ -202,8 +198,7 @@ public class LdifUserAdmin extends AbstractUserDirectory {
                        else if (groups.containsKey(dn))
                                groups.remove(dn);
                        else
-                               throw new UserDirectoryException("User to delete not found "
-                                               + dn);
+                               throw new UserDirectoryException("User to delete not found " + dn);
                }
                // add
                for (LdapName dn : wc.getNewUsers().keySet()) {
@@ -215,8 +210,7 @@ public class LdifUserAdmin extends AbstractUserDirectory {
                        else if (Role.GROUP == user.getType())
                                groups.put(dn, (DirectoryGroup) user);
                        else
-                               throw new UserDirectoryException("Unsupported role type "
-                                               + user.getType() + " for new user " + dn);
+                               throw new UserDirectoryException("Unsupported role type " + user.getType() + " for new user " + dn);
                }
                // modify
                for (LdapName dn : wc.getModifiedUsers().keySet()) {
@@ -227,8 +221,7 @@ public class LdifUserAdmin extends AbstractUserDirectory {
                        else if (groups.containsKey(dn))
                                user = groups.get(dn);
                        else
-                               throw new UserDirectoryException("User to modify no found "
-                                               + dn);
+                               throw new UserDirectoryException("User to modify no found " + dn);
                        user.publishAttributes(modifiedAttrs);
                }
        }
index f13ad4922da1805883b8eb209ede7e5d381a1bfa..1491721228bfeac52923b90dc9d556fa0cc26d46 100644 (file)
@@ -14,7 +14,7 @@ public interface UserDirectory {
        public void setExternalRoles(UserAdmin externalRoles);
 
        /** Keys listed and described in {@link UserAdminConf}. */
-       public Dictionary<String, ?> getProperties();
+       public Dictionary<String, Object> getProperties();
 
        // Transitional. In the future, more will be managed in OSGi.
        public void setTransactionManager(TransactionManager transactionManager);