hop-2012/hop/TestSexpIO.java

83 lines
2.6 KiB
Java

/*
* Copyright (c) 2011 Tony Garnock-Jones. All rights reserved.
*/
package hop;
import junit.framework.TestCase;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*/
public class TestSexpIO extends TestCase {
public Object read(String s) throws IOException {
return new SexpReader(new ByteArrayInputStream(s.getBytes())).read();
}
public byte[] write(Object x) throws IOException {
ByteArrayOutputStream o = new ByteArrayOutputStream();
new SexpWriter(o).write(x);
return o.toByteArray();
}
public void assertBytesEqual(String expected, byte[] actual) {
assertBytesEqual(expected.getBytes(), actual);
}
public void assertBytesEqual(byte[] expected, byte[] actual) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], actual[i]);
}
}
public void testEndOfStream() throws IOException {
assertNull(read(""));
}
public void testEmptyList() throws IOException {
assertEquals(new ArrayList<Object>(), read("()"));
}
public void testSimpleString() throws IOException {
assertBytesEqual("hello", ((SexpBytes) read("5:hello")).getData());
}
public void testDisplayHint() throws IOException {
SexpDisplayHint v = (SexpDisplayHint) read("[1:h]1:b");
assertBytesEqual("b", v.getData());
assertBytesEqual("h", v.getHint());
assertBytesEqual("[1:h]1:b", write(v));
}
public void testSimpleList() throws IOException {
List<Object> l = (List<Object>) read("(1:a1:b1:c)");
assertEquals(3, l.size());
assertBytesEqual("a", ((SexpBytes) l.get(0)).getData());
assertBytesEqual("b", ((SexpBytes) l.get(1)).getData());
assertBytesEqual("c", ((SexpBytes) l.get(2)).getData());
}
public void testNestedList() throws IOException {
List<Object> l = (List<Object>) read("(1:a(1:b1:c)())");
assertEquals(3, l.size());
assertBytesEqual("a", ((SexpBytes) l.get(0)).getData());
List<Object> k = (List<Object>) l.get(1);
assertEquals(2, k.size());
assertBytesEqual("b", ((SexpBytes) k.get(0)).getData());
assertBytesEqual("c", ((SexpBytes) k.get(1)).getData());
assertEquals(new ArrayList<Object>(), l.get(2));
assertBytesEqual("(1:b1:c)", write(k));
assertBytesEqual("(1:a(1:b1:c)())", write(l));
}
public void testNullWrite() throws IOException {
assertBytesEqual("0:", write(null));
}
}