Moving files around

This commit is contained in:
Erlend Hamnaberg
2009-11-06 21:26:32 +01:00
parent ba5f0a2f5f
commit 9b615de8ed
86 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,228 @@
package com.twelvemonkeys.lang;
import junit.framework.TestCase;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.InvocationTargetException;
import java.text.NumberFormat;
/**
* BeanUtilTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/lang/BeanUtilTestCase.java#1 $
*/
public class BeanUtilTestCase extends TestCase {
public void testConfigureNoMehtod() {
TestBean bean = new TestBean();
Map map = new HashMap();
map.put("noSuchMethod", "jaffa");
try {
BeanUtil.configure(bean, map);
}
catch (InvocationTargetException e) {
fail(e.getMessage());
}
}
public void testConfigureNoMethodArgs() {
TestBean bean = new TestBean();
Map map = new HashMap();
map.put("doubleValue", new Object()); // Should not be able to convert this
try {
BeanUtil.configure(bean, map);
}
catch (InvocationTargetException e) {
fail(e.getMessage());
}
assertNull(bean.getDoubleValue());
}
public void testConfigureNullValue() {
TestBean bean = new TestBean();
Map map = new HashMap();
map.put("stringValue", null);
try {
BeanUtil.configure(bean, map);
}
catch (InvocationTargetException e) {
fail(e.getMessage());
}
assertNull(bean.getStringValue());
}
public void testConfigureSimple() {
TestBean bean = new TestBean();
Map map = new HashMap();
map.put("stringValue", "one");
map.put("intValue", new Integer(2));
map.put("doubleValue", new Double(.3));
try {
BeanUtil.configure(bean, map);
}
catch (InvocationTargetException e) {
fail(e.getMessage());
}
assertEquals("one", bean.getStringValue());
assertEquals(2, bean.getIntValue());
assertEquals(new Double(.3), bean.getDoubleValue());
}
public void testConfigureConvert() {
TestBean bean = new TestBean();
Map map = new HashMap();
map.put("stringValue", new Integer(1));
map.put("intValue", "2");
map.put("doubleValue", NumberFormat.getNumberInstance().format(0.3)); // Note, format is locale specific...
try {
BeanUtil.configure(bean, map);
}
catch (InvocationTargetException e) {
fail(e.getMessage());
}
assertEquals("1", bean.getStringValue());
assertEquals(2, bean.getIntValue());
assertEquals(new Double(.3), bean.getDoubleValue());
}
public void testConfigureAmbigious1() {
TestBean bean = new TestBean();
Map map = new HashMap();
String value = "one";
map.put("ambigious", value);
try {
BeanUtil.configure(bean, map);
}
catch (InvocationTargetException e) {
fail(e.getMessage());
}
assertNotNull(bean.getAmbigious());
assertEquals("String converted rather than invoking setAmbigiouos(String), ordering not predictable",
"one", bean.getAmbigious());
assertSame("String converted rather than invoking setAmbigiouos(String), ordering not predictable",
value, bean.getAmbigious());
}
public void testConfigureAmbigious2() {
TestBean bean = new TestBean();
Map map = new HashMap();
Integer value = new Integer(2);
map.put("ambigious", value);
try {
BeanUtil.configure(bean, map);
}
catch (InvocationTargetException e) {
fail(e.getMessage());
}
assertNotNull(bean.getAmbigious());
assertEquals("Integer converted rather than invoking setAmbigiouos(Integer), ordering not predictable",
new Integer(2), bean.getAmbigious());
assertSame("Integer converted rather than invoking setAmbigiouos(Integer), ordering not predictable",
value, bean.getAmbigious());
}
public void testConfigureAmbigious3() {
TestBean bean = new TestBean();
Map map = new HashMap();
Double value = new Double(.3);
map.put("ambigious", value);
try {
BeanUtil.configure(bean, map);
}
catch (InvocationTargetException e) {
fail(e.getMessage());
}
assertNotNull(bean.getAmbigious());
assertEquals("Object converted rather than invoking setAmbigious(Object), ordering not predictable",
value.getClass(), bean.getAmbigious().getClass());
assertSame("Object converted rather than invoking setAmbigious(Object), ordering not predictable",
value, bean.getAmbigious());
}
static class TestBean {
private String mString;
private int mInt;
private Double mDouble;
private Object mAmbigious;
public Double getDoubleValue() {
return mDouble;
}
public int getIntValue() {
return mInt;
}
public String getStringValue() {
return mString;
}
public void setStringValue(String pString) {
mString = pString;
}
public void setIntValue(int pInt) {
mInt = pInt;
}
public void setDoubleValue(Double pDouble) {
mDouble = pDouble;
}
public void setAmbigious(String pString) {
mAmbigious = pString;
}
public void setAmbigious(Object pObject) {
mAmbigious = pObject;
}
public void setAmbigious(Integer pInteger) {
mAmbigious = pInteger;
}
public void setAmbigious(int pInt) {
mAmbigious = new Long(pInt); // Just to differentiate...
}
public Object getAmbigious() {
return mAmbigious;
}
}
}

View File

@@ -0,0 +1,321 @@
package com.twelvemonkeys.lang;
import junit.framework.TestCase;
import java.lang.reflect.Method;
import java.io.*;
/**
* AbstractObjectTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/lang/ObjectAbstractTestCase.java#1 $
*/
public abstract class ObjectAbstractTestCase extends TestCase {
// TODO: See com.tm.util.ObjectAbstractTestCase
// TODO: The idea is that this should be some generic base-class that
// implements the basic object tests
// TODO: Create Serializable test similar way
// TODO: Create Comparable test similar way
/**
* Creates a {@code TestCase}.
*
* @param testName the test class name
*/
protected ObjectAbstractTestCase(String testName) {
super(testName);
}
protected ObjectAbstractTestCase() {
super();
}
/**
* Returns an instance of the class we are testing.
* Implement this method to return the object to test.
*
* @return the object to test
*/
protected abstract Object makeObject();
// TODO: Can we really do serious testing with just one object?
// TODO: How can we make sure we create equal or different objects?!
//protected abstract Object makeDifferentObject(Object pObject);
//protected abstract Object makeEqualObject(Object pObject);
public void testToString() {
assertNotNull(makeObject().toString());
// TODO: What more can we test?
}
// TODO: assert that either BOTH or NONE of equals/hashcode is overridden
public void testEqualsHashCode(){
Object obj = makeObject();
Class cl = obj.getClass();
if (isEqualsOverriden(cl)) {
assertTrue("Class " + cl.getName()
+ " implements equals but not hashCode", isHashCodeOverriden(cl));
}
else if (isHashCodeOverriden(cl)) {
assertTrue("Class " + cl.getName()
+ " implements hashCode but not equals", isEqualsOverriden(cl));
}
}
protected static boolean isEqualsOverriden(Class pClass) {
return getDeclaredMethod(pClass, "equals", new Class[]{Object.class}) != null;
}
protected static boolean isHashCodeOverriden(Class pClass) {
return getDeclaredMethod(pClass, "hashCode", null) != null;
}
private static Method getDeclaredMethod(Class pClass, String pName, Class[] pArameters) {
try {
return pClass.getDeclaredMethod(pName, pArameters);
}
catch (NoSuchMethodException ignore) {
return null;
}
}
public void testObjectEqualsSelf() {
Object obj = makeObject();
assertEquals("An Object should equal itself", obj, obj);
}
public void testEqualsNull() {
Object obj = makeObject();
// NOTE: Makes sure this doesn't throw NPE either
//noinspection ObjectEqualsNull
assertFalse("An object should never equal null", obj.equals(null));
}
public void testObjectHashCodeEqualsSelfHashCode() {
Object obj = makeObject();
assertEquals("hashCode should be repeatable", obj.hashCode(), obj.hashCode());
}
public void testObjectHashCodeEqualsContract() {
Object obj1 = makeObject();
if (obj1.equals(obj1)) {
assertEquals(
"[1] When two objects are equal, their hashCodes should be also.",
obj1.hashCode(), obj1.hashCode());
}
// TODO: Make sure we create at least one equal object, and one different object
Object obj2 = makeObject();
if (obj1.equals(obj2)) {
assertEquals(
"[2] When two objects are equal, their hashCodes should be also.",
obj1.hashCode(), obj2.hashCode());
assertTrue(
"When obj1.equals(obj2) is true, then obj2.equals(obj1) should also be true",
obj2.equals(obj1));
}
}
/*
public void testFinalize() {
// TODO: Implement
}
*/
////////////////////////////////////////////////////////////////////////////
// Cloneable interface
public void testClone() throws Exception {
Object obj = makeObject();
if (obj instanceof Cloneable) {
Class cl = obj.getClass();
Method clone = findMethod(cl, "clone");
// Disregard protected modifier
// NOTE: This will throw a SecurityException if a SecurityManager
// disallows access, but should not happen in a test context
if (!clone.isAccessible()) {
clone.setAccessible(true);
}
Object cloned = clone.invoke(obj, null);
assertNotNull("Cloned object should never be null", cloned);
// TODO: This can only be asserted if equals() test is based on
// value equality, not reference (identity) equality
// Maybe it's possible to do a reflective introspection of
// the objects fields?
if (isHashCodeOverriden(cl)) {
assertEquals("Cloned object not equal", obj, cloned);
}
}
}
private static Method findMethod(Class pClass, String pName) throws NoSuchMethodException {
if (pClass == null) {
throw new IllegalArgumentException("class == null");
}
if (pName == null) {
throw new IllegalArgumentException("name == null");
}
Class cl = pClass;
while (cl != null) {
try {
return cl.getDeclaredMethod(pName, new Class[0]);
}
catch (NoSuchMethodException e) {
}
catch (SecurityException e) {
}
cl = cl.getSuperclass();
}
throw new NoSuchMethodException(pName + " in class " + pClass.getName());
}
///////////////////////////////////////////////////////////////////////////
// Serializable interface
public void testSerializeDeserializeThenCompare() throws Exception {
Object obj = makeObject();
if (obj instanceof Serializable) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(buffer);
try {
out.writeObject(obj);
}
finally {
out.close();
}
Object dest;
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
try {
dest = in.readObject();
}
finally {
in.close();
}
// TODO: This can only be asserted if equals() test is based on
// value equality, not reference (identity) equality
// Maybe it's possible to do a reflective introspection of
// the objects fields?
if (isEqualsOverriden(obj.getClass())) {
assertEquals("obj != deserialize(serialize(obj))", obj, dest);
}
}
}
/**
* Sanity check method, makes sure that any {@code Serializable}
* class can be serialized and de-serialized in memory,
* using the handy makeObject() method
*
* @throws java.io.IOException
* @throws ClassNotFoundException
*/
public void testSimpleSerialization() throws Exception {
Object o = makeObject();
if (o instanceof Serializable) {
byte[] object = writeExternalFormToBytes((Serializable) o);
readExternalFormFromBytes(object);
}
}
/**
* Write a Serializable or Externalizable object as
* a file at the given path.
* <em>NOT USEFUL as part
* of a unit test; this is just a utility method
* for creating disk-based objects in CVS that can become
* the basis for compatibility tests using
* readExternalFormFromDisk(String path)</em>
*
* @param o Object to serialize
* @param path path to write the serialized Object
* @exception java.io.IOException
*/
protected void writeExternalFormToDisk(Serializable o, String path) throws IOException {
FileOutputStream fileStream = new FileOutputStream(path);
writeExternalFormToStream(o, fileStream);
}
/**
* Converts a Serializable or Externalizable object to
* bytes. Useful for in-memory tests of serialization
*
* @param o Object to convert to bytes
* @return serialized form of the Object
* @exception java.io.IOException
*/
protected byte[] writeExternalFormToBytes(Serializable o) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
writeExternalFormToStream(o, byteStream);
return byteStream.toByteArray();
}
/**
* Reads a Serialized or Externalized Object from disk.
* Useful for creating compatibility tests between
* different CVS versions of the same class
*
* @param path path to the serialized Object
* @return the Object at the given path
* @exception java.io.IOException
* @exception ClassNotFoundException
*/
protected Object readExternalFormFromDisk(String path) throws IOException, ClassNotFoundException {
FileInputStream stream = new FileInputStream(path);
return readExternalFormFromStream(stream);
}
/**
* Read a Serialized or Externalized Object from bytes.
* Useful for verifying serialization in memory.
*
* @param b byte array containing a serialized Object
* @return Object contained in the bytes
* @exception java.io.IOException
* @exception ClassNotFoundException
*/
protected Object readExternalFormFromBytes(byte[] b) throws IOException, ClassNotFoundException {
ByteArrayInputStream stream = new ByteArrayInputStream(b);
return readExternalFormFromStream(stream);
}
// private implementation
//-----------------------------------------------------------------------
private Object readExternalFormFromStream(InputStream stream) throws IOException, ClassNotFoundException {
ObjectInputStream oStream = new ObjectInputStream(stream);
return oStream.readObject();
}
private void writeExternalFormToStream(Serializable o, OutputStream stream) throws IOException {
ObjectOutputStream oStream = new ObjectOutputStream(stream);
oStream.writeObject(o);
}
public static final class SanityTestTestCase extends ObjectAbstractTestCase {
/**
* Creates a {@code TestCase}.
*
*/
public SanityTestTestCase() {
super(SanityTestTestCase.class.getName());
}
protected Object makeObject() {
return new Cloneable() {};
}
}
}

View File

@@ -0,0 +1,858 @@
package com.twelvemonkeys.lang;
import junit.framework.TestCase;
import java.awt.*;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
/**
* StringUtilTestCase
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/lang/StringUtilTestCase.java#1 $
*
*/
public class StringUtilTestCase extends TestCase {
final static Object TEST_OBJECT = new Object();
final static Integer TEST_INTEGER = 42;
final static String TEST_STRING = "TheQuickBrownFox"; // No WS!
final static String TEST_SUB_STRING = TEST_STRING.substring(2, 5);
final static String TEST_DELIM_STRING = "one,two, three\n four\tfive six";
final static String[] STRING_ARRAY = {"one", "two", "three", "four", "five", "six"};
final static String TEST_INT_DELIM_STRING = "1,2, 3\n 4\t5 6";
final static int[] INT_ARRAY = {1, 2, 3, 4, 5, 6};
final static String TEST_DOUBLE_DELIM_STRING = "1.4,2.1, 3\n .4\t-5 6e5";
final static double[] DOUBLE_ARRAY = {1.4, 2.1, 3, .4, -5, 6e5};
final static String EMPTY_STRING = "";
final static String WHITESPACE_STRING = " \t \r \n ";
public void testValueOfObject() {
assertNotNull(StringUtil.valueOf(TEST_OBJECT));
assertEquals(StringUtil.valueOf(TEST_OBJECT), TEST_OBJECT.toString());
assertEquals(StringUtil.valueOf(TEST_INTEGER), TEST_INTEGER.toString());
assertEquals(StringUtil.valueOf(TEST_STRING), TEST_STRING);
assertSame(StringUtil.valueOf(TEST_STRING), TEST_STRING);
assertNull(StringUtil.valueOf(null));
}
public void testToUpperCase() {
String str = StringUtil.toUpperCase(TEST_STRING);
assertNotNull(str);
assertEquals(TEST_STRING.toUpperCase(), str);
str = StringUtil.toUpperCase(null);
assertNull(str);
}
public void testToLowerCase() {
String str = StringUtil.toLowerCase(TEST_STRING);
assertNotNull(str);
assertEquals(TEST_STRING.toLowerCase(), str);
str = StringUtil.toLowerCase(null);
assertNull(str);
}
public void testIsEmpty() {
assertTrue(StringUtil.isEmpty((String) null));
assertTrue(StringUtil.isEmpty(EMPTY_STRING));
assertTrue(StringUtil.isEmpty(WHITESPACE_STRING));
assertFalse(StringUtil.isEmpty(TEST_STRING));
}
public void testIsEmptyArray() {
assertTrue(StringUtil.isEmpty((String[]) null));
assertTrue(StringUtil.isEmpty(new String[]{EMPTY_STRING}));
assertTrue(StringUtil.isEmpty(new String[]{EMPTY_STRING, WHITESPACE_STRING}));
assertFalse(StringUtil.isEmpty(new String[]{EMPTY_STRING, TEST_STRING}));
assertFalse(StringUtil.isEmpty(new String[]{WHITESPACE_STRING, TEST_STRING}));
}
public void testContains() {
assertTrue(StringUtil.contains(TEST_STRING, TEST_STRING));
assertTrue(StringUtil.contains(TEST_STRING, TEST_SUB_STRING));
assertTrue(StringUtil.contains(TEST_STRING, EMPTY_STRING));
assertFalse(StringUtil.contains(TEST_STRING, WHITESPACE_STRING));
assertFalse(StringUtil.contains(TEST_SUB_STRING, TEST_STRING));
assertFalse(StringUtil.contains(EMPTY_STRING, TEST_STRING));
assertFalse(StringUtil.contains(WHITESPACE_STRING, TEST_STRING));
assertFalse(StringUtil.contains(null, TEST_STRING));
assertFalse(StringUtil.contains(null, null));
}
public void testContainsIgnoreCase() {
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_STRING));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase()));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_SUB_STRING));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase()));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, EMPTY_STRING));
assertFalse(StringUtil.containsIgnoreCase(TEST_STRING, WHITESPACE_STRING));
assertFalse(StringUtil.containsIgnoreCase(TEST_SUB_STRING, TEST_STRING));
assertFalse(StringUtil.containsIgnoreCase(EMPTY_STRING, TEST_STRING));
assertFalse(StringUtil.containsIgnoreCase(WHITESPACE_STRING, TEST_STRING));
assertFalse(StringUtil.containsIgnoreCase(null, TEST_STRING));
assertFalse(StringUtil.containsIgnoreCase(null, null));
}
public void testContainsChar() {
for (int i = 0; i < TEST_STRING.length(); i++) {
assertTrue(StringUtil.contains(TEST_STRING, TEST_STRING.charAt(i)));
assertFalse(StringUtil.contains(EMPTY_STRING, TEST_STRING.charAt(i)));
assertFalse(StringUtil.contains(WHITESPACE_STRING, TEST_STRING.charAt(i)));
assertFalse(StringUtil.contains(null, TEST_STRING.charAt(i)));
}
for (int i = 0; i < TEST_SUB_STRING.length(); i++) {
assertTrue(StringUtil.contains(TEST_STRING, TEST_SUB_STRING.charAt(i)));
}
for (int i = 0; i < WHITESPACE_STRING.length(); i++) {
assertFalse(StringUtil.contains(TEST_STRING, WHITESPACE_STRING.charAt(i)));
}
// Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) {
if (TEST_STRING.indexOf(i) < 0) {
assertFalse(TEST_STRING + " seems to contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), StringUtil.contains(TEST_STRING, i));
}
else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), StringUtil.contains(TEST_STRING, i));
}
}
}
public void testContainsIgnoreCaseChar() {
// Must contain all chars in string
for (int i = 0; i < TEST_STRING.length(); i++) {
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_STRING.charAt(i)));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.charAt(i)));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.charAt(i)));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, Character.toUpperCase(TEST_STRING.charAt(i))));
assertFalse(StringUtil.containsIgnoreCase(EMPTY_STRING, TEST_STRING.charAt(i)));
assertFalse(StringUtil.containsIgnoreCase(WHITESPACE_STRING, TEST_STRING.charAt(i)));
assertFalse(StringUtil.containsIgnoreCase(null, TEST_STRING.charAt(i)));
}
for (int i = 0; i < TEST_SUB_STRING.length(); i++) {
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_SUB_STRING.charAt(i)));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING.charAt(i)));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING.charAt(i)));
assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase().charAt(i)));
}
for (int i = 0; i < WHITESPACE_STRING.length(); i++) {
assertFalse(StringUtil.containsIgnoreCase(TEST_STRING, WHITESPACE_STRING.charAt(i)));
}
// Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) {
if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) {
assertFalse(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), StringUtil.containsIgnoreCase(TEST_STRING, i));
}
else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), StringUtil.containsIgnoreCase(TEST_STRING, i));
}
}
}
public void testIndexOfIgnoreCase() {
assertEquals(0, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING));
assertEquals(0, StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING));
assertEquals(0, StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING));
assertEquals(0, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase()));
assertEquals(0, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase()));
for (int i = 1; i < TEST_STRING.length(); i++) {
assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.substring(i)));
assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.substring(i)));
assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.substring(i)));
assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase().substring(i)));
assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase().substring(i)));
}
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase()));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toLowerCase()));
for (int i = 1; i < TEST_STRING.length(); i++) {
assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING.substring(i), TEST_STRING));
assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING.substring(i), TEST_STRING));
}
assertEquals(-1, StringUtil.indexOfIgnoreCase(null, TEST_STRING));
assertEquals(-1, StringUtil.indexOfIgnoreCase(null, null));
}
public void testIndexOfIgnoreCasePos() {
assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING, 1));
assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING, 2));
assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING, 3));
assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase(), 4));
assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase(), 5));
for (int i = 1; i < TEST_STRING.length(); i++) {
assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.substring(i), i - 1));
assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.substring(i), i - 1));
assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.substring(i), i - 1));
assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase().substring(i), i - 1));
assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase().substring(i), i - 1));
}
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING, 1));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING, 1));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING, 2));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase(), 1));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toLowerCase(), 2));
assertEquals(-1, StringUtil.indexOfIgnoreCase(null, TEST_STRING, 234));
assertEquals(-1, StringUtil.indexOfIgnoreCase(null, null, -45));
}
public void testLastIndexOfIgnoreCase() {
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase()));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase()));
for (int i = 1; i < TEST_STRING.length(); i++) {
assertEquals(i, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.substring(i)));
assertEquals(i, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.substring(i)));
assertEquals(i, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.substring(i)));
assertEquals(i, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase().substring(i)));
assertEquals(i, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase().substring(i)));
}
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase()));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toLowerCase()));
for (int i = 1; i < TEST_STRING.length(); i++) {
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.substring(i), TEST_STRING));
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.substring(i), TEST_STRING));
}
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, TEST_STRING));
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, null));
}
public void testLastIndexOfIgnoreCasePos() {
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING, 1));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING, 2));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING, 3));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase(), 4));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase(), 5));
for (int i = 1; i < TEST_STRING.length(); i++) {
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.substring(0, i), i - 1));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.substring(0, i), i - 1));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.substring(0, i), i - 1));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase().substring(0, i), i - 1));
assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase().substring(0, i), i - 1));
}
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING, TEST_SUB_STRING.length() + 3));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING, TEST_SUB_STRING.length() + 3));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING, TEST_SUB_STRING.length() + 4));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase(), TEST_SUB_STRING.length() + 3));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toLowerCase(), TEST_SUB_STRING.length() + 4));
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, TEST_STRING, 234));
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, null, -45));
}
public void testIndexOfIgnoreCaseChar() {
// Must contain all chars in string
for (int i = 0; i < TEST_STRING.length(); i++) {
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.charAt(i)));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.charAt(i)));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.charAt(i)));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, Character.toUpperCase(TEST_STRING.charAt(i))));
assertEquals(-1, StringUtil.indexOfIgnoreCase(EMPTY_STRING, TEST_STRING.charAt(i)));
assertEquals(-1, StringUtil.indexOfIgnoreCase(WHITESPACE_STRING, TEST_STRING.charAt(i)));
assertEquals(-1, StringUtil.indexOfIgnoreCase(null, TEST_STRING.charAt(i)));
}
for (int i = 0; i < TEST_SUB_STRING.length(); i++) {
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.charAt(i)));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING.charAt(i)));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING.charAt(i)));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase().charAt(i)));
}
for (int i = 0; i < WHITESPACE_STRING.length(); i++) {
assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, WHITESPACE_STRING.charAt(i)));
}
// Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) {
if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) {
assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.indexOfIgnoreCase(TEST_STRING, i));
}
else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, i));
}
}
}
public void testIndexOfIgnoreCaseCharPos() {
// Must contain all chars in string
for (int i = 0; i < TEST_STRING.length(); i++) {
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.charAt(i), i));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.charAt(i), i));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.charAt(i), i));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, Character.toUpperCase(TEST_STRING.charAt(i)), i));
assertEquals(-1, StringUtil.indexOfIgnoreCase(EMPTY_STRING, TEST_STRING.charAt(i), i));
assertEquals(-1, StringUtil.indexOfIgnoreCase(WHITESPACE_STRING, TEST_STRING.charAt(i), i));
assertEquals(-1, StringUtil.indexOfIgnoreCase(null, TEST_STRING.charAt(i), i));
}
for (int i = 0; i < TEST_SUB_STRING.length(); i++) {
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.charAt(i), i));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING.charAt(i), i));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING.charAt(i), i));
assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase().charAt(i), i));
}
for (int i = 0; i < WHITESPACE_STRING.length(); i++) {
assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, WHITESPACE_STRING.charAt(i), i));
}
// Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) {
if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) {
assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.indexOfIgnoreCase(TEST_STRING, i, 0));
}
else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, i, 0));
}
}
}
public void testLastIndexOfIgnoreCaseChar() {
// Must contain all chars in string
for (int i = 0; i < TEST_STRING.length(); i++) {
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.charAt(i)));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.charAt(i)));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.charAt(i)));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, Character.toUpperCase(TEST_STRING.charAt(i))));
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(EMPTY_STRING, TEST_STRING.charAt(i)));
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(WHITESPACE_STRING, TEST_STRING.charAt(i)));
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, TEST_STRING.charAt(i)));
}
for (int i = 0; i < TEST_SUB_STRING.length(); i++) {
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.charAt(i)));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING.charAt(i)));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING.charAt(i)));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase().charAt(i)));
}
for (int i = 0; i < WHITESPACE_STRING.length(); i++) {
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, WHITESPACE_STRING.charAt(i)));
}
// Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) {
if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) {
assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i));
}
else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i));
}
}
}
public void testLastIndexOfIgnoreCaseCharPos() {
// Must contain all chars in string
for (int i = 0; i < TEST_STRING.length(); i++) {
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.charAt(i), i));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.charAt(i), i));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.charAt(i), i));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, Character.toUpperCase(TEST_STRING.charAt(i)), i));
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(EMPTY_STRING, TEST_STRING.charAt(i), i));
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(WHITESPACE_STRING, TEST_STRING.charAt(i), i));
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, TEST_STRING.charAt(i), i));
}
for (int i = 0; i < TEST_SUB_STRING.length(); i++) {
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.charAt(i), TEST_STRING.length()));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING.charAt(i), TEST_STRING.length()));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING.charAt(i), TEST_STRING.length()));
assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase().charAt(i), TEST_STRING.length()));
}
for (int i = 0; i < WHITESPACE_STRING.length(); i++) {
assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, WHITESPACE_STRING.charAt(i), TEST_STRING.length()));
}
// Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) {
if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) {
assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i, TEST_STRING.length()));
}
else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i, TEST_STRING.length()));
}
}
}
public void testLtrim() {
assertEquals(TEST_STRING, StringUtil.ltrim(TEST_STRING));
assertEquals(TEST_STRING, StringUtil.ltrim(" " + TEST_STRING));
assertEquals(TEST_STRING, StringUtil.ltrim(WHITESPACE_STRING + TEST_STRING));
assertFalse(TEST_STRING.equals(StringUtil.ltrim(TEST_STRING + WHITESPACE_STRING)));
// TODO: Test is not complete
}
public void testRtrim() {
assertEquals(TEST_STRING, StringUtil.rtrim(TEST_STRING));
assertEquals(TEST_STRING, StringUtil.rtrim(TEST_STRING + " "));
assertEquals(TEST_STRING, StringUtil.rtrim(TEST_STRING + WHITESPACE_STRING));
assertFalse(TEST_STRING.equals(StringUtil.rtrim(WHITESPACE_STRING + TEST_STRING)));
// TODO: Test is not complete
}
public void testReplace() {
assertEquals("", StringUtil.replace(TEST_STRING, TEST_STRING, ""));
assertEquals("", StringUtil.replace("", "", ""));
assertEquals("", StringUtil.replace("", "xyzzy", "xyzzy"));
assertEquals(TEST_STRING, StringUtil.replace(TEST_STRING, "", "xyzzy"));
assertEquals("aabbdd", StringUtil.replace("aabbccdd", "c", ""));
assertEquals("aabbccdd", StringUtil.replace("aabbdd", "bd", "bccd"));
// TODO: Test is not complete
}
public void testReplaceIgnoreCase() {
assertEquals("", StringUtil.replaceIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase(), ""));
assertEquals("", StringUtil.replaceIgnoreCase("", "", ""));
assertEquals("", StringUtil.replaceIgnoreCase("", "xyzzy", "xyzzy"));
assertEquals(TEST_STRING, StringUtil.replaceIgnoreCase(TEST_STRING, "", "xyzzy"));
assertEquals("aabbdd", StringUtil.replaceIgnoreCase("aabbCCdd", "c", ""));
assertEquals("aabbdd", StringUtil.replaceIgnoreCase("aabbccdd", "C", ""));
assertEquals("aabbccdd", StringUtil.replaceIgnoreCase("aabbdd", "BD", "bccd"));
assertEquals("aabbccdd", StringUtil.replaceIgnoreCase("aabBDd", "bd", "bccd"));
// TODO: Test is not complete
}
public void testCut() {
assertEquals(TEST_STRING, StringUtil.cut(TEST_STRING, TEST_STRING.length(), ".."));
assertEquals("This is a test..", StringUtil.cut("This is a test of how this works", 16, ".."));
assertEquals("This is a test", StringUtil.cut("This is a test of how this works", 16, null));
assertEquals("This is a test", StringUtil.cut("This is a test of how this works", 16, ""));
// TODO: Test is not complete
}
public void testCaptialize() {
assertNull(StringUtil.capitalize(null));
assertEquals(TEST_STRING.toUpperCase(), StringUtil.capitalize(TEST_STRING.toUpperCase()));
assertTrue(StringUtil.capitalize("abc").charAt(0) == 'A');
}
public void testCaptializePos() {
assertNull(StringUtil.capitalize(null, 45));
// TODO: Should this throw IllegalArgument or StringIndexOutOfBonds?
assertEquals(TEST_STRING, StringUtil.capitalize(TEST_STRING, TEST_STRING.length() + 45));
for (int i = 0; i < TEST_STRING.length(); i++) {
assertTrue(Character.isUpperCase(StringUtil.capitalize(TEST_STRING, i).charAt(i)));
}
}
public void testPad() {
assertEquals(TEST_STRING + "...", StringUtil.pad(TEST_STRING, TEST_STRING.length() + 3, "..", false));
assertEquals(TEST_STRING, StringUtil.pad(TEST_STRING, 4, ".", false));
assertEquals(TEST_STRING, StringUtil.pad(TEST_STRING, 4, ".", true));
assertEquals("..." + TEST_STRING, StringUtil.pad(TEST_STRING, TEST_STRING.length() + 3, "..", true));
}
public void testToDate() {
long time = System.currentTimeMillis();
Date now = new Date(time - time % 60000); // Default format seems to have no seconds..
Date date = StringUtil.toDate(DateFormat.getInstance().format(now));
assertNotNull(date);
assertEquals(now, date);
}
public void testToDateWithFormatString() {
Calendar cal = new GregorianCalendar();
cal.clear();
cal.set(1976, 2, 16); // Month is 0-based
Date date = StringUtil.toDate("16.03.1976", "dd.MM.yyyy");
assertNotNull(date);
assertEquals(cal.getTime(), date);
cal.clear();
cal.set(2004, 4, 13, 23, 51, 3);
date = StringUtil.toDate("2004-5-13 23:51 (03)", "yyyy-MM-dd hh:mm (ss)");
assertNotNull(date);
assertEquals(cal.getTime(), date);
cal.clear();
cal.set(Calendar.HOUR, 1);
cal.set(Calendar.MINUTE, 2);
cal.set(Calendar.SECOND, 3);
date = StringUtil.toDate("123", "hms");
assertNotNull(date);
assertEquals(cal.getTime(), date);
}
public void testToDateWithFormat() {
Calendar cal = new GregorianCalendar();
cal.clear();
cal.set(1976, 2, 16); // Month is 0-based
Date date = StringUtil.toDate("16.03.1976", new SimpleDateFormat("dd.MM.yyyy"));
assertNotNull(date);
assertEquals(cal.getTime(), date);
cal.clear();
cal.set(2004, 4, 13, 23, 51);
date = StringUtil.toDate("13.5.04 23:51",
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, new Locale("no", "NO")));
assertNotNull(date);
assertEquals(cal.getTime(), date);
cal.clear();
cal.set(Calendar.HOUR, 1);
cal.set(Calendar.MINUTE, 2);
date = StringUtil.toDate("1:02 am",
DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US));
assertNotNull(date);
assertEquals(cal.getTime(), date);
}
public void testToTimestamp() {
Calendar cal = new GregorianCalendar();
cal.clear();
cal.set(1976, 2, 16, 21, 28, 4); // Month is 0-based
Date date = StringUtil.toTimestamp("1976-03-16 21:28:04");
assertNotNull(date);
assertTrue(date instanceof Timestamp);
assertEquals(cal.getTime(), date);
}
public void testToStringArray() {
String[] arr = StringUtil.toStringArray(TEST_DELIM_STRING);
assertNotNull(arr);
assertEquals(STRING_ARRAY.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(STRING_ARRAY[i], arr[i]);
}
}
public void testToStringArrayDelim() {
String[] arr = StringUtil.toStringArray("-1---2-3--4-5", "---");
String[] arr2 = {"1", "2", "3", "4", "5"};
assertNotNull(arr);
assertEquals(arr2.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(arr2[i], arr[i]);
}
arr = StringUtil.toStringArray("1, 2, 3; 4 5", ",; ");
assertNotNull(arr);
assertEquals(arr2.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(arr2[i], arr[i]);
}
}
public void testToIntArray() {
int[] arr = StringUtil.toIntArray(TEST_INT_DELIM_STRING);
assertNotNull(arr);
assertEquals(INT_ARRAY.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(INT_ARRAY[i], arr[i]);
}
}
public void testToIntArrayDelim() {
int[] arr = StringUtil.toIntArray("-1---2-3--4-5", "---");
int[] arr2 = {1, 2, 3, 4, 5};
assertNotNull(arr);
assertEquals(arr2.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(arr2[i], arr[i]);
}
arr = StringUtil.toIntArray("1, 2, 3; 4 5", ",; ");
assertNotNull(arr);
assertEquals(arr2.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(arr2[i], arr[i]);
}
}
public void testToIntArrayDelimBase() {
int[] arr = StringUtil.toIntArray("-1___2_3__F_a", "___", 16);
int[] arr2 = {-1, 2, 3, 0xf, 0xa};
assertNotNull(arr);
assertEquals(arr2.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(arr2[i], arr[i]);
}
arr = StringUtil.toIntArray("-1, 2, 3; 17 12", ",; ", 8);
assertNotNull(arr);
assertEquals(arr2.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(arr2[i], arr[i]);
}
}
public void testToLongArray() {
long[] arr = StringUtil.toLongArray(TEST_INT_DELIM_STRING);
assertNotNull(arr);
assertEquals(INT_ARRAY.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(INT_ARRAY[i], arr[i]);
}
}
public void testToLongArrayDelim() {
long[] arr = StringUtil.toLongArray("-12854928752983___2_3__4_5", "___");
long[] arr2 = {-12854928752983L, 2, 3, 4, 5};
assertNotNull(arr);
assertEquals(arr2.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(arr2[i], arr[i]);
}
arr = StringUtil.toLongArray("-12854928752983, 2, 3; 4 5", ",; ");
assertNotNull(arr);
assertEquals(arr2.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(arr2[i], arr[i]);
}
}
public void testToDoubleArray() {
double[] arr = StringUtil.toDoubleArray(TEST_DOUBLE_DELIM_STRING);
assertNotNull(arr);
assertEquals(DOUBLE_ARRAY.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(DOUBLE_ARRAY[i], arr[i], 0d);
}
}
public void testToDoubleArrayDelim() {
double[] arr = StringUtil.toDoubleArray("-12854928752983___.2_3__4_5e4", "___");
double[] arr2 = {-12854928752983L, .2, 3, 4, 5e4};
assertNotNull(arr);
assertEquals(arr2.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(arr2[i], arr[i], 0d);
}
arr = StringUtil.toDoubleArray("-12854928752983, .2, 3; 4 5E4", ",; ");
assertNotNull(arr);
assertEquals(arr2.length, arr.length);
for (int i = 0; i < arr.length; i++) {
assertEquals(arr2[i], arr[i], 0d);
}
}
public void testTestToColor() {
// Test all constants
assertEquals(Color.black, StringUtil.toColor("black"));
assertEquals(Color.black, StringUtil.toColor("BLACK"));
assertEquals(Color.blue, StringUtil.toColor("blue"));
assertEquals(Color.blue, StringUtil.toColor("BLUE"));
assertEquals(Color.cyan, StringUtil.toColor("cyan"));
assertEquals(Color.cyan, StringUtil.toColor("CYAN"));
assertEquals(Color.darkGray, StringUtil.toColor("darkGray"));
assertEquals(Color.darkGray, StringUtil.toColor("DARK_GRAY"));
assertEquals(Color.gray, StringUtil.toColor("gray"));
assertEquals(Color.gray, StringUtil.toColor("GRAY"));
assertEquals(Color.green, StringUtil.toColor("green"));
assertEquals(Color.green, StringUtil.toColor("GREEN"));
assertEquals(Color.lightGray, StringUtil.toColor("lightGray"));
assertEquals(Color.lightGray, StringUtil.toColor("LIGHT_GRAY"));
assertEquals(Color.magenta, StringUtil.toColor("magenta"));
assertEquals(Color.magenta, StringUtil.toColor("MAGENTA"));
assertEquals(Color.orange, StringUtil.toColor("orange"));
assertEquals(Color.orange, StringUtil.toColor("ORANGE"));
assertEquals(Color.pink, StringUtil.toColor("pink"));
assertEquals(Color.pink, StringUtil.toColor("PINK"));
assertEquals(Color.red, StringUtil.toColor("red"));
assertEquals(Color.red, StringUtil.toColor("RED"));
assertEquals(Color.white, StringUtil.toColor("white"));
assertEquals(Color.white, StringUtil.toColor("WHITE"));
assertEquals(Color.yellow, StringUtil.toColor("yellow"));
assertEquals(Color.yellow, StringUtil.toColor("YELLOW"));
// System.out.println(StringUtil.deepToString(Color.yellow));
// System.out.println(StringUtil.deepToString(Color.pink, true, -1));
// Test HTML/CSS style color
for (int i = 0; i < 256; i++) {
int c = i;
if (i < 0x10) {
c = i * 16;
}
String colorStr = "#" + Integer.toHexString(i) + Integer.toHexString(i) + Integer.toHexString(i);
String colorStrAlpha = "#" + Integer.toHexString(i) + Integer.toHexString(i) + Integer.toHexString(i) + Integer.toHexString(i);
assertEquals(new Color(c, c, c), StringUtil.toColor(colorStr));
assertEquals(new Color(c, c, c, c), StringUtil.toColor(colorStrAlpha));
}
// Test null
// TODO: Hmmm.. Maybe reconsider this..
assertNull(StringUtil.toColor(null));
// Test
try {
StringUtil.toColor("illegal-color-value");
fail("toColor with illegal color value should throw IllegalArgumentException.");
}
catch (IllegalArgumentException e) {
assertNotNull(e.getMessage());
}
}
public void testToColorString() {
assertEquals("#ff0000", StringUtil.toColorString(Color.red));
assertEquals("#00ff00", StringUtil.toColorString(Color.green));
assertEquals("#0000ff", StringUtil.toColorString(Color.blue));
assertEquals("#101010", StringUtil.toColorString(new Color(0x10, 0x10, 0x10)));
for (int i = 0; i < 256; i++) {
String str = (i < 0x10 ? "0" : "") + Integer.toHexString(i);
assertEquals("#" + str + str + str, StringUtil.toColorString(new Color(i, i, i)));
}
// Test null
// TODO: Hmmm.. Maybe reconsider this..
assertNull(StringUtil.toColorString(null));
}
public void testIsNumber() {
assertTrue(StringUtil.isNumber("0"));
assertTrue(StringUtil.isNumber("12345"));
assertTrue(StringUtil.isNumber(TEST_INTEGER.toString()));
assertTrue(StringUtil.isNumber("1234567890123456789012345678901234567890"));
assertTrue(StringUtil.isNumber(String.valueOf(Long.MAX_VALUE) + String.valueOf(Long.MAX_VALUE)));
assertFalse(StringUtil.isNumber("abc"));
assertFalse(StringUtil.isNumber(TEST_STRING));
}
public void testIsNumberNegative() {
assertTrue(StringUtil.isNumber("-12345"));
assertTrue(StringUtil.isNumber('-' + TEST_INTEGER.toString()));
assertTrue(StringUtil.isNumber("-1234567890123456789012345678901234567890"));
assertTrue(StringUtil.isNumber('-' + String.valueOf(Long.MAX_VALUE) + String.valueOf(Long.MAX_VALUE)));
assertFalse(StringUtil.isNumber("-abc"));
assertFalse(StringUtil.isNumber('-' + TEST_STRING));
}
public void testCamelToLispNull() {
try {
StringUtil.camelToLisp(null);
fail("should not accept null");
}
catch (IllegalArgumentException iae) {
assertNotNull(iae.getMessage());
}
}
public void testCamelToLispNoConversion() {
assertEquals("", StringUtil.camelToLisp(""));
assertEquals("equal", StringUtil.camelToLisp("equal"));
assertEquals("allready-lisp", StringUtil.camelToLisp("allready-lisp"));
}
public void testCamelToLispSimple() {
// Simple tests
assertEquals("foo-bar", StringUtil.camelToLisp("fooBar"));
}
public void testCamelToLispCase() {
// Casing
assertEquals("my-url", StringUtil.camelToLisp("myURL"));
assertEquals("another-url", StringUtil.camelToLisp("AnotherURL"));
}
public void testCamelToLispMulti() {
// Several words
assertEquals("http-request-wrapper", StringUtil.camelToLisp("HttpRequestWrapper"));
String s = StringUtil.camelToLisp("HttpURLConnection");
assertEquals("http-url-connection", s);
// Long and short abbre in upper case
assertEquals("welcome-to-my-world", StringUtil.camelToLisp("WELCOMEToMYWorld"));
}
public void testCamelToLispLeaveUntouched() {
// Leave others untouched
assertEquals("a-slightly-longer-and-more-bumpy-string?.,[]()", StringUtil.camelToLisp("ASlightlyLongerANDMoreBumpyString?.,[]()"));
}
public void testCamelToLispNumbers() {
// Numbers
// TODO: FixMe
String s = StringUtil.camelToLisp("my45Caliber");
assertEquals("my-45-caliber", s);
assertEquals("hello-12345-world-67890", StringUtil.camelToLisp("Hello12345world67890"));
assertEquals("hello-12345-my-world-67890-this-time", StringUtil.camelToLisp("HELLO12345MyWorld67890thisTime"));
assertEquals("hello-12345-world-67890-too", StringUtil.camelToLisp("Hello12345WORLD67890too"));
}
public void testLispToCamelNull() {
try {
StringUtil.lispToCamel(null);
fail("should not accept null");
}
catch (IllegalArgumentException iae) {
assertNotNull(iae.getMessage());
}
}
public void testLispToCamelNoConversion() {
assertEquals("", StringUtil.lispToCamel(""));
assertEquals("equal", StringUtil.lispToCamel("equal"));
assertEquals("allreadyCamel", StringUtil.lispToCamel("allreadyCamel"));
}
public void testLispToCamelSimple() {
// Simple tests
assertEquals("fooBar", StringUtil.lispToCamel("foo-bar"));
assertEquals("myUrl", StringUtil.lispToCamel("my-URL"));
assertEquals("anotherUrl", StringUtil.lispToCamel("ANOTHER-URL"));
}
public void testLispToCamelCase() {
// Casing
assertEquals("Object", StringUtil.lispToCamel("object", true));
assertEquals("object", StringUtil.lispToCamel("Object", false));
}
public void testLispToCamelMulti() {
// Several words
assertEquals("HttpRequestWrapper", StringUtil.lispToCamel("http-request-wrapper", true));
}
public void testLispToCamelLeaveUntouched() {
// Leave others untouched
assertEquals("ASlightlyLongerAndMoreBumpyString?.,[]()", StringUtil.lispToCamel("a-slightly-longer-and-more-bumpy-string?.,[]()", true));
}
public void testLispToCamelNumber() {
// Numbers
assertEquals("my45Caliber", StringUtil.lispToCamel("my-45-caliber"));
}
}

View File

@@ -0,0 +1,146 @@
package com.twelvemonkeys.util;
import java.util.Map;
import java.beans.IntrospectionException;
import java.io.Serializable;
/**
* BeanMapTestCase
* <p/>
* @todo Extend with BeanMap specific tests
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/BeanMapTestCase.java#2 $
*/
public class BeanMapTestCase extends MapAbstractTestCase {
public boolean isPutAddSupported() {
return false;
}
public boolean isRemoveSupported() {
return false;
}
public boolean isSetValueSupported() {
return true;
}
public boolean isAllowNullKey() {
return false;
}
public Object[] getSampleKeys() {
return new Object[] {
"blah", "foo", "bar", "baz", "tmp", "gosh", "golly", "gee"
};
}
public Object[] getSampleValues() {
return new Object[] {
"blahv", "foov", "barv", "bazv", "tmpv", "goshv", "gollyv", "geev"
};
}
public Object[] getNewSampleValues() {
return new Object[] {
"newblahv", "newfoov", "newbarv", "newbazv", "newtmpv", "newgoshv", "newgollyv", "newgeev"
};
}
public Map makeEmptyMap() {
try {
return new BeanMap(new NullBean());
}
catch (IntrospectionException e) {
throw new RuntimeException(e);
}
}
public Map makeFullMap() {
try {
return new BeanMap(new MyBean());
}
catch (IntrospectionException e) {
throw new RuntimeException(e);
}
}
public static class MyBean implements Serializable {
Object blah = "blahv";
Object foo = "foov";
Object bar = "barv";
Object baz = "bazv";
Object tmp = "tmpv";
Object gosh = "goshv";
Object golly = "gollyv";
Object gee = "geev";
public Object getBar() {
return bar;
}
public void setBar(Object pBar) {
bar = pBar;
}
public Object getBaz() {
return baz;
}
public void setBaz(Object pBaz) {
baz = pBaz;
}
public Object getBlah() {
return blah;
}
public void setBlah(Object pBlah) {
blah = pBlah;
}
public Object getFoo() {
return foo;
}
public void setFoo(Object pFoo) {
foo = pFoo;
}
public Object getGee() {
return gee;
}
public void setGee(Object pGee) {
gee = pGee;
}
public Object getGolly() {
return golly;
}
public void setGolly(Object pGolly) {
golly = pGolly;
}
public Object getGosh() {
return gosh;
}
public void setGosh(Object pGosh) {
gosh = pGosh;
}
public Object getTmp() {
return tmp;
}
public void setTmp(Object pTmp) {
tmp = pTmp;
}
}
static class NullBean implements Serializable { }
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,182 @@
/*
* Copyright 2001-2004 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.twelvemonkeys.util;
import java.util.*;
/**
* Tests LRUMap.
*
* @version $Revision: #2 $ $Date: 2008/07/15 $
*
* @author James Strachan
* @author Morgan Delagrange
* @author Stephen Colebourne
*/
public class LRUMapTestCase extends LinkedMapTestCase {
public boolean isGetStructuralModify() {
return true;
}
//-----------------------------------------------------------------------
public Map makeEmptyMap() {
LRUMap map = new LRUMap();
return map;
}
//-----------------------------------------------------------------------
public void testRemoveLRU() {
LRUMap map2 = new LRUMap(3);
map2.put(new Integer(1),"foo");
map2.put(new Integer(2),"foo");
map2.put(new Integer(3),"foo");
map2.put(new Integer(4),"foo"); // removes 1 since max size exceeded
map2.removeLRU(); // should be Integer(2)
assertTrue("Second to last value should exist",map2.get(new Integer(3)).equals("foo"));
assertTrue("First value inserted should not exist", map2.get(new Integer(1)) == null);
}
public void testMultiplePuts() {
LRUMap map2 = new LRUMap(2);
map2.put(new Integer(1),"foo");
map2.put(new Integer(2),"bar");
map2.put(new Integer(3),"foo");
map2.put(new Integer(4),"bar");
assertTrue("last value should exist",map2.get(new Integer(4)).equals("bar"));
assertTrue("LRU should not exist", map2.get(new Integer(1)) == null);
}
/**
* Confirm that putAll(Map) does not cause the LRUMap
* to exceed its maxiumum size.
*/
public void testPutAll() {
LRUMap map2 = new LRUMap(3);
map2.put(new Integer(1),"foo");
map2.put(new Integer(2),"foo");
map2.put(new Integer(3),"foo");
HashMap hashMap = new HashMap();
hashMap.put(new Integer(4),"foo");
map2.putAll(hashMap);
assertTrue("max size is 3, but actual size is " + map2.size(),
map2.size() == 3);
assertTrue("map should contain the Integer(4) object",
map2.containsKey(new Integer(4)));
}
/**
* Test that the size of the map is reduced immediately
* when setMaximumSize(int) is called
*/
public void testSetMaximumSize() {
LRUMap map = new LRUMap(6);
map.put("1","1");
map.put("2","2");
map.put("3","3");
map.put("4","4");
map.put("5","5");
map.put("6","6");
map.setMaxSize(3);
assertTrue("map should have size = 3, but actually = " + map.size(),
map.size() == 3);
}
public void testGetPromotion() {
LRUMap map = new LRUMap(3);
map.put("1","1");
map.put("2","2");
map.put("3","3");
// LRU is now 1 (then 2 then 3)
// promote 1 to top
// eviction order is now 2,3,1
map.get("1");
// add another value, forcing a remove
// 2 should be evicted (then 3,1,4)
map.put("4","4");
Iterator keyIterator = map.keySet().iterator();
Object[] keys = new Object[3];
for (int i = 0; keyIterator.hasNext() ; ++i) {
keys[i] = keyIterator.next();
}
assertTrue("first evicted should be 3, was " + keys[0], keys[0].equals("3"));
assertTrue("second evicted should be 1, was " + keys[1], keys[1].equals("1"));
assertTrue("third evicted should be 4, was " + keys[2], keys[2].equals("4"));
}
/**
* You should be able to subclass LRUMap and perform a
* custom action when items are removed automatically
* by the LRU algorithm (the removeLRU() method).
*/
public void testLRUSubclass() {
LRUCounter counter = new LRUCounter(3);
// oldest <--> newest
// 1
counter.put("1","foo");
// 1 2
counter.put("2","foo");
// 1 2 3
counter.put("3","foo");
// 2 3 1
counter.put("1","foo");
// 3 1 4 (2 goes out)
counter.put("4","foo");
// 1 4 5 (3 goes out)
counter.put("5","foo");
// 4 5 2 (1 goes out)
counter.put("2","foo");
// 4 2
counter.remove("5");
assertTrue("size should be 2, but was " + counter.size(), counter.size() == 2);
assertTrue("removedCount should be 3 but was " + counter.removedCount,
counter.removedCount == 3);
assertTrue("first removed was '2'",counter.list.get(0).equals("2"));
assertTrue("second removed was '3'",counter.list.get(1).equals("3"));
assertTrue("third removed was '1'",counter.list.get(2).equals("1"));
//assertTrue("oldest key is '4'",counter.get(0).equals("4"));
//assertTrue("newest key is '2'",counter.get(1).equals("2"));
}
private class LRUCounter extends LRUMap {
int removedCount = 0;
List list = new ArrayList(3);
LRUCounter(int i) {
super(i);
}
public void processRemoved(Entry pEntry) {
++removedCount;
list.add(pEntry.getKey());
}
}
}

View File

@@ -0,0 +1,175 @@
/*
* Copyright 2001-2004 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.twelvemonkeys.util;
import java.util.Iterator;
import java.util.Map;
/**
* Unit tests
* {@link org.apache.commons.collections.SequencedHashMap}.
* Be sure to use the "labRat" instance whenever possible,
* so that subclasses will be tested correctly.
*
* @version $Revision: #2 $ $Date: 2008/07/15 $
*
* @author Morgan Delagrange
* @author Daniel Rall
* @author Henning P. Schmiedehausen
* @author James Strachan
*/
public class LinkedMapTestCase extends MapAbstractTestCase {
/**
* The instance to experiment on.
*/
protected LinkedMap labRat;
public void setUp() throws Exception {
super.setUp();
// use makeMap and cast the result to a SeqHashMap
// so that subclasses of SeqHashMap can share these tests
labRat = (LinkedMap) makeEmptyMap();
}
public Map makeEmptyMap() {
return new LinkedMap();
}
protected Object[] getKeys() {
return new Object[] { "foo", "baz", "eek" };
}
protected Object[] getValues() {
return new Object[] { "bar", "frob", new Object() };
}
public void testSequenceMap() throws Throwable {
Object[] keys = getKeys();
int expectedSize = keys.length;
Object[] values = getValues();
for (int i = 0; i < expectedSize; i++) {
labRat.put(keys[i], values[i]);
}
// Test size().
assertEquals("size() does not match expected size",
expectedSize, labRat.size());
// Test clone(), iterator(), and get(Object).
LinkedMap clone = (LinkedMap) labRat.clone();
assertEquals("Size of clone does not match original",
labRat.size(), clone.size());
Iterator origEntries = labRat.entrySet().iterator();
Iterator copiedEntries = clone.entrySet().iterator();
while (origEntries.hasNext()) {
Map.Entry origEntry = (Map.Entry)origEntries.next();
Map.Entry copiedEntry = (Map.Entry)copiedEntries.next();
assertEquals("Cloned key does not match original",
origEntry.getKey(), copiedEntry.getKey());
assertEquals("Cloned value does not match original",
origEntry.getValue(), copiedEntry.getValue());
assertEquals("Cloned entry does not match original",
origEntry, copiedEntry);
}
assertTrue("iterator() returned different number of elements than keys()",
!copiedEntries.hasNext());
// Test sequence()
/*
List seq = labRat.sequence();
assertEquals("sequence() returns more keys than in the Map",
expectedSize, seq.size());
for (int i = 0; i < seq.size(); i++) {
assertEquals("Key " + i + " is not the same as the key in the Map",
keys[i], seq.get(i));
}
*/
}
/*
public void testYoungest() {
labRat.put(new Integer(1),"foo");
labRat.put(new Integer(2),"bar");
assertTrue("first key is correct",labRat.get(0).equals(new Integer(1)));
labRat.put(new Integer(1),"boo");
assertTrue("second key is reassigned to first",labRat.get(0).equals(new Integer(2)));
}
public void testYoungestReplaceNullWithValue() {
labRat.put(new Integer(1),null);
labRat.put(new Integer(2),"foo");
assertTrue("first key is correct",labRat.get(0).equals(new Integer(1)));
labRat.put(new Integer(1),"bar");
assertTrue("second key is reassigned to first",labRat.get(0).equals(new Integer(2)));
}
public void testYoungestReplaceValueWithNull() {
labRat.put(new Integer(1),"bar");
labRat.put(new Integer(2),"foo");
assertTrue("first key is correct",labRat.get(0).equals(new Integer(1)));
labRat.put(new Integer(1),null);
assertTrue("second key is reassigned to first",labRat.get(0).equals(new Integer(2)));
}
*/
// override TestMap method with more specific tests
/*
public void testFullMapSerialization()
throws IOException, ClassNotFoundException {
LinkedMap map = (LinkedMap) makeFullMap();
if (!(map instanceof Serializable)) return;
byte[] objekt = writeExternalFormToBytes((Serializable) map);
LinkedMap map2 = (LinkedMap) readExternalFormFromBytes(objekt);
assertEquals("Both maps are same size",map.size(), getSampleKeys().length);
assertEquals("Both maps are same size",map2.size(),getSampleKeys().length);
assertEquals("Both maps have the same first key",
map.getFirstKey(),getSampleKeys()[0]);
assertEquals("Both maps have the same first key",
map2.getFirstKey(),getSampleKeys()[0]);
assertEquals("Both maps have the same last key",
map.getLastKey(),getSampleKeys()[getSampleKeys().length - 1]);
assertEquals("Both maps have the same last key",
map2.getLastKey(),getSampleKeys()[getSampleKeys().length - 1]);
}
*/
/*
public void testIndexOf() throws Exception {
Object[] keys = getKeys();
int expectedSize = keys.length;
Object[] values = getValues();
for (int i = 0; i < expectedSize; i++) {
labRat.put(keys[i], values[i]);
}
// test that the index returned are in the same order that they were
// placed in the map
for (int i = 0; i < keys.length; i++) {
assertEquals("indexOf with existing key failed", i, labRat.indexOf(keys[i]));
}
// test non existing key..
assertEquals("test with non-existing key failed", -1, labRat.indexOf("NonExistingKey"));
}
*/
public void tearDown() throws Exception {
labRat = null;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,187 @@
package com.twelvemonkeys.util;
import java.util.Map;
import java.util.HashMap;
/**
* NOTE: This TestCase is written especially for NullMap, and is full of dirty
* tricks. A good indication that NullMap is not a good, general-purpose Map
* implementation...
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/NullMapTestCase.java#2 $
*/
public class NullMapTestCase extends MapAbstractTestCase {
private boolean empty = true;
public Map makeEmptyMap() {
return new NullMap();
}
public Map makeFullMap() {
return new NullMap();
}
public Map makeConfirmedMap() {
// Always empty
return new HashMap();
}
public void resetEmpty() {
empty = true;
super.resetEmpty();
}
public void resetFull() {
empty = false;
super.resetFull();
}
public void verifyAll() {
if (empty) {
super.verifyAll();
}
}
// Overriden, as this map is always empty
public void testMapIsEmpty() {
resetEmpty();
assertEquals("Map.isEmpty() should return true with an empty map",
true, map.isEmpty());
verifyAll();
resetFull();
assertEquals("Map.isEmpty() should return true with a full map",
true, map.isEmpty());
}
// Overriden, as this map is always empty
public void testMapSize() {
resetEmpty();
assertEquals("Map.size() should be 0 with an empty map",
0, map.size());
verifyAll();
resetFull();
assertEquals("Map.size() should equal the number of entries " +
"in the map", 0, map.size());
}
public void testMapContainsKey() {
Object[] keys = getSampleKeys();
resetEmpty();
for(int i = 0; i < keys.length; i++) {
assertTrue("Map must not contain key when map is empty",
!map.containsKey(keys[i]));
}
verifyAll();
}
public void testMapContainsValue() {
Object[] values = getSampleValues();
resetEmpty();
for(int i = 0; i < values.length; i++) {
assertTrue("Empty map must not contain value",
!map.containsValue(values[i]));
}
verifyAll();
}
public void testMapEquals() {
resetEmpty();
assertTrue("Empty maps unequal.", map.equals(confirmed));
verifyAll();
}
public void testMapHashCode() {
resetEmpty();
assertTrue("Empty maps have different hashCodes.",
map.hashCode() == confirmed.hashCode());
}
public void testMapGet() {
resetEmpty();
Object[] keys = getSampleKeys();
for (int i = 0; i < keys.length; i++) {
assertTrue("Empty map.get() should return null.",
map.get(keys[i]) == null);
}
verifyAll();
}
public void testMapPut() {
resetEmpty();
Object[] keys = getSampleKeys();
Object[] values = getSampleValues();
Object[] newValues = getNewSampleValues();
for (int i = 0; i < keys.length; i++) {
Object o = map.put(keys[i], values[i]);
//confirmed.put(keys[i], values[i]);
verifyAll();
assertTrue("First map.put should return null", o == null);
}
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], newValues[i]);
//confirmed.put(keys[i], newValues[i]);
verifyAll();
}
}
public void testMapToString() {
resetEmpty();
assertTrue("Empty map toString() should not return null",
map.toString() != null);
verifyAll();
}
public void testMapPutAll() {
// TODO: Find a menaingful way to test this
}
public void testMapRemove() {
resetEmpty();
Object[] keys = getSampleKeys();
for(int i = 0; i < keys.length; i++) {
Object o = map.remove(keys[i]);
assertTrue("First map.remove should return null", o == null);
}
verifyAll();
}
//-----------------------------------------------------------------------
public void testEntrySetClearChangesMap() {
}
public void testKeySetClearChangesMap() {
}
public void testKeySetRemoveChangesMap() {
}
public void testValuesClearChangesMap() {
}
public void testEntrySetContains1() {
}
public void testEntrySetContains2() {
}
public void testEntrySetContains3() {
}
public void testEntrySetRemove1() {
}
public void testEntrySetRemove2() {
}
public void testEntrySetRemove3() {
}
}

View File

@@ -0,0 +1,307 @@
/*
* Copyright 2001-2004 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.twelvemonkeys.util;
import org.jmock.cglib.MockObjectTestCase;
import java.io.*;
/**
* Abstract test class for {@link Object} methods and contracts.
* <p>
* To use, simply extend this class, and implement
* the {@link #makeObject()} method.
* <p>
* If your {@link Object} fails one of these tests by design,
* you may still use this base set of cases. Simply override the
* test case (method) your {@link Object} fails.
*
* @version $Revision: #2 $ $Date: 2008/07/15 $
*
* @author Rodney Waldhoff
* @author Stephen Colebourne
* @author Anonymous
*/
public abstract class ObjectAbstractTestCase extends MockObjectTestCase {
//-----------------------------------------------------------------------
/**
* Implement this method to return the object to test.
*
* @return the object to test
*/
public abstract Object makeObject();
/**
* Override this method if a subclass is testing an object
* that cannot serialize an "empty" Collection.
* (e.g. Comparators have no contents)
*
* @return true
*/
public boolean supportsEmptyCollections() {
return true;
}
/**
* Override this method if a subclass is testing an object
* that cannot serialize a "full" Collection.
* (e.g. Comparators have no contents)
*
* @return true
*/
public boolean supportsFullCollections() {
return true;
}
/**
* Is serialization testing supported.
* Default is true.
*/
public boolean isTestSerialization() {
return true;
}
/**
* Returns true to indicate that the collection supports equals() comparisons.
* This implementation returns true;
*/
public boolean isEqualsCheckable() {
return true;
}
//-----------------------------------------------------------------------
public void testObjectEqualsSelf() {
Object obj = makeObject();
assertEquals("A Object should equal itself", obj, obj);
}
public void testEqualsNull() {
Object obj = makeObject();
assertEquals(false, obj.equals(null)); // make sure this doesn't throw NPE either
}
public void testObjectHashCodeEqualsSelfHashCode() {
Object obj = makeObject();
assertEquals("hashCode should be repeatable", obj.hashCode(), obj.hashCode());
}
public void testObjectHashCodeEqualsContract() {
Object obj1 = makeObject();
if (obj1.equals(obj1)) {
assertEquals(
"[1] When two objects are equal, their hashCodes should be also.",
obj1.hashCode(), obj1.hashCode());
}
Object obj2 = makeObject();
if (obj1.equals(obj2)) {
assertEquals(
"[2] When two objects are equal, their hashCodes should be also.",
obj1.hashCode(), obj2.hashCode());
assertTrue(
"When obj1.equals(obj2) is true, then obj2.equals(obj1) should also be true",
obj2.equals(obj1));
}
}
public void testSerializeDeserializeThenCompare() throws Exception {
Object obj = makeObject();
if (obj instanceof Serializable && isTestSerialization()) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(buffer);
out.writeObject(obj);
out.close();
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
Object dest = in.readObject();
in.close();
if (isEqualsCheckable()) {
assertEquals("obj != deserialize(serialize(obj))", obj, dest);
}
}
}
/**
* Sanity check method, makes sure that any Serializable
* class can be serialized and de-serialized in memory,
* using the handy makeObject() method
*
* @throws java.io.IOException
* @throws ClassNotFoundException
*/
public void testSimpleSerialization() throws Exception {
Object o = makeObject();
if (o instanceof Serializable && isTestSerialization()) {
byte[] objekt = writeExternalFormToBytes((Serializable) o);
Object p = readExternalFormFromBytes(objekt);
}
}
/**
* Tests serialization by comparing against a previously stored version in CVS.
* If the test object is serializable, confirm that a canonical form exists.
*/
public void testCanonicalEmptyCollectionExists() {
if (supportsEmptyCollections() && isTestSerialization() && !skipSerializedCanonicalTests()) {
Object object = makeObject();
if (object instanceof Serializable) {
String name = getCanonicalEmptyCollectionName(object);
assertTrue(
"Canonical empty collection (" + name + ") is not in CVS",
new File(name).exists());
}
}
}
/**
* Tests serialization by comparing against a previously stored version in CVS.
* If the test object is serializable, confirm that a canonical form exists.
*/
public void testCanonicalFullCollectionExists() {
if (supportsFullCollections() && isTestSerialization() && !skipSerializedCanonicalTests()) {
Object object = makeObject();
if (object instanceof Serializable) {
String name = getCanonicalFullCollectionName(object);
assertTrue(
"Canonical full collection (" + name + ") is not in CVS",
new File(name).exists());
}
}
}
// protected implementation
//-----------------------------------------------------------------------
/**
* Get the version of Collections that this object tries to
* maintain serialization compatibility with. Defaults to 1, the
* earliest Collections version. (Note: some collections did not
* even exist in this version).
*
* This constant makes it possible for TestMap (and other subclasses,
* if necessary) to automatically check CVS for a versionX copy of a
* Serialized object, so we can make sure that compatibility is maintained.
* See, for example, TestMap.getCanonicalFullMapName(Map map).
* Subclasses can override this variable, indicating compatibility
* with earlier Collections versions.
*
* @return The version, or {@code null} if this object shouldn't be
* tested for compatibility with previous versions.
*/
public String getCompatibilityVersion() {
return "1";
}
protected String getCanonicalEmptyCollectionName(Object object) {
StringBuilder retval = new StringBuilder();
retval.append("data/test/");
String colName = object.getClass().getName();
colName = colName.substring(colName.lastIndexOf(".") + 1, colName.length());
retval.append(colName);
retval.append(".emptyCollection.version");
retval.append(getCompatibilityVersion());
retval.append(".obj");
return retval.toString();
}
protected String getCanonicalFullCollectionName(Object object) {
StringBuilder retval = new StringBuilder();
retval.append("data/test/");
String colName = object.getClass().getName();
colName = colName.substring(colName.lastIndexOf(".") + 1, colName.length());
retval.append(colName);
retval.append(".fullCollection.version");
retval.append(getCompatibilityVersion());
retval.append(".obj");
return retval.toString();
}
/**
* Write a Serializable or Externalizable object as
* a file at the given path. NOT USEFUL as part
* of a unit test; this is just a utility method
* for creating disk-based objects in CVS that can become
* the basis for compatibility tests using
* readExternalFormFromDisk(String path)
*
* @param o Object to serialize
* @param path path to write the serialized Object
* @exception java.io.IOException
*/
protected void writeExternalFormToDisk(Serializable o, String path) throws IOException {
FileOutputStream fileStream = new FileOutputStream(path);
writeExternalFormToStream(o, fileStream);
}
/**
* Converts a Serializable or Externalizable object to
* bytes. Useful for in-memory tests of serialization
*
* @param o Object to convert to bytes
* @return serialized form of the Object
* @exception java.io.IOException
*/
protected byte[] writeExternalFormToBytes(Serializable o) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
writeExternalFormToStream(o, byteStream);
return byteStream.toByteArray();
}
/**
* Reads a Serialized or Externalized Object from disk.
* Useful for creating compatibility tests between
* different CVS versions of the same class
*
* @param path path to the serialized Object
* @return the Object at the given path
* @exception java.io.IOException
* @exception ClassNotFoundException
*/
protected Object readExternalFormFromDisk(String path) throws IOException, ClassNotFoundException {
FileInputStream stream = new FileInputStream(path);
return readExternalFormFromStream(stream);
}
/**
* Read a Serialized or Externalized Object from bytes.
* Useful for verifying serialization in memory.
*
* @param b byte array containing a serialized Object
* @return Object contained in the bytes
* @exception java.io.IOException
* @exception ClassNotFoundException
*/
protected Object readExternalFormFromBytes(byte[] b) throws IOException, ClassNotFoundException {
ByteArrayInputStream stream = new ByteArrayInputStream(b);
return readExternalFormFromStream(stream);
}
protected boolean skipSerializedCanonicalTests() {
return Boolean.getBoolean("org.apache.commons.collections:with-clover");
}
// private implementation
//-----------------------------------------------------------------------
private Object readExternalFormFromStream(InputStream stream) throws IOException, ClassNotFoundException {
ObjectInputStream oStream = new ObjectInputStream(stream);
return oStream.readObject();
}
private void writeExternalFormToStream(Serializable o, OutputStream stream) throws IOException {
ObjectOutputStream oStream = new ObjectOutputStream(stream);
oStream.writeObject(o);
}
}

View File

@@ -0,0 +1,183 @@
/*
* Copyright 2001-2004 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.twelvemonkeys.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Abstract test class for {@link Set} methods and contracts.
* <p>
* Since {@link Set} doesn't stipulate much new behavior that isn't already
* found in {@link Collection}, this class basically just adds tests for
* {@link Set#equals} and {@link Set#hashCode()} along with an updated
* {@link #verifyAll()} that ensures elements do not appear more than once in the
* set.
* <p>
* To use, subclass and override the {@link #makeEmptySet()}
* method. You may have to override other protected methods if your
* set is not modifiable, or if your set restricts what kinds of
* elements may be added; see {@link CollectionAbstractTestCase} for more details.
*
* @since Commons Collections 3.0
* @version $Revision: #2 $ $Date: 2008/07/15 $
*
* @author Paul Jack
*/
public abstract class SetAbstractTestCase extends CollectionAbstractTestCase {
//-----------------------------------------------------------------------
/**
* Provides additional verifications for sets.
*/
public void verifyAll() {
super.verifyAll();
assertEquals("Sets should be equal", confirmed, collection);
assertEquals("Sets should have equal hashCodes",
confirmed.hashCode(), collection.hashCode());
Collection set = makeConfirmedCollection();
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
assertTrue("Set.iterator should only return unique elements",
set.add(iterator.next()));
}
}
//-----------------------------------------------------------------------
/**
* Set equals method is defined.
*/
public boolean isEqualsCheckable() {
return true;
}
/**
* Returns an empty Set for use in modification testing.
*
* @return a confirmed empty collection
*/
public Collection makeConfirmedCollection() {
return new HashSet();
}
/**
* Returns a full Set for use in modification testing.
*
* @return a confirmed full collection
*/
public Collection makeConfirmedFullCollection() {
Collection set = makeConfirmedCollection();
set.addAll(Arrays.asList(getFullElements()));
return set;
}
/**
* Makes an empty set. The returned set should have no elements.
*
* @return an empty set
*/
public abstract Set makeEmptySet();
/**
* Makes a full set by first creating an empty set and then adding
* all the elements returned by {@link #getFullElements()}.
*
* Override if your set does not support the add operation.
*
* @return a full set
*/
public Set makeFullSet() {
Set set = makeEmptySet();
set.addAll(Arrays.asList(getFullElements()));
return set;
}
/**
* Makes an empty collection by invoking {@link #makeEmptySet()}.
*
* @return an empty collection
*/
public final Collection makeCollection() {
return makeEmptySet();
}
/**
* Makes a full collection by invoking {@link #makeFullSet()}.
*
* @return a full collection
*/
public final Collection makeFullCollection() {
return makeFullSet();
}
//-----------------------------------------------------------------------
/**
* Return the {@link CollectionAbstractTestCase#collection} fixture, but cast as a Set.
*/
public Set getSet() {
return (Set)collection;
}
/**
* Return the {@link CollectionAbstractTestCase#confirmed} fixture, but cast as a Set.
*/
public Set getConfirmedSet() {
return (Set)confirmed;
}
//-----------------------------------------------------------------------
/**
* Tests {@link Set#equals(Object)}.
*/
public void testSetEquals() {
resetEmpty();
assertEquals("Empty sets should be equal",
getSet(), getConfirmedSet());
verifyAll();
Collection set2 = makeConfirmedCollection();
set2.add("foo");
assertTrue("Empty set shouldn't equal nonempty set",
!getSet().equals(set2));
resetFull();
assertEquals("Full sets should be equal", getSet(), getConfirmedSet());
verifyAll();
set2.clear();
set2.addAll(Arrays.asList(getOtherElements()));
assertTrue("Sets with different contents shouldn't be equal",
!getSet().equals(set2));
}
/**
* Tests {@link Set#hashCode()}.
*/
public void testSetHashCode() {
resetEmpty();
assertEquals("Empty sets have equal hashCodes",
getSet().hashCode(), getConfirmedSet().hashCode());
resetFull();
assertEquals("Equal sets have equal hashCodes",
getSet().hashCode(), getConfirmedSet().hashCode());
}
}

View File

@@ -0,0 +1,111 @@
package com.twelvemonkeys.util;
import java.util.Iterator;
/**
* StringTokenIteratorTestCase
* <p/>
* <!-- To change this template use Options | File Templates. -->
* <!-- Created by IntelliJ IDEA. -->
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/StringTokenIteratorTestCase.java#1 $
*/
public class StringTokenIteratorTestCase extends TokenIteratorAbstractTestCase {
public void setUp() throws Exception {
super.setUp();
}
public void tearDown() throws Exception {
super.tearDown();
}
protected TokenIterator createTokenIterator(String pString) {
return new StringTokenIterator(pString);
}
protected TokenIterator createTokenIterator(String pString, String pDelimiters) {
return new StringTokenIterator(pString, pDelimiters);
}
public void testEmptyDelimiter() {
Iterator iterator = createTokenIterator("", "");
assertFalse("Empty string has elements", iterator.hasNext());
}
public void testSingleToken() {
Iterator iterator = createTokenIterator("A");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testSingleTokenEmptyDelimiter() {
Iterator iterator = createTokenIterator("A", "");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testSingleTokenSingleDelimiter() {
Iterator iterator = createTokenIterator("A", ",");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testSingleSeparatorDefaultDelimiter() {
Iterator iterator = createTokenIterator("A B C D");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("D", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testSingleSeparator() {
Iterator iterator = createTokenIterator("A,B,C", ",");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("C", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testMultipleSeparatorDefaultDelimiter() {
Iterator iterator = createTokenIterator("A B C\nD\t\t \nE");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("D", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("E", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testMultipleSeparator() {
Iterator iterator = createTokenIterator("A,B,;,C...D, ., ,E", " ,.;:");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("D", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("E", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
}

View File

@@ -0,0 +1,632 @@
/****************************************************
* *
* (c) 2000-2003 WM-data *
* All rights reserved *
* http://www.twelvemonkeys.no *
* *
* $RCSfile: TimeoutMapTestCase.java,v $
* @version $Revision: #2 $
* $Date: 2008/07/15 $
* *
* @author Last modified by: $Author: haku $
* *
****************************************************/
package com.twelvemonkeys.util;
import junit.framework.Test;
import junit.framework.TestSuite;
import java.util.*;
/**
* TimeoutMapTestCase
* <p/>
* <!-- To change this template use Options | File Templates. -->
* <!-- Created by IntelliJ IDEA. -->
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/TimeoutMapTestCase.java#2 $
*/
public class TimeoutMapTestCase extends MapAbstractTestCase {
/**
* Method suite
*
* @return
*/
public static Test suite() {
return new TestSuite(TimeoutMapTestCase.class);
}
public Map makeEmptyMap() {
return new TimeoutMap(60 * 60 * 1000);
}
/*
* The basic Map interface lets one associate keys and values:
*/
/**
* Method testBasicMap
*/
public void testBasicMap() {
Map map = new TimeoutMap(60000L);
Object key = "key";
Object value = new Integer(3);
map.put(key, value);
assertEquals(value, map.get(key));
}
/*
* If there is no value associated with a key,
* the basic Map will return null for that key:
*/
/**
* Method testBasicMapReturnsNullForMissingKey
*/
public void testBasicMapReturnsNullForMissingKey() {
Map map = new TimeoutMap(60000L);
assertNull(map.get("key"));
}
/*
* One can also explicitly store a null value for
* some key:
*/
/**
* Method testBasicMapAllowsNull
*/
public void testBasicMapAllowsNull() {
Map map = new TimeoutMap(60000L);
Object key = "key";
Object value = null;
map.put(key, value);
assertNull(map.get(key));
}
/**
* Method testBasicMapAllowsMultipleTypes
*/
public void testBasicMapAllowsMultipleTypes() {
Map map = new TimeoutMap(60000L);
map.put("key-1", "value-1");
map.put(new Integer(2), "value-2");
map.put("key-3", new Integer(3));
map.put(new Integer(4), new Integer(4));
map.put(Boolean.FALSE, "");
assertEquals("value-1", map.get("key-1"));
assertEquals("value-2", map.get(new Integer(2)));
assertEquals(new Integer(3), map.get("key-3"));
assertEquals(new Integer(4), map.get(new Integer(4)));
assertEquals("", map.get(Boolean.FALSE));
}
/**
* Method testBasicMapStoresOnlyOneValuePerKey
*/
public void testBasicMapStoresOnlyOneValuePerKey() {
Map map = new TimeoutMap(60000L);
assertNull(map.put("key", "value-1"));
assertEquals("value-1", map.get("key"));
assertEquals("value-1", map.put("key", "value-2"));
assertEquals("value-2", map.get("key"));
}
/**
* Method testBasicMapValuesView
*/
public void testBasicMapValuesView() {
Map map = new TimeoutMap(60000L);
assertNull(map.put("key-1", new Integer(1)));
assertNull(map.put("key-2", new Integer(2)));
assertNull(map.put("key-3", new Integer(3)));
assertNull(map.put("key-4", new Integer(4)));
assertEquals(4, map.size());
Collection values = map.values();
assertEquals(4, values.size());
Iterator it = values.iterator();
assertNotNull(it);
int count = 0;
while (it.hasNext()) {
Object o = it.next();
assertNotNull(o);
assertTrue(o instanceof Integer);
count++;
}
assertEquals(4, count);
}
/**
* Method testBasicMapKeySetView
*/
public void testBasicMapKeySetView() {
Map map = new TimeoutMap(60000L);
assertNull(map.put("key-1", "value-1"));
assertNull(map.put("key-2", "value-2"));
assertNull(map.put("key-3", "value-3"));
assertNull(map.put("key-4", "value-4"));
assertEquals(4, map.size());
Iterator it = map.keySet().iterator();
assertNotNull(it);
int count = 0;
while (it.hasNext()) {
Object o = it.next();
assertNotNull(o);
assertTrue(o instanceof String);
count++;
}
assertEquals(4, count);
}
/**
* Method testBasicMapEntrySetView
*/
public void testBasicMapEntrySetView() {
Map map = new TimeoutMap(60000L);
assertNull(map.put("key-1", new Integer(1)));
assertNull(map.put("key-2", "value-2"));
assertNull(map.put("key-3", new Object()));
assertNull(map.put("key-4", Boolean.FALSE));
assertEquals(4, map.size());
Iterator it = map.entrySet().iterator();
assertNotNull(it);
int count = 0;
while (it.hasNext()) {
Object o = it.next();
assertNotNull(o);
assertTrue(o instanceof Map.Entry);
count++;
}
assertEquals(4, count);
}
/**
* Method testBasicMapValuesView
*/
public void testBasicMapValuesViewRemoval() {
Map map = new TimeoutMap(60000L);
assertNull(map.put("key-1", new Integer(1)));
assertNull(map.put("key-2", new Integer(2)));
assertNull(map.put("key-3", new Integer(3)));
assertNull(map.put("key-4", new Integer(4)));
assertEquals(4, map.size());
Iterator it = map.values().iterator();
assertNotNull(it);
int count = 0;
while (it.hasNext()) {
Object o = it.next();
assertNotNull(o);
assertTrue(o instanceof Integer);
try {
it.remove();
}
catch (UnsupportedOperationException e) {
fail("Removal failed");
}
count++;
}
assertEquals(4, count);
}
/**
* Method testBasicMapKeySetView
*/
public void testBasicMapKeySetViewRemoval() {
Map map = new TimeoutMap(60000L);
assertNull(map.put("key-1", "value-1"));
assertNull(map.put("key-2", "value-2"));
assertNull(map.put("key-3", "value-3"));
assertNull(map.put("key-4", "value-4"));
assertEquals(4, map.size());
Iterator it = map.keySet().iterator();
assertNotNull(it);
int count = 0;
while (it.hasNext()) {
Object o = it.next();
assertNotNull(o);
assertTrue(o instanceof String);
try {
it.remove();
}
catch (UnsupportedOperationException e) {
fail("Removal failed");
}
count++;
}
assertEquals(4, count);
}
/**
* Method testBasicMapEntrySetView
*/
public void testBasicMapEntrySetViewRemoval() {
Map map = new TimeoutMap(60000L);
assertNull(map.put("key-1", new Integer(1)));
assertNull(map.put("key-2", "value-2"));
assertNull(map.put("key-3", new Object()));
assertNull(map.put("key-4", Boolean.FALSE));
assertEquals(4, map.size());
Iterator it = map.entrySet().iterator();
assertNotNull(it);
int count = 0;
while (it.hasNext()) {
Object o = it.next();
assertNotNull(o);
assertTrue(o instanceof Map.Entry);
try {
it.remove();
}
catch (UnsupportedOperationException e) {
fail("Removal failed");
}
count++;
}
assertEquals(4, count);
}
/**
* Method testBasicMapStoresOnlyOneValuePerKey
*/
public void testTimeoutReturnNull() {
Map map = new TimeoutMap(100L);
assertNull(map.put("key", "value-1"));
assertEquals("value-1", map.get("key"));
assertNull(map.put("another", "value-2"));
assertEquals("value-2", map.get("another"));
synchronized (this) {
try {
Thread.sleep(110L);
}
catch (InterruptedException e) {
// Continue, but might break the timeout thing below...
}
}
// Values should now time out
assertNull(map.get("key"));
assertNull(map.get("another"));
}
/**
* Method testTimeoutIsEmpty
*/
public void testTimeoutIsEmpty() {
TimeoutMap map = new TimeoutMap(50L);
assertNull(map.put("key", "value-1"));
assertEquals("value-1", map.get("key"));
assertNull(map.put("another", "value-2"));
assertEquals("value-2", map.get("another"));
synchronized (this) {
try {
Thread.sleep(100L);
}
catch (InterruptedException e) {
// Continue, but might break the timeout thing below...
}
}
// This for loop should not print anything, if the tests succeed.
Set set = map.keySet();
assertEquals(0, set.size());
for (Iterator iterator = set.iterator(); iterator.hasNext(); System.out.println(iterator.next())) {
;
}
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
/**
* Method testTimeoutWrapIsEmpty
*/
public void testTimeoutWrapIsEmpty() {
Map map = new TimeoutMap(new LRUMap(2), null, 100L);
assertNull(map.put("key", "value-1"));
assertEquals("value-1", map.get("key"));
assertNull(map.put("another", "value-2"));
assertEquals("value-2", map.get("another"));
assertNull(map.put("third", "value-3"));
assertEquals("value-3", map.get("third"));
synchronized (this) {
try {
Thread.sleep(110L);
}
catch (InterruptedException e) {
// Continue, but might break the timeout thing below...
}
}
// This for loop should not print anything, if the tests succeed.
Set set = map.keySet();
assertEquals(0, set.size());
for (Iterator iterator = set.iterator(); iterator.hasNext(); System.out.println(iterator.next())) {
;
}
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
/**
* Method testTimeoutWrapReturnNull
*/
public void testTimeoutWrapReturnNull() {
Map map = new TimeoutMap(new LRUMap(), null, 100L);
assertNull(map.put("key", "value-1"));
assertEquals("value-1", map.get("key"));
assertNull(map.put("another", "value-2"));
assertEquals("value-2", map.get("another"));
synchronized (this) {
try {
Thread.sleep(110L);
}
catch (InterruptedException e) {
// Continue, but might break the timeout thing below...
}
}
// Values should now time out
assertNull(map.get("key"));
assertNull(map.get("another"));
}
/**
* Method testWrapMaxSize
*/
public void testWrapMaxSize() {
LRUMap lru = new LRUMap();
lru.setMaxSize(2);
TimeoutMap map = new TimeoutMap(lru, null, 1000L);
assertNull(map.put("key", "value-1"));
assertEquals("value-1", map.get("key"));
assertNull(map.put("another", "value-2"));
assertEquals("value-2", map.get("another"));
assertNull(map.put("third", "value-3"));
assertEquals("value-3", map.get("third"));
// This value should have expired
assertNull(map.get("key"));
// These should be left
assertEquals("value-2", map.get("another"));
assertEquals("value-3", map.get("third"));
}
/**
* Method testWrapMapContainingValues
*/
public void testWrapMapContainingValues() {
Map backing = new TreeMap();
backing.put("key", "original");
TimeoutMap map = null;
try {
map = new TimeoutMap(backing, backing, 1000L);
Object value = map.put("key", "value-1");
assertNotNull(value); // Should now have value!
assertEquals("original", value);
}
catch (ClassCastException cce) {
cce.printStackTrace();
fail("Content not converted to TimedEntries properly!");
}
assertEquals("value-1", map.get("key"));
assertNull(map.put("another", "value-2"));
assertEquals("value-2", map.get("another"));
assertNull(map.put("third", "value-3"));
assertEquals("value-3", map.get("third"));
}
public void testIteratorRemove() {
Map map = makeFullMap();
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
iterator.remove();
}
assertEquals(0, map.size());
map = makeFullMap();
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
iterator.next();
iterator.remove();
}
assertEquals(0, map.size());
}
public void testIteratorPredictableNext() {
TimeoutMap map = (TimeoutMap) makeFullMap();
map.setExpiryTime(50l);
assertFalse(map.isEmpty());
int count = 0;
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
if (count == 0) {
// NOTE: Only wait fist time, to avoid slooow tests
synchronized (this) {
try {
wait(60l);
}
catch (InterruptedException e) {
}
}
}
try {
Map.Entry entry = (Map.Entry) iterator.next();
assertNotNull(entry);
count++;
}
catch (NoSuchElementException nse) {
fail("Elements expire between Interator.hasNext() and Iterator.next()");
}
}
assertTrue("Elements expired too early, test did not run as expected.", count > 0);
//assertEquals("Elements did not expire as expected.", 1, count);
}
public void testIteratorPredictableRemove() {
TimeoutMap map = (TimeoutMap) makeFullMap();
map.setExpiryTime(50l);
assertFalse(map.isEmpty());
int count = 0;
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
if (count == 0) {
// NOTE: Only wait fist time, to avoid slooow tests
synchronized (this) {
try {
wait(60l);
}
catch (InterruptedException e) {
}
}
}
try {
iterator.remove();
count++;
}
catch (NoSuchElementException nse) {
fail("Elements expired between Interator.hasNext() and Iterator.remove()");
}
}
assertTrue("Elements expired too early, test did not run as expected.", count > 0);
//assertEquals("Elements did not expire as expected.", 1, count);
}
public void testIteratorPredictableNextRemove() {
TimeoutMap map = (TimeoutMap) makeFullMap();
map.setExpiryTime(50l);
assertFalse(map.isEmpty());
int count = 0;
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
if (count == 0) {
// NOTE: Only wait fist time, to avoid slooow tests
synchronized (this) {
try {
wait(60l);
}
catch (InterruptedException e) {
}
}
}
try {
Map.Entry entry = (Map.Entry) iterator.next();
assertNotNull(entry);
}
catch (NoSuchElementException nse) {
fail("Elements expired between Interator.hasNext() and Iterator.next()");
}
try {
iterator.remove();
count++;
}
catch (NoSuchElementException nse) {
fail("Elements expired between Interator.hasNext() and Iterator.remove()");
}
}
assertTrue("Elements expired too early, test did not run as expected.", count > 0);
//assertEquals("Elements did not expire as expected.", 1, count);
}
public void testIteratorPredictableRemovedEntry() {
TimeoutMap map = (TimeoutMap) makeEmptyMap();
map.setExpiryTime(1000l); // No elements should expire during this test
map.put("key-1", new Integer(1));
map.put("key-2", new Integer(2));
assertFalse(map.isEmpty());
Object removedKey = null;
Object otherKey = null;
Iterator iterator = map.entrySet().iterator();
assertTrue("Iterator was empty", iterator.hasNext());
try {
Map.Entry entry = (Map.Entry) iterator.next();
assertNotNull(entry);
removedKey = entry.getKey();
otherKey = "key-1".equals(removedKey) ? "key-2" : "key-1";
}
catch (NoSuchElementException nse) {
fail("Elements expired between Interator.hasNext() and Iterator.next()");
}
try {
iterator.remove();
}
catch (NoSuchElementException nse) {
fail("Elements expired between Interator.hasNext() and Iterator.remove()");
}
assertTrue("Wrong entry removed, keySet().iterator() is broken.", !map.containsKey(removedKey));
assertTrue("Wrong entry removed, keySet().iterator() is broken.", map.containsKey(otherKey));
}
}

View File

@@ -0,0 +1,52 @@
package com.twelvemonkeys.util;
import junit.framework.TestCase;
import java.util.Iterator;
/**
* TokenIteratorAbstractTestCase
* <p/>
* <!-- To change this template use Options | File Templates. -->
* <!-- Created by IntelliJ IDEA. -->
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/TokenIteratorAbstractTestCase.java#1 $
*/
public abstract class TokenIteratorAbstractTestCase extends TestCase {
protected abstract TokenIterator createTokenIterator(String pString);
protected abstract TokenIterator createTokenIterator(String pString, String pDelimiters);
public void testNullString() {
try {
createTokenIterator(null);
fail("Null string parameter not allowed");
}
catch (IllegalArgumentException e) {
// okay!
}
catch (Throwable t) {
fail(t.getMessage());
}
}
public void testNullDelimmiter() {
try {
createTokenIterator("", null);
fail("Null delimiter parameter not allowed");
}
catch (IllegalArgumentException e) {
// okay!
}
catch (Throwable t) {
fail(t.getMessage());
}
}
public void testEmptyString() {
Iterator iterator = createTokenIterator("");
assertFalse("Empty string has elements", iterator.hasNext());
}
}

View File

@@ -0,0 +1,18 @@
package com.twelvemonkeys.util.convert;
import junit.framework.TestCase;
/**
* ConverterTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/convert/ConverterTestCase.java#1 $
*/
public class ConverterTestCase extends TestCase {
public void testMe() {
// TODO: Implement tests
}
}

View File

@@ -0,0 +1,58 @@
package com.twelvemonkeys.util.convert;
import com.twelvemonkeys.lang.DateUtil;
import java.text.DateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* DateConverterTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/convert/DateConverterTestCase.java#2 $
*/
public class DateConverterTestCase extends PropertyConverterAbstractTestCase {
protected final static String FORMAT_STR_1 = "dd.MM.yyyy HH:mm:ss";
protected final static String FORMAT_STR_2 = "dd-MM-yyyy hh:mm:ss a";
protected PropertyConverter makePropertyConverter() {
return new DateConverter();
}
protected Conversion[] getTestConversions() {
// The default format doesn't contain milliseconds, so we have to round
long time = System.currentTimeMillis();
final Date now = new Date(DateUtil.roundToSecond(time));
DateFormat df = DateFormat.getDateTimeInstance();
return new Conversion[] {
new Conversion("01.11.2006 15:26:23", new GregorianCalendar(2006, 10, 1, 15, 26, 23).getTime(), FORMAT_STR_1),
// This doesn't really work.. But close enough
new Conversion(df.format(now), now),
// This format is really stupid
new Conversion("01-11-2006 03:27:44 pm", new GregorianCalendar(2006, 10, 1, 15, 27, 44).getTime(), FORMAT_STR_2, "01-11-2006 03:27:44 PM"),
// These seems to be an hour off (no timezone?)...
new Conversion("42", new Date(42l), "S"),
new Conversion(String.valueOf(time % 1000l), new Date(time % 1000l), "S"),
};
}
@Override
public void testConvert() {
TimeZone old = TimeZone.getDefault();
try {
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
super.testConvert();
}
finally {
TimeZone.setDefault(old);
}
}
}

View File

@@ -0,0 +1,71 @@
package com.twelvemonkeys.util.convert;
/**
* DefaultConverterTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/convert/DefaultConverterTestCase.java#1 $
*/
public class DefaultConverterTestCase extends PropertyConverterAbstractTestCase {
protected PropertyConverter makePropertyConverter() {
return new DefaultConverter();
}
protected Conversion[] getTestConversions() {
//noinspection BooleanConstructorCall
return new Conversion[] {
// Booleans
new Conversion("true", Boolean.TRUE),
new Conversion("TRUE", Boolean.TRUE, null, "true"),
new Conversion("false", Boolean.FALSE),
new Conversion("FALSE", new Boolean(false), null, "false"),
// Stupid but valid
new Conversion("fooBar", "fooBar"),
//new Conversion("fooBar", new StringBuilder("fooBar")), - StringBuilder does not impl equals()...
// Stupid test class that reveres chars
new Conversion("fooBar", new FooBar("fooBar")),
// TODO: More tests
};
}
// TODO: Test boolean -> Boolean conversion
public static class FooBar {
private final String mBar;
public FooBar(String pFoo) {
if (pFoo == null) {
throw new IllegalArgumentException("pFoo == null");
}
mBar = reverse(pFoo);
}
private String reverse(String pFoo) {
StringBuilder buffer = new StringBuilder(pFoo.length());
for (int i = pFoo.length() - 1; i >= 0; i--) {
buffer.append(pFoo.charAt(i));
}
return buffer.toString();
}
public String toString() {
return reverse(mBar);
}
public boolean equals(Object obj) {
return obj == this || (obj instanceof FooBar && ((FooBar) obj).mBar.equals(mBar));
}
public int hashCode() {
return 7 * mBar.hashCode();
}
}
}

View File

@@ -0,0 +1,42 @@
package com.twelvemonkeys.util.convert;
/**
* NumberConverterTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/convert/NumberConverterTestCase.java#2 $
*/
public class NumberConverterTestCase extends PropertyConverterAbstractTestCase {
protected PropertyConverter makePropertyConverter() {
return new NumberConverter();
}
protected Conversion[] getTestConversions() {
return new Conversion[] {
new Conversion("0", 0),
new Conversion("1", 1),
new Conversion("-1001", -1001),
new Conversion("1E3", 1000, null, "1000"),
new Conversion("-2", -2l),
new Conversion("2000651651854", 2000651651854l),
new Conversion("2E10", 20000000000l, null, "20000000000"),
new Conversion("3", 3.0f),
new Conversion("3.1", 3.1f),
new Conversion("3.2", 3.2f, "#.#"),
//new Conversion("3,3", new Float(3), "#", "3"), // Seems to need parseIntegerOnly
new Conversion("-3.4", -3.4f),
new Conversion("-3.5E10", -3.5e10f, null, "-35000000512"),
new Conversion("4", 4.0),
new Conversion("4.1", 4.1),
new Conversion("4.2", 4.2, "#.#"),
//new Conversion("4,3", new Double(4), "#", "4"), // Seems to need parseIntegerOnly
new Conversion("-4.4", -4.4),
new Conversion("-4.5E97", -4.5e97, null, "-45000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
};
}
}

View File

@@ -0,0 +1,99 @@
package com.twelvemonkeys.util.convert;
import com.twelvemonkeys.lang.ObjectAbstractTestCase;
/**
* PropertyConverterAbstractTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/convert/PropertyConverterAbstractTestCase.java#2 $
*/
public abstract class PropertyConverterAbstractTestCase extends ObjectAbstractTestCase {
protected Object makeObject() {
return makePropertyConverter();
}
protected abstract PropertyConverter makePropertyConverter();
protected abstract Conversion[] getTestConversions();
public void testConvert() {
PropertyConverter converter = makePropertyConverter();
Conversion[] tests = getTestConversions();
for (Conversion test : tests) {
Object obj;
try {
obj = converter.toObject(test.original(), test.type(), test.format());
assertEquals("'" + test.original() + "' convtered to incorrect type", test.type(), obj.getClass());
assertEquals("'" + test.original() + "' not converted", test.value(), obj);
String result = converter.toString(test.value(), test.format());
assertEquals("'" + test.converted() + "' does not macth", test.converted(), result);
obj = converter.toObject(result, test.type(), test.format());
assertEquals("'" + test.original() + "' convtered to incorrect type", test.type(), obj.getClass());
assertEquals("'" + test.original() + "' did not survive roundrip conversion", test.value(), obj);
}
catch (ConversionException e) {
e.printStackTrace();
fail("Converting '" + test.original() + "' to " + test.type() + " failed: " + e.getMessage());
}
}
}
public static final class Conversion {
private final String mStrVal;
private final Object mObjVal;
private final String mFormat;
private final String mConvertedStrVal;
public Conversion(String pStrVal, Object pObjVal) {
this(pStrVal, pObjVal, null, null);
}
public Conversion(String pStrVal, Object pObjVal, String pFormat) {
this(pStrVal, pObjVal, pFormat, null);
}
public Conversion(String pStrVal, Object pObjVal, String pFormat, String pConvertedStrVal) {
if (pStrVal == null) {
throw new IllegalArgumentException("pStrVal == null");
}
if (pObjVal == null) {
throw new IllegalArgumentException("pObjVal == null");
}
mStrVal = pStrVal;
mObjVal = pObjVal;
mFormat = pFormat;
mConvertedStrVal = pConvertedStrVal != null ? pConvertedStrVal : pStrVal;
}
public String original() {
return mStrVal;
}
public Object value() {
return mObjVal;
}
public Class type() {
return mObjVal.getClass();
}
public String format() {
return mFormat;
}
public String converted() {
return mConvertedStrVal;
}
}
}

View File

@@ -0,0 +1,19 @@
package com.twelvemonkeys.util.convert;
/**
* TimeConverterTestCase
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/convert/TimeConverterTestCase.java#1 $
*/
public class TimeConverterTestCase extends PropertyConverterAbstractTestCase {
protected PropertyConverter makePropertyConverter() {
return new TimeConverter();
}
protected Conversion[] getTestConversions() {
return new Conversion[0];// TODO: Implement
}
}

View File

@@ -0,0 +1,122 @@
package com.twelvemonkeys.util.regex;
import com.twelvemonkeys.util.TokenIterator;
import com.twelvemonkeys.util.TokenIteratorAbstractTestCase;
import java.util.Iterator;
/**
* StringTokenIteratorTestCase
* <p/>
* <!-- To change this template use Options | File Templates. -->
* <!-- Created by IntelliJ IDEA. -->
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/util/regex/RegExTokenIteratorTestCase.java#1 $
*/
public class RegExTokenIteratorTestCase extends TokenIteratorAbstractTestCase {
public void setUp() throws Exception {
super.setUp();
}
public void tearDown() throws Exception {
super.tearDown();
}
protected TokenIterator createTokenIterator(String pString) {
return new RegExTokenIterator(pString);
}
protected TokenIterator createTokenIterator(String pString, String pDelimiters) {
return new RegExTokenIterator(pString, pDelimiters);
}
public void testEmptyDelimiter() {
// TODO: What is it supposed to match?
/*
Iterator iterator = createTokenIterator("", ".*");
assertTrue("Empty string has no elements", iterator.hasNext());
iterator.next();
assertFalse("Empty string has more then one element", iterator.hasNext());
*/
}
public void testSingleToken() {
Iterator iterator = createTokenIterator("A");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testSingleTokenEmptyDelimiter() {
// TODO: What is it supposed to match?
/*
Iterator iterator = createTokenIterator("A", ".*");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
*/
}
public void testSingleTokenSingleDelimiter() {
Iterator iterator = createTokenIterator("A", "[^,]+");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testSingleSeparatorDefaultDelimiter() {
Iterator iterator = createTokenIterator("A B C D");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("D", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testSingleSeparator() {
Iterator iterator = createTokenIterator("A,B,C", "[^,]+");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("C", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testMultipleSeparatorDefaultDelimiter() {
Iterator iterator = createTokenIterator("A B C\nD\t\t \nE");
assertTrue("String has no elements", iterator.hasNext());
assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("D", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("E", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
public void testMultipleSeparator() {
Iterator iterator = createTokenIterator("A,B,;,C...D, ., ,E", "[^ ,.;:]+");
assertTrue("String has no elements", iterator.hasNext());
Object o = iterator.next();
assertEquals("A", o);
assertTrue("String has no elements", iterator.hasNext());
assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("D", iterator.next());
assertTrue("String has no elements", iterator.hasNext());
assertEquals("E", iterator.next());
assertFalse("String has more than one element", iterator.hasNext());
}
}