You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jspwiki.apache.org by aj...@apache.org on 2008/02/13 07:24:06 UTC

svn commit: r627271 [2/8] - in /incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki: ./ action/ attachment/ auth/ auth/acl/ auth/authorize/ auth/login/ auth/permissions/ auth/user/ dav/ diff/ filters/ htmltowiki/ parser/

Added: incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/TestJNDIContext.java
URL: http://svn.apache.org/viewvc/incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/TestJNDIContext.java?rev=627271&view=auto
==============================================================================
--- incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/TestJNDIContext.java (added)
+++ incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/TestJNDIContext.java Tue Feb 12 22:24:02 2008
@@ -0,0 +1,350 @@
+package com.ecyrd.jspwiki;
+
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.naming.Context;
+import javax.naming.Name;
+import javax.naming.NameParser;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.spi.InitialContextFactory;
+
+/**
+ * <p>Mock JNDI context that permits String names to be bound to objects. 
+ * It is intended to simulate JNDI factories in web containers and
+ * application servers, and provides only the bare minimum functions.
+ * This class contains a static member InitialContextFactory class 
+ * called Factory that installs a "root" instance of TestJNDIContext
+ * as the initial context for the entire JVM. Additional contexts can 
+ * be bound by supplying pairs of Strings and Objects using
+ * {@link #bind(String, Object)}. Objects are looked up and retrieved 
+ * using {@link #lookup(String)}. All other methods in this class no-op.</p>
+ * <p>For example, simulating a JNDI DataSource requires us to first
+ * establish an initial context of <code>java:comp/env</code>. Inside
+ * the initial context, we bind our data source:</p>
+ * <blockquote><code>Context initCtx = new InitialContext();<br/>
+ * initCtx.bind( "java:comp/env", new TestJNDIContext() );<br/>
+ * Context ctx = (Context)initCtx.lookup("java:comp/env");<br/>
+ * DataSource ds = new TestJDBCDataSource();<br/>
+ * ctx.bind( "jdbc/UserDatabase", ds);<br/>
+ * </code></blockquote>
+ * 
+ * @author Andrew R. Jaquith
+ * @since 2.3
+ */
+public class TestJNDIContext implements Context
+{
+
+    private final Map      m_bindings  = new HashMap();
+
+    private static boolean initialized = false;
+
+    /**
+     * InitialContextFactory class that configures the JVM to
+     * always return a particular TestJNDIContext.
+     * @author Andrew R. Jaquith
+     */
+    public static class Factory implements InitialContextFactory
+    {
+
+        private static Context ctx = null;
+
+        public Context getInitialContext( Hashtable environment ) throws NamingException
+        {
+            return ctx;
+        }
+
+        protected static void setContext( Context context )
+        {
+            if ( ctx == null )
+            {
+                ctx = context;
+            }
+        }
+    }
+
+    /**
+     * Constructs a new mock JNDI context. Note that the instance has no
+     * relationship to the JVM's initial context <em>per se</em>.
+     * To configure the JVM so that it always returns a TestJNDIContext
+     * instance, see {@link #initialize()}.
+     */
+    public TestJNDIContext()
+    {
+    }
+
+    /**
+     * Static factory method that creates a new TestJNDIContext and 
+     * configures the JVM so that the <code>new InitialContext()</code>
+     * always returns this context.
+     */
+    public static void initialize()
+    {
+        if ( !initialized )
+        {
+            System.setProperty( Context.INITIAL_CONTEXT_FACTORY, Factory.class.getName() );
+            Factory.setContext( new TestJNDIContext() );
+            initialized = true;
+        }
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#addToEnvironment(java.lang.String, java.lang.Object)
+     */
+    public Object addToEnvironment( String propName, Object propVal ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op.
+     * @see javax.naming.Context#bind(javax.naming.Name, java.lang.Object)
+     */
+    public void bind( Name name, Object obj ) throws NamingException
+    {
+    }
+
+    /**
+     * No-op.
+     * @see javax.naming.Context#close()
+     */
+    public void close() throws NamingException
+    {
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#composeName(javax.naming.Name, javax.naming.Name)
+     */
+    public Name composeName( Name name, Name prefix ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#composeName(java.lang.String, java.lang.String)
+     */
+    public String composeName( String name, String prefix ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#createSubcontext(javax.naming.Name)
+     */
+    public Context createSubcontext( Name name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#createSubcontext(java.lang.String)
+     */
+    public Context createSubcontext( String name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op.
+     * @see javax.naming.Context#destroySubcontext(javax.naming.Name)
+     */
+    public void destroySubcontext( Name name ) throws NamingException
+    {
+    }
+
+    /**
+     * No-op.
+     * @see javax.naming.Context#destroySubcontext(java.lang.String)
+     */
+    public void destroySubcontext( String name ) throws NamingException
+    {
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#getEnvironment()
+     */
+    public Hashtable getEnvironment() throws NamingException
+    {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#getNameInNamespace()
+     */
+    public String getNameInNamespace() throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#getNameParser(javax.naming.Name)
+     */
+    public NameParser getNameParser( Name name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#getNameParser(java.lang.String)
+     */
+    public NameParser getNameParser( String name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#list(javax.naming.Name)
+     */
+    public NamingEnumeration list( Name name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#list(java.lang.String)
+     */
+    public NamingEnumeration list( String name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#listBindings(javax.naming.Name)
+     */
+    public NamingEnumeration listBindings( Name name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#listBindings(java.lang.String)
+     */
+    public NamingEnumeration listBindings( String name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#lookup(javax.naming.Name)
+     */
+    public Object lookup( Name name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * Binds an object to a supplied String key.
+     * @see javax.naming.InitialContext#bind(java.lang.String, java.lang.Object)
+     */
+    public void bind( String name, Object obj ) throws NamingException
+    {
+        m_bindings.put( name, obj );
+    }
+
+    /**
+     * Retrieves an object using a String key. If not found, 
+     * throws a NamingException.
+     * @see javax.naming.InitialContext#lookup(java.lang.String)
+     */
+    public Object lookup( String name ) throws NamingException
+    {
+        Object obj = m_bindings.get( name );
+        if( obj == null )
+        {
+            throw new NamingException( "Object named '" + name + "' not found in JNDI context." );
+        }
+        return obj;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#lookupLink(javax.naming.Name)
+     */
+    public Object lookupLink( Name name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#lookupLink(java.lang.String)
+     */
+    public Object lookupLink( String name ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op.
+     * @see javax.naming.Context#rebind(javax.naming.Name, java.lang.Object)
+     */
+    public void rebind( Name name, Object obj ) throws NamingException
+    {
+    }
+
+    /**
+     * No-op.
+     * @see javax.naming.Context#rebind(java.lang.String, java.lang.Object)
+     */
+    public void rebind( String name, Object obj ) throws NamingException
+    {
+    }
+
+    /**
+     * No-op; always returns <code>null</code>.
+     * @see javax.naming.Context#removeFromEnvironment(java.lang.String)
+     */
+    public Object removeFromEnvironment( String propName ) throws NamingException
+    {
+        return null;
+    }
+
+    /**
+     * No-op.
+     * @see javax.naming.Context#rename(javax.naming.Name, javax.naming.Name)
+     */
+    public void rename( Name oldName, Name newName ) throws NamingException
+    {
+    }
+
+    /**
+     * No-op.
+     * @see javax.naming.Context#rename(java.lang.String, java.lang.String)
+     */
+    public void rename( String oldName, String newName ) throws NamingException
+    {
+    }
+
+    /**
+     * No-op.
+     * @see javax.naming.Context#unbind(javax.naming.Name)
+     */
+    public void unbind( Name name ) throws NamingException
+    {
+    }
+
+    /**
+     * No-op.
+     * @see javax.naming.Context#unbind(java.lang.String)
+     */
+    public void unbind( String name ) throws NamingException
+    {
+    }
+}

Added: incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/TextUtilTest.java
URL: http://svn.apache.org/viewvc/incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/TextUtilTest.java?rev=627271&view=auto
==============================================================================
--- incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/TextUtilTest.java (added)
+++ incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/TextUtilTest.java Tue Feb 12 22:24:02 2008
@@ -0,0 +1,317 @@
+
+package com.ecyrd.jspwiki;
+
+import junit.framework.*;
+import java.util.*;
+
+public class TextUtilTest extends TestCase
+{
+
+    public TextUtilTest( String s )
+    {
+        super( s );
+    }
+
+    public void setUp()
+        throws Exception
+    {
+    }
+
+    public void tearDown()
+    {
+    }
+
+    public void testEncodeName_1()
+    {
+        String name = "Hello/World";
+
+        assertEquals( "Hello/World",
+                      TextUtil.urlEncode(name,"ISO-8859-1") );
+    }
+
+    public void testEncodeName_2()
+    {
+        String name = "Hello~World";
+
+        assertEquals( "Hello%7EWorld",
+                      TextUtil.urlEncode(name,"ISO-8859-1") );
+    }
+
+    public void testEncodeName_3()
+    {
+        String name = "Hello/World ~";
+
+        assertEquals( "Hello/World+%7E",
+                      TextUtil.urlEncode(name,"ISO-8859-1") );
+    }
+
+    public void testDecodeName_1()
+         throws Exception
+    {
+        String name = "Hello/World+%7E+%2F";
+
+        assertEquals( "Hello/World ~ /",
+                      TextUtil.urlDecode(name,"ISO-8859-1") );
+    }
+
+    public void testEncodeNameUTF8_1()
+    {
+        String name = "\u0041\u2262\u0391\u002E";
+
+        assertEquals( "A%E2%89%A2%CE%91.",
+                      TextUtil.urlEncodeUTF8(name) );
+    }
+
+    public void testEncodeNameUTF8_2()
+    {
+        String name = "\uD55C\uAD6D\uC5B4";
+
+        assertEquals( "%ED%95%9C%EA%B5%AD%EC%96%B4",
+                      TextUtil.urlEncodeUTF8(name) );
+    }
+
+    public void testEncodeNameUTF8_3()
+    {
+        String name = "\u65E5\u672C\u8A9E";
+
+        assertEquals( "%E6%97%A5%E6%9C%AC%E8%AA%9E",
+                      TextUtil.urlEncodeUTF8(name) );
+    }
+
+    public void testEncodeNameUTF8_4()
+    {
+        String name = "Hello World";
+
+        assertEquals( "Hello+World",
+                      TextUtil.urlEncodeUTF8(name) );
+    }
+
+    public void testDecodeNameUTF8_1()
+    {
+        String name = "A%E2%89%A2%CE%91.";
+
+        assertEquals( "\u0041\u2262\u0391\u002E",
+                      TextUtil.urlDecodeUTF8(name) );
+    }
+
+    public void testDecodeNameUTF8_2()
+    {
+        String name = "%ED%95%9C%EA%B5%AD%EC%96%B4";
+
+        assertEquals( "\uD55C\uAD6D\uC5B4",
+                      TextUtil.urlDecodeUTF8(name) );
+    }
+
+    public void testDecodeNameUTF8_3()
+    {
+        String name = "%E6%97%A5%E6%9C%AC%E8%AA%9E";
+
+        assertEquals( "\u65E5\u672C\u8A9E",
+                      TextUtil.urlDecodeUTF8(name) );
+    }
+
+    public void testReplaceString1()
+    {
+        String text = "aabacaa";
+
+        assertEquals( "ddbacdd", TextUtil.replaceString( text, "aa", "dd" ) ); 
+    }
+
+    public void testReplaceString4()
+    {
+        String text = "aabacaafaa";
+
+        assertEquals( "ddbacddfdd", TextUtil.replaceString( text, "aa", "dd" ) ); 
+    }
+
+    public void testReplaceString5()
+    {
+        String text = "aaabacaaafaa";
+
+        assertEquals( "dbacdfaa", TextUtil.replaceString( text, "aaa", "d" ) );     
+    }
+
+    public void testReplaceString2()
+    {
+        String text = "abcde";
+
+        assertEquals( "fbcde", TextUtil.replaceString( text, "a", "f" ) ); 
+    }
+
+    public void testReplaceString3()
+    {
+        String text = "ababab";
+
+        assertEquals( "afafaf", TextUtil.replaceString( text, "b", "f" ) ); 
+    }
+
+    // Pure UNIX.
+    public void testNormalizePostdata1()
+    {
+        String text = "ab\ncd";
+
+        assertEquals( "ab\r\ncd\r\n", TextUtil.normalizePostData( text ) );
+    }
+
+    // Pure MSDOS.
+    public void testNormalizePostdata2()
+    {
+        String text = "ab\r\ncd";
+
+        assertEquals( "ab\r\ncd\r\n", TextUtil.normalizePostData( text ) );
+    }
+
+    // Pure Mac
+    public void testNormalizePostdata3()
+    {
+        String text = "ab\rcd";
+
+        assertEquals( "ab\r\ncd\r\n", TextUtil.normalizePostData( text ) );
+    }
+
+    // Mixed, ending correct.
+    public void testNormalizePostdata4()
+    {
+        String text = "ab\ncd\r\n\r\n\r";
+
+        assertEquals( "ab\r\ncd\r\n\r\n\r\n", TextUtil.normalizePostData( text ) );
+    }
+
+    // Multiple newlines
+    public void testNormalizePostdata5()
+    {
+        String text = "ab\ncd\n\n\n\n";
+
+        assertEquals( "ab\r\ncd\r\n\r\n\r\n\r\n", TextUtil.normalizePostData( text ) );
+    }
+
+    // Empty.
+    public void testNormalizePostdata6()
+    {
+        String text = "";
+
+        assertEquals( "\r\n", TextUtil.normalizePostData( text ) );
+    }
+
+    // Just a newline.
+    public void testNormalizePostdata7()
+    {
+        String text = "\n";
+
+        assertEquals( "\r\n", TextUtil.normalizePostData( text ) );
+    }
+
+    public void testGetBooleanProperty()
+    {
+        Properties props = new Properties();
+
+        props.setProperty("foobar.0", "YES");
+        props.setProperty("foobar.1", "true");
+        props.setProperty("foobar.2", "false");
+        props.setProperty("foobar.3", "no");
+        props.setProperty("foobar.4", "on");
+        props.setProperty("foobar.5", "OFF");
+        props.setProperty("foobar.6", "gewkjoigew");
+
+        assertTrue( "foobar.0", 
+                    TextUtil.getBooleanProperty( props, "foobar.0", false ) );
+        assertTrue( "foobar.1", 
+                    TextUtil.getBooleanProperty( props, "foobar.1", false ) );
+
+        assertFalse( "foobar.2", 
+                     TextUtil.getBooleanProperty( props, "foobar.2", true ) );
+        assertFalse( "foobar.3", 
+                    TextUtil.getBooleanProperty( props, "foobar.3", true ) );
+        assertTrue( "foobar.4", 
+                    TextUtil.getBooleanProperty( props, "foobar.4", false ) );
+
+        assertFalse( "foobar.5", 
+                     TextUtil.getBooleanProperty( props, "foobar.5", true ) );
+
+        assertFalse( "foobar.6", 
+                     TextUtil.getBooleanProperty( props, "foobar.6", true ) );
+
+
+    }
+
+    public void testGetSection1()
+        throws Exception
+    {
+        String src = "Single page.";
+
+        assertEquals( "section 1", src, TextUtil.getSection(src,1) );
+
+        try
+        {
+            TextUtil.getSection( src, 5 );
+            fail("Did not get exception for 2");
+        }
+        catch( IllegalArgumentException e ) {}
+
+        try
+        {
+            TextUtil.getSection( src, -1 );
+            fail("Did not get exception for -1");
+        }
+        catch( IllegalArgumentException e ) {}
+    }
+
+    public void testGetSection2()
+        throws Exception
+    {
+        String src = "First section\n----\nSecond section\n\n----\n\nThird section";
+
+        assertEquals( "section 1", "First section\n", TextUtil.getSection(src,1) );
+        assertEquals( "section 2", "\nSecond section\n\n", TextUtil.getSection(src,2) );
+        assertEquals( "section 3", "\n\nThird section", TextUtil.getSection(src,3) );
+
+        try
+        {
+            TextUtil.getSection( src, 4 );
+            fail("Did not get exception for section 4");
+        }
+        catch( IllegalArgumentException e ) {}
+    }
+
+    public void testGetSection3()
+        throws Exception
+    {
+        String src = "----\nSecond section\n----";
+
+        
+        assertEquals( "section 1", "", TextUtil.getSection(src,1) );
+        assertEquals( "section 2", "\nSecond section\n", TextUtil.getSection(src,2) );
+        assertEquals( "section 3", "", TextUtil.getSection(src,3) );
+
+        try
+        {
+            TextUtil.getSection( src, 4 );
+            fail("Did not get exception for section 4");
+        }
+        catch( IllegalArgumentException e ) {}
+    }
+
+    public void testBooleanParameter()
+       throws Exception
+    {
+        assertEquals( "1", true, TextUtil.isPositive(" true ") );
+        assertEquals( "2", false, TextUtil.isPositive(" fewqkfow kfpokwe ") );
+        assertEquals( "3", true, TextUtil.isPositive("on") );
+        assertEquals( "4", true, TextUtil.isPositive("\t\ton") );
+    }
+    
+    public void testTrimmedProperty()
+    {
+        String[] vals = { "foo", " this is a property ", "bar", "60" };
+        
+        Properties props = TextUtil.createProperties(vals);
+        
+        assertEquals( "foo", "this is a property", TextUtil.getStringProperty(props,"foo","") );
+        assertEquals( "bar", 60, TextUtil.getIntegerProperty(props,"bar",0) );
+    }
+    
+    public static Test suite()
+    {
+        return new TestSuite( TextUtilTest.class );
+    }
+}

Added: incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/Util.java
URL: http://svn.apache.org/viewvc/incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/Util.java?rev=627271&view=auto
==============================================================================
--- incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/Util.java (added)
+++ incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/Util.java Tue Feb 12 22:24:02 2008
@@ -0,0 +1,26 @@
+package com.ecyrd.jspwiki;
+
+import java.util.*;
+
+/**
+ * Utilities for tests.
+ */
+public class Util
+{
+    /**
+     * Check that a collection contains the required string.
+     */
+    public static boolean collectionContains( Collection container,
+                                              String captive )
+    {
+        Iterator i = container.iterator();
+        while( i.hasNext() )
+        {
+            Object cap = i.next();
+            if( cap instanceof String && captive.equals( cap ) )
+                return true;
+        }
+
+        return false;
+    }
+}

Added: incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/VariableManagerTest.java
URL: http://svn.apache.org/viewvc/incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/VariableManagerTest.java?rev=627271&view=auto
==============================================================================
--- incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/VariableManagerTest.java (added)
+++ incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/VariableManagerTest.java Tue Feb 12 22:24:02 2008
@@ -0,0 +1,171 @@
+
+package com.ecyrd.jspwiki;
+
+import junit.framework.*;
+import java.io.*;
+import java.util.*;
+import org.apache.log4j.*;
+
+public class VariableManagerTest extends TestCase
+{
+    VariableManager m_variableManager;
+    WikiContext     m_context;
+
+    static final String PAGE_NAME = "TestPage";
+
+    public VariableManagerTest( String s )
+    {
+        super( s );
+    }
+
+    public void setUp()
+        throws Exception
+    {
+        Properties props = new Properties();
+        try
+        {
+            props.load( TestEngine.findTestProperties() );
+            PropertyConfigurator.configure(props);
+
+            m_variableManager = new VariableManager( props );
+            TestEngine testEngine = new TestEngine( props );
+            m_context = testEngine.getWikiActionBeanFactory().newViewActionBean( new WikiPage( testEngine, PAGE_NAME ) );
+
+        }
+        catch( IOException e ) {}
+    }
+
+    public void tearDown()
+    {
+    }
+
+    public void testIllegalInsert1()
+        throws Exception
+    {
+        try
+        {
+            m_variableManager.parseAndGetValue( m_context, "" );
+            fail( "Did not fail" );
+        }
+        catch( IllegalArgumentException e )
+        {
+            // OK.
+        }
+    }
+
+    public void testIllegalInsert2()
+        throws Exception
+    {
+        try
+        {
+            m_variableManager.parseAndGetValue( m_context, "{$" );
+            fail( "Did not fail" );
+        }
+        catch( IllegalArgumentException e )
+        {
+            // OK.
+        }
+    }
+
+    public void testIllegalInsert3()
+        throws Exception
+    {
+        try
+        {
+            m_variableManager.parseAndGetValue( m_context, "{$pagename" );
+            fail( "Did not fail" );
+        }
+        catch( IllegalArgumentException e )
+        {
+            // OK.
+        }
+    }
+
+    public void testIllegalInsert4()
+        throws Exception
+    {
+        try
+        {
+            m_variableManager.parseAndGetValue( m_context, "{$}" );
+            fail( "Did not fail" );
+        }
+        catch( IllegalArgumentException e )
+        {
+            // OK.
+        }
+    }
+
+    public void testNonExistantVariable()
+    {
+        try
+        {
+            m_variableManager.parseAndGetValue( m_context, "{$no_such_variable}" );
+            fail( "Did not fail" );
+        }
+        catch( NoSuchVariableException e )
+        {
+            // OK.
+        }
+    }
+
+    public void testPageName()
+        throws Exception
+    {
+        String res = m_variableManager.getValue( m_context, "pagename" );
+
+        assertEquals( PAGE_NAME, res );
+    }
+
+    public void testPageName2()
+        throws Exception
+    {
+        String res =  m_variableManager.parseAndGetValue( m_context, "{$  pagename  }" );
+
+        assertEquals( PAGE_NAME, res );
+    }
+
+    public void testMixedCase()
+        throws Exception
+    {
+        String res =  m_variableManager.parseAndGetValue( m_context, "{$PAGeNamE}" );
+
+        assertEquals( PAGE_NAME, res );
+    }
+
+    public void testExpand1()
+        throws Exception
+    {
+        String res = m_variableManager.expandVariables( m_context, "Testing {$pagename}..." );
+
+        assertEquals( "Testing "+PAGE_NAME+"...", res );
+    }
+
+    public void testExpand2()
+        throws Exception
+    {
+        String res = m_variableManager.expandVariables( m_context, "{$pagename} tested..." );
+
+        assertEquals( PAGE_NAME+" tested...", res );
+    }
+
+    public void testExpand3()
+        throws Exception
+    {
+        String res = m_variableManager.expandVariables( m_context, "Testing {$pagename}, {$applicationname}" );
+
+        assertEquals( "Testing "+PAGE_NAME+", JSPWiki", res );
+    }
+
+    public void testExpand4()
+        throws Exception
+    {
+        String res = m_variableManager.expandVariables( m_context, "Testing {}, {{{}" );
+
+        assertEquals( "Testing {}, {{{}", res );
+    }
+
+    public static Test suite()
+    {
+        return new TestSuite( VariableManagerTest.class );
+    }
+}

Added: incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/WikiEngineTest.java
URL: http://svn.apache.org/viewvc/incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/WikiEngineTest.java?rev=627271&view=auto
==============================================================================
--- incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/WikiEngineTest.java (added)
+++ incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/WikiEngineTest.java Tue Feb 12 22:24:02 2008
@@ -0,0 +1,931 @@
+
+package com.ecyrd.jspwiki;
+
+import junit.framework.*;
+import java.io.*;
+import java.util.*;
+
+import com.ecyrd.jspwiki.providers.*;
+import com.ecyrd.jspwiki.attachment.*;
+
+public class WikiEngineTest extends TestCase
+{
+    public static final String NAME1 = "Test1";
+    public static final long PAGEPROVIDER_RESCAN_PERIOD = 2;
+
+    Properties props = new Properties();
+
+    TestEngine m_engine;
+
+
+    public WikiEngineTest( String s )
+    {
+        super( s );
+    }
+
+    public static Test suite()
+    {
+        return new TestSuite( WikiEngineTest.class );
+    }
+
+    public static void main(String[] args)
+    {
+        junit.textui.TestRunner.main(new String[] { WikiEngineTest.class.getName() } );
+    }
+
+    public void setUp()
+        throws Exception
+    {
+        props.load( TestEngine.findTestProperties() );
+
+        props.setProperty( WikiEngine.PROP_MATCHPLURALS, "true" );
+        // We'll need a shorter-than-default consistency check for
+        // the page-changed checks. This will cause additional load
+        // to the file system, though.
+        props.setProperty( CachingProvider.PROP_CACHECHECKINTERVAL, 
+                           Long.toString(PAGEPROVIDER_RESCAN_PERIOD) );
+
+        TestEngine.emptyWorkDir();
+        m_engine = new TestEngine(props);        
+    }
+
+    public void tearDown()
+    {
+        String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+
+        if( files != null )
+        {
+            File f = new File( files );
+
+            TestEngine.deleteAll( f );
+        }
+
+        TestEngine.emptyWorkDir();
+    }
+    
+    public void testNonExistantDirectory()
+        throws Exception
+    {
+        String tmpdir = System.getProperties().getProperty("java.io.tmpdir");
+        String dirname = "non-existant-directory";
+
+        String newdir = tmpdir + File.separator + dirname;
+
+        props.setProperty( FileSystemProvider.PROP_PAGEDIR, 
+                           newdir );
+
+        new TestEngine( props );
+
+        File f = new File( newdir );
+
+        assertTrue( "didn't create it", f.exists() );
+        assertTrue( "isn't a dir", f.isDirectory() );
+
+        f.delete();
+    }
+
+    public void testNonExistantDirProperty()
+        throws Exception
+    {
+        props.remove( FileSystemProvider.PROP_PAGEDIR );
+
+        try
+        {
+            new TestEngine( props );
+
+            fail( "Wiki did not warn about missing property." );
+        }
+        catch( WikiException e )
+        {
+            // This is okay.
+        }
+    }
+
+    /**
+     *  Check that calling pageExists( String ) works.
+     */
+    public void testNonExistantPage()
+        throws Exception
+    {
+        String pagename = "Test1";
+
+        assertEquals( "Page already exists",
+                      false,
+                      m_engine.pageExists( pagename ) );
+    }
+
+    /**
+     *  Check that calling pageExists( WikiPage ) works.
+     */
+    public void testNonExistantPage2()
+        throws Exception
+    {
+        WikiPage page = new WikiPage(m_engine, "Test1");
+
+        assertEquals( "Page already exists",
+                      false,
+                      m_engine.pageExists( page ) );
+    }
+
+    public void testFinalPageName()
+        throws Exception
+    {
+        m_engine.saveText( "Foobar", "1" );
+        m_engine.saveText( "Foobars", "2" );
+
+        assertEquals( "plural mistake", "Foobars",
+                      m_engine.getFinalPageName( "Foobars" ) );
+
+        assertEquals( "singular mistake", "Foobar",
+                      m_engine.getFinalPageName( "Foobar" ) );
+    }
+
+    public void testFinalPageNameSingular()
+        throws Exception
+    {
+        m_engine.saveText( "Foobar", "1" );
+
+        assertEquals( "plural mistake", "Foobar",
+                      m_engine.getFinalPageName( "Foobars" ) );
+        assertEquals( "singular mistake", "Foobar",
+                      m_engine.getFinalPageName( "Foobar" ) );
+    }
+
+    public void testFinalPageNamePlural()
+        throws Exception
+    {
+        m_engine.saveText( "Foobars", "1" );
+
+        assertEquals( "plural mistake", "Foobars",
+                      m_engine.getFinalPageName( "Foobars" ) );
+        assertEquals( "singular mistake", "Foobars",
+                      m_engine.getFinalPageName( "Foobar" ) );
+    }
+    
+    public void testPutPage()
+        throws Exception
+    {
+        String text = "Foobar.\r\n";
+        String name = NAME1;
+
+        m_engine.saveText( name, text );
+
+        assertEquals( "page does not exist",
+                      true,
+                      m_engine.pageExists( name ) );
+
+        assertEquals( "wrong content",
+                      text,
+                      m_engine.getText( name ) );
+    }
+
+    public void testPutPageEntities()
+        throws Exception
+    {
+        String text = "Foobar. &quot;\r\n";
+        String name = NAME1;
+
+        m_engine.saveText( name, text );
+
+        assertEquals( "page does not exist",
+                      true,
+                      m_engine.pageExists( name ) );
+
+        assertEquals( "wrong content",
+                      "Foobar. &amp;quot;\r\n",
+                      m_engine.getText( name ) );
+    }
+
+    /**
+     *  Cgeck that basic " is changed.
+     */
+    public void testPutPageEntities2()
+        throws Exception
+    {
+        String text = "Foobar. \"\r\n";
+        String name = NAME1;
+
+        m_engine.saveText( name, text );
+
+        assertEquals( "page does not exist",
+                      true,
+                      m_engine.pageExists( name ) );
+
+        assertEquals( "wrong content",
+                      "Foobar. &quot;\r\n",
+                      m_engine.getText( name ) );
+    }
+
+    public void testGetHTML()
+        throws Exception
+    {
+        String text = "''Foobar.''";
+        String name = NAME1;
+
+        m_engine.saveText( name, text );
+
+        String data = m_engine.getHTML( name );
+
+        assertEquals( "<i>Foobar.</i>\n",
+                       data );
+    }
+
+    public void testEncodeNameLatin1()
+    {
+        String name = "abc\u00e5\u00e4\u00f6";
+
+        assertEquals( "abc%E5%E4%F6",
+                      m_engine.encodeName(name) );
+    }
+
+    public void testEncodeNameUTF8()
+        throws Exception
+    {
+        String name = "\u0041\u2262\u0391\u002E";
+
+        props.setProperty( WikiEngine.PROP_ENCODING, "UTF-8" );
+
+        WikiEngine engine = new TestEngine( props );
+
+        assertEquals( "A%E2%89%A2%CE%91.",
+                      engine.encodeName(name) );
+    }
+
+    public void testReadLinks()
+        throws Exception
+    {
+        String src="Foobar. [Foobar].  Frobozz.  [This is a link].";
+
+        Object[] result = m_engine.scanWikiLinks( new WikiPage(m_engine, "Test"), src ).toArray();
+        
+        assertEquals( "item 0", "Foobar", result[0] );
+        assertEquals( "item 1", "This is a link", result[1] );
+    }
+
+    public void testBeautifyTitle()
+    {
+        String src = "WikiNameThingy";
+
+        assertEquals("Wiki Name Thingy", m_engine.beautifyTitle( src ) );
+    }
+
+    /**
+     *  Acronyms should be treated wisely.
+     */
+    public void testBeautifyTitleAcronym()
+    {
+        String src = "JSPWikiPage";
+
+        assertEquals("JSP Wiki Page", m_engine.beautifyTitle( src ) );
+    }
+
+    /**
+     *  Acronyms should be treated wisely.
+     */
+    public void testBeautifyTitleAcronym2()
+    {
+        String src = "DELETEME";
+
+        assertEquals("DELETEME", m_engine.beautifyTitle( src ) );
+    }
+
+    public void testBeautifyTitleAcronym3()
+    {
+        String src = "JSPWikiFAQ";
+
+        assertEquals("JSP Wiki FAQ", m_engine.beautifyTitle( src ) );
+    }
+
+    public void testBeautifyTitleNumbers()
+    {
+        String src = "TestPage12";
+
+        assertEquals("Test Page 12", m_engine.beautifyTitle( src ) );
+    }
+
+    /**
+     *  English articles too.
+     */
+    public void testBeautifyTitleArticle()
+    {
+        String src = "ThisIsAPage";
+
+        assertEquals("This Is A Page", m_engine.beautifyTitle( src ) );
+    }
+
+    /**
+     *  English articles too, pathological case...
+     */
+    /*
+    public void testBeautifyTitleArticle2()
+    {
+        String src = "ThisIsAJSPWikiPage";
+
+        assertEquals("This Is A JSP Wiki Page", m_engine.beautifyTitle( src ) );
+    }
+    */
+
+    public void testLatestGet()
+        throws Exception
+    {
+        props.setProperty( "jspwiki.pageProvider", 
+                           "com.ecyrd.jspwiki.providers.VerySimpleProvider" );
+        props.setProperty( "jspwiki.usePageCache", "false" );
+
+        WikiEngine engine = new TestEngine( props );
+
+        WikiPage p = engine.getPage( "test", -1 );
+
+        VerySimpleProvider vsp = (VerySimpleProvider) engine.getPageManager().getProvider();
+
+        assertEquals( "wrong page", "test", vsp.m_latestReq );
+        assertEquals( "wrong version", -1, vsp.m_latestVers );
+        assertNotNull("null", p);
+    }
+
+    public void testLatestGet2()
+        throws Exception
+    {
+        props.setProperty( "jspwiki.pageProvider", 
+                           "com.ecyrd.jspwiki.providers.VerySimpleProvider" );
+        props.setProperty( "jspwiki.usePageCache", "false" );
+
+        WikiEngine engine = new TestEngine( props );
+
+        String p = engine.getText( "test", -1 );
+
+        VerySimpleProvider vsp = (VerySimpleProvider) engine.getPageManager().getProvider();
+
+        assertEquals( "wrong page", "test", vsp.m_latestReq );
+        assertEquals( "wrong version", -1, vsp.m_latestVers );
+        assertNotNull("null", p);
+    }
+
+    public void testLatestGet3()
+        throws Exception
+    {
+        props.setProperty( "jspwiki.pageProvider", 
+                           "com.ecyrd.jspwiki.providers.VerySimpleProvider" );
+        props.setProperty( "jspwiki.usePageCache", "false" );
+
+        WikiEngine engine = new TestEngine( props );
+
+        String p = engine.getHTML( "test", -1 );
+
+        VerySimpleProvider vsp = (VerySimpleProvider) engine.getPageManager().getProvider();
+
+        assertEquals( "wrong page", "test", vsp.m_latestReq );
+        assertEquals( "wrong version", 5, vsp.m_latestVers );
+        assertNotNull("null", p);
+    }
+
+    public void testLatestGet4()
+        throws Exception
+    {
+        props.setProperty( "jspwiki.pageProvider", 
+                           "com.ecyrd.jspwiki.providers.VerySimpleProvider" );
+        props.setProperty( "jspwiki.usePageCache", "true" );
+
+        WikiEngine engine = new TestEngine( props );
+
+        String p = engine.getHTML( VerySimpleProvider.PAGENAME, -1 );
+
+        CachingProvider cp = (CachingProvider)engine.getPageManager().getProvider();
+        VerySimpleProvider vsp = (VerySimpleProvider) cp.getRealProvider();
+
+        assertEquals( "wrong page", VerySimpleProvider.PAGENAME, vsp.m_latestReq );
+        assertEquals( "wrong version", -1, vsp.m_latestVers );
+        assertNotNull("null", p);
+    }
+
+    /**
+     *  Checks, if ReferenceManager is informed of new attachments.
+     */
+    public void testAttachmentRefs()
+        throws Exception
+    {
+        ReferenceManager refMgr = m_engine.getReferenceManager();
+        AttachmentManager attMgr = m_engine.getAttachmentManager();
+        
+        m_engine.saveText( NAME1, "fooBar");
+
+        Attachment att = new Attachment( m_engine, NAME1, "TestAtt.txt" );
+        att.setAuthor( "FirstPost" );
+        attMgr.storeAttachment( att, m_engine.makeAttachmentFile() );
+
+        try
+        {    
+            // and check post-conditions        
+            Collection c = refMgr.findUncreated();
+            assertTrue("attachment exists: "+c,            
+                       c==null || c.size()==0 );
+    
+            c = refMgr.findUnreferenced();
+            assertEquals( "unreferenced count", 2, c.size() );
+            Iterator i = c.iterator();
+            String first = (String) i.next();
+            String second = (String) i.next();
+            assertTrue( "unreferenced",            
+                        (first.equals( NAME1 ) && second.equals( NAME1+"/TestAtt.txt"))
+                        || (first.equals( NAME1+"/TestAtt.txt" ) && second.equals( NAME1 )) );
+        }
+        finally
+        { 
+            // do cleanup
+            String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+            TestEngine.deleteAll( new File( files, NAME1+BasicAttachmentProvider.DIR_EXTENSION ) );
+        }
+    }
+
+    /**
+     *  Is ReferenceManager updated properly if a page references 
+     *  its own attachments?
+     */
+
+    /*
+      FIXME: This is a deep problem.  The real problem is that the reference
+      manager cannot know when it encounters a link like "testatt.txt" that it
+      is really a link to an attachment IF the link is created before
+      the attachment.  This means that when the attachment is created,
+      the link will stay in the "uncreated" list.
+
+      There are two issues here: first of all, TranslatorReader should
+      able to return the proper attachment references (which I think
+      it does), and second, the ReferenceManager should be able to
+      remove any links that are not referred to, nor they are created.
+
+      However, doing this in a relatively sane timeframe can be a problem.
+    */
+
+    public void testAttachmentRefs2()
+        throws Exception
+    {
+        ReferenceManager refMgr = m_engine.getReferenceManager();
+        AttachmentManager attMgr = m_engine.getAttachmentManager();
+        
+        m_engine.saveText( NAME1, "[TestAtt.txt]");
+
+        // check a few pre-conditions
+        
+        Collection c = refMgr.findReferrers( "TestAtt.txt" );
+        assertTrue( "normal, unexisting page", 
+                    c!=null && ((String)c.iterator().next()).equals( NAME1 ) );
+        
+        c = refMgr.findReferrers( NAME1+"/TestAtt.txt" );
+        assertTrue( "no attachment", c==null || c.size()==0 );
+        
+        c = refMgr.findUncreated();
+        assertTrue( "unknown attachment", 
+                    c!=null && 
+                    c.size()==1 && 
+                    ((String)c.iterator().next()).equals( "TestAtt.txt" ) );
+        
+        // now we create the attachment
+            
+        Attachment att = new Attachment( m_engine, NAME1, "TestAtt.txt" );
+        att.setAuthor( "FirstPost" );
+        attMgr.storeAttachment( att, m_engine.makeAttachmentFile() );
+        try
+        {    
+            // and check post-conditions        
+            c = refMgr.findUncreated();
+            assertTrue( "attachment exists: ",            
+                        c==null || c.size()==0 );
+    
+            c = refMgr.findReferrers( "TestAtt.txt" );
+            assertTrue( "no normal page", c==null || c.size()==0 );
+    
+            c = refMgr.findReferrers( NAME1+"/TestAtt.txt" );
+            assertTrue( "attachment exists now", c!=null && ((String)c.iterator().next()).equals( NAME1 ) );
+
+            c = refMgr.findUnreferenced();
+            assertTrue( "unreferenced",            
+                        c.size()==1 && ((String)c.iterator().next()).equals( NAME1 ));
+        }
+        finally
+        { 
+            // do cleanup
+            String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+            TestEngine.deleteAll( new File( files, NAME1+BasicAttachmentProvider.DIR_EXTENSION ) );
+        }
+    }
+
+    /** 
+     *  Checks, if ReferenceManager is informed if a link to an attachment is added.
+     */
+    public void testAttachmentRefs3()
+        throws Exception
+    {
+        ReferenceManager refMgr = m_engine.getReferenceManager();
+        AttachmentManager attMgr = m_engine.getAttachmentManager();
+        
+        m_engine.saveText( NAME1, "fooBar");
+
+        Attachment att = new Attachment( m_engine, NAME1, "TestAtt.txt" );
+        att.setAuthor( "FirstPost" );
+        attMgr.storeAttachment( att, m_engine.makeAttachmentFile() );
+
+        m_engine.saveText( NAME1, " ["+NAME1+"/TestAtt.txt] ");
+
+        try
+        {    
+            // and check post-conditions        
+            Collection c = refMgr.findUncreated();
+            assertTrue( "attachment exists",            
+                        c==null || c.size()==0 );
+    
+            c = refMgr.findUnreferenced();
+            assertEquals( "unreferenced count", c.size(), 1 );
+            assertTrue( "unreferenced",            
+                        ((String)c.iterator().next()).equals( NAME1 ) );
+        }
+        finally
+        { 
+            // do cleanup
+            String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+            TestEngine.deleteAll( new File( files, NAME1+BasicAttachmentProvider.DIR_EXTENSION ) );
+        }
+    }
+    
+    /** 
+     *  Checks, if ReferenceManager is informed if a third page references an attachment.
+     */
+    public void testAttachmentRefs4()
+        throws Exception
+    {
+        ReferenceManager refMgr = m_engine.getReferenceManager();
+        AttachmentManager attMgr = m_engine.getAttachmentManager();
+        
+        m_engine.saveText( NAME1, "[TestPage2]");
+
+        Attachment att = new Attachment( m_engine, NAME1, "TestAtt.txt" );
+        att.setAuthor( "FirstPost" );
+        attMgr.storeAttachment( att, m_engine.makeAttachmentFile() );
+
+        m_engine.saveText( "TestPage2", "["+NAME1+"/TestAtt.txt]");
+
+        try
+        {    
+            // and check post-conditions        
+            Collection c = refMgr.findUncreated();
+            assertTrue( "attachment exists",            
+                        c==null || c.size()==0 );
+    
+            c = refMgr.findUnreferenced();
+            assertEquals( "unreferenced count", c.size(), 1 );
+            assertTrue( "unreferenced",            
+                        ((String)c.iterator().next()).equals( NAME1 ) );
+        }
+        finally
+        { 
+            // do cleanup
+            String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+            TestEngine.deleteAll( new File( files, NAME1+BasicAttachmentProvider.DIR_EXTENSION ) );
+            new File( files, "TestPage2"+FileSystemProvider.FILE_EXT ).delete();
+        }
+    }    
+
+
+    
+
+    public void testDeletePage()
+        throws Exception
+    {
+        m_engine.saveText( NAME1, "Test" );
+
+        String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+        File saved = new File( files, NAME1+FileSystemProvider.FILE_EXT );
+
+        assertTrue( "Didn't create it!", saved.exists() );
+
+        WikiPage page = m_engine.getPage( NAME1, WikiProvider.LATEST_VERSION );
+
+        m_engine.deletePage( page.getName() );
+
+        assertFalse( "Page has not been removed!", saved.exists() );
+    }
+
+
+    public void testDeletePageAndAttachments()
+        throws Exception
+    {
+        m_engine.saveText( NAME1, "Test" );
+
+        Attachment att = new Attachment( m_engine, NAME1, "TestAtt.txt" );
+        att.setAuthor( "FirstPost" );
+        m_engine.getAttachmentManager().storeAttachment( att, m_engine.makeAttachmentFile() );
+        
+        String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+        File saved = new File( files, NAME1+FileSystemProvider.FILE_EXT );
+
+        String atts = props.getProperty( BasicAttachmentProvider.PROP_STORAGEDIR );
+        File attfile = new File( atts, NAME1+"-att/TestAtt.txt-dir" );
+        
+        assertTrue( "Didn't create it!", saved.exists() );
+
+        assertTrue( "Attachment dir does not exist", attfile.exists() );
+        
+        WikiPage page = m_engine.getPage( NAME1, WikiProvider.LATEST_VERSION );
+
+        m_engine.deletePage( page.getName() );
+
+        assertFalse( "Page has not been removed!", saved.exists() );
+        assertFalse( "Attachment has not been removed", attfile.exists() );
+    }
+
+    public void testDeletePageAndAttachments2()
+        throws Exception
+    {
+        m_engine.saveText( NAME1, "Test" );
+
+        Attachment att = new Attachment( m_engine, NAME1, "TestAtt.txt" );
+        att.setAuthor( "FirstPost" );
+        m_engine.getAttachmentManager().storeAttachment( att, m_engine.makeAttachmentFile() );
+        
+        String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+        File saved = new File( files, NAME1+FileSystemProvider.FILE_EXT );
+
+        String atts = props.getProperty( BasicAttachmentProvider.PROP_STORAGEDIR );
+        File attfile = new File( atts, NAME1+"-att/TestAtt.txt-dir" );
+        
+        assertTrue( "Didn't create it!", saved.exists() );
+
+        assertTrue( "Attachment dir does not exist", attfile.exists() );
+        
+        WikiPage page = m_engine.getPage( NAME1, WikiProvider.LATEST_VERSION );
+
+        assertNotNull( "page", page );
+
+        att = m_engine.getAttachmentManager().getAttachmentInfo(NAME1+"/TestAtt.txt");
+        
+        m_engine.deletePage(att.getName());
+        
+        m_engine.deletePage( NAME1 );
+        
+        assertNull( "Page not removed", m_engine.getPage(NAME1) );
+        assertNull( "Att not removed", m_engine.getPage(NAME1+"/TestAtt.txt") );
+        
+        Collection refs = m_engine.getReferenceManager().findReferrers(NAME1);
+        
+        assertNull( "referrers", refs );
+    }
+    
+    public void testDeleteVersion()
+        throws Exception
+    {
+        props.setProperty( "jspwiki.pageProvider", "VersioningFileProvider" );
+        
+        TestEngine engine = new TestEngine( props );
+        engine.saveText( NAME1, "Test1" );
+        engine.saveText( NAME1, "Test2" );
+        engine.saveText( NAME1, "Test3" );
+
+        WikiPage page = engine.getPage( NAME1, 3 );
+
+        engine.deleteVersion( page );
+        
+        assertNull( "got page", engine.getPage( NAME1, 3 ) );
+        
+        String content = engine.getText( NAME1, WikiProvider.LATEST_VERSION );
+        
+        assertEquals( "content", "Test2", content.trim() );
+    }
+
+    public void testDeleteVersion2()
+        throws Exception
+    {
+        props.setProperty( "jspwiki.pageProvider", "VersioningFileProvider" );
+    
+        TestEngine engine = new TestEngine( props );
+        engine.saveText( NAME1, "Test1" );
+        engine.saveText( NAME1, "Test2" );
+        engine.saveText( NAME1, "Test3" );
+
+        WikiPage page = engine.getPage( NAME1, 1 );
+        
+        engine.deleteVersion( page );
+        
+        assertNull( "got page", engine.getPage( NAME1, 1 ) );
+        
+        String content = engine.getText( NAME1, WikiProvider.LATEST_VERSION );
+        
+        assertEquals( "content", "Test3", content.trim() );
+        
+        assertEquals( "content1", "", engine.getText(NAME1, 1).trim() );
+    }
+    
+    /**
+     *  Assumes that CachingProvider is in use.
+     */
+    public void testExternalModificationRefs()
+        throws Exception
+    {
+        ReferenceManager refMgr = m_engine.getReferenceManager();
+
+        m_engine.saveText( NAME1, "[Foobar]" );
+        m_engine.getText( NAME1 ); // Ensure that page is cached.
+
+        Collection c = refMgr.findUncreated();
+        assertTrue( "Non-existent reference not detected by ReferenceManager",
+            Util.collectionContains( c, "Foobar" ));
+
+        Thread.sleep( 2000L ); // Wait two seconds for filesystem granularity
+
+        String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+
+        File saved = new File( files, NAME1+FileSystemProvider.FILE_EXT );
+
+        assertTrue( "No file!", saved.exists() );
+
+        FileWriter out = new FileWriter( saved );
+        FileUtil.copyContents( new StringReader("[Puppaa]"), out );
+        out.close();
+
+        Thread.sleep( 2000L*PAGEPROVIDER_RESCAN_PERIOD ); // Wait five seconds for CachingProvider to wake up.
+
+        String text = m_engine.getText( NAME1 );
+
+        assertEquals( "wrong contents", "[Puppaa]", text );
+
+        c = refMgr.findUncreated();
+
+        assertTrue( "Non-existent reference after external page change " +
+                    "not detected by ReferenceManager",
+                    Util.collectionContains( c, "Puppaa" ));
+    }
+
+
+    /**
+     *  Assumes that CachingProvider is in use.
+     */
+    public void testExternalModificationRefsDeleted()
+        throws Exception
+    {
+        ReferenceManager refMgr = m_engine.getReferenceManager();
+
+        m_engine.saveText( NAME1, "[Foobar]" );
+        m_engine.getText( NAME1 ); // Ensure that page is cached.
+
+        Collection c = refMgr.findUncreated();
+        assertEquals( "uncreated count", 1, c.size() );
+        assertEquals( "wrong referenced page", "Foobar", (String)c.iterator().next() );
+
+        Thread.sleep( 2000L ); // Wait two seconds for filesystem granularity
+
+        String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+
+        File saved = new File( files, NAME1+FileSystemProvider.FILE_EXT );
+
+        assertTrue( "No file!", saved.exists() );
+
+        saved.delete();
+
+        assertFalse( "File not deleted!", saved.exists() );
+
+        Thread.sleep( 2000L*PAGEPROVIDER_RESCAN_PERIOD ); // Wait five seconds for CachingProvider to catch up.
+
+        WikiPage p = m_engine.getPage( NAME1 );
+
+        assertNull( "Got page!", p );
+
+        String text = m_engine.getText( NAME1 );
+
+        assertEquals( "wrong contents", "", text );
+
+        c = refMgr.findUncreated();
+        assertEquals( "NEW: uncreated count", 0, c.size() );
+    }
+
+    /**
+     *  Assumes that CachingProvider is in use.
+     */
+    public void testExternalModification()
+        throws Exception
+    {
+        m_engine.saveText( NAME1, "Foobar" );
+
+        m_engine.getText( NAME1 ); // Ensure that page is cached.
+
+        Thread.sleep( 2000L ); // Wait two seconds for filesystem granularity
+
+        String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR );
+
+        File saved = new File( files, NAME1+FileSystemProvider.FILE_EXT );
+
+        assertTrue( "No file!", saved.exists() );
+
+        FileWriter out = new FileWriter( saved );
+        FileUtil.copyContents( new StringReader("Puppaa"), out );
+        out.close();
+
+        // Wait for the caching provider to notice a refresh.
+        Thread.sleep( 2000L*PAGEPROVIDER_RESCAN_PERIOD );
+
+        // Trim - engine.saveText() may append a newline.
+        String text = m_engine.getText( NAME1 ).trim();
+        assertEquals( "wrong contents", "Puppaa", text );
+    }
+
+    /**
+     *  Tests BugReadingOfVariableNotWorkingForOlderVersions
+     * @throws Exception
+     */
+    public void testOldVersionVars()
+        throws Exception
+    {   
+        Properties pr = new Properties();
+        pr.load( TestEngine.findTestProperties("/jspwiki_vers.properties"));
+        
+        pr.setProperty( PageManager.PROP_USECACHE, "true" );
+        
+        TestEngine engine = new TestEngine( pr );
+        
+        engine.saveText( NAME1, "[{SET foo=bar}]" );
+    
+        engine.saveText( NAME1, "[{SET foo=notbar}]");
+    
+        WikiPage v1 = engine.getPage( NAME1, 1 );
+        
+        WikiPage v2 = engine.getPage( NAME1, 2 );
+        
+        assertEquals( "V1", "bar", v1.getAttribute("foo") );
+        
+        // FIXME: The following must run as well
+        assertEquals( "V2", "notbar", v2.getAttribute("foo") );
+        
+        engine.deletePage( NAME1 );
+    }
+    
+    public void testSpacedNames1()
+        throws Exception
+    {
+        m_engine.saveText("This is a test", "puppaa");
+        
+        assertEquals( "normal", "puppaa", m_engine.getText("This is a test").trim() );
+        assertEquals( "lowercase", "puppaa", m_engine.getText("this is a test").trim() );
+        assertEquals( "randomcase", "puppaa", m_engine.getText("ThiS Is a teSt").trim() );
+    }
+
+
+    public void testParsedVariables() throws Exception
+    {
+        m_engine.saveText( "TestPage", "[{SET foo=bar}][{SamplePlugin text='{$foo}'}]");
+        
+        String res = m_engine.getHTML( "TestPage" );
+        
+        assertEquals( "bar\n", res );
+    }
+    
+    /**
+     * Tests BugReferenceToRenamedPageNotCleared
+     * 
+     * @throws Exception
+     */
+    public void testRename() throws Exception
+    {
+        m_engine.saveText( "RenameBugTestPage", "Mary had a little generic object" );
+        m_engine.saveText( "OldNameTestPage", "Linked to RenameBugTestPage" );
+       
+        Collection pages = m_engine.getReferenceManager().findReferrers( "RenameBugTestPage" );
+        assertEquals( "has one", "OldNameTestPage", pages.iterator().next() );
+        
+        WikiContext ctx = m_engine.getWikiActionBeanFactory().newViewActionBean( m_engine.getPage("OldNameTestPage") );
+        
+        m_engine.renamePage( ctx, "OldNameTestPage", "NewNameTestPage", true );
+            
+        assertFalse( "did not vanish", m_engine.pageExists( "OldNameTestPage") );
+        assertTrue( "did not appear", m_engine.pageExists( "NewNameTestPage") );
+        
+        pages = m_engine.getReferenceManager().findReferrers( "RenameBugTestPage" );
+        
+        assertEquals( "wrong # of referrers", 1, pages.size() );
+        
+        assertEquals( "has wrong referrer", "NewNameTestPage", pages.iterator().next() );        
+    }
+    
+    public void testChangeNoteOldVersion2() throws Exception
+    {
+        WikiPage p = new WikiPage( m_engine, NAME1 );
+    
+        WikiContext context = m_engine.getWikiActionBeanFactory().newViewActionBean( p );
+
+        context.getPage().setAttribute( WikiPage.CHANGENOTE, "Test change" );
+        
+        m_engine.saveText( context, "test" );
+
+        for( int i = 0; i < 5; i++ )
+        {
+            WikiPage p2 = (WikiPage)m_engine.getPage( NAME1 ).clone();
+            p2.removeAttribute(WikiPage.CHANGENOTE);
+
+            context.setPage( p2 );
+
+            m_engine.saveText( context, "test"+i );
+        }
+
+        WikiPage p3 = m_engine.getPage( NAME1, -1 );
+    
+        assertEquals( null, p3.getAttribute(WikiPage.CHANGENOTE) );
+    }
+
+}

Added: incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/WikiSessionTest.java
URL: http://svn.apache.org/viewvc/incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/WikiSessionTest.java?rev=627271&view=auto
==============================================================================
--- incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/WikiSessionTest.java (added)
+++ incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/WikiSessionTest.java Tue Feb 12 22:24:02 2008
@@ -0,0 +1,306 @@
+package com.ecyrd.jspwiki;
+
+import java.security.Principal;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import javax.servlet.http.Cookie;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+import net.sourceforge.stripes.action.UrlBinding;
+import net.sourceforge.stripes.mock.MockHttpServletRequest;
+import net.sourceforge.stripes.mock.MockHttpSession;
+import net.sourceforge.stripes.mock.MockRoundtrip;
+
+import org.apache.commons.lang.ArrayUtils;
+
+import com.ecyrd.jspwiki.action.ViewActionBean;
+import com.ecyrd.jspwiki.auth.AuthenticationManager;
+import com.ecyrd.jspwiki.auth.Users;
+import com.ecyrd.jspwiki.auth.WikiPrincipal;
+import com.ecyrd.jspwiki.auth.authorize.Role;
+import com.ecyrd.jspwiki.auth.login.CookieAssertionLoginModule;
+
+public class WikiSessionTest extends TestCase
+{
+
+    private TestEngine m_engine = null;
+    
+    protected void setUp() throws Exception
+    {
+        super.setUp();
+        Properties props = new Properties();
+        props.load( TestEngine.findTestProperties() );
+        m_engine = new TestEngine( props );
+    }
+
+    protected void tearDown() throws Exception
+    {
+        super.tearDown();
+    }
+
+    public void testRoles() throws Exception
+    {
+        WikiSession session;
+        Principal[] principals;
+        
+        // Test roles for guest session
+        session = WikiSession.guestSession( m_engine );
+        principals = session.getRoles();
+        assertTrue(  session.isAnonymous() );
+        assertFalse( session.isAuthenticated() );
+        assertTrue(  ArrayUtils.contains( principals, Role.ALL ) );
+        assertTrue(  ArrayUtils.contains( principals, Role.ANONYMOUS ) );
+        assertFalse( ArrayUtils.contains( principals, Role.ASSERTED ) );
+        assertFalse( ArrayUtils.contains( principals, Role.AUTHENTICATED ) );
+        
+        // Test roles for anonymous session
+        
+        session = anonymousSession( m_engine );
+        principals = session.getRoles();
+        assertTrue(  session.isAnonymous() );
+        assertFalse( session.isAuthenticated() );
+        assertTrue(  ArrayUtils.contains( principals, Role.ALL ) );
+        assertTrue(  ArrayUtils.contains( principals, Role.ANONYMOUS ) );
+        assertFalse( ArrayUtils.contains( principals, Role.ASSERTED ) );
+        assertFalse( ArrayUtils.contains( principals, Role.AUTHENTICATED ) );
+        
+        // Test roles for authenticated session
+        session = authenticatedSession( m_engine, 
+                                        Users.JANNE, 
+                                        Users.JANNE_PASS );
+        principals = session.getRoles();
+        assertFalse( session.isAnonymous() );
+        assertTrue(  session.isAuthenticated() );
+        assertTrue(  ArrayUtils.contains( principals, Role.ALL ) );
+        assertFalse( ArrayUtils.contains( principals, Role.ANONYMOUS ) );
+        assertFalse( ArrayUtils.contains( principals, Role.ASSERTED ) );
+        assertTrue(  ArrayUtils.contains( principals, Role.AUTHENTICATED ) );
+        
+        // Test roles for admin session
+        session = adminSession( m_engine );
+        principals = session.getRoles();
+        assertFalse( session.isAnonymous() );
+        assertTrue(  session.isAuthenticated() );
+        assertTrue(  ArrayUtils.contains( principals, Role.ALL ) );
+        assertFalse( ArrayUtils.contains( principals, Role.ANONYMOUS ) );
+        assertFalse( ArrayUtils.contains( principals, Role.ASSERTED ) );
+        assertTrue(  ArrayUtils.contains( principals, Role.AUTHENTICATED ) );
+    }
+
+    public void testIsIPAddress()
+    {
+        assertFalse( WikiSession.isIPV4Address( "Me" ) );
+        assertFalse( WikiSession.isIPV4Address( "Guest" ) );
+        assertTrue( WikiSession.isIPV4Address( "127.0.0.1" ) );
+        assertFalse( WikiSession.isIPV4Address( "1207.0.0.1" ) );
+        assertFalse( WikiSession.isIPV4Address( "127..0.1" ) );
+        assertFalse( WikiSession.isIPV4Address( "1207.0.0." ) );
+        assertFalse( WikiSession.isIPV4Address( ".0.0.1" ) );
+        assertFalse( WikiSession.isIPV4Address( "..." ) );
+    }
+    
+    public void testIsContainerStatusChanged()
+    {
+        MockRoundtrip trip;
+        MockHttpSession session;
+        MockHttpServletRequest request;
+        WikiSession wikiSession;
+        String servletContext;
+        
+        // A naked HTTP request without userPrincipal/remoteUser shouldn't count as changed
+        trip = m_engine.guestTrip( ViewActionBean.class );
+        request = trip.getRequest();
+        session = (MockHttpSession)request.getSession();
+        servletContext = "/" + m_engine.getServletContext().getServletContextName();
+        request.setUserPrincipal( null );
+        wikiSession = WikiSession.getWikiSession( m_engine, request );
+        assertFalse( wikiSession.isContainerStatusChanged( request ) );
+        
+        // Changing the UserPrincipal value should trigger a change...
+        request = new MockHttpServletRequest(servletContext, ViewActionBean.class.getAnnotation(UrlBinding.class).value());
+        request.setSession(session);
+        request.setUserPrincipal( new WikiPrincipal( "Fred Flintstone") );
+        assertTrue( wikiSession.isContainerStatusChanged( request ) );
+        
+        // ...but if the next request has the same UserPrincipal, it shouldn't.
+        request = new MockHttpServletRequest(servletContext, ViewActionBean.class.getAnnotation(UrlBinding.class).value());
+        request.setSession(session);
+        request = m_engine.guestTrip( ViewActionBean.class ).getRequest();
+        request.setUserPrincipal( new WikiPrincipal( "Fred Flintstone") );
+        assertFalse( wikiSession.isContainerStatusChanged( request ) );
+        
+        // If we twiddle the remoteUser field, it should trigger a change again...
+        request = new MockHttpServletRequest(servletContext, ViewActionBean.class.getAnnotation(UrlBinding.class).value());
+        request.setSession(session);
+        request.setUserPrincipal( new WikiPrincipal( "Fred") );
+        assertTrue( wikiSession.isContainerStatusChanged( request ) );
+        
+        // ...but not if we follow up with a similar request again.
+        request = new MockHttpServletRequest(servletContext, ViewActionBean.class.getAnnotation(UrlBinding.class).value());
+        request.setSession(session);
+        request.setUserPrincipal( new WikiPrincipal( "Fred") );
+        assertFalse( wikiSession.isContainerStatusChanged( request ) );
+        
+        // And finally, if we null the UserPrincipal again, 
+        // it should not trigger a change.
+        request = new MockHttpServletRequest(servletContext, ViewActionBean.class.getAnnotation(UrlBinding.class).value());
+        request.setSession(session);
+        request.setUserPrincipal( null );
+        assertFalse( wikiSession.isContainerStatusChanged( request ) );
+        
+        // Adding the magic "assertion cookie" should trigger a change in status.
+        request = new MockHttpServletRequest(servletContext, ViewActionBean.class.getAnnotation(UrlBinding.class).value());
+        request.setSession(session);
+        request.setUserPrincipal( null );
+        String cookieName = CookieAssertionLoginModule.PREFS_COOKIE_NAME;
+        request.setCookies( new Cookie[] { new Cookie( cookieName, "FredFlintstone" ) });
+        assertTrue( wikiSession.isContainerStatusChanged( request ) );
+    }
+
+    public void testGetStatus()
+    {
+    }
+    
+    /**
+     * Creates an anonymous user session.
+     * @param engine the wiki engine
+     * @return the new session
+     * @throws Exception
+     */
+    public static WikiSession anonymousSession( TestEngine engine ) throws Exception
+    {
+        // Build anon session
+        MockHttpServletRequest request = engine.guestTrip( ViewActionBean.class ).getRequest();
+        
+        // Log in
+        boolean loggedIn = engine.getAuthenticationManager().login( request );
+        if ( !loggedIn )
+        {
+            throw new IllegalStateException( "Couldn't set up anonymous user." );
+        }
+        
+        WikiSession session = WikiSession.getWikiSession( engine, request );
+        
+        // Make sure the user is actually anonymous
+        if ( !session.isAnonymous() )
+        {
+            throw new IllegalStateException( "Session is not anonymous." );
+        }
+        return session;
+    }
+
+    public static WikiSession assertedSession( TestEngine engine, String name ) throws Exception
+    {
+        return assertedSession( engine, name, new Principal[0] );
+    }
+    
+    public static WikiSession assertedSession( TestEngine engine, String name, Principal[] roles ) throws Exception
+    {
+        // We can use cookies right?
+        if ( !AuthenticationManager.allowsCookieAssertions() )
+        {
+            throw new IllegalStateException( "Couldn't set up asserted user: login config doesn't allow cookies." );
+        }
+        
+        // Build anon session
+        MockHttpServletRequest request = engine.guestTrip( ViewActionBean.class ).getRequest();
+        Set<String> r = new HashSet<String>();
+        for ( int i = 0; i < roles.length; i++ )
+        {
+            r.add( roles[i].getName() );
+        }
+        request.setRoles( r );
+        
+        // Set cookie
+        Cookie cookie = new Cookie( CookieAssertionLoginModule.PREFS_COOKIE_NAME, name );
+        request.setCookies( new Cookie[] { cookie } );
+        
+        // Log in
+        boolean loggedIn = engine.getAuthenticationManager().login( request );
+        if ( !loggedIn )
+        {
+            throw new IllegalStateException( "Couldn't log in asserted user." );
+        }
+        
+        WikiSession session = WikiSession.getWikiSession( engine, request );
+        
+        // Make sure the user is actually asserted
+        if ( !session.hasPrincipal( Role.ASSERTED ) )
+        {
+            throw new IllegalStateException( "Didn't find Role.ASSERTED in session." );
+        }
+        return session;
+    }
+    
+    public static WikiSession adminSession( TestEngine engine ) throws Exception
+    {
+        return authenticatedSession( engine, Users.ADMIN, Users.ADMIN_PASS );
+    }
+    
+    public static WikiSession authenticatedSession( TestEngine engine, String id, String password ) throws Exception
+    {
+        // Build anon session
+        MockHttpServletRequest request = engine.guestTrip( ViewActionBean.class ).getRequest();
+        
+        // Log in as anon
+        boolean loggedIn = engine.getAuthenticationManager().login( request );
+        if ( !loggedIn )
+        {
+            throw new IllegalStateException( "Couldn't log in anonymous user." );
+        }
+        
+        WikiSession session = WikiSession.getWikiSession( engine, request );
+        
+        // Log in the user with credentials
+        engine.getAuthenticationManager().login( session, id, password );
+        
+        // Make sure the user is actually authenticated
+        if ( !session.isAuthenticated() )
+        {
+            throw new IllegalStateException( "Could not log in authenticated user '" + id + "'" );
+        }
+        return session;
+    }
+    
+    public static WikiSession containerAuthenticatedSession( TestEngine engine, String id, Principal[] roles ) throws Exception
+    {
+        // Build container session
+        MockHttpServletRequest request = engine.guestTrip( ViewActionBean.class ).getRequest();
+        Set<String> r = new HashSet<String>();
+        for ( int i = 0; i < roles.length; i++ )
+        {
+            r.add( roles[i].getName() );
+        }
+        request.setRoles( r );
+        request.setUserPrincipal( new WikiPrincipal( id ) );
+        
+        // Log in as anon
+        boolean loggedIn = engine.getAuthenticationManager().login( request );
+        if ( !loggedIn )
+        {
+            throw new IllegalStateException( "Couldn't log in anonymous user." );
+        }
+        
+        WikiSession session = WikiSession.getWikiSession( engine, request );
+        
+        // Log in the user with credentials
+        engine.getAuthenticationManager().login( request );
+        
+        // Make sure the user is actually authenticated
+        if ( !session.isAuthenticated() )
+        {
+            throw new IllegalStateException( "Could not log in authenticated user '" + id + "'" );
+        }
+        return session;
+    }
+
+    public static Test suite() 
+    {
+        return new TestSuite( WikiSessionTest.class );
+    }
+
+}

Added: incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/AllTests.java
URL: http://svn.apache.org/viewvc/incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/AllTests.java?rev=627271&view=auto
==============================================================================
--- incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/AllTests.java (added)
+++ incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/AllTests.java Tue Feb 12 22:24:02 2008
@@ -0,0 +1,26 @@
+
+package com.ecyrd.jspwiki.action;
+
+import junit.framework.*;
+
+public class AllTests extends TestCase
+{
+    public AllTests( String s )
+    {
+        super( s );
+    }
+
+    public static Test suite()
+    {
+        TestSuite suite = new TestSuite("ActionBean tests");
+
+        suite.addTest( EventPermissionInfoTest.suite() );
+        suite.addTest( RenameActionBeanTest.suite() );
+        suite.addTest( UserPreferencesActionBeanTest.suite() );
+        suite.addTest( UserProfileActionBeanTest.suite() );
+        suite.addTest( ViewActionBeanTest.suite() );
+        suite.addTest( WikiActionBeanFactoryTest.suite() );
+
+        return suite;
+    }
+}

Added: incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/EventPermissionInfoTest.java
URL: http://svn.apache.org/viewvc/incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/EventPermissionInfoTest.java?rev=627271&view=auto
==============================================================================
--- incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/EventPermissionInfoTest.java (added)
+++ incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/EventPermissionInfoTest.java Tue Feb 12 22:24:02 2008
@@ -0,0 +1,152 @@
+package com.ecyrd.jspwiki.action;
+
+import java.lang.reflect.Method;
+import java.security.Permission;
+import java.util.Map;
+import java.util.Properties;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+import net.sourceforge.stripes.mock.MockRoundtrip;
+import net.sourceforge.stripes.mock.MockServletContext;
+
+import com.ecyrd.jspwiki.TestEngine;
+import com.ecyrd.jspwiki.auth.permissions.GroupPermission;
+
+public class EventPermissionInfoTest extends TestCase
+{
+    TestEngine m_engine;
+    
+    public void setUp()
+    {
+        // Start the WikiEngine, and stash reference
+        Properties props = new Properties();
+        try 
+        {
+            props.load( TestEngine.findTestProperties() );
+            m_engine = new TestEngine( props );
+        }
+        catch (Exception e)
+        {
+            throw new RuntimeException("Could not set up TestEngine: " + e.getMessage());
+        }
+    }
+    
+    public void testActionBeanAnnotation() throws Exception {
+        Map<Method,EventPermissionInfo> map = EventPermissionInfo.getEventPermissionInfo(GroupActionBean.class);
+        assertEquals(3, map.size());
+        
+        Method method = GroupActionBean.class.getMethod("view", new Class[0]);
+        assertTrue(map.containsKey(method));
+        EventPermissionInfo info = map.get(method);
+        assertEquals(GroupPermission.class, info.getPermissionClass());
+        assertEquals("${group.qualifiedName}", info.getTarget());
+        assertNotNull(info.getTargetExpression());
+        assertEquals("view", info.getActions());
+        assertNull(info.getActionsExpression());
+        
+        method = GroupActionBean.class.getMethod("save", new Class[0]);
+        assertTrue(map.containsKey(method));
+        info = map.get(method);
+        assertEquals(GroupPermission.class, info.getPermissionClass());
+        assertEquals("${group.qualifiedName}", info.getTarget());
+        assertNotNull(info.getTargetExpression());
+        assertEquals("edit", info.getActions());
+        assertNull(info.getActionsExpression());
+        
+        method = GroupActionBean.class.getMethod("delete", new Class[0]);
+        assertTrue(map.containsKey(method));
+        info = map.get(method);
+        assertEquals(GroupPermission.class, info.getPermissionClass());
+        assertEquals("${group.qualifiedName}", info.getTarget());
+        assertNotNull(info.getTargetExpression());
+        assertEquals("delete", info.getActions());
+        assertNull(info.getActionsExpression());
+    }
+    
+    public void testEvaluatedAnnotation() throws Exception {
+        MockServletContext ctx = m_engine.getServletContext();
+        MockRoundtrip trip;
+        GroupActionBean bean;
+        Method method;
+        EventPermissionInfo permInfo;
+        Permission perm;
+
+        // Set up a new GroupActionBean with the real group Admin and event "view"
+        trip = new MockRoundtrip(ctx, "/Group.action");
+        trip.addParameter("group","Admin");
+        trip.execute("view");
+        bean = trip.getActionBean(GroupActionBean.class);
+
+        // The view handler should return a "view" GroupPermission
+        method = GroupActionBean.class.getMethod("view",new Class[0]);
+        permInfo = bean.getContext().getPermissionInfo(method);
+        assertNotNull(permInfo);
+        perm = permInfo.getPermission(bean);
+        assertNotNull(perm);
+        assertEquals(GroupPermission.class,perm.getClass());
+        assertEquals("JSPWiki:Admin",perm.getName());
+        assertEquals("view",perm.getActions());
+        
+        // Set up a new GroupActionBean with the real group Admin and event "save"
+        trip = new MockRoundtrip(ctx, "/Group.action");
+        trip.addParameter("group","Admin");
+        trip.execute("save");
+        bean = trip.getActionBean(GroupActionBean.class);
+
+        // The view handler should return a "edit" GroupPermission
+        method = GroupActionBean.class.getMethod("save",new Class[0]);
+        permInfo = bean.getContext().getPermissionInfo(method);
+        assertNotNull(permInfo);
+        perm = permInfo.getPermission(bean);
+        assertNotNull(perm);
+        assertEquals(GroupPermission.class,perm.getClass());
+        assertEquals("JSPWiki:Admin",perm.getName());
+        assertEquals("edit",perm.getActions());
+        
+        // Set up a new GroupActionBean with the real group Admin and event "delete"
+        trip = new MockRoundtrip(ctx, "/Group.action");
+        trip.addParameter("group","Admin");
+        trip.execute("delete");
+        bean = trip.getActionBean(GroupActionBean.class);
+
+        // The view handler should return a "view" GroupPermission
+        method = GroupActionBean.class.getMethod("delete",new Class[0]);
+        permInfo = bean.getContext().getPermissionInfo(method);
+        assertNotNull(permInfo);
+        perm = permInfo.getPermission(bean);
+        assertNotNull(perm);
+        assertEquals(GroupPermission.class,perm.getClass());
+        assertEquals("JSPWiki:Admin",perm.getName());
+        assertEquals("delete",perm.getActions());
+    }
+    
+    public void testNotEvaluatedAnnotation() throws Exception
+    {
+        MockServletContext ctx = m_engine.getServletContext();
+        MockRoundtrip trip;
+        GroupActionBean bean;
+        Method method;
+        EventPermissionInfo permInfo;
+        Permission perm;
+
+        // Set up a new GroupActionBean with the non-existent group Foo
+        trip = new MockRoundtrip(ctx, "/Group.action");
+        trip.addParameter("group","Foo");
+        trip.execute("view");
+        bean = trip.getActionBean(GroupActionBean.class);
+        
+        // The view handler should NOT return a "view" GroupPermission (because EL can't evaluate)
+        method = GroupActionBean.class.getMethod("view",new Class[0]);
+        permInfo = bean.getContext().getPermissionInfo(method);
+        assertNotNull(permInfo);
+        perm = permInfo.getPermission(bean);
+        assertNull(perm);
+    }
+
+    public static Test suite()
+    {
+        return new TestSuite( EventPermissionInfoTest.class );
+    }
+}

Added: incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/RenameActionBeanTest.java
URL: http://svn.apache.org/viewvc/incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/RenameActionBeanTest.java?rev=627271&view=auto
==============================================================================
--- incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/RenameActionBeanTest.java (added)
+++ incubator/jspwiki/branches/JSPWIKI_STRIPES_BRANCH/tests/com/ecyrd/jspwiki/action/RenameActionBeanTest.java Tue Feb 12 22:24:02 2008
@@ -0,0 +1,202 @@
+package com.ecyrd.jspwiki.action;
+
+import java.util.Properties;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+import net.sourceforge.stripes.mock.MockRoundtrip;
+import net.sourceforge.stripes.validation.ValidationErrors;
+
+import com.ecyrd.jspwiki.TestEngine;
+import com.ecyrd.jspwiki.WikiPage;
+import com.ecyrd.jspwiki.auth.Users;
+
+public class RenameActionBeanTest extends TestCase
+{
+    TestEngine m_engine;
+    
+    public void setUp()
+    {
+        // Start the WikiEngine, and stash reference
+        Properties props = new Properties();
+        try 
+        {
+            TestEngine.emptyPageDir();
+            TestEngine.emptyWorkDir();
+            props.load( TestEngine.findTestProperties() );
+            m_engine = new TestEngine( props );
+        }
+        catch (Exception e)
+        {
+            throw new RuntimeException("Could not set up TestEngine: " + e.getMessage());
+        }
+    }
+    
+    public void testValidation() throws Exception {
+        // Save test page
+        m_engine.saveText("Test", "This is a test.");
+        WikiPage page = m_engine.getPage("Test");
+        assertNotNull("Did not save page Test!", page);
+        
+        MockRoundtrip trip;
+        ValidationErrors errors;
+        
+        // Try renaming without 'page' or 'renameTo' params; should see 2 validation errors
+        trip = m_engine.authenticatedTrip( Users.ADMIN,Users.ADMIN_PASS, RenameActionBean.class );
+        trip.execute("rename");
+        errors = trip.getValidationErrors();
+        assertEquals( 2, errors.size() );
+        assertTrue ( errors.containsKey( "page" ) );
+        assertTrue ( errors.containsKey( "renameTo" ) );
+        
+        // Try again, with 'page' param but 'renameTo'; should see 1 validation error
+        trip = m_engine.authenticatedTrip( Users.ADMIN,Users.ADMIN_PASS, RenameActionBean.class );
+        trip.setParameter("page", "Test");
+        trip.execute("rename");
+        RenameActionBean bean = trip.getActionBean(RenameActionBean.class);
+        assertEquals( page, bean.getPage() );
+        errors = trip.getValidationErrors();
+        assertEquals( 1, errors.size() );
+        assertTrue( errors.containsKey("renameTo") );
+        assertEquals(MockRoundtrip.DEFAULT_SOURCE_PAGE, trip.getDestination() );
+    
+        // Delete test page
+        m_engine.deletePage( "Test" );
+    }
+    
+    public void testValidationWithCollision() throws Exception {
+        // Save 2 test pages
+        m_engine.saveText("Test", "This is a test.");
+        WikiPage page = m_engine.getPage("Test");
+        assertNotNull("Did not save page Test!", page );
+        m_engine.saveText("TestCollision", "This is a second test page.");
+        WikiPage collisionPage = m_engine.getPage("TestCollision");
+        assertNotNull("Did not save page TestCollision!", collisionPage );
+        
+        MockRoundtrip trip;
+        ValidationErrors errors;
+        
+        // Try renaming to 'TestCollision'; should see 1 validation error
+        trip = m_engine.authenticatedTrip( Users.ADMIN,Users.ADMIN_PASS, RenameActionBean.class );
+        trip.setParameter("page", "Test");
+        trip.setParameter("renameTo", "TestCollision");
+        trip.execute("rename");
+        errors = trip.getValidationErrors();
+        assertEquals( 1, errors.size() );
+        assertTrue ( errors.containsKey( "renameTo" ) );
+        assertEquals(MockRoundtrip.DEFAULT_SOURCE_PAGE, trip.getDestination() );
+    
+        // Delete test page
+        m_engine.deletePage( "Test" );
+        m_engine.deletePage( "TestCollision" );
+    }
+    
+    public void testRename() throws Exception {
+        // Save test page
+        m_engine.saveText("Test", "This is a test.");
+        WikiPage page = m_engine.getPage("Test");
+        assertNotNull("Did not save page Test!", page );
+        
+        MockRoundtrip trip;
+        ValidationErrors errors;
+        
+        // Try renaming to 'TestRenamed'; should save without error
+        trip = m_engine.authenticatedTrip( Users.ADMIN,Users.ADMIN_PASS, RenameActionBean.class );
+        trip.setParameter("page", "Test");
+        trip.setParameter("renameTo", "TestRenamed");
+        trip.execute("rename");
+        errors = trip.getValidationErrors();
+        assertEquals( 0, errors.size() );
+        assertEquals( "/Wiki.action?page=TestRenamed", trip.getDestination() );
+        assertFalse( m_engine.pageExists( "Test" ) );
+        assertTrue( m_engine.pageExists( "TestRenamed" ) );
+    
+        // Delete test page
+        m_engine.deletePage( "TestRenamed" );
+    }
+    
+    public void testRenameReferences() throws Exception {
+        // Save test page and referring page
+        m_engine.saveText("Test", "This is a test.");
+        WikiPage page = m_engine.getPage("Test");
+        assertNotNull("Did not save page Test!", page );
+        m_engine.saveText("ReferstoTest", "This page refers to [Test].\n");
+        WikiPage referringPage = m_engine.getPage("ReferstoTest");
+        assertNotNull("Did not save page ReferstoTest!", referringPage );
+        assertNotNull( m_engine.getReferenceManager().findReferrers("Test") );
+        assertEquals( 1, m_engine.getReferenceManager().findReferrers("Test").size() );
+        
+        MockRoundtrip trip;
+        ValidationErrors errors;
+        String referringText;
+        
+        // Try renaming to 'TestRenamed' with missing 'changeReferences' param. Referee should not change.
+        trip = m_engine.authenticatedTrip( Users.ADMIN,Users.ADMIN_PASS, RenameActionBean.class );
+        trip.setParameter("page", "Test");
+        trip.setParameter("renameTo", "TestRenamed");
+        trip.execute("rename");
+        errors = trip.getValidationErrors();
+        assertEquals( 0, errors.size() );
+        assertEquals( "/Wiki.action?page=TestRenamed", trip.getDestination() );
+        assertFalse( m_engine.pageExists( "Test" ) );
+        assertTrue( m_engine.pageExists( "TestRenamed" ) );
+        referringText = m_engine.getPureText( m_engine.getPage("ReferstoTest") );
+        assertFalse( referringText.contains("[TestRenamed]"));
+        m_engine.deletePage( "TestRenamed" );
+    }
+    
+    public void testRenameReferencesChangeRefsFalse() throws Exception {
+        MockRoundtrip trip;
+        ValidationErrors errors;
+        String referringText;
+        
+        // Try renaming to 'TestRenamed' with 'changeReferences' = 'false'. Referee should not change.
+        m_engine.saveText("Test", "This is a test.");
+        m_engine.saveText("ReferstoTest", "This page refers to [Test].");
+        trip = m_engine.authenticatedTrip( Users.ADMIN,Users.ADMIN_PASS, RenameActionBean.class );
+        trip.setParameter("page", "Test");
+        trip.setParameter("renameTo", "TestRenamed");
+        trip.setParameter("changeReferences", "false");
+        trip.execute("rename");
+         errors = trip.getValidationErrors();
+        assertEquals( 0, errors.size() );
+        assertEquals( "/Wiki.action?page=TestRenamed", trip.getDestination() );
+        assertFalse( m_engine.pageExists( "Test" ) );
+        assertTrue( m_engine.pageExists( "TestRenamed" ) );
+        referringText = m_engine.getPureText( m_engine.getPage("ReferstoTest") );
+        assertFalse( referringText.contains("[TestRenamed]"));
+        m_engine.deletePage( "TestRenamed" );
+    }
+        
+    public void testRenameReferencesChangeRefsTrue() throws Exception {
+        MockRoundtrip trip;
+        ValidationErrors errors;
+        String referringText;
+        
+        // Try renaming to 'TestRenamed' with 'changeReferences' = 'true'. NOW, referee should change!
+        m_engine.saveText("Test", "This is a test.");
+        m_engine.saveText("ReferstoTest", "This page refers to [Test].");
+        trip = m_engine.authenticatedTrip( Users.ADMIN,Users.ADMIN_PASS, RenameActionBean.class );
+        trip.setParameter("page", "Test");
+        trip.setParameter("renameTo", "TestRenamed");
+        trip.setParameter("changeReferences", "true");
+        trip.execute("rename");
+        errors = trip.getValidationErrors();
+        assertEquals( 0, errors.size() );
+        assertEquals( "/Wiki.action?page=TestRenamed", trip.getDestination() );
+        assertFalse( m_engine.pageExists( "Test" ) );
+        assertTrue( m_engine.pageExists( "TestRenamed" ) );
+        referringText = m_engine.getPureText( m_engine.getPage("ReferstoTest") );
+        assertTrue( referringText.contains("[TestRenamed]"));
+        m_engine.deletePage( "TestRenamed" );
+        
+        // Clean up
+        m_engine.deletePage( "ReferstoTest" );
+    }
+    
+    public static Test suite()
+    {
+        return new TestSuite( RenameActionBeanTest.class );
+    }
+}