You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@harmony.apache.org by te...@apache.org on 2006/03/15 12:47:39 UTC
svn commit: r386058 [9/49] - in /incubator/harmony/enhanced/classlib/trunk:
make/ modules/archive/make/common/ modules/archive/src/test/java/tests/
modules/archive/src/test/java/tests/api/
modules/archive/src/test/java/tests/api/java/ modules/archive/s...
Added: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java?rev=386058&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java Wed Mar 15 03:46:17 2006
@@ -0,0 +1,685 @@
+/* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
+ *
+ * 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 tests.api.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.NotActiveException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.io.StreamCorruptedException;
+import java.util.Hashtable;
+import java.util.Vector;
+
+import tests.support.resource.Support_Resources;
+
+public class ObjectInputStreamTest extends junit.framework.TestCase implements
+ Serializable {
+
+ ObjectInputStream ois;
+
+ ObjectOutputStream oos;
+
+ ByteArrayOutputStream bao;
+
+ public class SerializableTestHelper implements Serializable {
+ public String aField1;
+
+ public String aField2;
+
+ SerializableTestHelper() {
+ aField1 = null;
+ aField2 = null;
+ }
+
+ SerializableTestHelper(String s, String t) {
+ aField1 = s;
+ aField2 = t;
+ }
+
+ private void readObject(ObjectInputStream ois) throws IOException {
+ // note aField2 is not read
+ try {
+ ObjectInputStream.GetField fields = ois.readFields();
+ aField1 = (String) fields.get("aField1", "Zap");
+ } catch (Exception e) {
+ System.out.println("Exception during test: " + e.toString());
+ }
+ }
+
+ private void writeObject(ObjectOutputStream oos) throws IOException {
+ // note aField2 is not written
+ ObjectOutputStream.PutField fields = oos.putFields();
+ fields.put("aField1", aField1);
+ oos.writeFields();
+ }
+
+ public String getText1() {
+ return aField1;
+ }
+
+ public void setText1(String s) {
+ aField1 = s;
+ }
+
+ public String getText2() {
+ return aField2;
+ }
+
+ public void setText2(String s) {
+ aField2 = s;
+ }
+ }
+
+ public static class A1 implements Serializable {
+ static final long serialVersionUID = 5942584913446079661L;
+
+ B1 b1 = new B1();
+
+ B1 b2 = b1;
+
+ Vector v = new Vector();
+ }
+
+ public static class B1 implements Serializable {
+ int i = 5;
+
+ Hashtable h = new Hashtable();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readObject()
+ */
+ public void test_readObjectMissingClasses() {
+ try {
+ // To create or update the resource, uncomment the following, and
+ // the B1 class definition and references above.
+ ObjectOutputStream out = new ObjectOutputStream(
+ new FileOutputStream("hyts_missingclass.ser"));
+ out.writeObject(new tests.api.java.io.ObjectInputStreamTest.A1());
+ out.close();
+
+ ObjectInputStream in = new ObjectInputStream(Support_Resources
+ .getStream("hyts_missingclass.ser"));
+ in.readObject();
+ in.close();
+ // the serialized data should load without any exceptions.
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail("unexpected: " + e);
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#ObjectInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() {
+ // Test for method java.io.ObjectInputStream(java.io.InputStream)
+ try {
+ oos.writeDouble(Double.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.close();
+ oos.close();
+ } catch (IOException e) {
+ fail("Exception contructing stream : " + e.getMessage());
+ }
+ boolean exception = false;
+ try {
+ ois = new ObjectInputStream(new ByteArrayInputStream(new byte[90]));
+ } catch (StreamCorruptedException e) {
+ // Correct
+ exception = true;
+ } catch (IOException e) {
+ fail("Exception contructing stream : " + e.getMessage());
+ }
+ assertTrue("Expected exception", exception);
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#ObjectInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream_subtest0() {
+ System.setSecurityManager(new SecurityManager());
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ObjectOutputStream obout = new ObjectOutputStream(out);
+ obout.write(0);
+ obout.close();
+ InputStream in = new ByteArrayInputStream(out.toByteArray());
+ // should not cause SecurityException
+ new ObjectInputStream(in);
+ class SubTest1 extends ObjectInputStream {
+ SubTest1(InputStream in) throws IOException {
+ super(in);
+ }
+ }
+ ;
+ in.reset();
+ // should not cause SecurityException
+ new SubTest1(in);
+ class SubTest2 extends ObjectInputStream {
+ SubTest2(InputStream in) throws IOException {
+ super(in);
+ }
+
+ public Object readUnshared() throws IOException,
+ ClassNotFoundException {
+ return null;
+ }
+ }
+ ;
+ in.reset();
+ try {
+ new SubTest2(in);
+ fail("should throw SecurityException 1");
+ } catch (SecurityException e) {
+ }
+ class SubTest3 extends ObjectInputStream {
+ SubTest3(InputStream in) throws IOException {
+ super(in);
+ }
+
+ public GetField readFields() throws IOException,
+ ClassNotFoundException, NotActiveException {
+ return null;
+ }
+ }
+ ;
+ in.reset();
+ try {
+ new SubTest3(in);
+ fail("should throw SecurityException 2");
+ } catch (SecurityException e) {
+ }
+ } catch (IOException e) {
+ fail("Unexpeced: " + e);
+ } finally {
+ System.setSecurityManager(null);
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#available()
+ */
+ public void test_available() {
+ // Test for method int java.io.ObjectInputStream.available()
+ try {
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect bytes", ois.available() == 10);
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#close()
+ */
+ public void test_close() {
+ // Test for method void java.io.ObjectInputStream.close()
+ try {
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.close();
+ } catch (IOException e) {
+ fail("Failed closing stream : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#defaultReadObject()
+ */
+ public void test_defaultReadObject() {
+ // Test for method void java.io.ObjectInputStream.defaultReadObject()
+ // SM. This method may as well be private, as if called directly it
+ // throws an exception.
+ try {
+ String s = "HelloWorld";
+ oos.writeObject(s);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.defaultReadObject();
+ fail("defaultReadObject should fail.");
+ ois.close();
+ } catch (NotActiveException e) {
+ // Desired behavior.
+ return;
+ } catch (Exception e) {
+ fail("Wrong exception during test : " + e.getMessage());
+ }
+ fail("defaultReadObject should have thrown exception");
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#read()
+ */
+ public void test_read() {
+ // Test for method int java.io.ObjectInputStream.read()
+ try {
+ oos.write('T');
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect byte value", ois.read() == 'T');
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() {
+ // Test for method int java.io.ObjectInputStream.read(byte [], int, int)
+ try {
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.read(buf, 0, 10);
+ ois.close();
+ assertTrue("Read incorrect bytes", new String(buf, 0, 10)
+ .equals("HelloWorld"));
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readBoolean()
+ */
+ public void test_readBoolean() {
+ // Test for method boolean java.io.ObjectInputStream.readBoolean()
+ try {
+ oos.writeBoolean(true);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect boolean value", ois.readBoolean());
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readByte()
+ */
+ public void test_readByte() {
+ // Test for method byte java.io.ObjectInputStream.readByte()
+ try {
+ oos.writeByte(127);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect byte value", ois.readByte() == 127);
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readChar()
+ */
+ public void test_readChar() {
+ // Test for method char java.io.ObjectInputStream.readChar()
+ try {
+ oos.writeChar('T');
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect char value", ois.readChar() == 'T');
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readDouble()
+ */
+ public void test_readDouble() {
+ // Test for method double java.io.ObjectInputStream.readDouble()
+ try {
+ oos.writeDouble(Double.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect double value",
+ ois.readDouble() == Double.MAX_VALUE);
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readFields()
+ */
+ public void test_readFields() {
+ // Test for method java.io.ObjectInputStream$GetField
+ // java.io.ObjectInputStream.readFields()
+
+ SerializableTestHelper sth;
+
+ /*
+ * "SerializableTestHelper" is an object created for these tests with
+ * two fields (Strings) and simple implementations of readObject and
+ * writeObject which simply read and write the first field but not the
+ * second
+ */
+
+ try {
+ oos.writeObject(new SerializableTestHelper("Gabba", "Jabba"));
+ oos.flush();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ sth = (SerializableTestHelper) (ois.readObject());
+ assertTrue("readFields / writeFields failed--first field not set",
+ sth.getText1().equals("Gabba"));
+ assertTrue(
+ "readFields / writeFields failed--second field should not have been set",
+ sth.getText2() == null);
+ } catch (Exception e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readFloat()
+ */
+ public void test_readFloat() {
+ // Test for method float java.io.ObjectInputStream.readFloat()
+ try {
+ oos.writeFloat(Float.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect float value",
+ ois.readFloat() == Float.MAX_VALUE);
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readFully(byte[])
+ */
+ public void test_readFully$B() {
+ // Test for method void java.io.ObjectInputStream.readFully(byte [])
+ try {
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.readFully(buf);
+ ois.close();
+ assertTrue("Read incorrect bytes", new String(buf, 0, 10)
+ .equals("HelloWorld"));
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readFully(byte[], int, int)
+ */
+ public void test_readFully$BII() {
+ // Test for method void java.io.ObjectInputStream.readFully(byte [],
+ // int, int)
+ try {
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.readFully(buf, 0, 10);
+ ois.close();
+ assertTrue("Read incorrect bytes", new String(buf, 0, 10)
+ .equals("HelloWorld"));
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readInt()
+ */
+ public void test_readInt() {
+ // Test for method int java.io.ObjectInputStream.readInt()
+ try {
+ oos.writeInt(Integer.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect int value",
+ ois.readInt() == Integer.MAX_VALUE);
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readLine()
+ */
+ public void test_readLine() {
+ // Test for method java.lang.String java.io.ObjectInputStream.readLine()
+ try {
+ oos.writeBytes("HelloWorld\nSecondLine");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.readLine();
+ assertTrue("Read incorrect string value", ois.readLine().equals(
+ "SecondLine"));
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readLong()
+ */
+ public void test_readLong() {
+ // Test for method long java.io.ObjectInputStream.readLong()
+ try {
+ oos.writeLong(Long.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect long value",
+ ois.readLong() == Long.MAX_VALUE);
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readObject()
+ */
+ public void test_readObject() {
+ // Test for method java.lang.Object
+ // java.io.ObjectInputStream.readObject()
+ try {
+ String s = "HelloWorld";
+ oos.writeObject(s);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect Object value", ((String) ois
+ .readObject()).equals(s));
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readObject()
+ */
+ public void test_readObjectCorrupt() {
+ byte[] bytes = { 00, 00, 00, 0x64, 0x43, 0x48, (byte) 0xFD, 0x71, 00,
+ 00, 0x0B, (byte) 0xB8, 0x4D, 0x65 };
+ ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
+ boolean exception = false;
+ try {
+ ObjectInputStream in = new ObjectInputStream(bin);
+ in.readObject();
+ fail("Unexpected read of corrupted stream");
+ } catch (StreamCorruptedException e) {
+ exception = true;
+ } catch (IOException e) {
+ fail("Unexpected: " + e);
+ } catch (ClassNotFoundException e) {
+ fail("Unexpected: " + e);
+ }
+ assertTrue("Expected StreamCorruptedException", exception);
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readShort()
+ */
+ public void test_readShort() {
+ // Test for method short java.io.ObjectInputStream.readShort()
+ try {
+ oos.writeShort(Short.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect short value",
+ ois.readShort() == Short.MAX_VALUE);
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readUnsignedByte()
+ */
+ public void test_readUnsignedByte() {
+ // Test for method int java.io.ObjectInputStream.readUnsignedByte()
+ try {
+ oos.writeByte(-1);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect unsignedByte value", ois
+ .readUnsignedByte() == 255);
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readUnsignedShort()
+ */
+ public void test_readUnsignedShort() {
+ // Test for method int java.io.ObjectInputStream.readUnsignedShort()
+ try {
+ oos.writeShort(-1);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect unsignedShort value", ois
+ .readUnsignedShort() == 65535);
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readUTF()
+ */
+ public void test_readUTF() {
+ // Test for method java.lang.String java.io.ObjectInputStream.readUTF()
+ try {
+ oos.writeUTF("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect utf value", ois.readUTF().equals(
+ "HelloWorld"));
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#skipBytes(int)
+ */
+ public void test_skipBytesI() {
+ // Test for method int java.io.ObjectInputStream.skipBytes(int)
+ try {
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.skipBytes(5);
+ ois.read(buf, 0, 5);
+ ois.close();
+ assertTrue("Skipped incorrect bytes", new String(buf, 0, 5)
+ .equals("World"));
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ try {
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ } catch (Exception e) {
+ fail("Setup failed : " + e.getMessage());
+ }
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ }
+}
Added: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectOutputStreamTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectOutputStreamTest.java?rev=386058&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectOutputStreamTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectOutputStreamTest.java Wed Mar 15 03:46:17 2006
@@ -0,0 +1,1156 @@
+/* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
+ *
+ * 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 tests.api.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.Externalizable;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.NotActiveException;
+import java.io.NotSerializableException;
+import java.io.ObjectInput;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
+import java.io.ObjectStreamField;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.util.Arrays;
+
+public class ObjectOutputStreamTest extends junit.framework.TestCase implements
+ Serializable {
+
+ java.io.File f;
+
+ public class SerializableTestHelper implements Serializable {
+ public String aField1;
+
+ public String aField2;
+
+ SerializableTestHelper() {
+ aField1 = null;
+ aField2 = null;
+ }
+
+ SerializableTestHelper(String s, String t) {
+ aField1 = s;
+ aField2 = t;
+ }
+
+ private void readObject(ObjectInputStream ois) throws IOException {
+ // note aField2 is not read
+ try {
+ ObjectInputStream.GetField fields = ois.readFields();
+ aField1 = (String) fields.get("aField1", "Zap");
+ } catch (Exception e) {
+ }
+ }
+
+ private void writeObject(ObjectOutputStream oos) throws IOException {
+ // note aField2 is not written
+ ObjectOutputStream.PutField fields = oos.putFields();
+ fields.put("aField1", aField1);
+ oos.writeFields();
+ }
+
+ public String getText1() {
+ return aField1;
+ }
+
+ public void setText1(String s) {
+ aField1 = s;
+ }
+
+ public String getText2() {
+ return aField2;
+ }
+
+ public void setText2(String s) {
+ aField2 = s;
+ }
+ }
+
+ private static class SerializationTest implements java.io.Serializable {
+ int anInt = INIT_INT_VALUE;
+
+ public SerializationTest() {
+ super();
+ }
+ }
+
+ private static class SerializationTestSubclass1 extends SerializationTest
+ implements Serializable {
+ String aString = INIT_STR_VALUE;
+
+ public SerializationTestSubclass1() {
+ super();
+ // Just to change default superclass init value
+ anInt = INIT_INT_VALUE / 2;
+ }
+ }
+
+ private static class SpecTestSuperClass implements Runnable, Serializable {
+ protected java.lang.String instVar;
+
+ public void run() {
+ }
+ }
+
+ private static class SpecTest extends SpecTestSuperClass implements
+ Cloneable, Serializable {
+ public java.lang.String instVar1;
+
+ public static java.lang.String staticVar1;
+
+ public static java.lang.String staticVar2;
+ {
+ instVar1 = "NonStaticInitialValue";
+ }
+ static {
+ staticVar1 = "StaticInitialValue";
+ staticVar1 = new String(staticVar1);
+ }
+
+ public Object method(Object objParam, Object objParam2) {
+ return new Object();
+ }
+
+ public boolean method(boolean bParam, Object objParam) {
+ return true;
+ }
+
+ public boolean method(boolean bParam, Object objParam, Object objParam2) {
+ return true;
+ }
+
+ }
+
+ private static class SpecTestSubclass extends SpecTest implements
+ Serializable {
+ public transient java.lang.String transientInstVar = "transientValue";
+ }
+
+ private static class ReadWriteObject implements java.io.Serializable {
+ public boolean calledWriteObject = false;
+
+ public boolean calledReadObject = false;
+
+ public ReadWriteObject() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ calledReadObject = true;
+ in.readObject();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException {
+ calledWriteObject = true;
+ out.writeObject(FOO);
+ }
+ }
+
+ private static class PublicReadWriteObject implements java.io.Serializable {
+ public boolean calledWriteObject = false;
+
+ public boolean calledReadObject = false;
+
+ public PublicReadWriteObject() {
+ super();
+ }
+
+ public void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ calledReadObject = true;
+ in.readObject();
+ }
+
+ public void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException {
+ calledWriteObject = true;
+ out.writeObject(FOO);
+ }
+ }
+
+ private static class FieldOrder implements Serializable {
+ String aaa1NonPrimitive = "aaa1";
+
+ int bbb1PrimitiveInt = 5;
+
+ boolean aaa2PrimitiveBoolean = true;
+
+ String bbb2NonPrimitive = "bbb2";
+ }
+
+ private static class JustReadObject implements java.io.Serializable {
+ public boolean calledReadObject = false;
+
+ public JustReadObject() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ calledReadObject = true;
+ in.defaultReadObject();
+ }
+ }
+
+ private static class JustWriteObject implements java.io.Serializable {
+ public boolean calledWriteObject = false;
+
+ public JustWriteObject() {
+ super();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ calledWriteObject = true;
+ out.defaultWriteObject();
+ }
+ }
+
+ private static class ClassBasedReplacementWhenDumping implements
+ java.io.Serializable {
+ public boolean calledReplacement = false;
+
+ public ClassBasedReplacementWhenDumping() {
+ super();
+ }
+
+ private Object writeReplace() {
+ calledReplacement = true;
+ return FOO; // Replacement is a String
+ }
+ }
+
+ private static class MultipleClassBasedReplacementWhenDumping implements
+ java.io.Serializable {
+ private static class C1 implements java.io.Serializable {
+ private Object writeReplace() {
+ return new C2();
+ }
+ }
+
+ private static class C2 implements java.io.Serializable {
+ private Object writeReplace() {
+ return new C3();
+ }
+ }
+
+ private static class C3 implements java.io.Serializable {
+ private Object writeReplace() {
+ return FOO;
+ }
+ }
+
+ public MultipleClassBasedReplacementWhenDumping() {
+ super();
+ }
+
+ private Object writeReplace() {
+ return new C1();
+ }
+ }
+
+ private static class ClassBasedReplacementWhenLoading implements
+ java.io.Serializable {
+ public ClassBasedReplacementWhenLoading() {
+ super();
+ }
+
+ private Object readResolve() {
+ return FOO; // Replacement is a String
+ }
+ }
+
+ private static class ClassBasedReplacementWhenLoadingViolatesFieldType
+ implements java.io.Serializable {
+ public ClassBasedReplacementWhenLoading classBasedReplacementWhenLoading = new ClassBasedReplacementWhenLoading();
+
+ public ClassBasedReplacementWhenLoadingViolatesFieldType() {
+ super();
+ }
+ }
+
+ private static class MyExceptionWhenDumping implements java.io.Serializable {
+ private static class MyException extends java.io.IOException {
+ };
+
+ public boolean anInstanceVar = false;
+
+ public MyExceptionWhenDumping() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ throw new MyException();
+ }
+ }
+
+ private static class NonSerializableExceptionWhenDumping implements
+ java.io.Serializable {
+ public Object anInstanceVar = new Object();
+
+ public NonSerializableExceptionWhenDumping() {
+ super();
+ }
+ }
+
+ private static class MyUnserializableExceptionWhenDumping implements
+ java.io.Serializable {
+ private static class MyException extends java.io.IOException {
+ private Object notSerializable = new Object();
+ };
+
+ public boolean anInstanceVar = false;
+
+ public MyUnserializableExceptionWhenDumping() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ throw new MyException();
+ }
+ }
+
+ private static class WithUnmatchingSerialPersistentFields implements
+ java.io.Serializable {
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ "value", String.class) };
+
+ public int anInstanceVar = 5;
+
+ public WithUnmatchingSerialPersistentFields() {
+ super();
+ }
+ }
+
+ private static class WithMatchingSerialPersistentFields implements
+ java.io.Serializable {
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ "anInstanceVar", String.class) };
+
+ public String anInstanceVar = FOO + FOO;
+
+ public WithMatchingSerialPersistentFields() {
+ super();
+ }
+ }
+
+ private static class SerialPersistentFields implements java.io.Serializable {
+ private static final String SIMULATED_FIELD_NAME = "text";
+
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ SIMULATED_FIELD_NAME, String.class) };
+
+ public int anInstanceVar = 5;
+
+ public SerialPersistentFields() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ ObjectInputStream.GetField fields = in.readFields();
+ anInstanceVar = Integer.parseInt((String) fields.get(
+ SIMULATED_FIELD_NAME, "-5"));
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ ObjectOutputStream.PutField fields = out.putFields();
+ fields.put(SIMULATED_FIELD_NAME, Integer.toString(anInstanceVar));
+ out.writeFields();
+ }
+ }
+
+ private static class WriteFieldsWithoutFetchingPutFields implements
+ java.io.Serializable {
+ private static final String SIMULATED_FIELD_NAME = "text";
+
+ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
+ SIMULATED_FIELD_NAME, String.class) };
+
+ public int anInstanceVar = 5;
+
+ public WriteFieldsWithoutFetchingPutFields() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.readFields();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ out.writeFields();
+ }
+ }
+
+ private static class SerialPersistentFieldsWithoutField implements
+ java.io.Serializable {
+ public int anInstanceVar = 5;
+
+ public SerialPersistentFieldsWithoutField() {
+ super();
+ }
+
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException, ClassNotFoundException {
+ in.readFields();
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException, ClassNotFoundException {
+ out.putFields();
+ out.writeFields();
+ }
+ }
+
+ private static class NotSerializable {
+ private int foo;
+
+ public NotSerializable() {
+ }
+
+ protected Object writeReplace() throws ObjectStreamException {
+ return new Integer(42);
+ }
+ }
+
+ private static class ExternalizableWithReplace implements Externalizable {
+ private int foo;
+
+ public ExternalizableWithReplace() {
+ }
+
+ protected Object writeReplace() throws ObjectStreamException {
+ return new Integer(42);
+ }
+
+ public void writeExternal(ObjectOutput out) {
+ }
+
+ public void readExternal(ObjectInput in) {
+ }
+ }
+
+ protected static final String MODE_XLOAD = "xload";
+
+ protected static final String MODE_XDUMP = "xdump";
+
+ static final String FOO = "foo";
+
+ static final String MSG_WITE_FAILED = "Failed to write: ";
+
+ private static final boolean DEBUG = false;
+
+ protected static boolean xload = false;
+
+ protected static boolean xdump = false;
+
+ protected static String xFileName = null;
+
+ protected ObjectInputStream ois;
+
+ protected ObjectOutputStream oos;
+
+ protected ByteArrayOutputStream bao;
+
+ static final int INIT_INT_VALUE = 7;
+
+ static final String INIT_STR_VALUE = "a string that is blortz";
+
+ /**
+ * @tests java.io.ObjectOutputStream#ObjectOutputStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() {
+ // Test for method java.io.ObjectOutputStream(java.io.OutputStream)
+
+ try {
+ oos.close();
+ oos = new ObjectOutputStream(new ByteArrayOutputStream());
+ oos.close();
+ } catch (Exception e) {
+ fail("Failed to create ObjectOutputStream : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#ObjectOutputStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream_subtest0() {
+ System.setSecurityManager(new SecurityManager());
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ // should not cause SecurityException
+ new ObjectOutputStream(out);
+ // should not cause SecurityException
+ class SubTest1 extends ObjectOutputStream {
+ SubTest1(OutputStream out) throws IOException {
+ super(out);
+ }
+ }
+ ;
+ // should not cause SecurityException
+ new SubTest1(out);
+ class SubTest2 extends ObjectOutputStream {
+ SubTest2(OutputStream out) throws IOException {
+ super(out);
+ }
+
+ public void writeUnshared(Object obj) throws IOException {
+ }
+ }
+ ;
+ try {
+ new SubTest2(out);
+ fail("should throw SecurityException 1");
+ } catch (SecurityException e) {
+ }
+ class SubTest3 extends ObjectOutputStream {
+ SubTest3(OutputStream out) throws IOException {
+ super(out);
+ }
+
+ public PutField putFields() throws IOException {
+ return null;
+ }
+ }
+ ;
+ try {
+ new SubTest3(out);
+ fail("should throw SecurityException 2");
+ } catch (SecurityException e) {
+ }
+ } catch (IOException e) {
+ fail("Unexpeced: " + e);
+ } finally {
+ System.setSecurityManager(null);
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#close()
+ */
+ public void test_close() {
+ // Test for method void java.io.ObjectOutputStream.close()
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#defaultWriteObject()
+ */
+ public void test_defaultWriteObject() {
+ // Test for method void java.io.ObjectOutputStream.defaultWriteObject()
+
+ try {
+ oos.defaultWriteObject();
+ } catch (NotActiveException e) {
+ // Correct
+ return;
+ } catch (IOException e) {
+ }
+ fail(
+ "Failed to throw NotActiveException when invoked outside readObject");
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#flush()
+ */
+ public void test_flush() {
+ // Test for method void java.io.ObjectOutputStream.flush()
+ try {
+ int size = bao.size();
+ oos.writeByte(127);
+ assertTrue("Data flushed already", bao.size() == size);
+ oos.flush();
+ assertTrue("Failed to flush data", bao.size() > size);
+ // we don't know how many bytes are actually written for 1
+ // byte, so we test > <before>
+ oos.close();
+ oos = null;
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#putFields()
+ */
+ public void test_putFields() {
+ // Test for method java.io.ObjectOutputStream$PutField
+ // java.io.ObjectOutputStream.putFields()
+
+ SerializableTestHelper sth;
+
+ /*
+ * "SerializableTestHelper" is an object created for these tests with
+ * two fields (Strings) and simple implementations of readObject and
+ * writeObject which simply read and write the first field but not the
+ * second
+ */
+
+ try {
+ oos.writeObject(new SerializableTestHelper("Gabba", "Jabba"));
+ oos.flush();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ sth = (SerializableTestHelper) (ois.readObject());
+ assertTrue("readFields / writeFields failed--first field not set",
+ sth.getText1().equals("Gabba"));
+ assertTrue(
+ "readFields / writeFields failed--second field should not have been set",
+ sth.getText2() == null);
+ } catch (Exception e) {
+ fail("Exception thrown : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#reset()
+ */
+ public void test_reset() {
+ // Test for method void java.io.ObjectOutputStream.reset()
+ try {
+ String o = "HelloWorld";
+ oos.writeObject(o);
+ oos.writeObject(o);
+ oos.reset();
+ oos.writeObject(o);
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ private static class ExternalTest implements Externalizable {
+ public String value;
+
+ public ExternalTest() {
+ }
+
+ public void setValue(String val) {
+ value = val;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void writeExternal(ObjectOutput output) {
+ try {
+ output.writeUTF(value);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void readExternal(ObjectInput input) {
+ try {
+ value = input.readUTF();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#useProtocolVersion(int)
+ */
+ public void test_useProtocolVersionI() {
+ // Test for method void
+ // java.io.ObjectOutputStream.useProtocolVersion(int)
+ try {
+ oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
+ ExternalTest t1 = new ExternalTest();
+ t1.setValue("hello1");
+ oos.writeObject(t1);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ExternalTest t2 = (ExternalTest) ois.readObject();
+ ois.close();
+ assertTrue(
+ "Cannot read/write PROTOCAL_VERSION_1 Externalizable objects: "
+ + t2.getValue(), t1.getValue()
+ .equals(t2.getValue()));
+ } catch (IOException e) {
+ fail("Unexpected: " + e);
+ } catch (ClassNotFoundException e) {
+ fail("Unexpected: " + e);
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#write(byte[])
+ */
+ public void test_write$B() {
+ // Test for method void java.io.ObjectOutputStream.write(byte [])
+ try {
+ byte[] buf = new byte[10];
+ oos.write("HelloWorld".getBytes());
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.read(buf, 0, 10);
+ ois.close();
+ assertTrue("Read incorrect bytes", new String(buf, 0, 10)
+ .equals("HelloWorld"));
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() {
+ // Test for method void java.io.ObjectOutputStream.write(byte [], int,
+ // int)
+ try {
+ byte[] buf = new byte[10];
+ oos.write("HelloWorld".getBytes(), 0, 10);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.read(buf, 0, 10);
+ ois.close();
+ assertTrue("Read incorrect bytes", new String(buf, 0, 10)
+ .equals("HelloWorld"));
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#write(int)
+ */
+ public void test_writeI() {
+ // Test for method void java.io.ObjectOutputStream.write(int)
+ try {
+ oos.write('T');
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Read incorrect byte", ois.read() == 'T');
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeBoolean(boolean)
+ */
+ public void test_writeBooleanZ() {
+ // Test for method void java.io.ObjectOutputStream.writeBoolean(boolean)
+ try {
+ oos.writeBoolean(true);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Wrote incorrect byte value", ois.readBoolean());
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeByte(int)
+ */
+ public void test_writeByteI() {
+ // Test for method void java.io.ObjectOutputStream.writeByte(int)
+ try {
+ oos.writeByte(127);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Wrote incorrect byte value", ois.readByte() == 127);
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeBytes(java.lang.String)
+ */
+ public void test_writeBytesLjava_lang_String() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeBytes(java.lang.String)
+ try {
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ ois.readFully(buf);
+ ois.close();
+ assertTrue("Wrote incorrect bytes value", new String(buf, 0, 10)
+ .equals("HelloWorld"));
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeChar(int)
+ */
+ public void test_writeCharI() {
+ // Test for method void java.io.ObjectOutputStream.writeChar(int)
+ try {
+ oos.writeChar('T');
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Wrote incorrect char value", ois.readChar() == 'T');
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeChars(java.lang.String)
+ */
+ public void test_writeCharsLjava_lang_String() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeChars(java.lang.String)
+ try {
+ int avail = 0;
+ char[] buf = new char[10];
+ oos.writeChars("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ // Number of prim data bytes in stream / 2 to give char index
+ avail = ois.available() / 2;
+ for (int i = 0; i < avail; ++i)
+ buf[i] = ois.readChar();
+ ois.close();
+ assertTrue("Wrote incorrect chars", new String(buf, 0, 10)
+ .equals("HelloWorld"));
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeDouble(double)
+ */
+ public void test_writeDoubleD() {
+ // Test for method void java.io.ObjectOutputStream.writeDouble(double)
+ try {
+ oos.writeDouble(Double.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Wrote incorrect double value",
+ ois.readDouble() == Double.MAX_VALUE);
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeFields()
+ */
+ public void test_writeFields() {
+ // Test for method void java.io.ObjectOutputStream.writeFields()
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeFloat(float)
+ */
+ public void test_writeFloatF() {
+ // Test for method void java.io.ObjectOutputStream.writeFloat(float)
+ try {
+ oos.writeFloat(Float.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Wrote incorrect double value",
+ ois.readFloat() == Float.MAX_VALUE);
+ ois.close();
+ ois = null;
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeInt(int)
+ */
+ public void test_writeIntI() {
+ // Test for method void java.io.ObjectOutputStream.writeInt(int)
+ try {
+ oos.writeInt(Integer.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Wrote incorrect double value",
+ ois.readInt() == Integer.MAX_VALUE);
+ ois.close();
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeLong(long)
+ */
+ public void test_writeLongJ() {
+ // Test for method void java.io.ObjectOutputStream.writeLong(long)
+ try {
+ oos.writeLong(Long.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Wrote incorrect double value",
+ ois.readLong() == Long.MAX_VALUE);
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
+ */
+ public void test_writeObjectLjava_lang_Object() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeObject(java.lang.Object)
+
+ Object objToSave = null;
+ Object objLoaded;
+
+ try {
+ SerialPersistentFieldsWithoutField spf = new SerialPersistentFieldsWithoutField();
+ final int CONST = -500;
+ spf.anInstanceVar = CONST;
+ objToSave = spf;
+ if (DEBUG)
+ System.out.println("Obj = " + objToSave);
+ objLoaded = dumpAndReload(objToSave);
+ assertTrue(
+ "serialPersistentFields do not work properly in this implementation",
+ ((SerialPersistentFieldsWithoutField) objLoaded).anInstanceVar != CONST);
+
+ } catch (IOException e) {
+ fail("Exception serializing " + objToSave + "\t->"
+ + e.getMessage());
+ } catch (ClassNotFoundException e) {
+ fail("Unable to read Object type : " + e.getMessage());
+ } catch (Error err) {
+ System.out.println("Error when obj = " + objToSave);
+ err.printStackTrace();
+ throw err;
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
+ */
+ public void test_writeObject_NotSerializable() {
+ ObjectOutput out = null;
+ try {
+ out = new ObjectOutputStream(new ByteArrayOutputStream());
+ out.writeObject(new NotSerializable());
+ fail("Expected NotSerializableException");
+ } catch (NotSerializableException e) {
+ } catch (IOException e) {
+ fail("Unexpected1: " + e);
+ }
+ try {
+ out.writeObject(new ExternalizableWithReplace());
+ } catch (IOException e) {
+ fail("Unexpected2: " + e);
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeShort(int)
+ */
+ public void test_writeShortI() {
+ // Test for method void java.io.ObjectOutputStream.writeShort(int)
+ try {
+ oos.writeShort(127);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Wrote incorrect short value", ois.readShort() == 127);
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeUTF(java.lang.String)
+ */
+ public void test_writeUTFLjava_lang_String() {
+ // Test for method void
+ // java.io.ObjectOutputStream.writeUTF(java.lang.String)
+ try {
+ oos.writeUTF("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ assertTrue("Wrote incorrect UTF value", ois.readUTF().equals(
+ "HelloWorld"));
+ } catch (IOException e) {
+ fail("Exception serializing data : " + e.getMessage());
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ try {
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ } catch (Exception e) {
+ fail("Setup failed : " + e.getMessage());
+ }
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ if (oos != null)
+ try {
+ oos.close();
+ } catch (Exception e) {
+ }
+ if (f != null && f.exists())
+ if (!f.delete()) {
+ fail("Error cleaning up files during teardown");
+ }
+ }
+
+ protected Object reload() throws IOException, ClassNotFoundException {
+
+ // Choose the load stream
+ if (xload || xdump) {
+ // Load from pre-existing file
+ ois = new ObjectInputStream(new FileInputStream(xFileName + "-"
+ + getName() + ".ser"));
+ } else {
+ // Just load from memory, we dumped to memory
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+ }
+
+ try {
+ return ois.readObject();
+ } finally {
+ ois.close();
+ }
+ }
+
+ protected void dump(Object o) throws IOException, ClassNotFoundException {
+
+ // Choose the dump stream
+ if (xdump) {
+ oos = new ObjectOutputStream(new FileOutputStream(
+ f = new java.io.File(xFileName + "-" + getName() + ".ser")));
+ } else {
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ }
+
+ // Dump the object
+ try {
+ oos.writeObject(o);
+ } finally {
+ oos.close();
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectOutputStream#writeInt(int)
+ * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
+ * @tests java.io.ObjectOutputStream#writeUTF(java.lang.String)
+ */
+
+ public void testMixPrimitivesAndObjects() {
+ int i = 7;
+ String s1 = "string 1";
+ String s2 = "string 2";
+ byte[] bytes = { 1, 2, 3 };
+ try {
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ oos.writeInt(i);
+ oos.writeObject(s1);
+ oos.writeUTF(s2);
+ oos.writeObject(bytes);
+ oos.close();
+
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao
+ .toByteArray()));
+
+ int j = ois.readInt();
+ assertTrue("Wrong int :" + j, i == j);
+
+ String l1 = (String) ois.readObject();
+ assertTrue("Wrong obj String :" + l1, s1.equals(l1));
+
+ String l2 = (String) ois.readUTF();
+ assertTrue("Wrong UTF String :" + l2, s2.equals(l2));
+
+ byte[] bytes2 = (byte[]) ois.readObject();
+ assertTrue("Wrong byte[]", Arrays.equals(bytes, bytes2));
+ } catch (IOException e) {
+ fail("Unexpected IOException: " + e.toString());
+ } catch (ClassNotFoundException e) {
+ fail("Unexpected ClassNotFoundException: " + e.toString());
+ } finally {
+ try {
+ if (oos != null)
+ oos.close();
+ if (ois != null)
+ ois.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ protected Object dumpAndReload(Object o) throws IOException,
+ ClassNotFoundException {
+ dump(o);
+ return reload();
+ }
+}
Added: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectStreamClassTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectStreamClassTest.java?rev=386058&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectStreamClassTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectStreamClassTest.java Wed Mar 15 03:46:17 2006
@@ -0,0 +1,137 @@
+/* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
+ *
+ * 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 tests.api.java.io;
+
+import java.io.ObjectStreamClass;
+import java.io.ObjectStreamField;
+import java.io.Serializable;
+
+public class ObjectStreamClassTest extends junit.framework.TestCase {
+
+ static class DummyClass implements Serializable {
+ private static final long serialVersionUID = 999999999999999L;
+
+ long bam = 999L;
+
+ int ham = 9999;
+
+ public static long getUID() {
+ return serialVersionUID;
+ }
+ }
+
+ /**
+ * @tests java.io.ObjectStreamClass#forClass()
+ */
+ public void test_forClass() {
+ // Test for method java.lang.Class java.io.ObjectStreamClass.forClass()
+ // Need to test during serialization to be sure an instance is
+ // returned
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ assertTrue("forClass returned an object: " + osc.forClass(), osc
+ .forClass().equals(DummyClass.class));
+ }
+
+ /**
+ * @tests java.io.ObjectStreamClass#getField(java.lang.String)
+ */
+ public void test_getFieldLjava_lang_String() {
+ // Test for method java.io.ObjectStreamField
+ // java.io.ObjectStreamClass.getField(java.lang.String)
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ assertTrue("getField did not return correct field", osc.getField("bam")
+ .getTypeCode() == 'J');
+ assertTrue("getField did not null for non-existent field", osc
+ .getField("wham") == null);
+ }
+
+ /**
+ * @tests java.io.ObjectStreamClass#getFields()
+ */
+ public void test_getFields() {
+ // Test for method java.io.ObjectStreamField []
+ // java.io.ObjectStreamClass.getFields()
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ ObjectStreamField[] osfArray = osc.getFields();
+ assertTrue(
+ "Array of fields should be of length 2 but is instead of length: "
+ + osfArray.length, osfArray.length == 2);
+ }
+
+ /**
+ * @tests java.io.ObjectStreamClass#getName()
+ */
+ public void test_getName() {
+ // Test for method java.lang.String java.io.ObjectStreamClass.getName()
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ assertTrue("getName returned incorrect name: " + osc.getName(), osc
+ .getName().equals(
+ "tests.api.java.io.ObjectStreamClassTest$DummyClass"));
+ }
+
+ /**
+ * @tests java.io.ObjectStreamClass#getSerialVersionUID()
+ */
+ public void test_getSerialVersionUID() {
+ // Test for method long java.io.ObjectStreamClass.getSerialVersionUID()
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ assertTrue("getSerialversionUID returned incorrect uid: "
+ + osc.getSerialVersionUID() + " instead of "
+ + DummyClass.getUID(), osc.getSerialVersionUID() == DummyClass
+ .getUID());
+ }
+
+ /**
+ * @tests java.io.ObjectStreamClass#lookup(java.lang.Class)
+ */
+ public void test_lookupLjava_lang_Class() {
+ // Test for method java.io.ObjectStreamClass
+ // java.io.ObjectStreamClass.lookup(java.lang.Class)
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ assertTrue("lookup returned wrong class: " + osc.getName(), osc
+ .getName().equals(
+ "tests.api.java.io.ObjectStreamClassTest$DummyClass"));
+ }
+
+ /**
+ * @tests java.io.ObjectStreamClass#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.io.ObjectStreamClass.toString()
+ ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
+ String oscString = osc.toString();
+ // The previous test was more specific than the spec so it was replaced
+ // with the test below
+ assertTrue("toString returned incorrect string: " + osc.toString(),
+ oscString.indexOf("serialVersionUID") >= 0
+ && oscString.indexOf("999999999999999L") >= 0);
+ ;
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ }
+}
Added: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectStreamFieldTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectStreamFieldTest.java?rev=386058&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectStreamFieldTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/ObjectStreamFieldTest.java Wed Mar 15 03:46:17 2006
@@ -0,0 +1,157 @@
+/* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
+ *
+ * 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 tests.api.java.io;
+
+import java.io.ObjectStreamClass;
+import java.io.ObjectStreamField;
+import java.io.Serializable;
+
+public class ObjectStreamFieldTest extends junit.framework.TestCase {
+
+ static class DummyClass implements Serializable {
+ private static final long serialVersionUID = 999999999999998L;
+
+ long bam = 999L;
+
+ int ham = 9999;
+
+ int sam = 8888;
+
+ Object hola = new Object();
+
+ public static long getUID() {
+ return serialVersionUID;
+ }
+ }
+
+ ObjectStreamClass osc;
+
+ ObjectStreamField hamField;
+
+ ObjectStreamField samField;
+
+ ObjectStreamField bamField;
+
+ ObjectStreamField holaField;
+
+ /**
+ * @tests java.io.ObjectStreamField#ObjectStreamField(java.lang.String,
+ * java.lang.Class)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_Class() {
+ // Test for method java.io.ObjectStreamField(java.lang.String,
+ // java.lang.Class)
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * @tests java.io.ObjectStreamField#compareTo(java.lang.Object)
+ */
+ public void test_compareToLjava_lang_Object() {
+ // Test for method int
+ // java.io.ObjectStreamField.compareTo(java.lang.Object)
+ assertTrue("Object compared to int did not return > 0", holaField
+ .compareTo(hamField) > 0);
+ assertTrue("Int compared to itself did not return 0", hamField
+ .compareTo(hamField) == 0);
+ assertTrue("(Int)ham compared to (Int)sam did not return < 0", hamField
+ .compareTo(samField) < 0);
+ }
+
+ /**
+ * @tests java.io.ObjectStreamField#getName()
+ */
+ public void test_getName() {
+ // Test for method java.lang.String java.io.ObjectStreamField.getName()
+ assertTrue("Field did not return correct name", holaField.getName()
+ .equals("hola"));
+ }
+
+ /**
+ * @tests java.io.ObjectStreamField#getOffset()
+ */
+ public void test_getOffset() {
+ // Test for method int java.io.ObjectStreamField.getOffset()
+ ObjectStreamField[] osfArray;
+ osfArray = osc.getFields();
+ assertTrue("getOffset did not return reasonable values", osfArray[0]
+ .getOffset() != osfArray[1].getOffset());
+ assertTrue("getOffset for osfArray[0].getOffset() did not return 0",
+ osfArray[0].getOffset() == 0);
+ assertTrue("osfArray[1].getOffset() did not return 8", osfArray[1]
+ .getOffset() == 8);
+ assertTrue("osfArray[2].getOffset() did not return 12", osfArray[2]
+ .getOffset() == 12);
+ }
+
+ /**
+ * @tests java.io.ObjectStreamField#getType()
+ */
+ public void test_getType() {
+ // Test for method java.lang.Class java.io.ObjectStreamField.getType()
+ assertTrue("getType on an Object field did not answer Object",
+ holaField.getType().equals(Object.class));
+ }
+
+ /**
+ * @tests java.io.ObjectStreamField#getTypeCode()
+ */
+ public void test_getTypeCode() {
+ // Test for method char java.io.ObjectStreamField.getTypeCode()
+ assertTrue("getTypeCode on an Object field did not answer 'L'",
+ holaField.getTypeCode() == 'L');
+ assertTrue("getTypeCode on a long field did not answer 'J'", bamField
+ .getTypeCode() == 'J');
+ }
+
+ /**
+ * @tests java.io.ObjectStreamField#getTypeString()
+ */
+ public void test_getTypeString() {
+ // Test for method java.lang.String
+ // java.io.ObjectStreamField.getTypeString()
+ assertTrue("getTypeString returned: " + holaField.getTypeString(),
+ holaField.getTypeString().indexOf("Object") >= 0);
+ }
+
+ /**
+ * @tests java.io.ObjectStreamField#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.io.ObjectStreamField.toString()
+ assertTrue("toString on a long returned: " + bamField.toString(),
+ bamField.toString().indexOf("bam") >= 0);
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void setUp() {
+ osc = ObjectStreamClass.lookup(DummyClass.class);
+ bamField = osc.getField("bam");
+ samField = osc.getField("sam");
+ hamField = osc.getField("ham");
+ holaField = osc.getField("hola");
+ }
+
+ /**
+ * Tears down the fixture, for example, close a network connection. This
+ * method is called after a test is executed.
+ */
+ protected void tearDown() {
+ }
+}
Added: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/OpenRandomFileTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/OpenRandomFileTest.java?rev=386058&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/OpenRandomFileTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/OpenRandomFileTest.java Wed Mar 15 03:46:17 2006
@@ -0,0 +1,68 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ *
+ * 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 tests.api.java.io;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+
+import junit.framework.TestCase;
+
+/**
+ * TODO Type description
+ */
+public class OpenRandomFileTest extends TestCase {
+
+ public static void main(String[] args) {
+ new OpenRandomFileTest().testOpenEmptyFile();
+ }
+
+ public OpenRandomFileTest() {
+ super();
+ }
+
+ public void testOpenNonEmptyFile() {
+ try {
+ File file = File.createTempFile("test", "tmp");
+ assertTrue(file.exists());
+ file.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(file);
+ fos.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
+ fos.close();
+
+ String fileName = file.getCanonicalPath();
+ RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
+ raf.close();
+ } catch (IOException ex) {
+ fail(ex.getLocalizedMessage());
+ }
+ }
+
+ public void testOpenEmptyFile() {
+ try {
+ File file = File.createTempFile("test", "tmp");
+ assertTrue(file.exists());
+ file.deleteOnExit();
+
+ String fileName = file.getCanonicalPath();
+ RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
+ raf.close();
+ } catch (IOException ex) {
+ fail(ex.getLocalizedMessage());
+ }
+ }
+}
Added: incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/OutputStreamWriterTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/OutputStreamWriterTest.java?rev=386058&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/OutputStreamWriterTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/luni/src/test/java/tests/api/java/io/OutputStreamWriterTest.java Wed Mar 15 03:46:17 2006
@@ -0,0 +1,629 @@
+/* Copyright 2005 The Apache Software Foundation or its licensors, as applicable
+ *
+ * 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 tests.api.java.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+
+import junit.framework.TestCase;
+
+/**
+ *
+ */
+public class OutputStreamWriterTest extends TestCase {
+
+ private static final int UPPER = 0xd800;
+
+ private static final int BUFFER_SIZE = 10000;
+
+ private ByteArrayOutputStream out;
+
+ private OutputStreamWriter writer;
+
+ static private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese";
+
+ static private final String[] MINIMAL_CHARSETS = new String[] { "US-ASCII",
+ "ISO-8859-1", "UTF-16BE", "UTF-16LE", "UTF-16", "UTF-8" };
+
+ OutputStreamWriter osw;
+
+ InputStreamReader isr;
+
+ private ByteArrayOutputStream fos;
+
+ String testString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
+
+ /*
+ * @see TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ out = new ByteArrayOutputStream();
+ writer = new OutputStreamWriter(out, "utf-8");
+
+ fos = new ByteArrayOutputStream();
+ osw = new OutputStreamWriter(fos);
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ try {
+ writer.close();
+
+ if (isr != null)
+ isr.close();
+ osw.close();
+ } catch (Exception e) {
+ }
+
+ super.tearDown();
+ }
+
+ public void testClose() throws Exception {
+ writer.flush();
+ writer.close();
+ try {
+ writer.flush();
+ fail();
+ } catch (IOException e) {
+ }
+ }
+
+ public void testFlush() throws Exception {
+ writer.write(source);
+ writer.flush();
+ String result = out.toString("utf-8");
+ assertEquals(source, result);
+ }
+
+ /*
+ * Class under test for void write(char[], int, int)
+ */
+ public void testWritecharArrayintint() throws IOException {
+ char[] chars = source.toCharArray();
+ try {
+ writer.write((char[]) null, 1, 1);
+ fail();
+ } catch (NullPointerException e) {
+ }
+ try {
+ writer.write(new char[0], 0, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+ try {
+ writer.write(chars, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+ try {
+ writer.write(chars, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+ try {
+ writer.write(chars, 1, chars.length);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+ writer.write(chars, 1, 2);
+ writer.flush();
+ assertEquals("hi", out.toString("utf-8"));
+ writer.write(chars, 0, chars.length);
+ writer.flush();
+ assertEquals("hi" + source, out.toString("utf-8"));
+
+ }
+
+ /*
+ * Class under test for void write(int)
+ */
+ public void testWriteint() throws IOException {
+ writer.write(1);
+ writer.flush();
+ String str = new String(out.toByteArray(), "utf-8");
+ assertEquals("\u0001", str);
+
+ writer.write(2);
+ writer.flush();
+ str = new String(out.toByteArray(), "utf-8");
+ assertEquals("\u0001\u0002", str);
+
+ writer.write(-1);
+ writer.flush();
+ str = new String(out.toByteArray(), "utf-8");
+ assertEquals("\u0001\u0002\uffff", str);
+
+ writer.write(0xfedcb);
+ writer.flush();
+ str = new String(out.toByteArray(), "utf-8");
+ assertEquals("\u0001\u0002\uffff\uedcb", str);
+ }
+
+ /*
+ * Class under test for void write(String, int, int)
+ */
+ public void testWriteStringintint() throws IOException {
+ try {
+ writer.write((String) null, 1, 1);
+ fail();
+ } catch (NullPointerException e) {
+ }
+ try {
+ writer.write("", 0, 1);
+ fail();
+ } catch (StringIndexOutOfBoundsException e) {
+ }
+ try {
+ writer.write("abc", -1, 1);
+ fail();
+ } catch (StringIndexOutOfBoundsException e) {
+ }
+ try {
+ writer.write("abc", 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ }
+ try {
+ writer.write("abc", 1, 3);
+ fail();
+ } catch (StringIndexOutOfBoundsException e) {
+ }
+ writer.write("abc", 1, 2);
+ writer.flush();
+ assertEquals("bc", out.toString("utf-8"));
+ writer.write(source, 0, source.length());
+ writer.flush();
+ assertEquals("bc" + source, out.toString("utf-8"));
+
+ }
+
+ /*
+ * Class under test for void OutputStreamWriter(OutputStream)
+ */
+ public void testOutputStreamWriterOutputStream() throws IOException {
+ try {
+ writer = new OutputStreamWriter(null);
+ fail();
+ } catch (NullPointerException e) {
+ }
+ OutputStreamWriter writer2 = new OutputStreamWriter(out);
+ writer2.close();
+ }
+
+ /*
+ * Class under test for void OutputStreamWriter(OutputStream, String)
+ */
+ public void testOutputStreamWriterOutputStreamString() throws IOException {
+ try {
+ writer = new OutputStreamWriter(null, "utf-8");
+ fail();
+ } catch (NullPointerException e) {
+ }
+ try {
+ writer = new OutputStreamWriter(out, "");
+ fail();
+ } catch (UnsupportedEncodingException e) {
+ }
+ try {
+ writer = new OutputStreamWriter(out, "badname");
+ fail();
+ } catch (UnsupportedEncodingException e) {
+ }
+ try {
+ writer = new OutputStreamWriter(out, (String) null);
+ fail();
+ } catch (NullPointerException e) {
+ }
+ OutputStreamWriter writer2 = new OutputStreamWriter(out, "ascii");
+ assertEquals(Charset.forName("ascii"), Charset.forName(writer2
+ .getEncoding()));
+ writer2.close();
+ }
+
+ /*
+ * Class under test for void OutputStreamWriter(OutputStream)
+ */
+ public void testOutputStreamWriterOutputStreamCharset() throws IOException {
+ Charset cs = Charset.forName("ascii");
+ try {
+ writer = new OutputStreamWriter(null, cs);
+ fail();
+ } catch (NullPointerException e) {
+ }
+ try {
+ writer = new OutputStreamWriter(out, (Charset) null);
+ fail();
+ } catch (NullPointerException e) {
+ }
+ OutputStreamWriter writer2 = new OutputStreamWriter(out, cs);
+ assertEquals(cs, Charset.forName(writer2.getEncoding()));
+ writer2.close();
+ }
+
+ /*
+ * Class under test for void OutputStreamWriter(OutputStream, String)
+ */
+ public void testOutputStreamWriterOutputStreamCharsetEncoder()
+ throws IOException {
+ Charset cs = Charset.forName("ascii");
+ CharsetEncoder enc = cs.newEncoder();
+ try {
+ writer = new OutputStreamWriter(null, enc);
+ fail();
+ } catch (NullPointerException e) {
+ }
+ try {
+ writer = new OutputStreamWriter(out, (CharsetEncoder) null);
+ fail();
+ } catch (NullPointerException e) {
+ }
+ OutputStreamWriter writer2 = new OutputStreamWriter(out, cs);
+ assertEquals(cs, Charset.forName(writer2.getEncoding()));
+ writer2.close();
+ }
+
+ public void testGetEncoding() {
+ Charset cs = Charset.forName("utf-8");
+ assertEquals(cs, Charset.forName(writer.getEncoding()));
+ }
+
+ public void testHandleEarlyEOFChar_1() {
+ String str = "All work and no play makes Jack a dull boy\n"; //$NON-NLS-1$
+ int NUMBER = 2048;
+ int j = 0;
+ int len = str.length() * NUMBER;
+ /* == 88064 *//* NUMBER compulsively written copies of the same string */
+ char[] strChars = new char[len];
+ for (int i = 0; i < NUMBER; ++i) {
+ for (int k = 0; k < str.length(); ++k) {
+ strChars[j++] = str.charAt(k);
+ }
+ }
+ File f = null;
+ FileWriter fw = null;
+ try {
+ f = File.createTempFile("ony", "by_one");
+ fw = new FileWriter(f);
+ fw.write(strChars);
+ fw.close();
+ InputStreamReader in = null;
+ FileInputStream fis = new FileInputStream(f);
+ in = new InputStreamReader(fis);
+ int b;
+ int errors = 0;
+ for (int offset = 0; offset < strChars.length; ++offset) {
+ b = in.read();
+ if (b == -1) {
+ fail("Early EOF at offset " + offset + "\n");
+ return;
+ }
+ }
+ assertEquals(0, errors);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void testHandleEarlyEOFChar_2() throws IOException {
+ int capacity = 65536;
+ byte[] bytes = new byte[capacity];
+ byte[] bs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
+ for (int i = 0; i < bytes.length; i++) {
+ bytes[i] = bs[i / 8192];
+ }
+ String inputStr = new String(bytes);
+ int len = inputStr.length();
+ File f = File.createTempFile("FileWriterBugTest ", null); //$NON-NLS-1$
+ FileWriter writer = new FileWriter(f);
+ writer.write(inputStr);
+ writer.close();
+ long flen = f.length();
+
+ FileReader reader = new FileReader(f);
+ char[] outChars = new char[capacity];
+ int outCount = reader.read(outChars);
+ String outStr = new String(outChars, 0, outCount);
+
+ f.deleteOnExit();
+ assertEquals(len, flen);
+ assertEquals(inputStr, outStr);
+
+ }
+
+ public void testSingleCharIO() throws Exception {
+ InputStreamReader isr = null;
+ for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) {
+ try {
+ out = new ByteArrayOutputStream();
+ writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]);
+
+ int upper = UPPER;
+ switch (i) {
+ case 0:
+ upper = 128;
+ break;
+ case 1:
+ upper = 256;
+ break;
+ }
+
+ for (int c = 0; c < upper; ++c) {
+ writer.write(c);
+ }
+ writer.flush();
+ byte[] result = out.toByteArray();
+
+ isr = new InputStreamReader(new ByteArrayInputStream(result),
+ MINIMAL_CHARSETS[i]);
+ for (int expected = 0; expected < upper; ++expected) {
+ assertEquals("Error when reading bytes in "
+ + MINIMAL_CHARSETS[i], expected, isr.read());
+ }
+ } finally {
+ try {
+ isr.close();
+ } catch (Exception e) {
+ }
+ try {
+ writer.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+
+ public void testBlockIO() throws Exception {
+ InputStreamReader isr = null;
+ char[] largeBuffer = new char[BUFFER_SIZE];
+ for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) {
+ try {
+ out = new ByteArrayOutputStream();
+ writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]);
+
+ int upper = UPPER;
+ switch (i) {
+ case 0:
+ upper = 128;
+ break;
+ case 1:
+ upper = 256;
+ break;
+ }
+
+ int m = 0;
+ for (int c = 0; c < upper; ++c) {
+ largeBuffer[m++] = (char) c;
+ if (m == BUFFER_SIZE) {
+ writer.write(largeBuffer);
+ m = 0;
+ }
+ }
+ writer.write(largeBuffer, 0, m);
+ writer.flush();
+ byte[] result = out.toByteArray();
+
+ isr = new InputStreamReader(new ByteArrayInputStream(result),
+ MINIMAL_CHARSETS[i]);
+ int expected = 0, read = 0, j = 0;
+ while (expected < upper) {
+ if (j == read) {
+ read = isr.read(largeBuffer);
+ j = 0;
+ }
+ assertEquals("Error when reading bytes in "
+ + MINIMAL_CHARSETS[i], expected++, largeBuffer[j++]);
+ }
+ } finally {
+ try {
+ isr.close();
+ } catch (Exception e) {
+ }
+ try {
+ writer.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() {
+ // Test for method java.io.OutputStreamWriter(java.io.OutputStream)
+ assertTrue("Used in tests", true);
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream,
+ * java.lang.String)
+ */
+ public void test_ConstructorLjava_io_OutputStreamLjava_lang_String() {
+ // Test for method java.io.OutputStreamWriter(java.io.OutputStream,
+ // java.lang.String)
+ try {
+ osw = new OutputStreamWriter(fos, "8859_1");
+ } catch (UnsupportedEncodingException e) {
+ fail("Unable to create output stream : " + e.getMessage());
+ }
+ try {
+ osw = new OutputStreamWriter(fos, "Bogus");
+ } catch (UnsupportedEncodingException e) {
+ return;
+ }
+ fail("Failed to throw Unsupported Encoding exception");
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#close()
+ */
+ public void test_close() {
+ // Test for method void java.io.OutputStreamWriter.close()
+ boolean exception = false;
+ try {
+ osw.close();
+ osw.write(testString, 0, testString.length());
+ } catch (IOException e) {
+ exception = true;
+ }
+ assertTrue("Chars written after close", exception);
+
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ try {
+ OutputStreamWriter writer = new OutputStreamWriter(bout,
+ "ISO2022JP");
+ writer.write(new char[] { 'a' });
+ writer.close();
+ // the default is ASCII, there should not be any mode changes
+ String converted = new String(bout.toByteArray(), "ISO8859_1");
+ assertTrue("invalid conversion 1: " + converted, converted
+ .equals("a"));
+
+ bout.reset();
+ writer = new OutputStreamWriter(bout, "ISO2022JP");
+ writer.write(new char[] { '\u3048' });
+ writer.flush();
+ // the byte sequence should not switch to ASCII mode until the
+ // stream is closed
+ converted = new String(bout.toByteArray(), "ISO8859_1");
+ assertTrue("invalid conversion 2: " + converted, converted
+ .equals("\u001b$B$("));
+ writer.close();
+ converted = new String(bout.toByteArray(), "ISO8859_1");
+ assertTrue("invalid conversion 3: " + converted, converted
+ .equals("\u001b$B$(\u001b(B"));
+
+ bout.reset();
+ writer = new OutputStreamWriter(bout, "ISO2022JP");
+ writer.write(new char[] { '\u3048' });
+ writer.write(new char[] { '\u3048' });
+ writer.close();
+ // there should not be a mode switch between writes
+ assertTrue("invalid conversion 4", new String(bout.toByteArray(),
+ "ISO8859_1").equals("\u001b$B$($(\u001b(B"));
+ } catch (UnsupportedEncodingException e) {
+ // Can't test missing converter
+ System.out.println(e);
+ } catch (IOException e) {
+ fail("Unexpected: " + e);
+ }
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#flush()
+ */
+ public void test_flush() {
+ // Test for method void java.io.OutputStreamWriter.flush()
+ try {
+ char[] buf = new char[testString.length()];
+ osw.write(testString, 0, testString.length());
+ osw.flush();
+ openInputStream();
+ isr.read(buf, 0, buf.length);
+ assertTrue("Chars not flushed", new String(buf, 0, buf.length)
+ .equals(testString));
+ } catch (Exception e) {
+ fail("Exception during write test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#getEncoding()
+ */
+ public void test_getEncoding() {
+ // Test for method java.lang.String
+ // java.io.OutputStreamWriter.getEncoding()
+ try {
+ osw = new OutputStreamWriter(fos, "8859_1");
+ } catch (UnsupportedEncodingException e) {
+ assertTrue("Returned incorrect encoding", osw.getEncoding().equals(
+ "8859_1"));
+ }
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#write(char[], int, int)
+ */
+ public void test_write$CII() {
+ // Test for method void java.io.OutputStreamWriter.write(char [], int,
+ // int)
+ try {
+ char[] buf = new char[testString.length()];
+ osw.write(testString, 0, testString.length());
+ osw.close();
+ openInputStream();
+ isr.read(buf, 0, buf.length);
+ assertTrue("Incorrect chars returned", new String(buf, 0,
+ buf.length).equals(testString));
+ } catch (Exception e) {
+ fail("Exception during write test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#write(int)
+ */
+ public void test_writeI() {
+ // Test for method void java.io.OutputStreamWriter.write(int)
+ try {
+ osw.write('T');
+ osw.close();
+ openInputStream();
+ int c = isr.read();
+ assertTrue("Incorrect char returned", (char) c == 'T');
+ } catch (Exception e) {
+ fail("Exception during write test : " + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#write(java.lang.String, int, int)
+ */
+ public void test_writeLjava_lang_StringII() {
+ // Test for method void
+ // java.io.OutputStreamWriter.write(java.lang.String, int, int)
+
+ try {
+ char[] buf = new char[testString.length()];
+ osw.write(testString, 0, testString.length());
+ osw.close();
+ openInputStream();
+ isr.read(buf);
+ assertTrue("Incorrect chars returned", new String(buf, 0,
+ buf.length).equals(testString));
+ } catch (Exception e) {
+ fail("Exception during write test : " + e.getMessage());
+ }
+ }
+
+ private void openInputStream() {
+ isr = new InputStreamReader(new ByteArrayInputStream(fos.toByteArray()));
+ }
+
+}