http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/TextProviderSupportTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/TextProviderSupportTest.java b/core/src/test/java/com/opensymphony/xwork2/TextProviderSupportTest.java new file mode 100644 index 0000000..cb360f7 --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/TextProviderSupportTest.java @@ -0,0 +1,126 @@ +/* + * 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 com.opensymphony.xwork2; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.ResourceBundle; + +/** + * Unit test for {@link TextProviderSupport}. + * + * @author Claus Ibsen + */ +public class TextProviderSupportTest extends XWorkTestCase { + + private TextProviderSupport tp; + private java.util.ResourceBundle rb; + + public void testHasKey() throws Exception { + assertTrue(tp.hasKey("hello")); + assertFalse(tp.hasKey("not.in.bundle")); + } + + public void testSimpleGetTexts() throws Exception { + assertEquals("Hello World", tp.getText("hello")); + assertEquals("not.in.bundle", tp.getText("not.in.bundle")); + + assertEquals("Hello World", tp.getText("hello", "this is default")); + assertEquals("this is default", tp.getText("not.in.bundle", "this is default")); + } + + public void testGetTextsWithArgs() throws Exception { + assertEquals("Hello World", tp.getText("hello", "this is default", "from me")); // no args in bundle + assertEquals("Hello World from me", tp.getText("hello.0", "this is default", "from me")); + assertEquals("this is default", tp.getText("not.in.bundle", "this is default", "from me")); + assertEquals("this is default from me", tp.getText("not.in.bundle", "this is default {0}", "from me")); + + assertEquals("not.in.bundle", tp.getText("not.in.bundle")); + } + + public void testGetTextsWithListArgs() throws Exception { + List<Object> args = new ArrayList<>(); + args.add("Santa"); + args.add("loud"); + assertEquals("Hello World", tp.getText("hello", "this is default", args)); // no args in bundle + assertEquals("Hello World Santa", tp.getText("hello.0", "this is default", args)); // only 1 arg in bundle + assertEquals("Hello World. This is Santa speaking loud", tp.getText("hello.1", "this is default", args)); + + assertEquals("this is default", tp.getText("not.in.bundle", "this is default", args)); + assertEquals("this is default Santa", tp.getText("not.in.bundle", "this is default {0}", args)); + assertEquals("this is default Santa speaking loud", tp.getText("not.in.bundle", "this is default {0} speaking {1}", args)); + + assertEquals("Hello World", tp.getText("hello", args)); // no args in bundle + assertEquals("Hello World Santa", tp.getText("hello.0", args)); // only 1 arg in bundle + assertEquals("Hello World. This is Santa speaking loud", tp.getText("hello.1", args)); + + assertEquals("not.in.bundle", tp.getText("not.in.bundle", args)); + } + + public void testGetTextsWithArrayArgs() throws Exception { + String[] args = { "Santa", "loud" }; + assertEquals("Hello World", tp.getText("hello", "this is default", args)); // no args in bundle + assertEquals("Hello World Santa", tp.getText("hello.0", "this is default", args)); // only 1 arg in bundle + assertEquals("Hello World. This is Santa speaking loud", tp.getText("hello.1", "this is default", args)); + + assertEquals("this is default", tp.getText("not.in.bundle", "this is default", args)); + assertEquals("this is default Santa", tp.getText("not.in.bundle", "this is default {0}", args)); + assertEquals("this is default Santa speaking loud", tp.getText("not.in.bundle", "this is default {0} speaking {1}", args)); + + assertEquals("Hello World", tp.getText("hello", args)); // no args in bundle + assertEquals("Hello World Santa", tp.getText("hello.0", args)); // only 1 arg in bundle + assertEquals("Hello World. This is Santa speaking loud", tp.getText("hello.1", args)); + + assertEquals("not.in.bundle", tp.getText("not.in.bundle", args)); + } + + public void testGetBundle() throws Exception { + assertEquals(rb, tp.getTexts()); + assertEquals(rb, tp.getTexts(TextProviderSupportTest.class.getName())); + } + + public void testDifficultSymbols1() { + String val= tp.getText("symbols1"); + assertEquals("\"=!@#$%^&*(){qwe}<>?:|}{[]\\';/.,<>`~'", val); + } + + public void testDifficultSymbols2() { + String val= tp.getText("symbols2"); + assertEquals("\"=!@#$%^&*()<>?:|[]\\';/.,<>`~'", val); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + rb = ResourceBundle.getBundle(TextProviderSupportTest.class.getName(), Locale.ENGLISH); + tp = new TextProviderSupport(rb, new LocaleProvider() { + public Locale getLocale() { + return Locale.ENGLISH; + } + }); + } + + @Override + protected void tearDown() throws Exception { + rb = null; + tp = null; + } + + +} +
http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/UnknownHandlerManagerMock.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/UnknownHandlerManagerMock.java b/core/src/test/java/com/opensymphony/xwork2/UnknownHandlerManagerMock.java new file mode 100644 index 0000000..d439eda --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/UnknownHandlerManagerMock.java @@ -0,0 +1,15 @@ +package com.opensymphony.xwork2; + +import java.util.ArrayList; + +/* + * Utility class for testing DefaultUnknownHandlerManager, which does not allow to add + * UnknownHandlers directly + */ +public class UnknownHandlerManagerMock extends DefaultUnknownHandlerManager { + public void addUnknownHandler(UnknownHandler uh) { + if (this.unknownHandlers == null) + this.unknownHandlers = new ArrayList<>(); + this.unknownHandlers.add(uh); + } +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/UserSpecifiedDefaultAction.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/UserSpecifiedDefaultAction.java b/core/src/test/java/com/opensymphony/xwork2/UserSpecifiedDefaultAction.java new file mode 100644 index 0000000..a9345e1 --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/UserSpecifiedDefaultAction.java @@ -0,0 +1,10 @@ +package com.opensymphony.xwork2; + +/** + * <code>UserSpecifiedDefaultAction</code> + * + * @author <a href="mailto:[email protected]">Rainer Hermanns</a> + * @version $Id$ + */ +public class UserSpecifiedDefaultAction extends ActionSupport { +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/ValidationOrderAction.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/ValidationOrderAction.java b/core/src/test/java/com/opensymphony/xwork2/ValidationOrderAction.java new file mode 100644 index 0000000..f287fdd --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/ValidationOrderAction.java @@ -0,0 +1,189 @@ +/* + * 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 com.opensymphony.xwork2; + +/** + * A sample action to test validation order. + * + * @author tm_jee + * @version $Date$ $Id$ + */ +public class ValidationOrderAction extends ActionSupport { + + private String username; + private String password; + private String confirmPassword; + private String firstName; + private String lastName; + private String city; + private String province; + private String country; + private String postalCode; + private String email; + private String website; + private String passwordHint; + + + + @Override + public String execute() throws Exception { + return SUCCESS; + } + + + + public String getCity() { + return city; + } + + + + public void setCity(String city) { + this.city = city; + } + + + + public String getConfirmPassword() { + return confirmPassword; + } + + + + public void setConfirmPassword(String confirmPassword) { + this.confirmPassword = confirmPassword; + } + + + + public String getCountry() { + return country; + } + + + + public void setCountry(String country) { + this.country = country; + } + + + + public String getEmail() { + return email; + } + + + + public void setEmail(String email) { + this.email = email; + } + + + + public String getFirstName() { + return firstName; + } + + + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + + public String getLastName() { + return lastName; + } + + + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + + public String getPassword() { + return password; + } + + + + public void setPassword(String password) { + this.password = password; + } + + + + public String getPasswordHint() { + return passwordHint; + } + + + + public void setPasswordHint(String passwordHint) { + this.passwordHint = passwordHint; + } + + + + public String getPostalCode() { + return postalCode; + } + + + + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + + + + public String getProvince() { + return province; + } + + + + public void setProvince(String province) { + this.province = province; + } + + + + public String getUsername() { + return username; + } + + + + public void setUsername(String username) { + this.username = username; + } + + + + public String getWebsite() { + return website; + } + + + + public void setWebsite(String website) { + this.website = website; + } +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/VoidResult.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/VoidResult.java b/core/src/test/java/com/opensymphony/xwork2/VoidResult.java new file mode 100644 index 0000000..ccb9ba4 --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/VoidResult.java @@ -0,0 +1,38 @@ +/* + * 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 com.opensymphony.xwork2; + +/** + */ +public class VoidResult implements Result { + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + return o instanceof VoidResult; + } + + public void execute(ActionInvocation invocation) throws Exception { + } + + @Override + public int hashCode() { + return 42; + } +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/WildCardResultTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/WildCardResultTest.java b/core/src/test/java/com/opensymphony/xwork2/WildCardResultTest.java new file mode 100644 index 0000000..c478f49 --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/WildCardResultTest.java @@ -0,0 +1,57 @@ +/* + * 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 com.opensymphony.xwork2; + +import com.opensymphony.xwork2.config.providers.XmlConfigurationProvider; +import com.opensymphony.xwork2.mock.MockResult; + +/** + * <code>WildCardResultTest</code> + * + * @author <a href="mailto:[email protected]">Rainer Hermanns</a> + * @version $Id$ + */ +public class WildCardResultTest extends XWorkTestCase { + + @Override + protected void setUp() throws Exception { + super.setUp(); + + // ensure we're using the default configuration, not simple config + XmlConfigurationProvider configurationProvider = new XmlConfigurationProvider("xwork-sample.xml"); + container.inject(configurationProvider); + loadConfigurationProviders(configurationProvider); + } + + public void testWildCardEvaluation() throws Exception { + ActionContext.setContext(null); + ActionProxy proxy = actionProxyFactory.createActionProxy(null, "WildCard", null); + assertEquals("success", proxy.execute()); + assertEquals(VoidResult.class, proxy.getInvocation().getResult().getClass()); + + ActionContext.setContext(null); + proxy = actionProxyFactory.createActionProxy(null, "WildCardInput", null); + assertEquals("input", proxy.execute()); + assertEquals(MockResult.class, proxy.getInvocation().getResult().getClass()); + + ActionContext.setContext(null); + proxy = actionProxyFactory.createActionProxy(null, "WildCardError", null); + assertEquals("error", proxy.execute()); + assertEquals(MockResult.class, proxy.getInvocation().getResult().getClass()); + } + +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/XWorkExceptionTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/XWorkExceptionTest.java b/core/src/test/java/com/opensymphony/xwork2/XWorkExceptionTest.java new file mode 100644 index 0000000..787d6e5 --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/XWorkExceptionTest.java @@ -0,0 +1,82 @@ +/* + * Copyright 2002-2007,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 com.opensymphony.xwork2; + +import com.opensymphony.xwork2.util.location.Location; + +public class XWorkExceptionTest extends XWorkTestCase { + + public void testUnknown() throws Exception { + XWorkException e = new XWorkException("testXXX", this); + assertEquals(Location.UNKNOWN, e.getLocation()); + } + + public void testThrowable() { + XWorkException e = new XWorkException("testThrowable", new IllegalArgumentException("Arg is null")); + assertEquals("com/opensymphony/xwork2/XWorkExceptionTest.java", e.getLocation().getURI()); + String s = e.getLocation().toString(); + assertTrue(s.contains("Method: testThrowable")); + } + + public void testCauseAndTarget() { + XWorkException e = new XWorkException(new IllegalArgumentException("Arg is null"), this); + assertEquals("com/opensymphony/xwork2/XWorkExceptionTest.java", e.getLocation().getURI()); + String s = e.getLocation().toString(); + assertTrue(s.contains("Method: testCauseAndTarget")); + } + + public void testDefaultConstructor() { + XWorkException e = new XWorkException(); + + assertNull(e.getCause()); + assertNull(e.getThrowable()); + assertNull(e.getMessage()); + assertNull(e.getLocation()); + + assertNull(e.toString()); // mo message so it returns null + } + + public void testMessageOnly() { + XWorkException e = new XWorkException("Hello World"); + + assertNull(e.getCause()); + assertEquals("Hello World", e.getMessage()); + assertEquals(Location.UNKNOWN, e.getLocation()); + } + + public void testCauseOnly() { + XWorkException e = new XWorkException(new IllegalArgumentException("Arg is null")); + + assertNotNull(e.getCause()); + assertNotNull(e.getLocation()); + assertEquals("com/opensymphony/xwork2/XWorkExceptionTest.java", e.getLocation().getURI()); + String s = e.getLocation().toString(); + assertTrue(s.contains("Method: testCauseOnly")); + assertTrue(e.toString().contains("Arg is null")); + } + + public void testCauseOnlyNoMessage() { + XWorkException e = new XWorkException(new IllegalArgumentException()); + + assertNotNull(e.getCause()); + assertNotNull(e.getLocation()); + assertEquals("com/opensymphony/xwork2/XWorkExceptionTest.java", e.getLocation().getURI()); + String s = e.getLocation().toString(); + assertTrue(s.contains("Method: testCauseOnly")); + assertTrue(e.toString().contains("Method: testCauseOnly")); + } + +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/config/ConfigurationManagerTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/config/ConfigurationManagerTest.java b/core/src/test/java/com/opensymphony/xwork2/config/ConfigurationManagerTest.java new file mode 100644 index 0000000..e1d81bd --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/config/ConfigurationManagerTest.java @@ -0,0 +1,180 @@ +/* + * 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 com.opensymphony.xwork2.config; + +//import org.easymock.MockControl; + +import com.mockobjects.dynamic.C; +import com.mockobjects.dynamic.Mock; +import com.opensymphony.xwork2.FileManagerFactory; +import com.opensymphony.xwork2.XWorkTestCase; +import com.opensymphony.xwork2.config.providers.XWorkConfigurationProvider; +import com.opensymphony.xwork2.inject.ContainerBuilder; +import com.opensymphony.xwork2.util.location.LocatableProperties; + +import java.util.Properties; + + +/** + * ConfigurationManagerTest + * + * @author Jason Carreira + * Created May 6, 2003 10:59:59 PM + */ +public class ConfigurationManagerTest extends XWorkTestCase { + + Mock configProviderMock; + private Configuration configuration; + + public void testConfigurationReload() { + // now check that it reloads + configProviderMock.expectAndReturn("needsReload", Boolean.TRUE); + configProviderMock.expect("init", C.isA(Configuration.class)); + configProviderMock.expect("register", C.ANY_ARGS); + configProviderMock.expect("loadPackages", C.ANY_ARGS); + configProviderMock.expect("destroy", C.ANY_ARGS); + configProviderMock.matchAndReturn("toString", "mock"); + configuration.getContainer().getInstance(FileManagerFactory.class).getFileManager().setReloadingConfigs(true); + configuration = configurationManager.getConfiguration(); + configProviderMock.verify(); + + // this will be called in teardown + configProviderMock.expect("destroy"); + } + + public void testNoConfigurationReload() { + configProviderMock.expectAndReturn("needsReload", Boolean.FALSE); + // now check that it doesn't try to reload + configuration = configurationManager.getConfiguration(); + + configProviderMock.verify(); + + // this will be called in teardown + configProviderMock.expect("destroy"); + } + + public void testDestroyConfiguration() throws Exception { + class State { + public boolean isDestroyed1 =false; + public boolean isDestroyed2 =false; + } + + final State state = new State(); + ConfigurationManager configurationManager = new ConfigurationManager(); + configurationManager.addContainerProvider(new ConfigurationProvider() { + public void destroy() { + throw new RuntimeException("testing testing 123"); + } + public void init(Configuration configuration) throws ConfigurationException { + } + public void loadPackages() throws ConfigurationException { + } + public boolean needsReload() { return false; + } + public void register(ContainerBuilder builder, Properties props) throws ConfigurationException { + } + public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { + } + }); + configurationManager.addContainerProvider(new ConfigurationProvider() { + public void destroy() { + state.isDestroyed1 = true; + } + public void init(Configuration configuration) throws ConfigurationException { + } + public void loadPackages() throws ConfigurationException { + } + public boolean needsReload() { return false; + } + public void register(ContainerBuilder builder, Properties props) throws ConfigurationException { + } + public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { + } + }); + configurationManager.addContainerProvider(new ConfigurationProvider() { + public void destroy() { + throw new RuntimeException("testing testing 123"); + } + public void init(Configuration configuration) throws ConfigurationException { + } + public void loadPackages() throws ConfigurationException { + } + public boolean needsReload() { return false; + } + public void register(ContainerBuilder builder, Properties props) throws ConfigurationException { + } + public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { + } + }); + configurationManager.addContainerProvider(new ConfigurationProvider() { + public void destroy() { + state.isDestroyed2 = true; + } + public void init(Configuration configuration) throws ConfigurationException { + } + public void loadPackages() throws ConfigurationException { + } + public boolean needsReload() { return false; + } + public void register(ContainerBuilder builder, Properties props) throws ConfigurationException { + } + public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { + } + }); + + assertFalse(state.isDestroyed1); + assertFalse(state.isDestroyed2); + + configurationManager.clearContainerProviders(); + + assertTrue(state.isDestroyed1); + assertTrue(state.isDestroyed2); + } + + public void testClearConfigurationProviders() throws Exception { + configProviderMock.expect("destroy"); + configurationManager.clearContainerProviders(); + configProviderMock.verify(); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + configurationManager.destroyConfiguration(); + + configProviderMock = new Mock(ConfigurationProvider.class); + configProviderMock.matchAndReturn("equals", C.ANY_ARGS, false); + + ConfigurationProvider mockProvider = (ConfigurationProvider) configProviderMock.proxy(); + configurationManager.addContainerProvider(new XWorkConfigurationProvider()); + configurationManager.addContainerProvider(mockProvider); + + //the first time it always inits + configProviderMock.expect("init", C.isA(Configuration.class)); + configProviderMock.expect("register", C.ANY_ARGS); + configProviderMock.expect("loadPackages", C.ANY_ARGS); + configProviderMock.matchAndReturn("toString", "mock"); + + configuration = configurationManager.getConfiguration(); + } + + @Override + protected void tearDown() throws Exception { + configProviderMock.expect("destroy"); + super.tearDown(); + } + +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/config/ConfigurationTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/config/ConfigurationTest.java b/core/src/test/java/com/opensymphony/xwork2/config/ConfigurationTest.java new file mode 100644 index 0000000..f6b9c19 --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/config/ConfigurationTest.java @@ -0,0 +1,329 @@ +/* + * 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 com.opensymphony.xwork2.config; + +import com.mockobjects.dynamic.C; +import com.mockobjects.dynamic.Mock; +import com.opensymphony.xwork2.ActionContext; +import com.opensymphony.xwork2.ActionProxy; +import com.opensymphony.xwork2.SimpleAction; +import com.opensymphony.xwork2.XWorkTestCase; +import com.opensymphony.xwork2.config.entities.ActionConfig; +import com.opensymphony.xwork2.config.providers.MockConfigurationProvider; +import com.opensymphony.xwork2.config.providers.XmlConfigurationProvider; +import com.opensymphony.xwork2.inject.ContainerBuilder; +import com.opensymphony.xwork2.mock.MockInterceptor; +import com.opensymphony.xwork2.test.StubConfigurationProvider; +import com.opensymphony.xwork2.util.location.LocatableProperties; + +import java.util.HashMap; +import java.util.Map; + + +/** + * ConfigurationTest + * <p/> + * Created : Jan 27, 2003 1:30:08 AM + * + * @author Jason Carreira + */ +public class ConfigurationTest extends XWorkTestCase { + + public void testAbstract() { + try { + actionProxyFactory.createActionProxy("/abstract", "test", null); + fail(); + } catch (Exception e) { + // this is what we expected + } + + try { + ActionProxy proxy = actionProxyFactory.createActionProxy("/nonAbstract", "test", null); + assertTrue(proxy.getActionName().equals("test")); + assertTrue(proxy.getConfig().getClassName().equals(SimpleAction.class.getName())); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + public void testDefaultNamespace() { + HashMap<String, String> params = new HashMap<>(); + params.put("blah", "this is blah"); + + HashMap<String, Object> extraContext = new HashMap<>(); + extraContext.put(ActionContext.PARAMETERS, params); + + try { + ActionProxy proxy = actionProxyFactory.createActionProxy("/does/not/exist", "Foo", extraContext); + proxy.execute(); + assertEquals("this is blah", proxy.getInvocation().getStack().findValue("[1].blah")); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + public void testFileIncludeLoader() { + RuntimeConfiguration configuration = configurationManager.getConfiguration().getRuntimeConfiguration(); + + // check entityTest package + assertNotNull(configuration.getActionConfig("includeTest", "includeTest")); + + // check inheritance from Default + assertNotNull(configuration.getActionConfig("includeTest", "Foo")); + } + + public void testWildcardName() { + RuntimeConfiguration configuration = configurationManager.getConfiguration().getRuntimeConfiguration(); + + ActionConfig config = configuration.getActionConfig("", "WildCard/Simple/input"); + + assertNotNull(config); + assertTrue("Wrong class name, "+config.getClassName(), + "com.opensymphony.xwork2.SimpleAction".equals(config.getClassName())); + assertTrue("Wrong method name", "input".equals(config.getMethodName())); + + Map<String, String> p = config.getParams(); + assertTrue("Wrong parameter, "+p.get("foo"), "Simple".equals(p.get("foo"))); + assertTrue("Wrong parameter, "+p.get("bar"), "input".equals(p.get("bar"))); + } + + public void testWildcardNamespace() { + RuntimeConfiguration configuration = configurationManager.getConfiguration().getRuntimeConfiguration(); + + ActionConfig config = configuration.getActionConfig("/animals/dog", "commandTest"); + + assertNotNull(config); + assertTrue("Wrong class name, "+config.getClassName(), + "com.opensymphony.xwork2.SimpleAction".equals(config.getClassName())); + + Map<String, String> p = config.getParams(); + assertTrue("Wrong parameter, "+p.get("0"), "/animals/dog".equals(p.get("0"))); + assertTrue("Wrong parameter, "+p.get("1"), "dog".equals(p.get("1"))); + } + + public void testGlobalResults() { + try { + ActionProxy proxy = actionProxyFactory.createActionProxy("", "Foo", null); + assertNotNull(proxy.getConfig().getResults().get("login")); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + public void testInterceptorParamInehritanceOverride() { + try { + ActionProxy proxy = actionProxyFactory.createActionProxy("/foo/bar", "TestInterceptorParamInehritanceOverride", null); + assertEquals(1, proxy.getConfig().getInterceptors().size()); + + MockInterceptor testInterceptor = (MockInterceptor) proxy.getConfig().getInterceptors().get(0).getInterceptor(); + assertEquals("foo123", testInterceptor.getExpectedFoo()); + proxy.execute(); + assertTrue(testInterceptor.isExecuted()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + public void testInterceptorParamInheritance() { + try { + ActionProxy proxy = actionProxyFactory.createActionProxy("/foo/bar", "TestInterceptorParamInheritance", null); + assertEquals(1, proxy.getConfig().getInterceptors().size()); + + MockInterceptor testInterceptor = (MockInterceptor) proxy.getConfig().getInterceptors().get(0).getInterceptor(); + assertEquals("expectedFoo", testInterceptor.getExpectedFoo()); + proxy.execute(); + assertTrue(testInterceptor.isExecuted()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + public void testInterceptorParamOverride() { + try { + ActionProxy proxy = actionProxyFactory.createActionProxy("", "TestInterceptorParamOverride", null); + assertEquals(1, proxy.getConfig().getInterceptors().size()); + + MockInterceptor testInterceptor = (MockInterceptor) proxy.getConfig().getInterceptors().get(0).getInterceptor(); + assertEquals("foo123", testInterceptor.getExpectedFoo()); + proxy.execute(); + assertTrue(testInterceptor.isExecuted()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + public void testInterceptorParams() { + try { + ActionProxy proxy = actionProxyFactory.createActionProxy("", "TestInterceptorParam", null); + assertEquals(1, proxy.getConfig().getInterceptors().size()); + + MockInterceptor testInterceptor = (MockInterceptor) proxy.getConfig().getInterceptors().get(0).getInterceptor(); + assertEquals("expectedFoo", testInterceptor.getExpectedFoo()); + proxy.execute(); + assertTrue(testInterceptor.isExecuted()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + public void testMultipleConfigProviders() { + configurationManager.addContainerProvider(new MockConfigurationProvider()); + + try { + configurationManager.reload(); + } catch (ConfigurationException e) { + e.printStackTrace(); + fail(); + } + + RuntimeConfiguration configuration = configurationManager.getConfiguration().getRuntimeConfiguration(); + + // check that it has configuration from xml + assertNotNull(configuration.getActionConfig("/foo/bar", "Bar")); + + // check that it has configuration from MockConfigurationProvider + assertNotNull(configuration.getActionConfig("", MockConfigurationProvider.FOO_ACTION_NAME)); + } + + public void testMultipleContainerProviders() throws Exception { + // to start from scratch + configurationManager.destroyConfiguration(); + // to build basic configuration + configurationManager.getConfiguration(); + + Mock mockContainerProvider = new Mock(ContainerProvider.class); + mockContainerProvider.expect("init", C.ANY_ARGS); + mockContainerProvider.expect("register", C.ANY_ARGS); + mockContainerProvider.matchAndReturn("equals", C.ANY_ARGS, false); + mockContainerProvider.matchAndReturn("toString", "foo"); + mockContainerProvider.matchAndReturn("destroy", null); + mockContainerProvider.expectAndReturn("needsReload", true); + // the order of providers must be changed as just first is checked if reload is needed + configurationManager.addContainerProvider((ContainerProvider) mockContainerProvider.proxy()); + XmlConfigurationProvider provider = new XmlConfigurationProvider("xwork-sample.xml"); + container.inject(provider); + configurationManager.addContainerProvider(provider); + + Configuration config = null; + try { + config = configurationManager.getConfiguration(); + } catch (ConfigurationException e) { + e.printStackTrace(); + fail(); + } + + RuntimeConfiguration configuration = config.getRuntimeConfiguration(); + + // check that it has configuration from xml + assertNotNull(configuration.getActionConfig("/foo/bar", "Bar")); + + mockContainerProvider.verify(); + } + + public void testInitForPackageProviders() { + + loadConfigurationProviders(new StubConfigurationProvider() { + @Override + public void register(ContainerBuilder builder, + LocatableProperties props) throws ConfigurationException { + builder.factory(PackageProvider.class, "foo", MyPackageProvider.class); + } + }); + + assertEquals(configuration, MyPackageProvider.getConfiguration()); + } + + public void testInitOnceForConfigurationProviders() { + + loadConfigurationProviders(new StubConfigurationProvider() { + boolean called = false; + @Override + public void init(Configuration config) { + if (called) { + fail("Called twice"); + } + called = true; + } + + @Override + public void loadPackages() { + if (!called) { + fail("Never called"); + } + } + }); + } + + public void testMultipleInheritance() { + try { + ActionProxy proxy; + proxy = actionProxyFactory.createActionProxy("multipleInheritance", "test", null); + assertNotNull(proxy); + proxy = actionProxyFactory.createActionProxy("multipleInheritance", "Foo", null); + assertNotNull(proxy); + proxy = actionProxyFactory.createActionProxy("multipleInheritance", "testMultipleInheritance", null); + assertNotNull(proxy); + assertEquals(5, proxy.getConfig().getInterceptors().size()); + assertEquals(2, proxy.getConfig().getResults().size()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + public void testPackageExtension() { + try { + ActionProxy proxy = actionProxyFactory.createActionProxy("/foo/bar", "Bar", null); + assertEquals(5, proxy.getConfig().getInterceptors().size()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + + @Override + protected void setUp() throws Exception { + super.setUp(); + + // ensure we're using the default configuration, not simple config + XmlConfigurationProvider provider = new XmlConfigurationProvider("xwork-sample.xml"); + container.inject(provider); + loadConfigurationProviders(provider); + } + + public static class MyPackageProvider implements PackageProvider { + static Configuration config; + public void loadPackages() throws ConfigurationException {} + public boolean needsReload() { return config != null; } + + public static Configuration getConfiguration() { + return config; + } + public void init(Configuration configuration) + throws ConfigurationException { + config = configuration; + } + + } +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/conversion/ConversionTestAction.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/conversion/ConversionTestAction.java b/core/src/test/java/com/opensymphony/xwork2/conversion/ConversionTestAction.java new file mode 100644 index 0000000..de743fe --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/conversion/ConversionTestAction.java @@ -0,0 +1,97 @@ +/* + * 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 com.opensymphony.xwork2.conversion; + +import com.opensymphony.xwork2.Action; +import com.opensymphony.xwork2.conversion.annotations.Conversion; +import com.opensymphony.xwork2.conversion.annotations.ConversionRule; +import com.opensymphony.xwork2.conversion.annotations.ConversionType; +import com.opensymphony.xwork2.conversion.annotations.TypeConversion; + +import java.util.HashMap; +import java.util.List; + +/** + * <code>ConversionTestAction</code> + * + * @author Rainer Hermanns + * @version $Id$ + */ +@Conversion() +public class ConversionTestAction implements Action { + + + + private String convertInt; + + private String convertDouble; + + private List users = null; + + + private HashMap keyValues = null; + + + public String getConvertInt() { + return convertInt; + } + + @TypeConversion(type = ConversionType.APPLICATION, converter = "com.opensymphony.xwork2.util.XWorkBasicConverter") + public void setConvertInt( String convertInt ) { + this.convertInt = convertInt; + } + + public String getConvertDouble() { + return convertDouble; + } + + @TypeConversion(converter = "com.opensymphony.xwork2.util.XWorkBasicConverter") + public void setConvertDouble( String convertDouble ) { + this.convertDouble = convertDouble; + } + + public List getUsers() { + return users; + } + + @TypeConversion(rule = ConversionRule.COLLECTION, converter = "java.lang.String") + public void setUsers( List users ) { + this.users = users; + } + + public HashMap getKeyValues() { + return keyValues; + } + + @TypeConversion(rule = ConversionRule.MAP, converter = "java.math.BigInteger") + public void setKeyValues( HashMap keyValues ) { + this.keyValues = keyValues; + } + + /** + * Where the logic of the action is executed. + * + * @return a string representing the logical result of the execution. + * See constants in this interface for a list of standard result values. + * @throws Exception thrown if a system level exception occurs. + * Application level exceptions should be handled by returning + * an error value, such as Action.ERROR. + */ + @TypeConversion(type = ConversionType.APPLICATION, key = "java.util.Date", converter = "com.opensymphony.xwork2.util.XWorkBasicConverter") + public String execute() throws Exception { + return SUCCESS; + } +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/inject/ContainerImplTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/inject/ContainerImplTest.java b/core/src/test/java/com/opensymphony/xwork2/inject/ContainerImplTest.java new file mode 100644 index 0000000..2b3106d --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/inject/ContainerImplTest.java @@ -0,0 +1,119 @@ +package com.opensymphony.xwork2.inject; + +import junit.framework.TestCase; + +/** + * ContainerImpl Tester. + * + * @author Lukasz Lenart + * @version 1.0 + * @since <pre>11/26/2008</pre> + */ +public class ContainerImplTest extends TestCase { + + private Container c; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ContainerBuilder cb = new ContainerBuilder(); + cb.constant("methodCheck.name", "Lukasz"); + cb.constant("fieldCheck.name", "Lukasz"); + c = cb.create(false); + } + + /** + * Inject values into field + */ + public void testFieldInjector() throws Exception { + + FieldCheck fieldCheck = new FieldCheck(); + + try { + c.inject(fieldCheck); + assertTrue(true); + } catch (DependencyException expected) { + fail("No exception expected!"); + } + + assertEquals(fieldCheck.getName(), "Lukasz"); + } + + /** + * Inject values into method + */ + public void testMethodInjector() throws Exception { + + MethodCheck methodCheck = new MethodCheck(); + + try { + c.inject(methodCheck); + assertTrue(true); + } catch (DependencyException expected) { + fail("No exception expected!"); + } + } + + /** + * Inject values into field under SecurityManager + */ + public void testFieldInjectorWithSecurityEnabled() throws Exception { + + System.setSecurityManager(new SecurityManager()); + + FieldCheck fieldCheck = new FieldCheck(); + + try { + c.inject(fieldCheck); + assertEquals(fieldCheck.getName(), "Lukasz"); + fail("Exception should be thrown!"); + } catch (DependencyException expected) { + // that was expected + } + } + + /** + * Inject values into method under SecurityManager + */ + public void testMethodInjectorWithSecurityEnabled() throws Exception { + + // not needed, already set + //System.setSecurityManager(new SecurityManager()); + + MethodCheck methodCheck = new MethodCheck(); + + try { + c.inject(methodCheck); + assertEquals(methodCheck.getName(), "Lukasz"); + fail("Exception sould be thrown!"); + } catch (DependencyException expected) { + // that was expected + } + } + + class FieldCheck { + + @Inject("fieldCheck.name") + private String name; + + public String getName() { + return name; + } + } + + class MethodCheck { + + private String name; + + @Inject("methodCheck.name") + private void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + } + +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/interceptor/AliasInterceptorTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/interceptor/AliasInterceptorTest.java b/core/src/test/java/com/opensymphony/xwork2/interceptor/AliasInterceptorTest.java new file mode 100644 index 0000000..00077be --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/interceptor/AliasInterceptorTest.java @@ -0,0 +1,133 @@ +/* + * 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 com.opensymphony.xwork2.interceptor; + +import com.opensymphony.xwork2.*; +import com.opensymphony.xwork2.config.entities.ActionConfig; +import com.opensymphony.xwork2.config.providers.XmlConfigurationProvider; +import com.opensymphony.xwork2.mock.MockActionInvocation; +import com.opensymphony.xwork2.mock.MockActionProxy; + +import java.util.HashMap; +import java.util.Map; + + +/** + * AliasInterceptorTest + * + * Test of aliasInterceptor specifically depends on actionTest test defined in /test/xwork.xml + * stack.getContext().putAll(params); + * <p/> + * e.g. + * <action name="aliasTest" class="com.opensymphony.xwork2.SimpleAction"> + * <param name="aliases">#{ "aliasSource" : "aliasDest", "bar":"baz" }</param> + * <interceptor-ref name="defaultStack"/> + * <interceptor-ref name="alias"/> + * </action> + * + * @author Matthew Payne + */ +public class AliasInterceptorTest extends XWorkTestCase { + + public void testUsingDefaultInterceptorThatAliasPropertiesAreCopied() throws Exception { + Map<String, Object> params = new HashMap<>(); + params.put("aliasSource", "source here"); + + XmlConfigurationProvider provider = new XmlConfigurationProvider("xwork-sample.xml"); + container.inject(provider); + loadConfigurationProviders(provider); + ActionProxy proxy = actionProxyFactory.createActionProxy("", "aliasTest", params); + SimpleAction actionOne = (SimpleAction) proxy.getAction(); + actionOne.setAliasSource("name to be copied"); + actionOne.setFoo(17); + actionOne.setBar(23); + proxy.execute(); + assertEquals(actionOne.getAliasSource(), actionOne.getAliasDest()); + } + + public void testInvalidAliasExpression() throws Exception { + Action action = new SimpleFooAction(); + MockActionInvocation mai = new MockActionInvocation(); + + MockActionProxy map = new MockActionProxy(); + + ActionConfig cfg = new ActionConfig.Builder("", "", "") + .addParam("aliases", "invalid alias expression") + .build(); + map.setConfig(cfg); + + mai.setProxy(map); + mai.setAction(action); + mai.setInvocationContext(ActionContext.getContext()); + + AliasInterceptor ai = new AliasInterceptor(); + ai.init(); + + ai.intercept(mai); + + ai.destroy(); + } + + public void testSetAliasKeys() throws Exception { + Action action = new SimpleFooAction(); + MockActionInvocation mai = new MockActionInvocation(); + + MockActionProxy map = new MockActionProxy(); + + ActionConfig cfg = new ActionConfig.Builder("", "", "") + .addParam("hello", "invalid alias expression") + .build(); + map.setConfig(cfg); + + mai.setProxy(map); + mai.setAction(action); + mai.setInvocationContext(ActionContext.getContext()); + + AliasInterceptor ai = new AliasInterceptor(); + ai.init(); + ai.setAliasesKey("hello"); + + ai.intercept(mai); + + ai.destroy(); + } + + public void testSetInvalidAliasKeys() throws Exception { + Action action = new SimpleFooAction(); + MockActionInvocation mai = new MockActionInvocation(); + + MockActionProxy map = new MockActionProxy(); + + ActionConfig cfg = new ActionConfig.Builder("", "", "") + .addParam("hello", "invalid alias expression") + .build(); + map.setConfig(cfg); + + mai.setProxy(map); + mai.setAction(action); + mai.setInvocationContext(ActionContext.getContext()); + + AliasInterceptor ai = new AliasInterceptor(); + ai.init(); + ai.setAliasesKey("iamnotinconfig"); + + ai.intercept(mai); + + ai.destroy(); + } + +} + http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/interceptor/ChainingInterceptorTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/interceptor/ChainingInterceptorTest.java b/core/src/test/java/com/opensymphony/xwork2/interceptor/ChainingInterceptorTest.java new file mode 100644 index 0000000..1b84209 --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/interceptor/ChainingInterceptorTest.java @@ -0,0 +1,168 @@ +/* + * 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 com.opensymphony.xwork2.interceptor; + +import com.mockobjects.dynamic.Mock; +import com.opensymphony.xwork2.*; +import com.opensymphony.xwork2.util.ValueStack; + +import java.util.*; + + +/** + * Unit test for {@link ChainingInterceptor}. + * + * @author Jason Carreira + */ +public class ChainingInterceptorTest extends XWorkTestCase { + + ActionInvocation invocation; + ChainingInterceptor interceptor; + Mock mockInvocation; + ValueStack stack; + + + public void testActionErrorsCanBeAddedAfterChain() throws Exception { + SimpleAction action1 = new SimpleAction(); + SimpleAction action2 = new SimpleAction(); + action1.addActionError("foo"); + mockInvocation.matchAndReturn("getAction", action2); + stack.push(action1); + stack.push(action2); + interceptor.setCopyErrors("true"); + interceptor.setCopyMessages("true"); + + interceptor.intercept(invocation); + + assertEquals(action1.getActionErrors(), action2.getActionErrors()); + action2.addActionError("bar"); + assertEquals(1, action1.getActionErrors().size()); + assertEquals(2, action2.getActionErrors().size()); + assertTrue(action2.getActionErrors().contains("bar")); + } + + public void testActionErrorsNotCopiedAfterChain() throws Exception { + SimpleAction action1 = new SimpleAction(); + SimpleAction action2 = new SimpleAction(); + action1.addActionError("foo"); + mockInvocation.matchAndReturn("getAction", action2); + stack.push(action1); + stack.push(action2); + + interceptor.intercept(invocation); + + assertEquals(Collections.EMPTY_LIST, action2.getActionErrors()); + action2.addActionError("bar"); + assertEquals(1, action1.getActionErrors().size()); + assertEquals(1, action2.getActionErrors().size()); + assertTrue(action2.getActionErrors().contains("bar")); + assertFalse(action2.getActionErrors().contains("foo")); + } + + public void testPropertiesChained() throws Exception { + TestBean bean = new TestBean(); + TestBeanAction action = new TestBeanAction(); + mockInvocation.matchAndReturn("getAction", action); + bean.setBirth(new Date()); + bean.setName("foo"); + bean.setCount(1); + stack.push(bean); + stack.push(action); + interceptor.setCopyErrors("true"); + interceptor.setCopyMessages("true"); + + interceptor.intercept(invocation); + + assertEquals(bean.getBirth(), action.getBirth()); + assertEquals(bean.getName(), action.getName()); + assertEquals(bean.getCount(), action.getCount()); + } + + public void testExcludesPropertiesChained() throws Exception { + TestBean bean = new TestBean(); + TestBeanAction action = new TestBeanAction(); + mockInvocation.matchAndReturn("getAction", action); + bean.setBirth(new Date()); + bean.setName("foo"); + bean.setCount(1); + stack.push(bean); + stack.push(action); + interceptor.setCopyErrors("true"); + interceptor.setCopyMessages("true"); + + Collection<String> excludes = new ArrayList<>(); + excludes.add("count"); + interceptor.setExcludes(excludes); + + interceptor.intercept(invocation); + + assertEquals(bean.getBirth(), action.getBirth()); + assertEquals(bean.getName(), action.getName()); + assertEquals(0, action.getCount()); + assertEquals(excludes, interceptor.getExcludes()); + } + + public void testTwoExcludesPropertiesChained() throws Exception { + TestBean bean = new TestBean(); + TestBeanAction action = new TestBeanAction(); + mockInvocation.matchAndReturn("getAction", action); + bean.setBirth(new Date()); + bean.setName("foo"); + bean.setCount(1); + stack.push(bean); + stack.push(action); + + Collection<String> excludes = new ArrayList<>(); + excludes.add("name"); + excludes.add("count"); + interceptor.setExcludes(excludes); + interceptor.intercept(invocation); + assertEquals(bean.getBirth(), action.getBirth()); + assertEquals(null, action.getName()); + assertEquals(0, action.getCount()); + assertEquals(excludes, interceptor.getExcludes()); + } + + public void testNullCompoundRootElementAllowsProcessToContinue() throws Exception { + // we should not get NPE, but instead get a warning logged. + stack.push(null); + stack.push(null); + stack.push(null); + interceptor.intercept(invocation); + } + + + @Override + protected void setUp() throws Exception { + super.setUp(); + stack = ActionContext.getContext().getValueStack(); + mockInvocation = new Mock(ActionInvocation.class); + mockInvocation.expectAndReturn("getStack", stack); + mockInvocation.expectAndReturn("invoke", Action.SUCCESS); + mockInvocation.expectAndReturn("getInvocationContext", new ActionContext(new HashMap<String, Object>())); + mockInvocation.expectAndReturn("getResult", new ActionChainResult()); + invocation = (ActionInvocation) mockInvocation.proxy(); + interceptor = new ChainingInterceptor(); + container.inject(interceptor); + } + + + private class TestBeanAction extends TestBean implements Action { + public String execute() throws Exception { + return SUCCESS; + } + } +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptorTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptorTest.java b/core/src/test/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptorTest.java new file mode 100644 index 0000000..0e34ae1 --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/interceptor/ConversionErrorInterceptorTest.java @@ -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 com.opensymphony.xwork2.interceptor; + +import com.mockobjects.dynamic.C; +import com.mockobjects.dynamic.Mock; +import com.opensymphony.xwork2.*; +import com.opensymphony.xwork2.mock.MockActionInvocation; +import com.opensymphony.xwork2.util.ValueStack; + +import java.util.HashMap; +import java.util.Map; + + +/** + * Unit test for {@link ConversionErrorInterceptor}. + * + * @author Jason Carreira + */ +public class ConversionErrorInterceptorTest extends XWorkTestCase { + + protected ActionContext context; + protected ActionInvocation invocation; + protected ConversionErrorInterceptor interceptor; + protected Map<String, Object> conversionErrors; + protected Mock mockInvocation; + protected ValueStack stack; + + + public void testFieldErrorAdded() throws Exception { + conversionErrors.put("foo", 123L); + + SimpleAction action = new SimpleAction(); + mockInvocation.expectAndReturn("getAction", action); + stack.push(action); + mockInvocation.matchAndReturn("getAction", action); + assertNull(action.getFieldErrors().get("foo")); + interceptor.intercept(invocation); + assertTrue(action.hasFieldErrors()); + assertNotNull(action.getFieldErrors().get("foo")); + } + + public void testFieldErrorWithMapKeyAdded() throws Exception { + String fieldName = "foo['1'].intValue"; + conversionErrors.put(fieldName, "bar"); + ActionSupport action = new ActionSupport(); + mockInvocation.expectAndReturn("getAction", action); + stack.push(action); + mockInvocation.matchAndReturn("getAction", action); + assertNull(action.getFieldErrors().get(fieldName)); + interceptor.intercept(invocation); + assertTrue(action.hasFieldErrors()); // This fails! + assertNotNull(action.getFieldErrors().get(fieldName)); + } + + public void testWithPreResultListener() throws Exception { + conversionErrors.put("foo", "Hello"); + + ActionContext ac = createActionContext(); + MockActionInvocation mai = createActionInvocation(ac); + SimpleAction action = createAction(mai); + + assertNull(action.getFieldErrors().get("foo")); + assertEquals(55, stack.findValue("foo")); + + interceptor.intercept(mai); + + assertTrue(action.hasFieldErrors()); + assertNotNull(action.getFieldErrors().get("foo")); + + assertEquals("Hello", stack.findValue("foo")); // assume that the original value is reset + } + + /** + * See WW-3668 + * + * @throws Exception + */ + public void testWithPreResultListenerAgainstMaliciousCode() throws Exception { + conversionErrors.put("foo", "\" + #root + \""); + + ActionContext ac = createActionContext(); + + MockActionInvocation mai = createActionInvocation(ac); + + SimpleAction action = createAction(mai); + assertNull(action.getFieldErrors().get("foo")); + assertEquals(55, stack.findValue("foo")); + + interceptor.intercept(mai); + + assertTrue(action.hasFieldErrors()); + assertNotNull(action.getFieldErrors().get("foo")); + + assertEquals("\" + #root + \"", stack.findValue("foo")); + } + + private MockActionInvocation createActionInvocation(ActionContext ac) { + MockActionInvocation mai = new MockActionInvocation(); + mai.setInvocationContext(ac); + mai.setStack(stack); + return mai; + } + + private SimpleAction createAction(MockActionInvocation mai) { + SimpleAction action = new SimpleAction(); + action.setFoo(55); + mai.setAction(action); + stack.push(action); + return action; + } + + private ActionContext createActionContext() { + ActionContext ac = new ActionContext(stack.getContext()); + ac.setConversionErrors(conversionErrors); + ac.setValueStack(stack); + return ac; + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + interceptor = new ConversionErrorInterceptor(); + mockInvocation = new Mock(ActionInvocation.class); + invocation = (ActionInvocation) mockInvocation.proxy(); + stack = ActionContext.getContext().getValueStack(); + context = new ActionContext(stack.getContext()); + conversionErrors = new HashMap<>(); + context.setConversionErrors(conversionErrors); + mockInvocation.matchAndReturn("getInvocationContext", context); + mockInvocation.expect("addPreResultListener", C.isA(PreResultListener.class)); + mockInvocation.expectAndReturn("invoke", Action.SUCCESS); + } +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptorTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptorTest.java b/core/src/test/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptorTest.java new file mode 100644 index 0000000..80ccae2 --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/interceptor/DefaultWorkflowInterceptorTest.java @@ -0,0 +1,214 @@ +/* + * 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 com.opensymphony.xwork2.interceptor; + +import com.opensymphony.xwork2.*; +import com.opensymphony.xwork2.config.entities.ActionConfig; +import com.opensymphony.xwork2.config.entities.InterceptorConfig; +import com.opensymphony.xwork2.validator.ValidationInterceptor; +import org.easymock.EasyMock; +import org.easymock.IAnswer; + +import java.util.HashMap; + + +/** + * Unit test for {@link DefaultWorkflowInterceptor}. + * + * @author Jason Carreira + */ +public class DefaultWorkflowInterceptorTest extends XWorkTestCase { + + DefaultWorkflowInterceptor interceptor; + private ActionInvocation invocation; + private Action action; + private ActionProxy proxy; + private ActionConfig config; + private String result = "testing123"; + + + public void testInvokesActionInvocationIfNoErrors() throws Exception { + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.intercept(invocation); + assertEquals(result, interceptor.intercept(invocation)); + } + + public void testReturnsInputWithoutExecutingIfHasErrors() throws Exception { + result = Action.INPUT; + + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.intercept(invocation); + assertEquals(Action.INPUT, interceptor.intercept(invocation)); + } + + public void testExcludesMethod() throws Exception { + interceptor.setExcludeMethods("execute"); + + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.setExcludeMethods("execute"); + interceptor.setExcludeMethods("execute"); + validationInterceptor.intercept(invocation); + + assertEquals(result, interceptor.intercept(invocation)); + } + + public void testExcludesMethodWithWildCard() throws Exception { + interceptor.setExcludeMethods("*"); + + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.intercept(invocation); + validationInterceptor.setExcludeMethods("*"); + assertEquals(result, interceptor.intercept(invocation)); + } + + public void testIncludesMethodWithWildcard() throws Exception { + interceptor.setIncludeMethods("*"); + + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.setIncludeMethods("*"); + validationInterceptor.intercept(invocation); + + assertEquals(result, interceptor.intercept(invocation)); + } + + + public void testIncludesMethod() throws Exception { + interceptor.setIncludeMethods("execute"); + + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.setIncludeMethods("execute"); + validationInterceptor.intercept(invocation); + + assertEquals(result, interceptor.intercept(invocation)); + } + + public void testIncludesAndExcludesMethod() throws Exception { + interceptor.setExcludeMethods("execute,input,validate"); + interceptor.setIncludeMethods("execute"); + + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.setExcludeMethods("execute,input,validate"); + validationInterceptor.setIncludeMethods("execute"); + validationInterceptor.intercept(invocation); + + assertEquals(result, interceptor.intercept(invocation)); + } + + public void testIncludesAndExcludesMethodAllWildCarded() throws Exception { + interceptor.setExcludeMethods("*"); + interceptor.setIncludeMethods("*"); + + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.setExcludeMethods("*"); + validationInterceptor.setIncludeMethods("*"); + validationInterceptor.intercept(invocation); + + assertEquals(result, interceptor.intercept(invocation)); + } + + public void testIncludesAndExcludesMethodWithExcludeWildcard() throws Exception { + interceptor.setExcludeMethods("*"); + interceptor.setIncludeMethods("execute"); + + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.setExcludeMethods("*"); + validationInterceptor.setIncludeMethods("execute"); + validationInterceptor.intercept(invocation); + + assertEquals(result, interceptor.intercept(invocation)); + } + + public void testIncludesAndExcludesMethodWithIncludeWildcardAndNoMatches() throws Exception { + interceptor.setExcludeMethods("execute,input,validate"); + interceptor.setIncludeMethods("*"); + + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.setExcludeMethods("execute,input,validate"); + validationInterceptor.setIncludeMethods("*"); + validationInterceptor.intercept(invocation); + + assertEquals(result, interceptor.intercept(invocation)); + } + + public void testIncludesAndExcludesMethodWithIncludeWildcard() throws Exception { + interceptor.setExcludeMethods("input,validate"); + interceptor.setIncludeMethods("*"); + + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.setExcludeMethods("input,validate"); + validationInterceptor.setIncludeMethods("*"); + validationInterceptor.intercept(invocation); + + assertEquals(result, interceptor.intercept(invocation)); + } + + public void testNoValidateAction() throws Exception { + ValidationInterceptor validationInterceptor = create(); + validationInterceptor.setExcludeMethods("execute,input,validate"); + validationInterceptor.setIncludeMethods("execute"); + validationInterceptor.intercept(invocation); + + assertEquals(result, interceptor.intercept(invocation)); + } + + + @Override + protected void setUp() throws Exception { + super.setUp(); + config = new ActionConfig.Builder("", "name", "").build(); + action = EasyMock.createNiceMock(ValidateAction.class); + invocation = EasyMock.createNiceMock(ActionInvocation.class); + interceptor = new DefaultWorkflowInterceptor(); + proxy = EasyMock.createNiceMock(ActionProxy.class); + + EasyMock.expect(invocation.getProxy()).andReturn(proxy).anyTimes(); + EasyMock.expect(invocation.getAction()).andReturn(action).anyTimes(); + EasyMock.expect(invocation.invoke()).andAnswer(new IAnswer<String>() { + public String answer() throws Throwable { + return result; + } + }).anyTimes(); + + EasyMock.expect(proxy.getConfig()).andReturn(config).anyTimes(); + EasyMock.expect(proxy.getMethod()).andReturn("execute").anyTimes(); + + + EasyMock.replay(invocation); + EasyMock.replay(action); + EasyMock.replay(proxy); + + ActionContext actionContext = new ActionContext(new HashMap<String, Object>()); + ActionContext.setContext(actionContext); + actionContext.setActionInvocation(invocation); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + protected ValidationInterceptor create() { + ObjectFactory objectFactory = container.getInstance(ObjectFactory.class); + return (ValidationInterceptor) objectFactory.buildInterceptor( + new InterceptorConfig.Builder("model", ValidationInterceptor.class.getName()).build(), new HashMap<String, String>()); + } + + + + + private interface ValidateAction extends Action, Validateable, ValidationAware { + } +} http://git-wip-us.apache.org/repos/asf/struts/blob/31af5842/core/src/test/java/com/opensymphony/xwork2/interceptor/ExceptionMappingInterceptorTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/com/opensymphony/xwork2/interceptor/ExceptionMappingInterceptorTest.java b/core/src/test/java/com/opensymphony/xwork2/interceptor/ExceptionMappingInterceptorTest.java new file mode 100644 index 0000000..aad0aec --- /dev/null +++ b/core/src/test/java/com/opensymphony/xwork2/interceptor/ExceptionMappingInterceptorTest.java @@ -0,0 +1,307 @@ +/* + * 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 com.opensymphony.xwork2.interceptor; + +import com.mockobjects.dynamic.Mock; +import com.opensymphony.xwork2.*; +import com.opensymphony.xwork2.config.entities.ActionConfig; +import com.opensymphony.xwork2.config.entities.ExceptionMappingConfig; +import com.opensymphony.xwork2.util.ValueStack; +import com.opensymphony.xwork2.validator.ValidationException; + +import java.util.HashMap; + +/** + * Unit test for ExceptionMappingInterceptor. + * + * @author Matthew E. Porter (matthew dot porter at metissian dot com) + */ +public class ExceptionMappingInterceptorTest extends XWorkTestCase { + + ActionInvocation invocation; + ExceptionMappingInterceptor interceptor; + Mock mockInvocation; + ValueStack stack; + + + public void testThrownExceptionMatching() throws Exception { + this.setUpWithExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new XWorkException("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + String result = interceptor.intercept(invocation); + assertNotNull(stack.findValue("exception")); + assertEquals(stack.findValue("exception"), exception); + assertEquals(result, "spooky"); + ExceptionHolder holder = (ExceptionHolder) stack.getRoot().get(0); // is on top of the root + assertNotNull(holder.getExceptionStack()); // to invoke the method for unit test + } + + public void testThrownExceptionMatching2() throws Exception { + this.setUpWithExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new ValidationException("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + String result = interceptor.intercept(invocation); + assertNotNull(stack.findValue("exception")); + assertEquals(stack.findValue("exception"), exception); + assertEquals(result, "throwable"); + } + + public void testNoThrownException() throws Exception { + this.setUpWithExceptionMappings(); + + Mock action = new Mock(Action.class); + mockInvocation.expectAndReturn("invoke", Action.SUCCESS); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + String result = interceptor.intercept(invocation); + assertEquals(result, Action.SUCCESS); + assertNull(stack.findValue("exception")); + } + + public void testThrownExceptionNoMatch() throws Exception { + this.setupWithoutExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new Exception("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + + try { + interceptor.intercept(invocation); + fail("Should not have reached this point."); + } catch (Exception e) { + assertEquals(e, exception); + } + } + + public void testThrownExceptionNoMatchLogging() throws Exception { + this.setupWithoutExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new Exception("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + + try { + interceptor.setLogEnabled(true); + interceptor.intercept(invocation); + fail("Should not have reached this point."); + } catch (Exception e) { + assertEquals(e, exception); + } + } + + public void testThrownExceptionNoMatchLoggingCategory() throws Exception { + this.setupWithoutExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new Exception("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + + try { + interceptor.setLogEnabled(true); + interceptor.setLogCategory("showcase.unhandled"); + interceptor.intercept(invocation); + fail("Should not have reached this point."); + } catch (Exception e) { + assertEquals(e, exception); + } + } + + public void testThrownExceptionNoMatchLoggingCategoryLevelFatal() throws Exception { + this.setupWithoutExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new Exception("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + + try { + interceptor.setLogEnabled(true); + interceptor.setLogCategory("showcase.unhandled"); + interceptor.setLogLevel("fatal"); + interceptor.intercept(invocation); + fail("Should not have reached this point."); + } catch (Exception e) { + assertEquals(e, exception); + } + + assertEquals("fatal", interceptor.getLogLevel()); + assertEquals(true, interceptor.isLogEnabled()); + assertEquals("showcase.unhandled", interceptor.getLogCategory()); + } + + public void testThrownExceptionNoMatchLoggingCategoryLevelError() throws Exception { + this.setupWithoutExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new Exception("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + + try { + interceptor.setLogEnabled(true); + interceptor.setLogCategory("showcase.unhandled"); + interceptor.setLogLevel("error"); + interceptor.intercept(invocation); + fail("Should not have reached this point."); + } catch (Exception e) { + assertEquals(e, exception); + } + } + + public void testThrownExceptionNoMatchLoggingCategoryLevelWarn() throws Exception { + this.setupWithoutExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new Exception("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + + try { + interceptor.setLogEnabled(true); + interceptor.setLogCategory("showcase.unhandled"); + interceptor.setLogLevel("warn"); + interceptor.intercept(invocation); + fail("Should not have reached this point."); + } catch (Exception e) { + assertEquals(e, exception); + } + } + + public void testThrownExceptionNoMatchLoggingCategoryLevelInfo() throws Exception { + this.setupWithoutExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new Exception("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + + try { + interceptor.setLogEnabled(true); + interceptor.setLogCategory("showcase.unhandled"); + interceptor.setLogLevel("info"); + interceptor.intercept(invocation); + fail("Should not have reached this point."); + } catch (Exception e) { + assertEquals(e, exception); + } + } + + public void testThrownExceptionNoMatchLoggingCategoryLevelDebug() throws Exception { + this.setupWithoutExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new Exception("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + + try { + interceptor.setLogEnabled(true); + interceptor.setLogCategory("showcase.unhandled"); + interceptor.setLogLevel("debug"); + interceptor.intercept(invocation); + fail("Should not have reached this point."); + } catch (Exception e) { + assertEquals(e, exception); + } + } + + public void testThrownExceptionNoMatchLoggingCategoryLevelTrace() throws Exception { + this.setupWithoutExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new Exception("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + + try { + interceptor.setLogEnabled(true); + interceptor.setLogCategory("showcase.unhandled"); + interceptor.setLogLevel("trace"); + interceptor.intercept(invocation); + fail("Should not have reached this point."); + } catch (Exception e) { + assertEquals(e, exception); + } + } + + public void testThrownExceptionNoMatchLoggingUnknownLevel() throws Exception { + this.setupWithoutExceptionMappings(); + + Mock action = new Mock(Action.class); + Exception exception = new Exception("test"); + mockInvocation.expectAndThrow("invoke", exception); + mockInvocation.matchAndReturn("getAction", ((Action) action.proxy())); + + try { + interceptor.setLogEnabled(true); + interceptor.setLogLevel("xxx"); + interceptor.intercept(invocation); + fail("Should not have reached this point."); + } catch (IllegalArgumentException e) { + // success + } + } + + private void setupWithoutExceptionMappings() { + ActionConfig actionConfig = new ActionConfig.Builder("", "", "").build(); + Mock actionProxy = new Mock(ActionProxy.class); + actionProxy.expectAndReturn("getConfig", actionConfig); + mockInvocation.expectAndReturn("getProxy", ((ActionProxy) actionProxy.proxy())); + invocation = (ActionInvocation) mockInvocation.proxy(); + } + + private void setUpWithExceptionMappings() { + ActionConfig actionConfig = new ActionConfig.Builder("", "", "") + .addExceptionMapping(new ExceptionMappingConfig.Builder("xwork", "com.opensymphony.xwork2.XWorkException", "spooky").build()) + .addExceptionMapping(new ExceptionMappingConfig.Builder("throwable", "java.lang.Throwable", "throwable").build()) + .build(); + Mock actionProxy = new Mock(ActionProxy.class); + actionProxy.expectAndReturn("getConfig", actionConfig); + mockInvocation.expectAndReturn("getProxy", ((ActionProxy) actionProxy.proxy())); + + invocation = (ActionInvocation) mockInvocation.proxy(); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + stack = ActionContext.getContext().getValueStack(); + mockInvocation = new Mock(ActionInvocation.class); + mockInvocation.expectAndReturn("getStack", stack); + mockInvocation.expectAndReturn("getInvocationContext", new ActionContext(new HashMap<String, Object>())); + interceptor = new ExceptionMappingInterceptor(); + interceptor.init(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + interceptor.destroy(); + invocation = null; + interceptor = null; + mockInvocation = null; + stack = null; + } + +}
