struts-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From lukaszlen...@apache.org
Subject svn commit: r1209569 [47/50] - in /struts/struts2/branches/STRUTS_3_X: apps/blank/src/main/java/example/ apps/blank/src/test/java/example/ apps/jboss-blank/src/main/java/example/ apps/jboss-blank/src/test/java/example/ apps/mailreader/src/main/java/mai...
Date Fri, 02 Dec 2011 16:33:45 GMT
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DateRangeValidatorTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DateRangeValidatorTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DateRangeValidatorTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DateRangeValidatorTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import org.apache.struts2.xwork2.ActionProxy;
+import org.apache.struts2.xwork2.ValidationAware;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.config.providers.MockConfigurationProvider;
+import org.apache.struts2.xwork2.validator.validators.DateRangeFieldValidator;
+
+import java.util.*;
+
+
+/**
+ * DateRangeValidatorTest
+ *
+ * @author Jason Carreira
+ *         Created Feb 9, 2003 1:25:42 AM
+ */
+public class DateRangeValidatorTest extends XWorkTestCase {
+
+    private Locale origLocale;
+
+
+    /**
+     * Tests whether the date range validation is working. Should produce an validation error,
+     * because the action config sets date to 12/20/2002 while expected range is Dec 22-25.
+     */
+    public void testRangeValidation() throws Exception {
+        ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.VALIDATION_ACTION_NAME, null);
+        proxy.execute();
+        assertTrue(((ValidationAware) proxy.getAction()).hasFieldErrors());
+
+        Map errors = ((ValidationAware) proxy.getAction()).getFieldErrors();
+        Iterator it = errors.entrySet().iterator();
+
+        List errorMessages = (List) errors.get("date");
+        assertNotNull("Expected date range validation error message.", errorMessages);
+        assertEquals(1, errorMessages.size());
+
+        String errorMessage = (String) errorMessages.get(0);
+        assertNotNull(errorMessage);
+    }
+
+    public void testGetSetMinMax() throws Exception {
+        DateRangeFieldValidator val = new DateRangeFieldValidator();
+        Date max = new Date();
+        val.setMax(max);
+        assertEquals(max, val.getMax());
+
+        Date min = new Date();
+        val.setMin(min);
+        assertEquals(min, val.getMin());
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        origLocale = Locale.getDefault();
+        Locale.setDefault(Locale.US);
+        loadConfigurationProviders(new MockConfigurationProvider());
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        Locale.setDefault(origLocale);
+    }
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultActionValidatorManagerTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultActionValidatorManagerTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultActionValidatorManagerTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultActionValidatorManagerTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,353 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import com.mockobjects.dynamic.C;
+import com.mockobjects.dynamic.Mock;
+import org.apache.struts2.xwork2.config.ConfigurationException;
+import org.apache.struts2.xwork2.test.DataAware2;
+import org.apache.struts2.xwork2.test.SimpleAction2;
+import org.apache.struts2.xwork2.StubValueStack;
+import org.apache.struts2.xwork2.test.SimpleAction3;
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.util.ValueStack;
+import junit.framework.TestCase;
+import org.apache.struts2.xwork2.XWorkException;
+import org.apache.struts2.xwork2.SimpleAction;
+import org.apache.struts2.xwork2.TestBean;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+
+/**
+ * DefaultActionValidatorManagerTest
+ *
+ * @author Jason Carreira
+ * @author tm_jee 
+ * @version $Date: 2011-12-02 12:24:48 +0100 (Fri, 02 Dec 2011) $ $Id: DefaultActionValidatorManagerTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ */
+public class DefaultActionValidatorManagerTest extends TestCase {
+
+    protected final String alias = "validationAlias";
+
+    DefaultActionValidatorManager actionValidatorManager;
+    Mock mockValidatorFileParser;
+    Mock mockValidatorFactory;
+    ValueStack stubValueStack;
+
+    @Override
+    protected void setUp() throws Exception {
+        actionValidatorManager = new DefaultActionValidatorManager();
+        super.setUp();
+        mockValidatorFileParser = new Mock(ValidatorFileParser.class);
+        actionValidatorManager.setValidatorFileParser((ValidatorFileParser)mockValidatorFileParser.proxy());
+
+        mockValidatorFactory = new Mock(ValidatorFactory.class);
+        actionValidatorManager.setValidatorFactory((ValidatorFactory)mockValidatorFactory.proxy());
+
+        stubValueStack = new StubValueStack();
+        ActionContext.setContext(new ActionContext(new HashMap<String, Object>()));
+        ActionContext.getContext().setValueStack(stubValueStack);
+
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        actionValidatorManager = null;
+        super.tearDown();
+        mockValidatorFactory = null;
+        mockValidatorFileParser = null;
+    }
+
+
+    public void testBuildValidatorKey() {
+        String validatorKey = DefaultActionValidatorManager.buildValidatorKey(SimpleAction.class, alias);
+        assertEquals(SimpleAction.class.getName() + "/" + alias, validatorKey);
+    }
+
+    public void testBuildsValidatorsForAlias() {
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/SimpleAction-validation.xml")),
+                new ArrayList());
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/SimpleAction-validationAlias-validation.xml")),
+                new ArrayList());
+         actionValidatorManager.getValidators(SimpleAction.class, alias);
+        mockValidatorFileParser.verify();
+    }
+
+    public void testBuildsValidatorsForAliasError() {
+        boolean pass = false;
+        try {
+            mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/TestBean-validation.xml")),
+                new ArrayList());
+            mockValidatorFileParser.expectAndThrow("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/TestBean-badtest-validation.xml")),
+                new ConfigurationException());
+            List validatorList = actionValidatorManager.getValidators(TestBean.class, "badtest");
+        } catch (XWorkException ex) {
+            pass = true;
+        }
+        mockValidatorFileParser.verify();
+        assertTrue("Didn't throw exception on load failure", pass);
+    }
+
+
+    public void testGetValidatorsForInterface() {
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/test/DataAware-validation.xml")),
+                new ArrayList());
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/test/DataAware-validationAlias-validation.xml")),
+                new ArrayList());
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/test/DataAware2-validation.xml")),
+                new ArrayList());
+        actionValidatorManager.getValidators(DataAware2.class, alias);
+        mockValidatorFileParser.verify();
+    }
+
+    public void testGetValidatorsFromInterface() {
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/SimpleAction-validation.xml")),
+                new ArrayList());
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/SimpleAction-validationAlias-validation.xml")),
+                new ArrayList());
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/test/DataAware-validation.xml")),
+                new ArrayList());
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/test/DataAware-validationAlias-validation.xml")),
+                new ArrayList());
+        actionValidatorManager.getValidators(SimpleAction3.class, alias);
+        mockValidatorFileParser.verify();
+    }
+
+    public void testSameAliasWithDifferentClass() {
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/SimpleAction-validation.xml")),
+                new ArrayList());
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/SimpleAction-validationAlias-validation.xml")),
+                new ArrayList());
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/test/SimpleAction2-validation.xml")),
+                new ArrayList());
+        mockValidatorFileParser.expectAndReturn("parseActionValidatorConfigs",
+                C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/test/SimpleAction2-validationAlias-validation.xml")),
+                new ArrayList());
+        actionValidatorManager.getValidators(SimpleAction.class, alias);
+        actionValidatorManager.getValidators(SimpleAction2.class, alias);
+        mockValidatorFileParser.verify();
+    }
+
+    /*
+    // TODO: this all need to be converted to real unit tests
+
+    public void testSkipUserMarkerActionLevelShortCircuit() {
+        // get validators
+        List validatorList = actionValidatorManager.getValidators(User.class, null);
+        assertEquals(10, validatorList.size());
+
+        try {
+            User user = new User();
+            user.setName("Mark");
+            user.setEmail("bad_email");
+            user.setEmail2("bad_email");
+
+            ValidatorContext context = new GenericValidatorContext(user);
+            actionValidatorManager.validate(user, null, context);
+            assertTrue(context.hasFieldErrors());
+
+            // check field errors
+            List l = (List) context.getFieldErrors().get("email");
+            assertNotNull(l);
+            assertEquals(1, l.size());
+            assertEquals("Not a valid e-mail.", l.get(0));
+            l = (List) context.getFieldErrors().get("email2");
+            assertNotNull(l);
+            assertEquals(2, l.size());
+            assertEquals("Not a valid e-mail2.", l.get(0));
+            assertEquals("Email2 not from the right company.", l.get(1));
+
+            // check action errors
+            assertTrue(context.hasActionErrors());
+            l = (List) context.getActionErrors();
+            assertNotNull(l);
+            assertEquals(2, l.size()); // both expression test failed see User-validation.xml
+            assertEquals("Email does not start with mark", l.get(0));
+        } catch (ValidationException ex) {
+            ex.printStackTrace();
+            fail("Validation error: " + ex.getMessage());
+        }
+    }
+
+    public void testSkipAllActionLevelShortCircuit2() {
+        // get validators
+        List validatorList = actionValidatorManager.getValidators(User.class, null);
+        assertEquals(10, validatorList.size());
+
+        try {
+            User user = new User();
+            user.setName("Mark");
+            // * mark both email to starts with mark to get pass the action-level validator,
+            // so we could concentrate on testing the field-level validators (User-validation.xml)
+            // * make both email the same to pass the action-level validator at 
+            // UserMarker-validation.xml
+            user.setEmail("mark_bad_email_for_field_val@foo.com");
+            user.setEmail2("mark_bad_email_for_field_val@foo.com");
+
+            ValidatorContext context = new GenericValidatorContext(user);
+            actionValidatorManager.validate(user, null, context);
+            assertTrue(context.hasFieldErrors());
+
+            // check field errors
+            // we have an error in this field level, email does not ends with mycompany.com
+            List l = (List) context.getFieldErrors().get("email");
+            assertNotNull(l);
+            assertEquals(1, l.size()); // because email-field-val is short-circuit
+            assertEquals("Email not from the right company.", l.get(0));
+
+            
+            // check action errors
+            l = (List) context.getActionErrors();
+            assertFalse(context.hasActionErrors());
+            assertEquals(0, l.size());
+            
+            
+        } catch (ValidationException ex) {
+            ex.printStackTrace();
+            fail("Validation error: " + ex.getMessage());
+        }
+    }
+
+    
+    public void testActionLevelShortCircuit() throws Exception {
+    	
+    	List validatorList = actionValidatorManager.getValidators(User.class, null);
+        assertEquals(10, validatorList.size());
+        
+        User user = new User();
+        // all fields will trigger error, but sc of action-level, cause it to not appear
+        user.setName(null);		
+        user.setEmail("tmjee(at)yahoo.co.uk");
+        user.setEmail("tm_jee(at)yahoo.co.uk");
+        
+        ValidatorContext context = new GenericValidatorContext(user);
+        actionValidatorManager.validate(user, null, context);
+    	
+    	// check field level errors
+        // shouldn't have any because action error prevents validation of anything else
+        List l = (List) context.getFieldErrors().get("email2");
+        assertNull(l);
+    	
+    	
+        // check action errors
+        assertTrue(context.hasActionErrors());
+        l = (List) context.getActionErrors();
+        assertNotNull(l);
+        // we only get one, because UserMarker-validation.xml action-level validator
+        // already sc it   :-)
+        assertEquals(1, l.size()); 
+        assertEquals("Email not the same as email2", l.get(0));
+    }
+    
+    
+    public void testShortCircuitNoErrors() {
+        // get validators
+        List validatorList = actionValidatorManager.getValidators(User.class, null);
+        assertEquals(10, validatorList.size());
+
+        try {
+            User user = new User();
+            user.setName("Mark");
+            user.setEmail("mark@mycompany.com");
+            user.setEmail2("mark@mycompany.com");
+
+            ValidatorContext context = new GenericValidatorContext(user);
+            actionValidatorManager.validate(user, null, context);
+            assertFalse(context.hasErrors());
+        } catch (ValidationException ex) {
+            ex.printStackTrace();
+            fail("Validation error: " + ex.getMessage());
+        }
+    }
+    
+    public void testFieldErrorsOrder() throws Exception {
+    	ValidationOrderAction action = new ValidationOrderAction();
+    	actionValidatorManager.validate(action, "actionContext");
+    	Map fieldErrors = action.getFieldErrors();
+    	Iterator i = fieldErrors.entrySet().iterator();
+    	
+    	assertNotNull(fieldErrors);
+    	assertEquals(fieldErrors.size(), 12);
+    	
+    	
+    	Map.Entry e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "username");
+    	assertEquals(((List)e.getValue()).get(0), "username required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "password");
+    	assertEquals(((List)e.getValue()).get(0), "password required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "confirmPassword");
+    	assertEquals(((List)e.getValue()).get(0), "confirm password required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "firstName");
+    	assertEquals(((List)e.getValue()).get(0), "first name required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "lastName");
+    	assertEquals(((List)e.getValue()).get(0), "last name required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "city");
+    	assertEquals(((List)e.getValue()).get(0), "city is required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "province");
+    	assertEquals(((List)e.getValue()).get(0), "province is required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "country");
+    	assertEquals(((List)e.getValue()).get(0), "country is required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "postalCode");
+    	assertEquals(((List)e.getValue()).get(0), "postal code is required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "email");
+    	assertEquals(((List)e.getValue()).get(0), "email is required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "website");
+    	assertEquals(((List)e.getValue()).get(0), "website is required");
+    	
+    	e = (Map.Entry) i.next();
+    	assertEquals(e.getKey(), "passwordHint");
+    	assertEquals(((List)e.getValue()).get(0), "password hint is required");
+    	
+    }
+    */
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultValidatorFactoryTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultValidatorFactoryTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultValidatorFactoryTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultValidatorFactoryTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2002-2006,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import com.mockobjects.dynamic.C;
+import com.mockobjects.dynamic.Mock;
+import junit.framework.TestCase;
+
+/**
+ * <code>DefaultValidatorFactoryTest</code>
+ *
+ * @author <a href="mailto:hermanns@aixcept.de">Rainer Hermanns</a>
+ * @version $Id: DefaultValidatorFactoryTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ */
+public class DefaultValidatorFactoryTest extends TestCase {
+
+    public void testParseValidators() {
+        Mock mockValidatorFileParser = new Mock(ValidatorFileParser.class);
+        mockValidatorFileParser.expect("parseValidatorDefinitions", C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("org/apache/struts2/xwork2/validator/validators/default.xml")));
+        mockValidatorFileParser.expect("parseValidatorDefinitions", C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("validators.xml")));
+        mockValidatorFileParser.expect("parseValidatorDefinitions", C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("myOther-validators.xml")));
+        mockValidatorFileParser.expect("parseValidatorDefinitions", C.args(C.IS_NOT_NULL, C.IS_NOT_NULL, C.eq("my-validators.xml")));
+        DefaultValidatorFactory factory = new DefaultValidatorFactory(null, (ValidatorFileParser) mockValidatorFileParser.proxy());
+    }
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultValidatorFileParserTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultValidatorFileParserTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultValidatorFileParserTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DefaultValidatorFileParserTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,230 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import com.mockobjects.dynamic.C;
+import com.mockobjects.dynamic.Mock;
+import org.apache.struts2.xwork2.XWorkException;
+import org.apache.struts2.xwork2.util.ClassLoaderUtil;
+import junit.framework.TestCase;
+import org.apache.struts2.xwork2.validator.validators.ExpressionValidator;
+import org.apache.struts2.xwork2.validator.validators.IntRangeFieldValidator;
+import org.apache.struts2.xwork2.validator.validators.RegexFieldValidator;
+import org.apache.struts2.xwork2.validator.validators.RequiredFieldValidator;
+import org.apache.struts2.xwork2.validator.validators.RequiredStringValidator;
+
+import java.io.InputStream;
+import java.util.List;
+
+
+/**
+ * DefaultValidatorFileParserTest
+ * <p/>
+ * Created : Jan 20, 2003 3:41:26 PM
+ *
+ * @author Jason Carreira
+ * @author James House
+ * @author tm_jee ( tm_jee (at) yahoo.co.uk )
+ * @author Martin Gilday
+ */
+public class DefaultValidatorFileParserTest extends TestCase {
+
+    private static final String testFileName = "org/apache/struts2/xwork2/validator/validator-parser-test.xml";
+    private static final String testFileName2 = "org/apache/struts2/xwork2/validator/validator-parser-test2.xml";
+    private static final String testFileName3 = "org/apache/struts2/xwork2/validator/validator-parser-test3.xml";
+    private static final String testFileName4 = "org/apache/struts2/xwork2/validator/validator-parser-test4.xml";
+    private static final String testFileName5 = "org/apache/struts2/xwork2/validator/validator-parser-test5.xml";
+    private static final String testFileName6 = "org/apache/struts2/xwork2/validator/validator-parser-test6.xml";
+    private static final String testFileNameFail = "org/apache/struts2/xwork2/validator/validators-fail.xml";
+    private Mock mockValidatorFactory;
+    private ValidatorFileParser parser;
+
+    public void testParserActionLevelValidatorsShouldBeBeforeFieldLevelValidators() throws Exception {
+        InputStream is = ClassLoaderUtil.getResourceAsStream(testFileName2, this.getClass());
+
+        mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", C.args(C.eq("expression")), ExpressionValidator.class.getName());
+        mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", C.args(C.eq("required")), RequiredFieldValidator.class.getName());
+        List configs = parser.parseActionValidatorConfigs((ValidatorFactory) mockValidatorFactory.proxy(), is, testFileName2);
+        mockValidatorFactory.verify();
+
+        ValidatorConfig valCfg0 = (ValidatorConfig) configs.get(0);
+        ValidatorConfig valCfg1 = (ValidatorConfig) configs.get(1);
+
+        assertNotNull(configs);
+        assertEquals(configs.size(), 2);
+
+        assertEquals("expression", valCfg0.getType());
+        assertFalse(valCfg0.isShortCircuit());
+        assertEquals(valCfg0.getDefaultMessage(), "an expression error message");
+        assertEquals(valCfg0.getParams().get("expression"), "false");
+
+        assertEquals("required", valCfg1.getType());
+        assertFalse(valCfg1.isShortCircuit());
+        assertEquals(valCfg1.getDefaultMessage(), "a field error message");
+    }
+
+
+    public void testParser() {
+        InputStream is = ClassLoaderUtil.getResourceAsStream(testFileName, this.getClass());
+
+        mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", C.args(C.eq("expression")), ExpressionValidator.class.getName());
+        mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", C.args(C.eq("expression")), ExpressionValidator.class.getName());
+        mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", C.args(C.eq("required")), RequiredFieldValidator.class.getName());
+        mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", C.args(C.eq("required")), RequiredFieldValidator.class.getName());
+        mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", C.args(C.eq("int")), IntRangeFieldValidator.class.getName());
+        mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", C.args(C.eq("regex")), RegexFieldValidator.class.getName());
+        List configs = parser.parseActionValidatorConfigs((ValidatorFactory) mockValidatorFactory.proxy(), is, testFileName);
+        mockValidatorFactory.verify();
+
+
+        assertNotNull(configs);
+        assertEquals(6, configs.size());
+
+
+        ValidatorConfig cfg = (ValidatorConfig) configs.get(0);
+        assertEquals("expression", cfg.getType());
+        assertFalse(cfg.isShortCircuit());
+
+        cfg = (ValidatorConfig) configs.get(1);
+        assertEquals("expression", cfg.getType());
+        assertTrue(cfg.isShortCircuit());
+
+        cfg = (ValidatorConfig) configs.get(2);
+        assertEquals("required", cfg.getType());
+        assertEquals("foo", cfg.getParams().get("fieldName"));
+        assertEquals("You must enter a value for foo.", cfg.getDefaultMessage());
+        assertEquals(4, cfg.getLocation().getLineNumber());
+
+        cfg = (ValidatorConfig) configs.get(3);
+        assertEquals("required", cfg.getType());
+        assertTrue(cfg.isShortCircuit());
+
+        cfg = (ValidatorConfig) configs.get(4);
+        assertEquals("int", cfg.getType());
+        assertFalse(cfg.isShortCircuit());
+
+        cfg = (ValidatorConfig) configs.get(5);
+        assertEquals("regex", cfg.getType());
+        assertFalse(cfg.isShortCircuit());
+        assertEquals("([aAbBcCdD][123][eEfFgG][456])", cfg.getParams().get("expression"));
+    }
+
+    public void testParserWithBadValidation() {
+        InputStream is = ClassLoaderUtil.getResourceAsStream(testFileName3, this.getClass());
+
+        boolean pass = false;
+        try {
+            parser.parseActionValidatorConfigs((ValidatorFactory) mockValidatorFactory.proxy(), is, testFileName3);
+        } catch (XWorkException ex) {
+            assertTrue("Wrong line number", 3 == ex.getLocation().getLineNumber());
+            pass = true;
+        }
+        assertTrue("Validation file should have thrown exception", pass);
+    }
+
+    public void testParserWithBadXML() {
+        InputStream is = ClassLoaderUtil.getResourceAsStream(testFileName4, this.getClass());
+
+        boolean pass = false;
+        try {
+            parser.parseActionValidatorConfigs((ValidatorFactory) mockValidatorFactory.proxy(), is, testFileName4);
+        } catch (XWorkException ex) {
+            assertTrue("Wrong line number: " + ex.getLocation(), 13 == ex.getLocation().getLineNumber());
+            pass = true;
+        }
+        assertTrue("Validation file should have thrown exception", pass);
+    }
+
+    public void testParserWithBadXML2() {
+        InputStream is = ClassLoaderUtil.getResourceAsStream(testFileNameFail, this.getClass());
+
+        boolean pass = false;
+        try {
+            parser.parseActionValidatorConfigs((ValidatorFactory) mockValidatorFactory.proxy(), is, testFileNameFail);
+        } catch (XWorkException ex) {
+            assertTrue("Wrong line number: " + ex.getLocation(), 8 == ex.getLocation().getLineNumber());
+            pass = true;
+        }
+        assertTrue("Validation file should have thrown exception", pass);
+    }
+
+    public void testValidatorDefinitionsWithBadClassName() {
+        InputStream is = ClassLoaderUtil.getResourceAsStream(testFileName5, this.getClass());
+
+        boolean pass = false;
+        try {
+            parser.parseActionValidatorConfigs((ValidatorFactory) mockValidatorFactory.proxy(), is, testFileName5);
+        } catch (XWorkException ex) {
+            assertTrue("Wrong line number", 3 == ex.getLocation().getLineNumber());
+            pass = true;
+        }
+        assertTrue("Validation file should have thrown exception", pass);
+    }
+
+    public void testValidatorWithI18nMessage() throws Exception {
+        InputStream is = null;
+        try {
+            is = ClassLoaderUtil.getResourceAsStream(testFileName6, this.getClass());
+            mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", C.args(C.eq("requiredstring")), RequiredStringValidator.class.getName());
+            mockValidatorFactory.expectAndReturn("lookupRegisteredValidatorType", C.args(C.eq("requiredstring")), RequiredStringValidator.class.getName());
+
+            List validatorConfigs = parser.parseActionValidatorConfigs((ValidatorFactory) mockValidatorFactory.proxy(), is, "-//OpenSymphony Group//XWork Validator 1.0.3//EN");
+            mockValidatorFactory.verify();
+
+            assertEquals(validatorConfigs.size(), 2);
+
+            assertEquals(((ValidatorConfig)validatorConfigs.get(0)).getParams().get("fieldName"), "name");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(0)).getMessageParams().length, 0);
+            assertEquals(((ValidatorConfig)validatorConfigs.get(0)).getMessageKey(), "error.name");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(0)).getDefaultMessage(), "default message 1");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(0)).getParams().size(), 1);
+            assertEquals(((ValidatorConfig)validatorConfigs.get(0)).getType(), "requiredstring");
+
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getParams().get("fieldName"), "address");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getMessageParams().length, 5);
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getMessageParams()[0], "'tmjee'");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getMessageParams()[1], "'phil'");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getMessageParams()[2], "'rainer'");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getMessageParams()[3], "'hopkins'");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getMessageParams()[4], "'jimmy'");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getMessageKey(), "error.address");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getDefaultMessage(), "The Default Message");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getParams().size(), 3);
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getParams().get("trim"), "true");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getParams().get("anotherParam"), "anotherValue");
+            assertEquals(((ValidatorConfig)validatorConfigs.get(1)).getType(), "requiredstring");
+        }
+        finally {
+            if (is != null) {
+                is.close();
+            }
+        }
+    }
+
+    
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mockValidatorFactory = new Mock(ValidatorFactory.class);
+        parser = new DefaultValidatorFileParser();
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        mockValidatorFactory = null;
+        parser = null;
+    }
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DoubleRangeValidatorTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DoubleRangeValidatorTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DoubleRangeValidatorTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/DoubleRangeValidatorTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,225 @@
+package org.apache.struts2.xwork2.validator;
+
+import org.apache.struts2.xwork2.config.providers.MockConfigurationProvider;
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.config.providers.XmlConfigurationProvider;
+import org.apache.struts2.xwork2.ActionProxy;
+import org.apache.struts2.xwork2.util.ValueStack;
+import org.apache.struts2.xwork2.validator.validators.DoubleRangeFieldValidator;
+import org.apache.struts2.xwork2.ValidationAware;
+import org.apache.struts2.xwork2.ValidationAwareSupport;
+import org.apache.struts2.xwork2.XWorkTestCase;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * Unit test for {@link DoubleRangeFieldValidator}.
+ *
+ * @author <a href="mailto:hermanns@aixcept.de">Rainer Hermanns</a>
+ * @author Claus Ibsen
+ * @version $Id: DoubleRangeValidatorTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ */
+public class DoubleRangeValidatorTest extends XWorkTestCase {
+    private DoubleRangeFieldValidator val;
+
+    public void testRangeValidationWithError() throws Exception {
+        // must set a locale to US as error message contains a locale dependent number (see XW-490)
+        Locale defLocale = Locale.getDefault();
+        Locale.setDefault(Locale.US);
+        
+        ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.VALIDATION_ACTION_NAME, null);
+        proxy.execute();
+        assertTrue(((ValidationAware) proxy.getAction()).hasFieldErrors());
+
+        Map<String, List<String>> errors = ((ValidationAware) proxy.getAction()).getFieldErrors();
+        Iterator it = errors.entrySet().iterator();
+
+        List<String> errorMessages = errors.get("percentage");
+        assertNotNull("Expected double range validation error message.", errorMessages);
+        assertEquals(1, errorMessages.size());
+
+        String errorMessage = errorMessages.get(0);
+        assertNotNull("Expecting: percentage must be between 0.1 and 10.1, current value is 100.0123.", errorMessage);
+        assertEquals("percentage must be between 0.1 and 10.1, current value is 100.0123.", errorMessage);
+
+        Locale.setDefault(defLocale);
+    }
+
+    public void testRangeValidationNoError() throws Exception {
+        ActionProxy proxy = actionProxyFactory.createActionProxy("", "percentage", null);
+        proxy.execute();
+        assertTrue(((ValidationAware) proxy.getAction()).hasFieldErrors());
+
+        Map<String, List<String>> errors = ((ValidationAware) proxy.getAction()).getFieldErrors();
+        Iterator it = errors.entrySet().iterator();
+
+        List<String> errorMessages = errors.get("percentage");
+        assertNull("Expected no double range validation error message.", errorMessages);
+    }
+
+    public void testRangeNoExclusiveAndNoValueInStack() throws Exception {
+        val.setFieldName("hello");
+        val.validate("world");
+    }
+
+    public void testRangeSimpleDoubleValueInStack() throws Exception {
+        MyTestProduct prod = new MyTestProduct();
+        prod.setName("coca cola");
+        prod.setPrice(5.99);
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        stack.push(prod);
+        ActionContext.getContext().setValueStack(stack);
+
+        val.setMinInclusive("0");
+        val.setMaxInclusive("10");
+        val.setFieldName("price");
+        val.validate(prod);
+    }
+
+    public void testRangeRealDoubleValueInStack() throws Exception {
+        MyTestProduct prod = new MyTestProduct();
+        prod.setName("coca cola");
+        prod.setPrice(5.99);
+        prod.setVolume(new Double(12.34));
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        stack.push(prod);
+        ActionContext.getContext().setValueStack(stack);
+
+        val.setMinInclusive("0");
+        val.setMaxInclusive("30");
+        val.setFieldName("volume");
+        val.validate(prod);
+    }
+
+    public void testRangeNotADoubleObjectValueInStack() throws Exception {
+        MyTestProduct prod = new MyTestProduct();
+        prod.setName("coca cola");
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        stack.push(prod);
+        ActionContext.getContext().setValueStack(stack);
+
+        val.setMinInclusive("0");
+        val.setMaxInclusive("10");
+        val.setFieldName("name");
+
+        DelegatingValidatorContext context = new DelegatingValidatorContext(new ValidationAwareSupport());
+        val.setValidatorContext(context);
+
+        val.validate(prod);
+
+        assertEquals("0", val.getMinInclusive());
+        assertEquals("10", val.getMaxInclusive());
+    }
+
+    public void testEdgeOfMaxRange() throws Exception {
+        MyTestProduct prod = new MyTestProduct();
+        prod.setName("coca cola");
+        prod.setPrice(9.95);
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        stack.push(prod);
+        ActionContext.getContext().setValueStack(stack);
+
+        val.setFieldName("price");
+
+        DelegatingValidatorContext context = new DelegatingValidatorContext(new ValidationAwareSupport());
+        val.setValidatorContext(context);
+
+        val.setMaxInclusive("9.95");
+        val.validate(prod); // should pass
+        assertTrue(!context.hasErrors());
+        assertEquals("9.95", val.getMaxInclusive());
+
+        val.setMaxExclusive("9.95");
+        val.validate(prod); // should not pass
+        assertTrue(context.hasErrors());
+        assertEquals("9.95", val.getMaxExclusive());
+    }
+
+    public void testEdgeOfMinRange() throws Exception {
+        MyTestProduct prod = new MyTestProduct();
+        prod.setName("coca cola");
+        prod.setPrice(9.95);
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        stack.push(prod);
+        ActionContext.getContext().setValueStack(stack);
+
+        val.setFieldName("price");
+
+        DelegatingValidatorContext context = new DelegatingValidatorContext(new ValidationAwareSupport());
+        val.setValidatorContext(context);
+
+        val.setMinInclusive("9.95");
+        val.validate(prod); // should pass
+        assertTrue(!context.hasErrors());
+
+        val.setMinExclusive("9.95");
+        val.validate(prod); // should not pass
+        assertTrue(context.hasErrors());
+    }
+
+    public void testNoValue() throws Exception {
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        ActionContext.getContext().setValueStack(stack);
+
+        val.setFieldName("price");
+
+        DelegatingValidatorContext context = new DelegatingValidatorContext(new ValidationAwareSupport());
+        val.setValidatorContext(context);
+
+        val.setMinInclusive("9.95");
+        val.validate(null);
+        assertTrue(!context.hasErrors()); // should pass as null value passed in
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        loadConfigurationProviders(new XmlConfigurationProvider("xwork-default.xml"),  new MockConfigurationProvider());
+        val = new DoubleRangeFieldValidator();
+        val.setValueStack(ActionContext.getContext().getValueStack());
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        val = null;
+    }
+
+    private class MyTestProduct {
+        private double price;
+        private Double volume;
+        private String name;
+
+        public double getPrice() {
+            return price;
+        }
+
+        public void setPrice(double price) {
+            this.price = price;
+        }
+
+        public String getName() {
+            return name;
+        }
+
+        public void setName(String name) {
+            this.name = name;
+        }
+
+        public Double getVolume() {
+            return volume;
+        }
+
+        public void setVolume(Double volume) {
+            this.volume = volume;
+        }
+    }
+
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/EmailValidatorTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/EmailValidatorTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/EmailValidatorTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/EmailValidatorTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2002-2006,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.ActionSupport;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.validator.validators.EmailValidator;
+
+/**
+ * Test case for Email Validator
+ * 
+ * 
+ * @author tm_jee
+ * @version $Date: 2011-12-02 12:24:48 +0100 (Fri, 02 Dec 2011) $ $Id: EmailValidatorTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ */
+public class EmailValidatorTest extends XWorkTestCase {
+	
+	public void testEmailValidity() throws Exception {
+		assertTrue(verifyEmailValidity("tmjee@yahoo.com"));
+		assertTrue(verifyEmailValidity("tm_jee@yahoo.co"));
+		assertTrue(verifyEmailValidity("tm.jee@yahoo.co.uk"));
+		assertTrue(verifyEmailValidity("tm.jee@yahoo.co.biz"));
+		assertTrue(verifyEmailValidity("tm_jee@yahoo.com"));
+		assertTrue(verifyEmailValidity("tm_jee@yahoo.net"));
+		assertTrue(verifyEmailValidity(" user@subname1.subname2.subname3.domainname.co.uk "));
+        assertTrue(verifyEmailValidity("tm.j'ee@yahoo.co.uk"));
+        assertTrue(verifyEmailValidity("tm.j'e.e'@yahoo.co.uk"));
+        assertTrue(verifyEmailValidity("tmj'ee@yahoo.com"));
+		
+		assertFalse(verifyEmailValidity("tm_jee#marry@yahoo.co.uk"));
+		assertFalse(verifyEmailValidity("tm_jee@ yahoo.co.uk"));
+		assertFalse(verifyEmailValidity("tm_jee  @yahoo.co.uk"));
+		assertFalse(verifyEmailValidity("tm_j ee  @yah oo.co.uk"));
+		assertFalse(verifyEmailValidity("tm_jee  @yah oo.co.uk"));
+		assertFalse(verifyEmailValidity("tm_jee @ yahoo.com"));
+		assertFalse(verifyEmailValidity(" user@subname1.subname2.subname3.domainn#ame.co.uk "));
+	}
+	
+	protected boolean verifyEmailValidity(final String email) throws Exception {
+		ActionSupport action = new ActionSupport() {
+			public String getMyEmail() {
+				return email;
+			}
+		};
+		
+		EmailValidator validator = new EmailValidator();
+		validator.setValidatorContext(new DelegatingValidatorContext(action));
+		validator.setFieldName("myEmail");
+		validator.setDefaultMessage("invalid email");
+        validator.setValueStack(ActionContext.getContext().getValueStack());
+        validator.validate(action);
+		
+		return (action.getFieldErrors().size() == 0);
+	}
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ExpressionValidatorTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ExpressionValidatorTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ExpressionValidatorTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ExpressionValidatorTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,147 @@
+/*
+ * Copyright 2002-2006,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import com.mockobjects.dynamic.C;
+import com.mockobjects.dynamic.Mock;
+import org.apache.struts2.xwork2.config.providers.MockConfigurationProvider;
+import org.apache.struts2.xwork2.Action;
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.ActionInvocation;
+import org.apache.struts2.xwork2.ActionProxy;
+import org.apache.struts2.xwork2.ValidationAware;
+import org.apache.struts2.xwork2.ValidationAwareSupport;
+import org.apache.struts2.xwork2.config.entities.ActionConfig;
+import org.apache.struts2.xwork2.validator.validators.ExpressionValidator;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.TestBean;
+import org.easymock.EasyMock;
+
+/**
+ * Unit test for ExpressionValidator.
+ *
+ * @author Jason Carreira
+ * @author Claus Ibsen
+ */
+public class ExpressionValidatorTest extends XWorkTestCase {
+
+    public void testExpressionValidationOfStringLength() throws ValidationException {
+        TestBean bean = new TestBean();
+        bean.setName("abc");
+        ActionContext.getContext().getValueStack().push(bean);
+
+        DelegatingValidatorContext context = new DelegatingValidatorContext(new ValidationAwareSupport());
+        container.getInstance(ActionValidatorManager.class).validate(bean, "expressionValidation", context);
+        assertTrue(context.hasFieldErrors());
+
+        final Map fieldErrors = context.getFieldErrors();
+        assertTrue(fieldErrors.containsKey("name"));
+
+        List nameErrors = (List) fieldErrors.get("name");
+        assertEquals(1, nameErrors.size());
+        assertEquals("Name must be greater than 5 characters, it is currently 'abc'", nameErrors.get(0));
+
+        bean.setName("abcdefg");
+        context = new DelegatingValidatorContext(new ValidationAwareSupport());
+        container.getInstance(ActionValidatorManager.class).validate(bean, "expressionValidation", context);
+        assertFalse(context.hasFieldErrors());
+    }
+
+    public void testExpressionValidatorFailure() throws Exception {
+        HashMap<String, Object> params = new HashMap<String, Object>();
+        params.put("date", "12/23/2002");
+        params.put("foo", "5");
+        params.put("bar", "7");
+
+        HashMap<String, Object> extraContext = new HashMap<String, Object>();
+        extraContext.put(ActionContext.PARAMETERS, params);
+
+        ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.VALIDATION_ACTION_NAME, extraContext);
+        proxy.execute();
+        assertTrue(((ValidationAware) proxy.getAction()).hasActionErrors());
+
+        Collection errors = ((ValidationAware) proxy.getAction()).getActionErrors();
+        assertEquals(1, errors.size());
+
+        String message = (String) errors.iterator().next();
+        assertNotNull(message);
+        assertEquals("Foo must be greater than Bar. Foo = 5, Bar = 7.", message);
+    }
+
+    public void testExpressionValidatorSuccess() throws Exception {
+        HashMap<String, Object> params = new HashMap<String, Object>();
+
+        //make it not fail
+        params.put("date", "12/23/2002");
+        params.put("foo", "10");
+        params.put("bar", "7");
+
+        HashMap<String, Object> extraContext = new HashMap<String, Object>();
+        extraContext.put(ActionContext.PARAMETERS, params);
+
+        ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.VALIDATION_ACTION_NAME, extraContext);
+        proxy.execute();
+        assertFalse(((ValidationAware) proxy.getAction()).hasActionErrors());
+    }
+
+    public void testGetSetExpresion() {
+        ExpressionValidator ev = new ExpressionValidator();
+        ev.setExpression("{top}");
+        assertEquals("{top}", ev.getExpression());
+    }
+
+    public void testNoBooleanExpression() throws Exception {
+        Mock mock = new Mock(ValidationAware.class);
+        mock.expect("addActionError", C.ANY_ARGS);
+
+        ExpressionValidator ev = new ExpressionValidator();
+        ev.setValidatorContext(new DelegatingValidatorContext(mock.proxy()));
+        ev.setExpression("{top}");
+        ev.setValueStack(ActionContext.getContext().getValueStack());
+        ev.validate("Hello"); // {top} will evalute to Hello that is not a Boolean
+        mock.verify();
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        loadConfigurationProviders(new MockConfigurationProvider());
+
+        ActionConfig config = new ActionConfig.Builder("", "name", "").build();
+        ActionInvocation invocation = EasyMock.createNiceMock(ActionInvocation.class);
+        ActionProxy proxy = EasyMock.createNiceMock(ActionProxy.class);
+
+        EasyMock.expect(invocation.getProxy()).andReturn(proxy).anyTimes();
+        EasyMock.expect(invocation.getAction()).andReturn(null).anyTimes();
+        EasyMock.expect(invocation.invoke()).andReturn(Action.SUCCESS).anyTimes();
+        EasyMock.expect(proxy.getMethod()).andReturn("execute").anyTimes();
+        EasyMock.expect(proxy.getConfig()).andReturn(config).anyTimes();
+
+
+        EasyMock.replay(invocation);
+        EasyMock.replay(proxy);
+
+        ActionContext.getContext().setActionInvocation(invocation);
+    }
+
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/GenericValidatorContext.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/GenericValidatorContext.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/GenericValidatorContext.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/GenericValidatorContext.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import java.util.*;
+
+
+/**
+ * Dummy validator context to use to capture error messages.
+ *
+ * @author Mark Woon
+ * @author Matthew Payne
+ */
+public class GenericValidatorContext extends DelegatingValidatorContext {
+
+    private Collection<String> actionErrors;
+    private Collection<String> actionMessages;
+    private Map<String, List<String>> fieldErrors;
+
+
+    public GenericValidatorContext(Object object) {
+        super(object);
+    }
+
+
+    @Override
+    public synchronized void setActionErrors(Collection<String> errorMessages) {
+        this.actionErrors = errorMessages;
+    }
+
+    @Override
+    public synchronized Collection<String> getActionErrors() {
+        return new ArrayList<String>(internalGetActionErrors());
+    }
+
+    @Override
+    public synchronized void setActionMessages(Collection<String> messages) {
+        this.actionMessages = messages;
+    }
+
+    @Override
+    public synchronized Collection<String> getActionMessages() {
+        return new ArrayList<String>(internalGetActionMessages());
+    }
+
+    @Override
+    public synchronized void setFieldErrors(Map<String, List<String>> errorMap) {
+        this.fieldErrors = errorMap;
+    }
+
+    /**
+     * Get the field specific errors.
+     *
+     * @return an unmodifiable Map with errors mapped from fieldname (String) to Collection of String error messages
+     */
+    @Override
+    public synchronized Map<String, List<String>> getFieldErrors() {
+        return new HashMap<String, List<String>>(internalGetFieldErrors());
+    }
+
+    @Override
+    public synchronized void addActionError(String anErrorMessage) {
+        internalGetActionErrors().add(anErrorMessage);
+    }
+
+    /**
+     * Add an Action level message to this Action
+     */
+    @Override
+    public void addActionMessage(String aMessage) {
+        internalGetActionMessages().add(aMessage);
+    }
+
+    @Override
+    public synchronized void addFieldError(String fieldName, String errorMessage) {
+        final Map<String, List<String>> errors = internalGetFieldErrors();
+        List<String> thisFieldErrors = errors.get(fieldName);
+
+        if (thisFieldErrors == null) {
+            thisFieldErrors = new ArrayList<String>();
+            errors.put(fieldName, thisFieldErrors);
+        }
+
+        thisFieldErrors.add(errorMessage);
+    }
+
+    @Override
+    public synchronized boolean hasActionErrors() {
+        return (actionErrors != null) && !actionErrors.isEmpty();
+    }
+
+    /**
+     * Note that this does not have the same meaning as in WW 1.x
+     *
+     * @return (hasActionErrors() || hasFieldErrors())
+     */
+    @Override
+    public synchronized boolean hasErrors() {
+        return (hasActionErrors() || hasFieldErrors());
+    }
+
+    @Override
+    public synchronized boolean hasFieldErrors() {
+        return (fieldErrors != null) && !fieldErrors.isEmpty();
+    }
+
+    private Collection<String> internalGetActionErrors() {
+        if (actionErrors == null) {
+            actionErrors = new ArrayList<String>();
+        }
+
+        return actionErrors;
+    }
+
+    private Collection<String> internalGetActionMessages() {
+        if (actionMessages == null) {
+            actionMessages = new ArrayList<String>();
+        }
+
+        return actionMessages;
+    }
+
+    private Map<String, List<String>> internalGetFieldErrors() {
+        if (fieldErrors == null) {
+            fieldErrors = new HashMap<String, List<String>>();
+        }
+
+        return fieldErrors;
+    }
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/IntRangeValidatorTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/IntRangeValidatorTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/IntRangeValidatorTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/IntRangeValidatorTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.ActionProxy;
+import org.apache.struts2.xwork2.ValidationAware;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.config.providers.MockConfigurationProvider;
+import org.apache.struts2.xwork2.config.providers.XmlConfigurationProvider;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * IntRangeValidatorTest
+ * <p/>
+ * Created : Jan 21, 2003 12:16:01 AM
+ *
+ * @author Jason Carreira
+ */
+public class IntRangeValidatorTest extends XWorkTestCase {
+
+    public void testRangeValidation() {
+        HashMap<String, String> params = new HashMap<String, String>();
+        params.put("bar", "5");
+
+        HashMap<String, Object> extraContext = new HashMap<String, Object>();
+        extraContext.put(ActionContext.PARAMETERS, params);
+
+        try {
+            ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.VALIDATION_ACTION_NAME, extraContext);
+            proxy.execute();
+            assertTrue(((ValidationAware) proxy.getAction()).hasFieldErrors());
+
+            Map<String, List<String>> errors = ((ValidationAware) proxy.getAction()).getFieldErrors();
+            List<String> errorMessages = errors.get("bar");
+            assertEquals(1, errorMessages.size());
+
+            String errorMessage = errorMessages.get(0);
+            assertNotNull(errorMessage);
+        } catch (Exception e) {
+            e.printStackTrace();
+            fail();
+        }
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        loadConfigurationProviders(new XmlConfigurationProvider("xwork-test-beans.xml"), new MockConfigurationProvider());
+    }
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/LongRangeValidatorTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/LongRangeValidatorTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/LongRangeValidatorTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/LongRangeValidatorTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.ActionProxy;
+import org.apache.struts2.xwork2.ValidationAware;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.config.providers.MockConfigurationProvider;
+import org.apache.struts2.xwork2.config.providers.XmlConfigurationProvider;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * LongRangeValidatorTest
+ * <p/>
+ *
+ */
+public class LongRangeValidatorTest extends XWorkTestCase {
+
+    public void testRangeValidation() {
+        HashMap<String, String> params = new HashMap<String, String>();
+        params.put("longFoo", "200");
+
+        HashMap<String, Object> extraContext = new HashMap<String, Object>();
+        extraContext.put(ActionContext.PARAMETERS, params);
+
+        try {
+            ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.VALIDATION_ACTION_NAME, extraContext);
+            proxy.execute();
+            assertTrue(((ValidationAware) proxy.getAction()).hasFieldErrors());
+
+            Map errors = ((ValidationAware) proxy.getAction()).getFieldErrors();
+            List errorMessages = (List) errors.get("longFoo");
+            assertEquals(1, errorMessages.size());
+
+            String errorMessage = (String) errorMessages.get(0);
+            assertNotNull(errorMessage);
+        } catch (Exception e) {
+            e.printStackTrace();
+            fail();
+        }
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        loadConfigurationProviders(new XmlConfigurationProvider("xwork-test-beans.xml"), new MockConfigurationProvider());
+    }
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ModelDrivenValidationTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ModelDrivenValidationTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ModelDrivenValidationTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ModelDrivenValidationTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.config.providers.XmlConfigurationProvider;
+import org.apache.struts2.xwork2.Action;
+import org.apache.struts2.xwork2.ActionProxy;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.ModelDrivenAction;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * ModelDrivenValidationTest
+ *
+ * @author Jason Carreira
+ *         Created Oct 1, 2003 10:08:25 AM
+ */
+public class ModelDrivenValidationTest extends XWorkTestCase {
+
+    public void testModelDrivenValidation() throws Exception {
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("count", new String[]{"11"});
+
+        Map<String, Object> context = new HashMap<String, Object>();
+        context.put(ActionContext.PARAMETERS, params);
+
+        loadConfigurationProviders(new XmlConfigurationProvider("xwork-sample.xml"));
+        ActionProxy proxy = actionProxyFactory.createActionProxy(null, "TestModelDrivenValidation", context);
+        assertEquals(Action.SUCCESS, proxy.execute());
+
+        ModelDrivenAction action = (ModelDrivenAction) proxy.getAction();
+        assertTrue(action.hasFieldErrors());
+        assertTrue(action.getFieldErrors().containsKey("count"));
+        assertEquals("count must be between 1 and 10, current value is 11.", ((List) action.getFieldErrors().get("count")).get(0));
+    }
+
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/RegexFieldValidatorTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/RegexFieldValidatorTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/RegexFieldValidatorTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/RegexFieldValidatorTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,195 @@
+/*
+ * Copyright 2002-2006,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.util.ValueStack;
+import org.apache.struts2.xwork2.validator.validators.RegexFieldValidator;
+
+import java.util.List;
+
+/**
+ * Unit test for RegexFieldValidator.
+ * <p/>
+ * This unit test is only to test that the regex field validator works, not to
+ * unit test the build in reg.exp from JDK. That is why the expressions are so simple.
+ *
+ * @author Claus Ibsen
+ */
+public class RegexFieldValidatorTest extends XWorkTestCase {
+
+    public void testMatch() throws Exception {
+        MyTestPerson testPerson = new MyTestPerson();
+        testPerson.setUsername("Secret");
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        ActionContext.getContext().setValueStack(stack);
+
+        RegexFieldValidator validator = new RegexFieldValidator();
+        validator.setExpression("^Sec.*");
+        validator.setValidatorContext(new GenericValidatorContext(new Object()));
+        validator.setFieldName("username");
+        validator.setValueStack(ActionContext.getContext().getValueStack());
+        validator.validate(testPerson);
+
+        assertFalse(validator.getValidatorContext().hasErrors());
+        assertFalse(validator.getValidatorContext().hasActionErrors());
+        assertFalse(validator.getValidatorContext().hasActionMessages());
+        assertFalse(validator.getValidatorContext().hasFieldErrors());
+    }
+
+    public void testMatchNoTrim() throws Exception {
+        MyTestPerson testPerson = new MyTestPerson();
+        testPerson.setUsername("Secret "); // must end with one whitespace
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        ActionContext.getContext().setValueStack(stack);
+
+        RegexFieldValidator validator = new RegexFieldValidator();
+        validator.setTrim(false);
+        validator.setExpression("^Sec.*\\s");
+        validator.setValidatorContext(new GenericValidatorContext(new Object()));
+        validator.setFieldName("username");
+        validator.setValueStack(ActionContext.getContext().getValueStack());
+        validator.validate(testPerson);
+
+        assertFalse(validator.getValidatorContext().hasErrors());
+        assertFalse(validator.getValidatorContext().hasActionErrors());
+        assertFalse(validator.getValidatorContext().hasActionMessages());
+        assertFalse(validator.getValidatorContext().hasFieldErrors());
+    }
+
+    public void testFail() throws Exception {
+        MyTestPerson testPerson = new MyTestPerson();
+        testPerson.setUsername("Superman");
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        ActionContext.getContext().setValueStack(stack);
+
+        RegexFieldValidator validator = new RegexFieldValidator();
+        validator.setExpression("^Sec.*");
+        validator.setValidatorContext(new GenericValidatorContext(new Object()));
+        validator.setFieldName("username");
+        validator.setValueStack(ActionContext.getContext().getValueStack());
+        validator.validate(testPerson);
+
+        assertTrue(validator.getValidatorContext().hasErrors());
+        assertTrue(validator.getValidatorContext().hasFieldErrors());
+        List<String> msgs = validator.getValidatorContext().getFieldErrors().get("username");
+        assertNotNull(msgs);
+        assertTrue(msgs.size() == 1); // should contain 1 error message
+
+        // when failing the validator will not add action errors/msg
+        assertFalse(validator.getValidatorContext().hasActionErrors());
+        assertFalse(validator.getValidatorContext().hasActionMessages());
+    }
+
+    public void testNoFieldName() throws Exception {
+        MyTestPerson testPerson = new MyTestPerson();
+        testPerson.setUsername("NoExpression");
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        ActionContext.getContext().setValueStack(stack);
+
+        RegexFieldValidator validator = new RegexFieldValidator();
+        validator.setExpression("^Sec.*");
+        validator.setValidatorContext(new GenericValidatorContext(new Object()));
+        validator.setFieldName(null);
+        validator.setValueStack(ActionContext.getContext().getValueStack());
+        validator.validate(testPerson);
+
+        assertFalse(validator.getValidatorContext().hasErrors());
+        assertFalse(validator.getValidatorContext().hasActionErrors());
+        assertFalse(validator.getValidatorContext().hasActionMessages());
+        assertFalse(validator.getValidatorContext().hasFieldErrors());
+    }
+
+    public void testGetExpression() throws Exception {
+        RegexFieldValidator validator = new RegexFieldValidator();
+        validator.setExpression("^Hello.*");
+        assertEquals("^Hello.*", validator.getExpression());
+    }
+
+    public void testIsTrimmed() throws Exception {
+        RegexFieldValidator validator = new RegexFieldValidator();
+        assertEquals(true, validator.isTrimed());
+        validator.setTrim(false);
+        assertEquals(false, validator.isTrimed());
+    }
+
+    public void testEmptyName() throws Exception {
+        MyTestPerson testPerson = new MyTestPerson();
+        testPerson.setUsername("");
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        ActionContext.getContext().setValueStack(stack);
+
+        RegexFieldValidator validator = new RegexFieldValidator();
+        validator.setExpression("^Sec.*");
+        validator.setValidatorContext(new GenericValidatorContext(new Object()));
+        validator.setFieldName("username");
+        validator.setValueStack(ActionContext.getContext().getValueStack());
+        validator.validate(testPerson);
+
+        assertFalse(validator.getValidatorContext().hasErrors());
+        assertFalse(validator.getValidatorContext().hasActionErrors());
+        assertFalse(validator.getValidatorContext().hasActionMessages());
+        assertFalse(validator.getValidatorContext().hasFieldErrors());
+    }
+
+    public void testNoStringField() throws Exception {
+        MyTestPerson testPerson = new MyTestPerson();
+        testPerson.setAge(33);
+
+        ValueStack stack = ActionContext.getContext().getValueStack();
+        ActionContext.getContext().setValueStack(stack);
+
+        RegexFieldValidator validator = new RegexFieldValidator();
+        validator.setExpression("[0-9][0-9]");
+        validator.setValidatorContext(new GenericValidatorContext(new Object()));
+        validator.setFieldName("age");
+        validator.setValueStack(ActionContext.getContext().getValueStack());
+        validator.validate(testPerson);
+
+        assertFalse(validator.getValidatorContext().hasErrors());
+        assertFalse(validator.getValidatorContext().hasActionErrors());
+        assertFalse(validator.getValidatorContext().hasActionMessages());
+        assertFalse(validator.getValidatorContext().hasFieldErrors());
+    }
+
+    private class MyTestPerson {
+        private String username;
+        private int age;
+
+        public String getUsername() {
+            return username;
+        }
+
+        public void setUsername(String username) {
+            this.username = username;
+        }
+
+        public int getAge() {
+            return age;
+        }
+
+        public void setAge(int age) {
+            this.age = age;
+        }
+    }
+
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/RepopulateConversionErrorFieldValidatorSupportTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/RepopulateConversionErrorFieldValidatorSupportTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/RepopulateConversionErrorFieldValidatorSupportTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/RepopulateConversionErrorFieldValidatorSupportTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2002-2006,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.ActionSupport;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.mock.MockActionInvocation;
+import org.apache.struts2.xwork2.util.ValueStack;
+import org.apache.struts2.xwork2.validator.validators.RepopulateConversionErrorFieldValidatorSupport;
+
+import java.util.Map;
+
+/**
+ * Test RepopulateConversionErrorFieldValidatorSupport.
+ * 
+ * @author tm_jee
+ * @version $Date: 2011-12-02 12:24:48 +0100 (Fri, 02 Dec 2011) $ $Id: RepopulateConversionErrorFieldValidatorSupportTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ */
+public class RepopulateConversionErrorFieldValidatorSupportTest extends XWorkTestCase {
+
+	
+	InternalRepopulateConversionErrorFieldValidatorSupport validator1;
+	InternalRepopulateConversionErrorFieldValidatorSupport validator2;
+	ActionSupport action;
+	
+	public void testUseFullFieldName() throws Exception {
+		validator2.setRepopulateField("true");
+		validator2.validate(action);
+		
+		ActionContext.getContext().getActionInvocation().invoke();
+		Object valueFromStack1 = ActionContext.getContext().getValueStack().findValue("someFieldName", String.class);
+		Object valueFromStack2 = ActionContext.getContext().getValueStack().findValue("xxxsomeFieldName", String.class);
+		
+		assertNull(valueFromStack1);
+		assertEquals(valueFromStack2, "some value");
+	}
+	
+	public void testGetterSetterGetsCalledApropriately1() throws Exception {
+		
+		validator1.setRepopulateField("true");
+		validator1.validate(action);
+
+		
+		ActionContext.getContext().getActionInvocation().invoke();
+		
+		Object valueFromStack = ActionContext.getContext().getValueStack().findValue("someFieldName", String.class);
+		
+		assertEquals(valueFromStack, "some value");
+	}
+	
+	
+	public void testGetterSetterGetsCalledApropriately2() throws Exception {
+		
+		validator1.setRepopulateField("false");
+		validator1.validate(action);
+
+		
+		ActionContext.getContext().getActionInvocation().invoke();
+		
+		Object valueFromStack = ActionContext.getContext().getValueStack().findValue("someFieldName", String.class);
+		
+		assertEquals(valueFromStack, null);
+	}
+	
+	
+	@Override
+    protected void setUp() throws Exception {
+	    super.setUp();
+		ValueStack stack = ActionContext.getContext().getValueStack();
+		MockActionInvocation invocation = new MockActionInvocation();
+		invocation.setStack(stack);
+		ActionContext.getContext().setValueStack(stack);
+		ActionContext.getContext().setActionInvocation(invocation);
+		
+		String[] conversionErrorValue = new String[] { "some value" };
+		Map<String, Object> conversionErrors = ActionContext.getContext().getConversionErrors();
+		conversionErrors.put("someFieldName", conversionErrorValue);
+		conversionErrors.put("xxxsomeFieldName", conversionErrorValue);
+		
+		action = new ActionSupport();
+		validator1 = 
+			new InternalRepopulateConversionErrorFieldValidatorSupport();
+		validator1.setFieldName("someFieldName");
+		validator1.setValidatorContext(new DelegatingValidatorContext(action));
+		
+		validator2 = 
+			new InternalRepopulateConversionErrorFieldValidatorSupport();
+		validator2.setFieldName("someFieldName");
+		validator2.setValidatorContext(new DelegatingValidatorContext(action) {
+			@Override
+            public String getFullFieldName(String fieldName) {
+				return "xxx"+fieldName;
+			}
+		});
+	}
+	
+	@Override
+    protected void tearDown() throws Exception {
+	    super.tearDown();
+		validator1 = null;
+		action = null;
+	}
+	
+	
+	// === inner class ============
+	
+	class InternalRepopulateConversionErrorFieldValidatorSupport extends RepopulateConversionErrorFieldValidatorSupport {
+		public boolean doValidateGetsCalled = false;
+		
+		@Override
+        protected void doValidate(Object object) throws ValidationException {
+			doValidateGetsCalled = true;
+		}
+	}
+}

Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ShortRangeValidatorTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ShortRangeValidatorTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ShortRangeValidatorTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ShortRangeValidatorTest.java Fri Dec  2 16:33:03 2011
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.struts2.xwork2.validator;
+
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.ActionProxy;
+import org.apache.struts2.xwork2.ValidationAware;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.config.providers.MockConfigurationProvider;
+import org.apache.struts2.xwork2.config.providers.XmlConfigurationProvider;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * ShortRangeValidatorTest
+ * <p/>
+ *
+ */
+public class ShortRangeValidatorTest extends XWorkTestCase {
+
+    public void testRangeValidation() {
+        HashMap<String, Object> params = new HashMap<String, Object>();
+        params.put("shortFoo", "200");
+
+        HashMap<String, Object> extraContext = new HashMap<String, Object>();
+        extraContext.put(ActionContext.PARAMETERS, params);
+
+        try {
+            ActionProxy proxy = actionProxyFactory.createActionProxy("", MockConfigurationProvider.VALIDATION_ACTION_NAME, extraContext);
+            proxy.execute();
+            assertTrue(((ValidationAware) proxy.getAction()).hasFieldErrors());
+
+            Map errors = ((ValidationAware) proxy.getAction()).getFieldErrors();
+            List errorMessages = (List) errors.get("shortFoo");
+            assertEquals(1, errorMessages.size());
+
+            String errorMessage = (String) errorMessages.get(0);
+            assertNotNull(errorMessage);
+        } catch (Exception e) {
+            e.printStackTrace();
+            fail();
+        }
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        loadConfigurationProviders(new XmlConfigurationProvider("xwork-test-beans.xml"), new MockConfigurationProvider());
+    }
+}



Mime
View raw message