Completed SHL-1

Work in progress for SHL-2, SHL-3.
This commit is contained in:
Mark Pollack
2012-03-13 19:52:17 -04:00
parent 833c787403
commit f2debb62f4
195 changed files with 22089 additions and 22 deletions

View File

@@ -0,0 +1,31 @@
package org.springframework.roo.shell;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
/**
* Unit test of {@link AbstractShell} (not a superclass for writing tests for
* {@link AbstractShell} subclasses)
*
* @author Andrew Swan
* @since 1.2.0
*/
public class AbstractShellTest {
@Test
public void testProps() {
// Set up
final AbstractShell shell = mock(AbstractShell.class);
when(shell.props()).thenCallRealMethod();
// Invoke
final String props = shell.props();
// Check
assertNotNull(props);
}
}

View File

@@ -0,0 +1,44 @@
package org.springframework.roo.shell;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Test;
/**
* Unit test of {@link CliOptionContext}
*
* @author Andrew Swan
* @since 1.2.0
*/
public class CliOptionContextTest {
// Constants
private static final String OPTION_CONTEXT = "anything";
@Test
public void testGetOptionContextWhenNoneSet() {
assertNull(CliOptionContext.getOptionContext());
}
@Test
public void testSetAndGetOptionContext() {
// Set up
CliOptionContext.setOptionContext(OPTION_CONTEXT);
// Invoke and check
assertEquals(OPTION_CONTEXT, CliOptionContext.getOptionContext());
}
@Test
public void testResetOptionContext() {
// Set up
CliOptionContext.setOptionContext(OPTION_CONTEXT);
// Invoke
CliOptionContext.resetOptionContext();
// Check
assertNull(CliOptionContext.getOptionContext());
}
}

View File

@@ -0,0 +1,52 @@
package org.springframework.roo.shell;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.lang.reflect.Method;
import org.junit.Test;
/**
* Unit test of {@link MethodTarget}
*
* @author Andrew Swan
* @since 1.2.0
*/
public class MethodTargetTest {
// Constants
private static final Object TARGET_1 = new CommandMarker() {};
private static final Object TARGET_2 = new CommandMarker() {};
private static final Method METHOD_1 = TARGET_1.getClass().getMethods()[0]; // unmockable
private static final Method METHOD_2 = TARGET_2.getClass().getMethods()[1]; // unmockable
@Test
public void testInstanceEqualsItself() {
final MethodTarget instance = new MethodTarget(METHOD_1, TARGET_1);
assertEquals(instance, instance);
}
@Test
public void testInstanceDoesNotEqualNull() {
assertFalse(new MethodTarget(METHOD_1, TARGET_1).equals(null));
}
@Test
public void testInstancesWithSameMethodAndTargetAreEqualAndHaveSameHashCode() {
final MethodTarget instance1 = new MethodTarget(METHOD_1, TARGET_1, "the-buff", "the-key");
final MethodTarget instance2 = new MethodTarget(METHOD_1, TARGET_1);
assertEquals(instance1, instance2);
assertEquals(instance1.hashCode(), instance2.hashCode());
}
@Test
public void testInstancesWithDifferentMethodAreNotEqual() {
assertFalse(new MethodTarget(METHOD_1, TARGET_1).equals(new MethodTarget(METHOD_2, TARGET_1)));
}
@Test
public void testInstancesWithDifferentTargetAreNotEqual() {
assertFalse(new MethodTarget(METHOD_1, TARGET_1).equals(new MethodTarget(METHOD_1, TARGET_2)));
}
}

View File

@@ -0,0 +1,52 @@
package org.springframework.roo.shell;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Unit test of {@link SimpleParser}
*
* @author Andrew Swan
* @since 1.2.0
*/
public class SimpleParserTest {
// Fixture
private SimpleParser simpleParser;
@Before
public void setUp() {
this.simpleParser = new SimpleParser();
}
@Test
public void testNormaliseEmptyString() {
assertNormalised("", "");
}
@Test
public void testNormaliseSpaces() {
assertNormalised(" ", "");
}
@Test
public void testNormaliseSingleWord() {
assertNormalised("hint", "hint");
}
@Test
public void testNormaliseMultipleWords() {
assertNormalised(" security setup ", "security setup");
}
/**
* Asserts that normalising the given input produces the given output
*
* @param input can't be <code>null</code>
* @param output
*/
private void assertNormalised(final String input, final String output) {
Assert.assertEquals(output, simpleParser.normalise(input));
}
}

View File

@@ -0,0 +1,54 @@
package org.springframework.roo.support.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.HashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
/**
* Unit test for the {@link AnsiEscapeCode} enum.
*
* @author Andrew Swan
* @since 1.2.0
*/
public class AnsiEscapeCodeTest {
@Before
public void init() {
System.setProperty("roo.console.ansi", Boolean.TRUE.toString());
}
@Test
public void testCodesAreUnique() {
// Set up
final Set<Object> codes = new HashSet<Object>();
// Invoke
for (final AnsiEscapeCode escapeCode : AnsiEscapeCode.values()) {
codes.add(escapeCode.code);
}
// Check
assertEquals(AnsiEscapeCode.values().length, codes.size());
}
@Test
public void testDecorateNullText() {
assertNull(AnsiEscapeCode.decorate(null, AnsiEscapeCode.values()[0]));
}
@Test
public void testDecorateEmptyText() {
assertEquals("", AnsiEscapeCode.decorate("", AnsiEscapeCode.values()[0]));
}
@Test
public void testDecorateWhitespace() {
final AnsiEscapeCode effect = AnsiEscapeCode.values()[0]; // Arbitrary
assertEquals(effect.code + " " + AnsiEscapeCode.OFF.code, AnsiEscapeCode.decorate(" ", effect));
}
}

View File

@@ -0,0 +1,156 @@
package org.springframework.roo.support.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
/**
* Unit test of {@link CollectionUtils}
*
* @author Andrew Swan
* @since 1.2.0
*/
public class CollectionUtilsTest {
// A simple filter for testing the filtering methods
private static final Filter<String> NON_BLANK_FILTER = new Filter<String>() {
public boolean include(final String instance) {
return StringUtils.hasText(instance);
}
};
private static class Parent {
@Override
public String toString() {
return getClass().getSimpleName();
}
}
private static class Child extends Parent {}
@Test
public void testFilterNullCollection() {
assertEquals(0, CollectionUtils.filter(null, NON_BLANK_FILTER).size());
}
@Test
public void testFilterNonNullIterableWithNullFilter() {
// Set up
final Iterable<String> inputs = Arrays.asList("a", "");
// Invoke
final List<? extends String> results = CollectionUtils.filter(inputs, null);
// Check
assertEquals(inputs, results);
}
@Test
public void testFilterNonNullIterableWithNonNullFilter() {
// Set up
final Iterable<String> inputs = Arrays.asList("a", "", null, "b");
// Invoke
final List<? extends String> results = CollectionUtils.filter(inputs, NON_BLANK_FILTER);
// Check
assertEquals(Arrays.asList("a", "b"), results);
}
@Test
public void testAddNullCollectionToNullCollection() {
assertFalse(CollectionUtils.addAll(null, null));
}
@Test
public void testAddNullCollectionToNonNullCollection() {
// Set up
final Parent parent = new Parent();
final Collection<Parent> parents = Arrays.asList(parent);
// Invoke
final boolean added = CollectionUtils.addAll(null, parents);
// Check
assertFalse(added);
}
@Test
public void testAddNonNullCollectionToNonNullCollection() {
// Set up
final Parent parent = new Parent();
final Child child = new Child();
final Collection<Parent> parents = new ArrayList<Parent>();
parents.add(parent);
// Invoke
final boolean added = CollectionUtils.addAll(Arrays.asList(child), parents);
// Check
assertTrue(added);
assertEquals(Arrays.asList(parent, child), parents);
}
@Test
public void testPopulateNullCollectionWithNullCollection() {
assertNull(CollectionUtils.populate(null, null));
}
@Test
public void testPopulateNonNullCollectionWithNullCollection() {
// Set up
final Collection<Parent> collection = new ArrayList<Parent>();
collection.add(new Parent());
// Invoke
final Collection<Parent> result = CollectionUtils.populate(collection, null);
// Check
assertEquals(0, result.size());
}
@Test
public void testPopulateNonNullCollectionWithNonNullCollection() {
// Set up
final Collection<Parent> originalCollection = new ArrayList<Parent>();
originalCollection.add(new Parent());
final Child child = new Child();
// Invoke
final Collection<Parent> result = CollectionUtils.populate(originalCollection, Arrays.asList(child));
// Check
assertEquals(Collections.singletonList(child), result);
}
@Test
public void testFirstElementOfNullCollection() {
assertNull(CollectionUtils.firstElementOf(null));
}
@Test
public void testFirstElementOfEmptyCollection() {
assertNull(CollectionUtils.firstElementOf(Collections.emptySet()));
}
@Test
public void testFirstElementOfSingleElementCollection() {
final String member = "x";
assertEquals(member, CollectionUtils.firstElementOf(Collections.singleton(member)));
}
@Test
public void testFirstElementOfMultiElementCollection() {
final String[] members = {"x", "y", "z"};
assertEquals(members[0], CollectionUtils.firstElementOf(Arrays.asList(members)));
}
}

View File

@@ -0,0 +1,77 @@
package org.springframework.roo.support.util;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Unit test of {@link DomUtils}
*
* @author Andrew Swan
* @since 1.2.0
*/
public class DomUtilsTest {
// Constants
private static final String DEFAULT_TEXT = "foo";
private static final String NODE_TEXT = "bar";
private static final String XML_BEFORE_REMOVAL =
"<top>" +
" <middle>" +
" <bottom id=\"1\" />" +
" <bottom id=\"2\" />" +
" </middle>" +
"</top>";
private static final String XML_AFTER_REMOVAL =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<top> <middle/>\n" +
"</top>";
/**
* Asserts that the given XML node contains the expected content
*
* @param expectedLines the expected lines of XML (required); separate each
* line with "\n" regardless of the platform
* @param actualNode the actual XML node (required)
* @throws AssertionError if they are not equal
*/
private void assertXmlEquals(final String expectedXml, final Node actualNode) {
// Replace the dummy line terminator with the platform-specific one that
// will be applied by XmlUtils.nodeToString.
final String normalisedXml = expectedXml.replace("\n", StringUtils.LINE_SEPARATOR);
// Trim trailing whitespace as XmlUtils.nodeToString appends an extra newline.
final String actualXml = StringUtils.trimTrailingWhitespace(XmlUtils.nodeToString(actualNode));
assertEquals(normalisedXml, actualXml);
}
@Test
public void testGetTextContentOfNullNode() {
assertEquals(DEFAULT_TEXT, DomUtils.getTextContent(null, DEFAULT_TEXT));
}
@Test
public void testGetTextContentOfNonNullNode() {
// Set up
final Node mockNode = mock(Node.class);
when(mockNode.getTextContent()).thenReturn(NODE_TEXT);
assertEquals(NODE_TEXT, DomUtils.getTextContent(mockNode, DEFAULT_TEXT));
}
@Test
public void testRemoveElements() throws Exception {
// Set up
final Element root = XmlUtils.stringToElement(XML_BEFORE_REMOVAL);
final Element middle = DomUtils.getChildElementByTagName(root, "middle");
// Invoke
DomUtils.removeElements("bottom", middle);
// Check
assertXmlEquals(XML_AFTER_REMOVAL, root);
}
}

View File

@@ -0,0 +1,221 @@
package org.springframework.roo.support.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.junit.Test;
import org.springframework.roo.support.util.loader.Loader;
/**
* Unit test of {@link FileUtils}
*
* @author Andrew Swan
* @since 1.2.0
*/
public class FileUtilsTest {
private static final String MISSING_FILE = "no-such-file.txt";
private static final String TEST_FILE = "sub" + File.separator + "file-utils-test.txt";
@Test(expected = NullPointerException.class)
public void testGetSystemDependentPathFromNullArray() {
FileUtils.getSystemDependentPath((String[]) null);
}
@Test(expected = IllegalArgumentException.class)
public void testGetSystemDependentPathFromNoElements() {
FileUtils.getSystemDependentPath();
}
@Test
public void testGetSystemDependentPathFromOneElement() {
assertEquals("foo", FileUtils.getSystemDependentPath("foo"));
}
@Test
public void testGetSystemDependentPathFromMultipleElements() {
final String expectedPath = "foo" + File.separator + "bar";
assertEquals(expectedPath, FileUtils.getSystemDependentPath("foo", "bar"));
}
@Test
public void testGetFileSeparatorAsRegex() throws Exception {
// Set up
final String regex = FileUtils.getFileSeparatorAsRegex();
final String currentDirectory = new File(FileUtils.CURRENT_DIRECTORY).getCanonicalPath();
// Invoke
final String[] pathElements = currentDirectory.split(regex);
// Check
assertTrue(pathElements.length > 0);
}
@Test
public void testRemoveTrailingSeparatorFromNullPath() {
assertNull(FileUtils.removeTrailingSeparator(null));
}
@Test
public void testRemoveTrailingSeparatorFromEmptyPath() {
assertEquals("", FileUtils.removeTrailingSeparator(""));
}
@Test
public void testRemoveTrailingSeparatorFromPathWithLeadingSeparator() {
final String path = File.separator + "foo";
assertEquals(path, FileUtils.removeTrailingSeparator(path));
}
@Test
public void testRemoveTrailingSeparatorFromPathWithMultipleTrailingSeparators() {
final String path = "foo" + StringUtils.repeat(File.separator, 3);
assertEquals("foo", FileUtils.removeTrailingSeparator(path));
}
@Test(expected = IllegalArgumentException.class)
public void testEnsureTrailingSeparatorForNullPath() {
FileUtils.ensureTrailingSeparator(null);
}
@Test
public void testEnsureTrailingSeparatorForEmptyPath() {
assertEquals(File.separator, FileUtils.ensureTrailingSeparator(""));
}
@Test
public void testEnsureTrailingSeparatorForPathWithNoTrailingSeparator() {
final String path = "foo";
assertEquals(path + File.separator, FileUtils.ensureTrailingSeparator(path));
}
@Test
public void testEnsureTrailingSeparatorForPathWithOneTrailingSeparator() {
final String path = "foo" + File.separator;
assertEquals(path, FileUtils.ensureTrailingSeparator(path));
}
@Test
public void testEnsureTrailingSeparatorFromPathWithMultipleTrailingSeparators() {
final String path = "foo" + StringUtils.repeat(File.separator, 3);
assertEquals("foo" + File.separator, FileUtils.ensureTrailingSeparator(path));
}
@Test
public void testGetCanonicalPathForNullFile() {
assertNull(FileUtils.getCanonicalPath(null));
}
@Test(expected = IllegalStateException.class)
public void testGetCanonicalPathForInvalidFile() throws Exception {
// Set up
final File invalidFile = mock(File.class);
when(invalidFile.getCanonicalPath()).thenThrow(new IOException("dummy"));
// Invoke
FileUtils.getCanonicalPath(invalidFile);
}
@Test
public void testGetCanonicalPathForValidFile() throws Exception {
// Set up
final File validFile = mock(File.class);
final String canonicalPath = "the_path";
when(validFile.getCanonicalPath()).thenReturn(canonicalPath);
// Invoke
final String actualPath = FileUtils.getCanonicalPath(validFile);
// Check
assertEquals(canonicalPath, actualPath);
}
@Test
public void testRemoveLeadingAndTrailingSeparatorsFromNullPath() {
assertNull(FileUtils.removeLeadingAndTrailingSeparators(null));
}
@Test
public void testRemoveLeadingAndTrailingSeparatorsFromEmptyPath() {
assertEquals("", FileUtils.removeLeadingAndTrailingSeparators(""));
}
@Test
public void testRemoveLeadingAndTrailingSeparatorsFromPlainPath() {
final String path = "foo";
assertEquals(path, FileUtils.removeLeadingAndTrailingSeparators(path));
}
@Test
public void testRemoveLeadingAndTrailingSeparatorsFromPathWithBoth() {
// Set up
final String separators = StringUtils.repeat(File.separator, 4);
final String path = separators + "foo" + separators;
// Invoke and check
assertEquals("foo", FileUtils.removeLeadingAndTrailingSeparators(path));
}
@Test
public void testGetFile() {
assertTrue(FileUtils.getFile(Loader.class, TEST_FILE).isFile());
}
@Test
public void testGetPath() {
assertEquals("/org/springframework/roo/support/util/loader/sub/file-utils-test.txt", FileUtils.getPath(Loader.class, "sub/file-utils-test.txt"));
}
@Test
public void testGetInputStreamOfFileInSubDirectory() throws Exception {
// Invoke
final InputStream inputStream = FileUtils.getInputStream(Loader.class, TEST_FILE);
// Check
final String contents = FileCopyUtils.copyToString(new InputStreamReader(inputStream));
assertEquals("This file is required for FileUtilsTest.", contents);
}
@Test(expected = IllegalArgumentException.class)
public void testGetInputStreamOfInvalidFile() throws Exception {
FileUtils.getInputStream(Loader.class, MISSING_FILE);
}
private void assertFirstDirectory(final String path, final String expectedFirstDirectory) {
// Invoke
final String firstDirectory = FileUtils.getFirstDirectory(path);
// Check
assertEquals(expectedFirstDirectory, firstDirectory);
}
@Test
public void testGetFirstDirectoryOfExistingDirectory() {
// Set up
final String directory = FileUtils.getFile(Loader.class, TEST_FILE).getParent();
// Invoke
final String firstDirectory = FileUtils.getFirstDirectory(directory);
// Check
assertTrue(firstDirectory.endsWith("sub"));
}
@Test
public void testGetFirstDirectoryOfExistingFile() {
assertFirstDirectory(TEST_FILE, "sub");
}
@Test
public void testBackOneDirectory() {
assertEquals("foo" + File.separator + "bar", FileUtils.backOneDirectory("foo" + File.separator + "bar" + File.separator + "baz" + File.separator));
}
}

View File

@@ -0,0 +1,51 @@
package org.springframework.roo.support.util;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.Closeable;
import java.io.IOException;
import org.junit.Test;
/**
* Unit test of {@link IOUtils}.
*
* @author Andrew Swan
* @since 1.2.0
*/
public class IOUtilsTest {
@Test
public void testCloseNullCloseable() {
IOUtils.closeQuietly((Closeable) null); // Shouldn't throw an exception
}
@Test
public void testCloseNonNullCloseableWithoutError() throws Exception {
// Set up
final Closeable mockCloseable = mock(Closeable.class);
// Invoke
IOUtils.closeQuietly(mockCloseable);
// Check
verify(mockCloseable).close();
}
@Test
public void testCloseTwoNonNullCloseableWithErrorOnFirst() throws Exception {
// Set up
final Closeable mockCloseable1 = mock(Closeable.class);
doThrow(new IOException("dummy")).when(mockCloseable1).close();
final Closeable mockCloseable2 = mock(Closeable.class);
// Invoke
IOUtils.closeQuietly(mockCloseable1, mockCloseable2);
// Check
verify(mockCloseable1).close();
verify(mockCloseable2).close();
}
}

View File

@@ -0,0 +1,73 @@
package org.springframework.roo.support.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.Test;
/**
* Unit test of {@link NumberUtils}.
*
* @author Alan Stewart
* @since 1.2.0
*/
public class NumberUtilsTest {
@Test
public void testMinValueOfEmptyArray() {
assertNull(NumberUtils.min(new Number[0]));
}
@Test
public void testNullMinValues() {
assertNull(NumberUtils.min(null, null));
}
@Test
public void testOneMinValue() {
assertEquals(BigDecimal.ONE, NumberUtils.min(1));
}
@Test
public void testMinValues() {
assertEquals(new BigDecimal("11"), NumberUtils.min(21, 11, 20L, 33.3D, new Short("55"), 11.3));
}
@Test
public void testMinValues2() {
assertEquals(new BigDecimal("3"), NumberUtils.min(null, 3, null, 4));
}
@Test
public void testMultipleMinValues() {
assertEquals(new BigDecimal(-10), NumberUtils.min(0, 10, null, -10, Integer.MAX_VALUE, BigInteger.TEN));
}
@Test
public void testMultipleSameMinValues() {
assertEquals(-1, NumberUtils.min(-1, -1F, -1L, -1D).intValueExact());
}
@Test
public void testNullMaxValues() {
assertNull(NumberUtils.max(null, null));
}
@Test
public void testOneMaxValue() {
assertEquals(BigDecimal.ONE, NumberUtils.max(1));
}
@Test
public void testMaxValues() {
assertEquals(BigDecimal.ONE, NumberUtils.max(null, 1, -1, null));
}
@Test
public void testMultipleMaxValues() {
assertEquals(new BigDecimal(String.valueOf(Double.MAX_VALUE)), NumberUtils.max(0, null, Integer.MIN_VALUE, 10, -10, Integer.MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE));
}
}

View File

@@ -0,0 +1,105 @@
package org.springframework.roo.support.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit test of {@link ObjectUtils}
*
* @author Andrew Swan
* @since 1.2.0
*/
public class ObjectUtilsTest {
@Test
public void testCompareTwoNulls() {
assertEquals(0, ObjectUtils.nullSafeComparison(null, null));
}
@Test
public void testCompareNullWithNonNull() {
// Invoke
final int result = ObjectUtils.nullSafeComparison(null, "");
// Check
assertTrue(result < 0);
}
@Test
public void testCompareNonNullWithNull() {
// Invoke
final int result = ObjectUtils.nullSafeComparison("", null);
// Check
assertTrue(result > 0);
}
@Test
public void testCompareLesserWithGreater() {
// Invoke
final int result = ObjectUtils.nullSafeComparison(100, 200);
// Check
assertTrue(result < 0);
}
@Test
public void testCompareGreaterWithLesser() {
// Invoke
final int result = ObjectUtils.nullSafeComparison(300, 200);
// Check
assertTrue(result > 0);
}
@Test
public void testCompareTwoEqualObjects() {
assertEquals(0, ObjectUtils.nullSafeComparison(400, 400));
}
@Test
public void testToStringWithNullObjectAndNullDefault() {
assertNull(ObjectUtils.toString(null, null));
}
@Test
public void testToStringWithNullObjectAndEmptyDefault() {
assertEquals("", ObjectUtils.toString(null, ""));
}
@Test
public void testToStringWithNullObjectAndNonEmptyDefault() {
assertEquals("x", ObjectUtils.toString(null, "x"));
}
@Test
public void testToStringWithNonNullObjectAndNullDefault() {
assertEquals("1", ObjectUtils.toString(1, "anything"));
}
@Test
public void testDefaultIfNullWhenObjectIsNullAndDefaultIsNull() {
assertNull(ObjectUtils.defaultIfNull(null, null));
}
@Test
public void testDefaultIfNullWhenObjectIsNullAndDefaultIsNotNull() {
final Object defaultValue = 27;
assertEquals(defaultValue, ObjectUtils.defaultIfNull(null, defaultValue));
}
@Test
public void testDefaultIfNullWhenObjectIsNotNullAndDefaultIsNull() {
final Object value = 27;
assertEquals(value, ObjectUtils.defaultIfNull(value, null));
}
@Test
public void testDefaultIfNullWhenObjectIsNotNullAndDefaultIsNotNull() {
final Integer value = 27;
assertEquals(value, ObjectUtils.defaultIfNull(value, value + 1));
}
}

View File

@@ -0,0 +1,59 @@
package org.springframework.roo.support.util;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
/**
* Unit test of {@link PairList}
*
* @author Andrew Swan
* @since 1.2.0
*/
public class PairListTest {
// Constants
private static final int KEY_1 = 10;
private static final int KEY_2 = 20;
private static final String VALUE_1 = "a";
private static final String VALUE_2 = "b";
private static final Pair<Integer, String> PAIR_1 = new Pair<Integer, String>(KEY_1, VALUE_1);
private static final Pair<Integer, String> PAIR_2 = new Pair<Integer, String>(KEY_2, VALUE_2);
@SuppressWarnings("unchecked")
@Test
public void testConstructFromVarargArrayOfPairs() {
// Invoke
final PairList<Integer, String> pairs = new PairList<Integer, String>(PAIR_1, PAIR_2);
// Check
assertEquals(2, pairs.size());
assertEquals(Arrays.asList(KEY_1, KEY_2), pairs.getKeys());
assertEquals(Arrays.asList(VALUE_1, VALUE_2), pairs.getValues());
final Pair<Integer, String>[] array = pairs.toArray();
assertEquals(pairs.size(), array.length);
assertEquals(pairs, Arrays.asList(array));
}
@Test
public void testConstructFromListsOfKeysAndValues() {
// Invoke
final PairList<Integer, String> pairs = new PairList<Integer, String>(Arrays.asList(KEY_1, KEY_2), Arrays.asList(VALUE_1, VALUE_2));
// Check
assertEquals(2, pairs.size());
assertEquals(PAIR_1, pairs.get(0));
assertEquals(PAIR_2, pairs.get(1));
}
@Test
public void testConstructFromNulListsOfKeysAndValues() {
// Invoke
final PairList<Integer, String> pairs = new PairList<Integer, String>(null, null);
// Check
assertEquals(0, pairs.size());
}
}

View File

@@ -0,0 +1,51 @@
package org.springframework.roo.support.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
/**
* Unit test of the {@link Pair} class.
*
* @author Andrew Swan
* @since 1.2.0
*/
public class PairTest {
@Test
public void testConstructWithNullKey() {
new Pair<Object, Object>(null, "");
}
@Test
public void testConstructWithNullValue() {
new Pair<Object, Object>("", null);
}
@Test
public void testInstanceEqualsItself() {
final Pair<Integer, String> pair = new Pair<Integer, String>(1, "a");
assertEquals(pair, pair);
}
@Test
public void testEqualKeyAndValueAreEqual() {
assertEquals(new Pair<Integer, String>(1, "a"), new Pair<Integer, String>(1, "a"));
}
@Test
public void testUnequalKeyIsNotEqual() {
assertFalse(new Pair<Integer, String>(1, "a").equals(new Pair<Integer, String>(2, "a")));
}
@Test
public void testUnequalValueIsNotEqual() {
assertFalse(new Pair<Integer, String>(1, "a").equals(new Pair<Integer, String>(1, "b")));
}
@Test
public void testOtherClassIsNotAPair() {
assertFalse(new Pair<Integer, String>(1, "a").equals("foo"));
}
}

View File

@@ -0,0 +1,517 @@
package org.springframework.roo.support.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Test;
/**
* Unit tests for {@link StringUtils}.
*
* @author Alan Stewart
* @since 1.1.3
*/
public class StringUtilsTest {
@Test
public void testPadRight1() {
assertEquals("9999", StringUtils.padRight("9", 4, '9'));
}
@Test
public void testPadRight2() {
assertEquals("Foo999", StringUtils.padRight("Foo", 6, '9'));
}
@Test
public void testPadLeft1() {
assertEquals("999", StringUtils.padLeft("9", 3, '9'));
}
@Test
public void testPadLeft2() {
assertEquals("99Foo", StringUtils.padLeft("Foo", 5, '9'));
}
@Test
public void testHasText1() {
assertTrue(StringUtils.hasText("11111"));
}
@Test
public void testHasText2() {
assertFalse(StringUtils.hasText(" "));
}
@Test
public void testCountOccurrences() {
assertEquals(4, StringUtils.countOccurrencesOf("Alan Keith Stewart - Triathlete", " "));
}
@Test
public void testCountOccurrencesNull() {
assertEquals(0, StringUtils.countOccurrencesOf("Alan Keith Stewart - Triathlete", null));
}
@Test
public void testRepeatNull() {
assertNull(StringUtils.repeat(null, 27));
}
@Test
public void testRepeatEmptyString() {
assertEquals("", StringUtils.repeat("", 42));
}
@Test
public void testRepeatSpace() {
assertEquals(" ", StringUtils.repeat(" ", 4));
}
@Test
public void testRepeatSingleCharacter() {
assertEquals("qqq", StringUtils.repeat("q", 3));
}
@Test
public void testRepeatMultipleCharacters() {
assertEquals("xyzxyzxyzxyz", StringUtils.repeat("xyz", 4));
}
@Test
public void testPrefixNullWithNull() {
assertNull(StringUtils.prefix(null, null));
}
@Test
public void testPrefixNullWithEmpty() {
assertNull(StringUtils.prefix(null, ""));
}
@Test
public void testPrefixNullWithNonEmpty() {
assertNull(StringUtils.prefix(null, "anything"));
}
@Test
public void testPrefixEmptyWithNull() {
assertEquals("", StringUtils.prefix("", null));
}
@Test
public void testPrefixEmptyWithEmpty() {
assertEquals("", StringUtils.prefix("", ""));
}
@Test
public void testPrefixEmptyWithNonEmpty() {
assertEquals("x", StringUtils.prefix("", "x"));
}
@Test
public void testPrefixNonEmptyWithNewPrefix() {
assertEquals("pre-old", StringUtils.prefix("old", "pre-"));
}
@Test
public void testPrefixNonEmptyWithExistingPrefix() {
assertEquals("pre-old", StringUtils.prefix("pre-old", "pre-"));
}
@Test
public void testRemoveNullSuffixFromNullString() {
assertNull(StringUtils.removeSuffix(null, null));
}
@Test
public void testRemoveEmptySuffixFromNullString() {
assertNull(StringUtils.removeSuffix(null, ""));
}
@Test
public void testRemoveNonEmptySuffixFromNullString() {
assertNull(StringUtils.removeSuffix(null, "anything"));
}
@Test
public void testRemoveNullSuffixFromEmptyString() {
assertEquals("", StringUtils.removeSuffix("", null));
}
@Test
public void testRemoveEmptySuffixFromEmptyString() {
assertEquals("", StringUtils.removeSuffix("", ""));
}
@Test
public void testRemoveNonEmptySuffixFromEmptyString() {
assertEquals("", StringUtils.removeSuffix("", "anything"));
}
@Test
public void testRemoveMatchingSuffixFromString() {
assertEquals("a", StringUtils.removeSuffix("abc", "bc"));
}
@Test
public void testRemoveNonMatchingSuffixFromString() {
assertEquals("abc", StringUtils.removeSuffix("abc", "BC"));
}
@Test
public void testRemoveNullPrefixFromNullString() {
assertNull(StringUtils.removePrefix(null, null));
}
@Test
public void testRemoveEmptyPrefixFromNullString() {
assertNull(StringUtils.removePrefix(null, ""));
}
@Test
public void testRemoveNonEmptyPrefixFromNullString() {
assertNull(StringUtils.removePrefix(null, "anything"));
}
@Test
public void testRemoveNullPrefixFromEmptyString() {
assertEquals("", StringUtils.removePrefix("", null));
}
@Test
public void testRemoveEmptyPrefixFromEmptyString() {
assertEquals("", StringUtils.removePrefix("", ""));
}
@Test
public void testRemoveNonEmptyPrefixFromEmptyString() {
assertEquals("", StringUtils.removePrefix("", "anything"));
}
@Test
public void testRemoveMatchingPrefixFromString() {
assertEquals("c", StringUtils.removePrefix("abc", "ab"));
}
@Test
public void testRemoveNonMatchingPrefixFromString() {
assertEquals("abc", StringUtils.removePrefix("abc", "AB"));
}
@Test
public void testSuffixNullWithNull() {
assertNull(StringUtils.suffix(null, null));
}
@Test
public void testSuffixNullWithEmpty() {
assertNull(StringUtils.suffix(null, ""));
}
@Test
public void testSuffixNullWithNonEmpty() {
assertNull(StringUtils.suffix(null, "anything"));
}
@Test
public void testSuffixEmptyWithNull() {
assertEquals("", StringUtils.suffix("", null));
}
@Test
public void testSuffixEmptyWithEmpty() {
assertEquals("", StringUtils.suffix("", ""));
}
@Test
public void testSuffixEmptyWithNonEmpty() {
assertEquals("x", StringUtils.suffix("", "x"));
}
@Test
public void testSuffixNonEmptyWithNewSuffix() {
assertEquals("old-suf", StringUtils.suffix("old", "-suf"));
}
@Test
public void testSuffixNonEmptyWithExistingSuffix() {
assertEquals("old-suf", StringUtils.suffix("old-suf", "-suf"));
}
@Test
public void testNullEqualsNull() {
assertTrue(StringUtils.equals(null, null));
}
@Test
public void testEmptyDoesNotEqualNull() {
assertFalse(StringUtils.equals("", null));
}
@Test
public void testNullDoesNotEqualEmpty() {
assertFalse(StringUtils.equals(null, ""));
}
@Test
public void testUpperDoesNotEqualLower() {
assertFalse(StringUtils.equals("E", "e"));
}
@Test
public void testStringEqualsItself() {
assertTrue(StringUtils.equals("a", "a"));
}
@Test
public void testNullCollectionToDelimitedString() {
assertEquals("", StringUtils.collectionToDelimitedString(null, "anything"));
}
@Test
public void testEmptyCollectionToDelimitedString() {
assertEquals("", StringUtils.collectionToDelimitedString(Collections.emptySet(), "anything"));
}
@Test
public void testSingletonCollectionToDelimitedString() {
assertEquals("foo", StringUtils.collectionToDelimitedString(Collections.singleton("foo"), "anything"));
}
@Test
public void testDoubletonCollectionToDelimitedString() {
assertEquals("foo:bar", StringUtils.collectionToDelimitedString(Arrays.asList("foo", "bar"), ":"));
}
@Test
public void testNullIsBlank() {
assertTrue(StringUtils.isBlank(null));
}
@Test
public void testEmptyStringIsBlank() {
assertTrue(StringUtils.isBlank(""));
}
@Test
public void testSingleSpaceStringIsBlank() {
assertTrue(StringUtils.isBlank(" "));
}
@Test
public void testWhitespaceIsBlank() {
assertTrue(StringUtils.isBlank("\n\r\t "));
}
@Test
public void testNonBlankStringIsNotBlank() {
assertFalse(StringUtils.isBlank("x"));
}
@Test
public void testArrayToDelimitedStringWithNullArray() {
assertEquals("", StringUtils.arrayToDelimitedString(";", new Object[0]));
}
@Test
public void testArrayToDelimitedStringWithEmptyArray() {
assertEquals("", StringUtils.arrayToDelimitedString(";"));
}
@Test
public void testArrayToDelimitedStringWithSingleElementArray() {
assertEquals("foo", StringUtils.arrayToDelimitedString(";", "foo"));
}
@Test
public void testArrayToDelimitedStringWithMultiElementArray() {
assertEquals("foo;27", StringUtils.arrayToDelimitedString(";", "foo", 27));
}
@Test
public void testDefaultIfEmptyWhenValueIsNullAndNoDefaults() {
assertNull(StringUtils.defaultIfEmpty(null));
}
@Test
public void testDefaultIfEmptyWhenValueIsEmptyAndNoDefaults() {
assertEquals("", StringUtils.defaultIfEmpty(""));
}
@Test
public void testDefaultIfEmptyWhenValueIsNullAndOneDefault() {
assertEquals("x", StringUtils.defaultIfEmpty(null, "x"));
}
@Test
public void testDefaultIfEmptyWhenValueIsEmptyAndOneDefault() {
assertEquals("x", StringUtils.defaultIfEmpty("", "x"));
}
@Test
public void testDefaultIfEmptyWhenAllValuesAreBlank() {
assertEquals("", StringUtils.defaultIfEmpty(null, null, null, ""));
}
@Test
public void testDefaultIfEmptyWhenValueIsEmptyAndTwoDefaults() {
assertEquals("x", StringUtils.defaultIfEmpty("", null, "x"));
}
@Test
public void testReplaceAllWhenNoArgumentsAreBlank() {
// Deliberately chose characters with special meaning to regexs
assertEquals("[a[b[c[", StringUtils.replace(".a.b.c.", ".", "["));
}
@Test
public void testReplaceAllWhenReplacementIsNull() {
assertEquals(" ", StringUtils.replace(" ", " ", null));
}
@Test
public void testReplaceAllWhenReplacementIsEmpty() {
assertEquals(" a ", StringUtils.replace(" a b ", "b", ""));
}
@Test
public void testReplaceAllWhenReplacementIsWhitespace() {
assertEquals(" a ", StringUtils.replace(" a b ", "b", " "));
}
@Test
public void testReplaceAllWhenToReplaceIsNull() {
assertEquals(" ", StringUtils.replace(" ", null, "x"));
}
@Test
public void testReplaceAllWhenToReplaceIsEmpty() {
assertEquals(" ", StringUtils.replace(" ", "", "x"));
}
@Test
public void testReplaceAllWhenToReplaceIsWhiteSpace() {
assertEquals("x", StringUtils.replace(" ", " ", "x"));
}
@Test
public void testReplaceAllWhenOriginalIsNull() {
assertNull(StringUtils.replace(null, "x", "y"));
}
@Test
public void testReplaceAllWhenOriginalIsEmpty() {
assertEquals("", StringUtils.replace("", "x", "y"));
}
@Test
public void testReplaceFirstWhenOriginalIsNull() {
assertNull(StringUtils.replaceFirst(null, "x", "y"));
}
@Test
public void testReplaceFirstWhenOriginalIsEmpty() {
assertEquals("", StringUtils.replaceFirst("", "x", "y"));
}
@Test
public void testReplaceFirstWhenOriginalIsWhitespace() {
assertEquals("[ ", StringUtils.replaceFirst(" ", " ", "["));
}
@Test
public void testReplaceFirstWhenToReplaceIsNull() {
assertEquals(" ", StringUtils.replaceFirst(" ", null, "x"));
}
@Test
public void testReplaceFirstWhenToReplaceIsEmpty() {
assertEquals(" ", StringUtils.replaceFirst(" ", "", "x"));
}
@Test
public void testReplaceFirstWhenToReplaceIsWhitespace() {
assertEquals("x", StringUtils.replaceFirst("x", " ", "y"));
}
@Test
public void testReplaceFirstWhenReplacementIsNull() {
assertEquals("x", StringUtils.replaceFirst("x", "x", null));
}
@Test
public void testReplaceFirstWhenReplacementIsEmpty() {
assertEquals("x", StringUtils.replaceFirst("xx", "x", ""));
}
@Test
public void testReplaceFirstWhenReplacementIsWhitespace() {
assertEquals("x ", StringUtils.replaceFirst("x y", "y", " "));
}
@Test
public void testReplaceFirstWhenNoArgumentsAreBlank() {
assertEquals("x-yz", StringUtils.replaceFirst("xyyz", "y", "-"));
}
private static final String[][] SUBSTRING_AFTER_LAST_SCENARIOS = {
// 0 = original, 1 = separator, 2 = expected result
{null, "anything", null},
{"", "anything", ""},
{"anything", "", ""},
{"anything", null, ""},
{"abc", "a", "bc"},
{"abcba", "b", "a"},
{"abc", "c", ""},
{"a", "a", ""},
{"a", "z", ""}
};
@Test
public void testSubstringAfterLast() {
for (final String[] scenario : SUBSTRING_AFTER_LAST_SCENARIOS) {
assertEquals(scenario[2], StringUtils.substringAfterLast(scenario[0], scenario[1]));
}
}
private static final String[][] CONTAINS_SCENARIOS = {
{null, "anything", "false"},
{"anything", null, "false"},
{"", "", "true"},
{"abc", "", "true"},
{"abc", "a", "true"},
{"abc", "b", "true"},
{"abc", "c", "true"},
{"abc", "z", "false"}
};
@Test
public void testContains() {
for (final String[] scenario : CONTAINS_SCENARIOS) {
assertEquals("Failed on scenario " + Arrays.toString(scenario), Boolean.valueOf(scenario[2]), StringUtils.contains(scenario[0], scenario[1]));
}
}
@Test
public void testTrimToEmpty() {
String path = " ";
assertEquals(" roo>", StringUtils.trimToEmpty(path) + " roo>");
}
@Test
public void testTrimToEmpty2() {
String path = null;
assertEquals(" roo>", StringUtils.trimToEmpty(path) + " roo>");
}
@Test
public void testTrimToEmpty3() {
String path = "core";
assertEquals("core roo>", StringUtils.trimToEmpty(path) + " roo>");
}
}

View File

@@ -0,0 +1,237 @@
package org.springframework.roo.support.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Arrays;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.roo.support.util.WebXmlUtils.WebXmlParam;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Unit tests for {@link WebXmlUtils}
*
* @author Stefan Schmidt
* @since 1.1.1
*/
public class WebXmlUtilsTest {
private static Document webXml;
@BeforeClass
public static void setUp() throws Exception {
final DocumentBuilder builder = XmlUtils.getDocumentBuilder();
webXml = builder.newDocument();
webXml.appendChild(webXml.createElement("web-app"));
}
@Test
public void testSetDisplayName() {
WebXmlUtils.setDisplayName("display", webXml, null);
final Element displayElement = XmlUtils.findFirstElement("display-name", webXml.getDocumentElement());
assertNotNull(displayElement);
assertEquals("display", displayElement.getTextContent());
}
@Test
public void testSetDescription() {
WebXmlUtils.setDescription("test desc", webXml, null);
final Element descriptionElement = XmlUtils.findFirstElement("description", webXml.getDocumentElement());
assertNotNull(descriptionElement);
assertEquals("test desc", descriptionElement.getTextContent());
}
@Test
public void testAddContextParam() {
WebXmlUtils.addContextParam(new WebXmlUtils.WebXmlParam("key", "value"), webXml, null);
final Element contextParamElement = XmlUtils.findFirstElement("context-param", webXml.getDocumentElement());
assertNotNull(contextParamElement);
assertEquals(2, contextParamElement.getChildNodes().getLength());
assertEquals("key", XmlUtils.findFirstElement("param-name", contextParamElement).getTextContent());
assertEquals("value", XmlUtils.findFirstElement("param-value", contextParamElement).getTextContent());
}
@Test
public void testAddFilter() {
WebXmlUtils.addFilter("filter1", String.class.getName(), "/*", webXml, null, new WebXmlUtils.WebXmlParam("key", "value"), new WebXmlUtils.WebXmlParam("key2", "value2"));
final Element filterElement = XmlUtils.findFirstElement("filter", webXml.getDocumentElement());
assertNotNull(filterElement);
assertEquals("filter1", XmlUtils.findFirstElement("filter-name", filterElement).getTextContent());
assertEquals(String.class.getName(), XmlUtils.findFirstElement("filter-class", filterElement).getTextContent());
final Element filterMapping = XmlUtils.findFirstElement("filter-mapping", webXml.getDocumentElement());
assertNotNull(filterMapping);
assertEquals("filter1", XmlUtils.findFirstElement("filter-name", filterMapping).getTextContent());
assertEquals("/*", XmlUtils.findFirstElement("url-pattern", filterMapping).getTextContent());
final List<Element> initParams = XmlUtils.findElements("init-param", filterElement);
assertEquals(2, initParams.size());
assertEquals(2, initParams.get(0).getChildNodes().getLength());
assertEquals("key", XmlUtils.findFirstElement("param-name", initParams.get(0)).getTextContent());
assertEquals("value", XmlUtils.findFirstElement("param-value", initParams.get(0)).getTextContent());
assertEquals("key2", XmlUtils.findFirstElement("param-name", initParams.get(1)).getTextContent());
assertEquals("value2", XmlUtils.findFirstElement("param-value", initParams.get(1)).getTextContent());
}
@Test
public void testAddFilterAtPositionWithDispatcher() {
WebXmlUtils.addFilterAtPosition(WebXmlUtils.FilterPosition.BEFORE, null, "filter1", "filter2", Object.class.getName(), "/test", webXml, null, null, Arrays.asList(WebXmlUtils.Dispatcher.ERROR, WebXmlUtils.Dispatcher.INCLUDE, WebXmlUtils.Dispatcher.FORWARD, WebXmlUtils.Dispatcher.REQUEST));
final Element filterElement = XmlUtils.findFirstElement("filter", webXml.getDocumentElement());
assertNotNull(filterElement);
assertEquals("filter2", XmlUtils.findFirstElement("filter-name", filterElement).getTextContent());
assertEquals(Object.class.getName(), XmlUtils.findFirstElement("filter-class", filterElement).getTextContent());
final Element filterMapping = XmlUtils.findFirstElement("filter-mapping", webXml.getDocumentElement());
assertNotNull(filterMapping);
assertEquals("filter2", XmlUtils.findFirstElement("filter-name", filterMapping).getTextContent());
assertEquals("/test", XmlUtils.findFirstElement("url-pattern", filterMapping).getTextContent());
final List<Element> dispatchers = XmlUtils.findElements("dispatcher", filterMapping);
assertEquals(4, dispatchers.size());
assertEquals(WebXmlUtils.Dispatcher.ERROR.name(), dispatchers.get(0).getTextContent());
assertEquals(WebXmlUtils.Dispatcher.INCLUDE.name(), dispatchers.get(1).getTextContent());
assertEquals(WebXmlUtils.Dispatcher.FORWARD.name(), dispatchers.get(2).getTextContent());
assertEquals(WebXmlUtils.Dispatcher.REQUEST.name(), dispatchers.get(3).getTextContent());
}
@Test
public void testAddFilterAtPosition() {
WebXmlUtils.addFilterAtPosition(WebXmlUtils.FilterPosition.BETWEEN, "filter2", "filter1", "filter3", Integer.class.getName(), "/test2", webXml, null, (WebXmlParam[]) null);
final List<Element> filterElements = XmlUtils.findElements("filter", webXml.getDocumentElement());
assertEquals(3, filterElements.size());
assertEquals("filter2", XmlUtils.findFirstElement("filter-name", filterElements.get(0)).getTextContent());
assertEquals("filter3", XmlUtils.findFirstElement("filter-name", filterElements.get(1)).getTextContent());
assertEquals("filter1", XmlUtils.findFirstElement("filter-name", filterElements.get(2)).getTextContent());
assertEquals(Integer.class.getName(), XmlUtils.findFirstElement("filter-class", filterElements.get(1)).getTextContent());
final List<Element> filterMappings = XmlUtils.findElements("filter-mapping", webXml.getDocumentElement());
assertEquals(3, filterMappings.size());
assertEquals("filter2", XmlUtils.findFirstElement("filter-name", filterMappings.get(0)).getTextContent());
assertEquals("filter3", XmlUtils.findFirstElement("filter-name", filterMappings.get(1)).getTextContent());
assertEquals("filter1", XmlUtils.findFirstElement("filter-name", filterMappings.get(2)).getTextContent());
assertEquals("/test2", XmlUtils.findFirstElement("url-pattern", filterMappings.get(1)).getTextContent());
}
@Test
public void testAddListener() {
WebXmlUtils.addListener(String.class.getName(), webXml, null);
final Element listenerElement = XmlUtils.findFirstElement("listener", webXml.getDocumentElement());
assertNotNull(listenerElement);
assertEquals(String.class.getName(), XmlUtils.findFirstElement("listener-class", listenerElement).getTextContent());
}
@Test
public void testAddServlet() {
WebXmlUtils.addServlet("servlet1", Object.class.getName(), "/servlet1", 1, webXml, null, new WebXmlUtils.WebXmlParam("key1", "value1"), new WebXmlUtils.WebXmlParam("key2", "value2"));
final Element servletElement = XmlUtils.findFirstElement("servlet", webXml.getDocumentElement());
assertNotNull(servletElement);
assertEquals("servlet1", XmlUtils.findFirstElement("servlet-name", servletElement).getTextContent());
assertEquals(Object.class.getName(), XmlUtils.findFirstElement("servlet-class", servletElement).getTextContent());
final Element servletMapping = XmlUtils.findFirstElement("servlet-mapping", webXml.getDocumentElement());
assertNotNull(servletMapping);
assertEquals("servlet1", XmlUtils.findFirstElement("servlet-name", servletMapping).getTextContent());
assertEquals("/servlet1", XmlUtils.findFirstElement("url-pattern", servletMapping).getTextContent());
final List<Element> initParams = XmlUtils.findElements("init-param", servletElement);
assertEquals(2, initParams.size());
assertEquals(2, initParams.get(0).getChildNodes().getLength());
assertEquals("key1", XmlUtils.findFirstElement("param-name", initParams.get(0)).getTextContent());
assertEquals("value1", XmlUtils.findFirstElement("param-value", initParams.get(0)).getTextContent());
assertEquals("key2", XmlUtils.findFirstElement("param-name", initParams.get(1)).getTextContent());
assertEquals("value2", XmlUtils.findFirstElement("param-value", initParams.get(1)).getTextContent());
}
@Test
public void testSetSessionTimeout() {
WebXmlUtils.setSessionTimeout(1000, webXml, null);
final Element timeElement = XmlUtils.findFirstElement("session-config/session-timeout", webXml.getDocumentElement());
assertNotNull(timeElement);
assertEquals("1000", timeElement.getTextContent());
}
@Test
public void testAddWelcomeFile() {
WebXmlUtils.addWelcomeFile("/welcome", webXml, null);
final Element welcomeFileElement = XmlUtils.findFirstElement("welcome-file-list/welcome-file", webXml.getDocumentElement());
assertNotNull(welcomeFileElement);
assertEquals("/welcome", welcomeFileElement.getTextContent());
}
@Test
public void testAddExceptionType() {
WebXmlUtils.addExceptionType(IllegalStateException.class.getName(), "/illegal", webXml, null);
final Element errorPageElement = XmlUtils.findFirstElement("error-page", webXml.getDocumentElement());
assertNotNull(errorPageElement);
assertEquals(2, errorPageElement.getChildNodes().getLength());
assertEquals(IllegalStateException.class.getName(), XmlUtils.findFirstElement("exception-type", errorPageElement).getTextContent());
assertEquals("/illegal", XmlUtils.findFirstElement("location", errorPageElement).getTextContent());
}
@Test
public void testAddErrorCode() {
WebXmlUtils.addErrorCode(404, "/404", webXml, null);
final Element errorPageElement = (Element) webXml.getDocumentElement().getChildNodes().item(webXml.getDocumentElement().getChildNodes().getLength() - 1);
assertNotNull(errorPageElement);
assertEquals(2, errorPageElement.getChildNodes().getLength());
assertEquals("404", XmlUtils.findFirstElement("error-code", errorPageElement).getTextContent());
assertEquals("/404", XmlUtils.findFirstElement("location", errorPageElement).getTextContent());
}
@Test
public void testAddSecurityConstraint() {
WebXmlUtils.addSecurityConstraint("displayName",
Arrays.asList(new WebXmlUtils.WebResourceCollection("web-resource-name", "description", Arrays.asList("/", "/2"), Arrays.asList("POST", "GET"))),
Arrays.asList("user", "supervisor"), "transportGuarantee", webXml, null);
final Element securityConstraintElement = XmlUtils.findFirstElement("security-constraint", webXml.getDocumentElement());
assertNotNull(securityConstraintElement);
assertEquals("displayName", XmlUtils.findFirstElement("display-name", securityConstraintElement).getTextContent());
final Element webResourceCollection = XmlUtils.findFirstElement("web-resource-collection", securityConstraintElement);
assertNotNull(webResourceCollection);
assertEquals("web-resource-name", XmlUtils.findFirstElement("web-resource-name", webResourceCollection).getTextContent());
assertEquals(2, XmlUtils.findElements("url-pattern", webResourceCollection).size());
assertEquals(2, XmlUtils.findElements("http-method", webResourceCollection).size());
final Element authConstraint = XmlUtils.findFirstElement("auth-constraint", securityConstraintElement);
assertNotNull(authConstraint);
assertEquals(2, authConstraint.getChildNodes().getLength());
final Element userDataConstraint = XmlUtils.findFirstElement("user-data-constraint", securityConstraintElement);
assertNotNull(userDataConstraint);
assertEquals("transportGuarantee", userDataConstraint.getElementsByTagName("transport-guarantee").item(0).getTextContent());
}
@Test
public void validateElementSequence() {
final List<Element> contents = XmlUtils.findElements("/web-app/*", webXml.getDocumentElement());
assertEquals(17, contents.size());
assertEquals("display-name", contents.get(0).getNodeName());
assertEquals("description", contents.get(1).getNodeName());
assertEquals("context-param", contents.get(2).getNodeName());
assertEquals("filter2", contents.get(3).getChildNodes().item(0).getTextContent());
assertEquals("filter3", contents.get(4).getChildNodes().item(0).getTextContent());
assertEquals("filter1", contents.get(5).getChildNodes().item(0).getTextContent());
assertEquals("filter2", contents.get(6).getChildNodes().item(0).getTextContent());
assertEquals("filter3", contents.get(7).getChildNodes().item(0).getTextContent());
assertEquals("filter1", contents.get(8).getChildNodes().item(0).getTextContent());
assertEquals("listener", contents.get(9).getNodeName());
assertEquals("servlet", contents.get(10).getNodeName());
assertEquals("servlet-mapping", contents.get(11).getNodeName());
assertEquals("session-config", contents.get(12).getNodeName());
assertEquals("welcome-file-list", contents.get(13).getNodeName());
assertEquals("error-page", contents.get(14).getNodeName());
assertEquals("error-page", contents.get(15).getNodeName());
assertEquals("security-constraint", contents.get(16).getNodeName());
}
}

View File

@@ -0,0 +1,11 @@
package org.springframework.roo.support.util.loader;
import org.springframework.roo.support.util.FileUtilsTest;
/**
* Required for {@link FileUtilsTest}.
*
* @author Andrew Swan
* @since 1.2.0
*/
public class Loader {}

View File

@@ -0,0 +1 @@
This file is required for FileUtilsTest.