diff options
author | Elliott Hughes <enh@google.com> | 2013-05-03 13:29:31 -0700 |
---|---|---|
committer | Elliott Hughes <enh@google.com> | 2013-05-03 13:29:31 -0700 |
commit | 56ddb0af9c75dca21f10cd26e73b9f301c58771e (patch) | |
tree | 5c1d40686bdfee7b1a06cde8649290e4bd14c7e7 | |
parent | 4f5a23794efbb123751239c66917ecae43c936be (diff) | |
download | libcore-56ddb0af9c75dca21f10cd26e73b9f301c58771e.zip libcore-56ddb0af9c75dca21f10cd26e73b9f301c58771e.tar.gz libcore-56ddb0af9c75dca21f10cd26e73b9f301c58771e.tar.bz2 |
Add harmony java.nio.charset tests.
Change-Id: I713069b35865cc01f5ed2f384dbc50b39d8a9346
37 files changed, 7009 insertions, 0 deletions
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/ASCIICharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/ASCIICharsetEncoderTest.java new file mode 100644 index 0000000..6f59190 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/ASCIICharsetEncoderTest.java @@ -0,0 +1,453 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.harmony.nio_char.tests.java.nio.charset; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderResult; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.MalformedInputException; +import java.nio.charset.UnmappableCharacterException; + +import junit.framework.TestCase; + +public class ASCIICharsetEncoderTest extends TestCase { + + // charset for ascii + private static final Charset cs = Charset.forName("ascii"); + private static final CharsetEncoder encoder = cs.newEncoder(); + private static final int MAXCODEPOINT = 0x7F; + /* + * @see CharsetEncoderTest#setUp() + */ + protected void setUp() throws Exception { + } + + /* + * @see CharsetEncoderTest#tearDown() + */ + protected void tearDown() throws Exception { + } + + public void testCanEncodeCharSequence() { + // normal case for ascCS + assertTrue(encoder.canEncode("\u0077")); + assertFalse(encoder.canEncode("\uc2a3")); + assertFalse(encoder.canEncode("\ud800\udc00")); + try { + encoder.canEncode(null); + } catch (NullPointerException e) { + } + assertTrue(encoder.canEncode("")); + } + + public void testCanEncodeSurrogate () { + assertFalse(encoder.canEncode('\ud800')); + assertFalse(encoder.canEncode("\udc00")); + } + + public void testCanEncodechar() throws CharacterCodingException { + assertTrue(encoder.canEncode('\u0077')); + assertFalse(encoder.canEncode('\uc2a3')); + } + + public void testSpecificDefaultValue() { + assertEquals(1.0, encoder.averageBytesPerChar(), 0.0); + assertEquals(1.0, encoder.maxBytesPerChar(), 0.0); + } + + public void testMultiStepEncode() throws CharacterCodingException { + encoder.onMalformedInput(CodingErrorAction.REPORT); + encoder.onUnmappableCharacter(CodingErrorAction.REPORT); + try { + encoder.encode(CharBuffer.wrap("\ud800\udc00")); + fail("should unmappable"); + } catch (UnmappableCharacterException e) { + } + encoder.reset(); + ByteBuffer out = ByteBuffer.allocate(10); + assertTrue(encoder.encode(CharBuffer.wrap("\ud800"), out, true) + .isMalformed()); + encoder.flush(out); + encoder.reset(); + out = ByteBuffer.allocate(10); + assertSame(CoderResult.UNDERFLOW, encoder.encode(CharBuffer + .wrap("\ud800"), out, false)); + assertTrue(encoder.encode(CharBuffer.wrap("\udc00"), out, true) + .isMalformed()); + } + + public void testEncodeMapping() throws CharacterCodingException { + encoder.reset(); + + for (int i =0; i <= MAXCODEPOINT; i++) { + char[] chars = Character.toChars(i); + CharBuffer cb = CharBuffer.wrap(chars); + ByteBuffer bb = encoder.encode(cb); + assertEquals(i, bb.get(0)); + } + + CharBuffer cb = CharBuffer.wrap("\u0080"); + try { + encoder.encode(cb); + } catch (UnmappableCharacterException e) { + //expected + } + + cb = CharBuffer.wrap("\ud800"); + try { + encoder.encode(cb); + } catch (MalformedInputException e) { + //expected + } + + ByteBuffer bb = ByteBuffer.allocate(0x10); + cb = CharBuffer.wrap("A"); + encoder.reset(); + encoder.encode(cb, bb, false); + try { + encoder.encode(cb); + } catch (IllegalStateException e) { + //expected + } + } + + public void testInternalState() { + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + + //normal encoding process + encoder.reset(); + encoder.encode(in, out, false); + in = CharBuffer.wrap("B"); + encoder.encode(in, out, true); + encoder.flush(out); + } + + //reset could be called at any time + public void testInternalState_Reset() { + CharsetEncoder newEncoder = cs.newEncoder(); + //Init - > reset + newEncoder.reset(); + + //reset - > reset + newEncoder.reset(); + + //encoding - >reset + { + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, false); + newEncoder.reset(); + } + + //encoding end -> reset + { + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + newEncoder.reset(); + } + //flused -> reset + { + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + newEncoder.flush(out); + newEncoder.reset(); + } + } + + public void testInternalState_Encoding() { + CharsetEncoder newEncoder = cs.newEncoder(); + //Init - > encoding + { + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, false); + } + + //reset - > encoding + { + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.reset(); + newEncoder.encode(in, out, false); + } + //reset - > encoding - > encoding + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, false); + in = CharBuffer.wrap("BC"); + newEncoder.encode(in, out, false); + } + + //encoding_end - > encoding + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + in = CharBuffer.wrap("BC"); + try { + newEncoder.encode(in, out, false); + fail("Should throw IllegalStateException"); + } catch (IllegalStateException e) { + //expected + } + } + //flushed - > encoding + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + newEncoder.flush(out); + in = CharBuffer.wrap("BC"); + try { + newEncoder.encode(in, out, false); + fail("Should throw IllegalStateException"); + } catch (IllegalStateException e) { + //expected + } + } + } + + public void testInternalState_Encoding_END() { + CharsetEncoder newEncoder = cs.newEncoder(); + + //Init - >encoding_end + { + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + } + + //Reset -> encoding_end + { + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.reset(); + newEncoder.encode(in, out, true); + } + + //encoding -> encoding_end + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, false); + in = CharBuffer.wrap("BC"); + newEncoder.encode(in, out, true); + } + + //Reset -> encoding_end + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + in = CharBuffer.wrap("BC"); + newEncoder.encode(in, out, true); + } + + //Flushed -> encoding_end + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + newEncoder.flush(out); + in = CharBuffer.wrap("BC"); + try { + newEncoder.encode(in, out, true); + fail("Should throw IllegalStateException"); + } catch (IllegalStateException e) { + //expected + } + } + } + + public void testInternalState_Flushed() { + CharsetEncoder newEncoder = cs.newEncoder(); + + // init -> flushed + { + ByteBuffer out = ByteBuffer.allocate(0x10); + try { + newEncoder.flush(out); + fail("Should throw IllegalStateException"); + } catch (IllegalStateException e) { + //expected + } + + } + + // reset - > flushed + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + newEncoder.reset(); + try { + newEncoder.flush(out); + fail("Should throw IllegalStateException"); + } catch (IllegalStateException e) { + //expected + } + } + + //encoding - > flushed + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, false); + try { + + newEncoder.flush(out); + fail("Should throw IllegalStateException"); + } catch (IllegalStateException e) { + // expected + } + } + + //encoding_end -> flushed + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + newEncoder.flush(out); + } + + //flushd - > flushed + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + newEncoder.flush(out); + try { + newEncoder.flush(out); + fail("Should throw IllegalStateException"); + } catch (IllegalStateException e) { + // expected + } + } + } + + public void testInternalState_Encode() throws CharacterCodingException { + CharsetEncoder newEncoder = cs.newEncoder(); + //Init - > encode + { + CharBuffer in = CharBuffer.wrap("A"); + newEncoder.encode(in); + } + + //Reset - > encode + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + newEncoder.encode(in); + } + + //Encoding -> encode + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, false); + in = CharBuffer.wrap("BC"); + newEncoder.encode(in); + } + + //Encoding_end -> encode + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + in = CharBuffer.wrap("BC"); + newEncoder.encode(in); + } + + //Flushed -> reset + { + newEncoder.reset(); + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + in = CharBuffer.wrap("BC"); + newEncoder.flush(out); + out = newEncoder.encode(in); + } + } + + public void testInternalState_from_Encode() throws CharacterCodingException { + CharsetEncoder newEncoder = cs.newEncoder(); + + //Encode -> Reset + { + CharBuffer in = CharBuffer.wrap("A"); + newEncoder.encode(in); + newEncoder.reset(); + } + + // Encode -> encoding + { + CharBuffer in = CharBuffer.wrap("A"); + newEncoder.encode(in); + ByteBuffer out = ByteBuffer.allocate(0x10); + try { + newEncoder.encode(in, out, false); + fail("Should throw IllegalStateException"); + } catch (IllegalStateException e) { + // expected + } + } + + //Encode -> Encoding_end + { + CharBuffer in = CharBuffer.wrap("A"); + newEncoder.encode(in); + ByteBuffer out = ByteBuffer.allocate(0x10); + newEncoder.encode(in, out, true); + } + + //Encode -> Flushed + { + CharBuffer in = CharBuffer.wrap("A"); + ByteBuffer out = newEncoder.encode(in); + newEncoder.flush(out); + } + + //Encode - > encode + { + CharBuffer in = CharBuffer.wrap("A"); + newEncoder.encode(in); + in = CharBuffer.wrap("BC"); + newEncoder.encode(in); + } + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharacterCodingExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharacterCodingExceptionTest.java new file mode 100644 index 0000000..a45938f --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharacterCodingExceptionTest.java @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.harmony.nio_char.tests.java.nio.charset; + +import java.io.IOException; +import java.nio.charset.CharacterCodingException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Test CharacterCodingException + */ +public class CharacterCodingExceptionTest extends TestCase { + + public void testConstructor() { + CharacterCodingException ex = new CharacterCodingException(); + assertTrue(ex instanceof IOException); + assertNull(ex.getCause()); + assertNull(ex.getMessage()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new CharacterCodingException()); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + SerializationTest.verifyGolden(this, new CharacterCodingException()); + + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetDecoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetDecoderTest.java new file mode 100644 index 0000000..4ed4ab9 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetDecoderTest.java @@ -0,0 +1,280 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.harmony.nio_char.tests.java.nio.charset; + +import java.io.IOException; +import java.nio.BufferOverflowException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderMalfunctionError; +import java.nio.charset.CoderResult; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.MalformedInputException; +import java.util.Arrays; + +import junit.framework.TestCase; + +public class CharsetDecoderTest extends TestCase { + + /** + * @tests java.nio.charset.CharsetDecoder.CharsetDecoder(Charset, float, + * float) + */ + public void test_ConstructorLjava_nio_charset_CharsetFF() { + // Regression for HARMONY-142 + try { + Charset cs = Charset.forName("UTF-8"); //$NON-NLS-1$ + new MockCharsetDecoderForHarmony142(cs, 1.1f, 1); + fail("Assert 0: Should throw IllegalArgumentException."); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + } + + /* + * MockCharsetDecoderForHarmony142: for constructor test + */ + static class MockCharsetDecoderForHarmony142 extends CharsetDecoder { + protected MockCharsetDecoderForHarmony142(Charset cs, + float averageBytesPerChar, float maxBytesPerChar) { + super(cs, averageBytesPerChar, maxBytesPerChar); + } + + protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { + return null; + } + } + + /** + * @tests java.nio.charset.CharsetDecoder#decode(java.nio.ByteBuffer) + */ + public void test_decode() throws CharacterCodingException { + // Regression for HARMONY-33 +// ByteBuffer bb = ByteBuffer.allocate(1); +// bb.put(0, (byte) 77); +// CharsetDecoder decoder = Charset.forName("UTF-16").newDecoder(); +// decoder.onMalformedInput(CodingErrorAction.REPLACE); +// decoder.onUnmappableCharacter(CodingErrorAction.REPLACE); +// decoder.decode(bb); + + // Regression for HARMONY-67 +// byte[] b = new byte[] { (byte) 1 }; +// ByteBuffer buf = ByteBuffer.wrap(b); +// CharBuffer charbuf = Charset.forName("UTF-16").decode(buf); +// assertEquals("Assert 0: charset UTF-16", 1, charbuf.length()); +// +// charbuf = Charset.forName("UTF-16BE").decode(buf); +// assertEquals("Assert 1: charset UTF-16BE", 0, charbuf.length()); +// +// charbuf = Charset.forName("UTF-16LE").decode(buf); +// assertEquals("Assert 2: charset UTF16LE", 0, charbuf.length()); + + // Regression for HARMONY-99 + CharsetDecoder decoder2 = Charset.forName("UTF-16").newDecoder(); + decoder2.onMalformedInput(CodingErrorAction.REPORT); + decoder2.onUnmappableCharacter(CodingErrorAction.REPORT); + ByteBuffer in = ByteBuffer.wrap(new byte[] { 109, 97, 109 }); + try { + decoder2.decode(in); + fail("Assert 3: MalformedInputException should have thrown"); + } catch (MalformedInputException e) { + //expected + } + } + + /* + * Test malfunction decode(ByteBuffer) + */ + public void test_decodeLjava_nio_ByteBuffer() throws Exception { + MockMalfunctionCharset cs1 = new MockMalfunctionCharset( + "Harmony-124-1", null); //$NON-NLS-1$ + try { + cs1.newDecoder().onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE).decode( + ByteBuffer.wrap(new byte[] { 0x00, 0x11 })); + fail("Assert 0: should throw CoderMalfunctionError"); // NON-NLS-1$ + } catch (CoderMalfunctionError e) { + // expected + } + + MockMalfunctionCharset cs2 = new MockMalfunctionCharset( + "Harmony-124-2", null); //$NON-NLS-1$ + try { + cs2.decode(ByteBuffer.wrap(new byte[] { 0x00, 0x11 })); + fail("Assert 1: Charset.decode should throw CoderMalfunctionError"); // NON-NLS-1 + } catch (CoderMalfunctionError e) { + // expected + } + } + + /* + * Mock charset class with malfunction decode & encode. + */ + static final class MockMalfunctionCharset extends Charset { + + public MockMalfunctionCharset(String canonicalName, String[] aliases) { + super(canonicalName, aliases); + } + + public boolean contains(Charset cs) { + return false; + } + + public CharsetDecoder newDecoder() { + return new MockMalfunctionDecoder(this); + } + + public CharsetEncoder newEncoder() { + return new MockMalfunctionEncoder(this); + } + } + + /* + * Mock decoder. decodeLoop always throws unexpected exception. + */ + static class MockMalfunctionDecoder extends java.nio.charset.CharsetDecoder { + + public MockMalfunctionDecoder(Charset cs) { + super(cs, 1, 10); + } + + protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { + throw new BufferOverflowException(); + } + } + + /* + * Mock encoder. encodeLoop always throws unexpected exception. + */ + static class MockMalfunctionEncoder extends java.nio.charset.CharsetEncoder { + + public MockMalfunctionEncoder(Charset cs) { + super(cs, 1, 3, new byte[] { (byte) '?' }); + } + + protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { + throw new BufferOverflowException(); + } + } + + /* + * Test the method decode(ByteBuffer) . + */ + public void testDecodeLjava_nio_ByteBuffer_ReplaceOverflow() + throws Exception { + String replaceString = "a"; + Charset cs = Charset.forName("UTF-8"); + MockMalformedDecoder decoder = new MockMalformedDecoder(cs); + decoder.onMalformedInput(CodingErrorAction.REPLACE); + decoder.replaceWith(replaceString); + CharBuffer out = CharBuffer.allocate(1); + // MockMalformedDecoder treats the second byte '0x38' as malformed, + // but "out" doesn't have enough space for replace string. + ByteBuffer in = ByteBuffer.wrap(new byte[] { 0x45, 0x38, 0x45, 0x45 }); + CoderResult result = decoder.decode(in, out, false); + assertTrue(result.isOverflow()); + + // allocate enough space for "out" + out = CharBuffer.allocate(10); + // replace string should be put into "out" firstly, + // and then decode "in". + result = decoder.decode(in, out, true); + out.flip(); + assertTrue(result.isUnderflow()); + assertEquals("bb", out.toString()); + } + + /* + * Mock decoder. It treats byte whose value is less than "0x40" as + * malformed. + */ + static class MockMalformedDecoder extends java.nio.charset.CharsetDecoder { + + public MockMalformedDecoder(Charset cs) { + super(cs, 1, 10); + } + + /* + * It treats byte whose value is less than "0x40" as malformed. + * Otherwise, it's decoded as 'b'. + */ + protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { + while (in.hasRemaining()) { + byte b = in.get(); + if (b < 0x40) { + return CoderResult.malformedForLength(1); + } + if (!out.hasRemaining()) { + return CoderResult.OVERFLOW; + } + out.put((char) 'b'); + } + return CoderResult.UNDERFLOW; + } + } + + + public void testInvalidDecoding() throws IOException { + + byte[][] invalidSequences = new byte[][] { + // overlong NULL + { (byte) 0xC0, (byte) 0x80 }, + // overlong ascii 'A' + { (byte) 0xC0, (byte) 0xC1 }, + // overlong "/../" + { (byte) 0x2F, (byte) 0xC0, (byte) 0xAE, (byte) 0x2E, (byte) 0x2F }, + // Invalid encoding 2r11111000 (sequence too long) + { (byte) 0xF8 }, + // Invalid encoding 2r10000000 (sequence too short) + { (byte) 0x80 } + }; + + CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); + decoder.onMalformedInput(CodingErrorAction.REPORT); + + /* + * When bytebuffer has a backing array... + */ + for (byte[] bytes : invalidSequences) { + try { + decoder.decode(ByteBuffer.wrap(bytes)); + fail("No exception thrown on " + Arrays.toString(bytes)); + } catch (MalformedInputException e) { + // expected + } + } + + /* + * When bytebuffer has _not_ got a backing array... + */ + for (byte[] bytes : invalidSequences) { + try { + ByteBuffer bb = ByteBuffer.allocateDirect(8); + bb.put(bytes).flip(); + decoder.decode(bb); + fail("No exception thrown on " + Arrays.toString(bytes)); + } catch (MalformedInputException e) { + // expected + } + } + } + +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetEncoderTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetEncoderTest.java new file mode 100644 index 0000000..da176e6 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetEncoderTest.java @@ -0,0 +1,189 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.harmony.nio_char.tests.java.nio.charset; + +import java.io.IOException; +import java.nio.BufferOverflowException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderMalfunctionError; +import java.nio.charset.CoderResult; + +import junit.framework.TestCase; + +public class CharsetEncoderTest extends TestCase { + + /** + * @tests java.nio.charset.CharsetEncoder.CharsetEncoder( + * java.nio.charset.Charset, float, float) + */ + public void test_ConstructorLjava_nio_charset_CharsetFF() { + // Regression for HARMONY-141 + try { + Charset cs = Charset.forName("UTF-8"); //$NON-NLS-1$ + new MockCharsetEncoderForHarmony141(cs, 1.1f, 1); + fail("Assert 0: Should throw IllegalArgumentException."); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + + try { + Charset cs = Charset.forName("ISO8859-1"); //$NON-NLS-1$ + new MockCharsetEncoderForHarmony141(cs, 1.1f, 1, + new byte[] { 0x1a }); + fail("Assert 1: Should throw IllegalArgumentException."); //$NON-NLS-1$ + } catch (IllegalArgumentException e) { + // expected + } + } + + /** + * @tests java.nio.charset.CharsetEncoder.CharsetEncoder( + * java.nio.charset.Charset, float, float) + */ + public void test_ConstructorLjava_nio_charset_CharsetNull() { + // Regression for HARMONY-491 + CharsetEncoder ech = new MockCharsetEncoderForHarmony491(null, 1, 1); + assertNull(ech.charset()); + } + + /** + * Helper for constructor tests + */ + + public static class MockCharsetEncoderForHarmony141 extends CharsetEncoder { + + protected MockCharsetEncoderForHarmony141(Charset cs, + float averageBytesPerChar, float maxBytesPerChar) { + super(cs, averageBytesPerChar, maxBytesPerChar); + } + + public MockCharsetEncoderForHarmony141(Charset cs, + float averageBytesPerChar, float maxBytesPerChar, + byte[] replacement) { + super(cs, averageBytesPerChar, maxBytesPerChar, replacement); + } + + protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { + return null; + } + } + + public static class MockCharsetEncoderForHarmony491 extends CharsetEncoder { + + public MockCharsetEncoderForHarmony491(Charset arg0, float arg1, + float arg2) { + super(arg0, arg1, arg2); + } + + protected CoderResult encodeLoop(CharBuffer arg0, ByteBuffer arg1) { + return null; + } + + public boolean isLegalReplacement(byte[] arg0) { + return true; + } + } + + /* + * Test malfunction encode(CharBuffer) + */ + public void test_EncodeLjava_nio_CharBuffer() throws Exception { + MockMalfunctionCharset cs = new MockMalfunctionCharset("mock", null); + try { + cs.encode(CharBuffer.wrap("AB")); + fail("should throw CoderMalfunctionError");// NON-NLS-1$ + } catch (CoderMalfunctionError e) { + // expected + } + } + + /* + * Mock charset class with malfunction decode & encode. + */ + static final class MockMalfunctionCharset extends Charset { + + public MockMalfunctionCharset(String canonicalName, String[] aliases) { + super(canonicalName, aliases); + } + + public boolean contains(Charset cs) { + return false; + } + + public CharsetDecoder newDecoder() { + return Charset.forName("UTF-8").newDecoder(); + } + + public CharsetEncoder newEncoder() { + return new MockMalfunctionEncoder(this); + } + } + + /* + * Mock encoder. encodeLoop always throws unexpected exception. + */ + static class MockMalfunctionEncoder extends java.nio.charset.CharsetEncoder { + + public MockMalfunctionEncoder(Charset cs) { + super(cs, 1, 3, new byte[] { (byte) '?' }); + } + + protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { + throw new BufferOverflowException(); + } + } + + /* + * Test reserve bytes encode(CharBuffer,ByteBuffer,boolean) + */ + public void test_EncodeLjava_nio_CharBufferLjava_nio_ByteBufferB() { + CharsetEncoder encoder = Charset.forName("utf-8").newEncoder(); + CharBuffer in1 = CharBuffer.wrap("\ud800"); + CharBuffer in2 = CharBuffer.wrap("\udc00"); + ByteBuffer out = ByteBuffer.allocate(4); + encoder.reset(); + CoderResult result = encoder.encode(in1, out, false); + assertEquals(4, out.remaining()); + assertTrue(result.isUnderflow()); + result = encoder.encode(in2, out, true); + assertEquals(4, out.remaining()); + assertTrue(result.isMalformed()); + } + + /** + * @tests {@link java.nio.charset.Charset#encode(java.nio.CharBuffer) + */ + public void testUtf8Encoding() throws IOException { + byte[] orig = new byte[] { (byte) 0xed, (byte) 0xa0, + (byte) 0x80 }; + String s = new String(orig, "UTF-8"); + assertEquals(1, s.length()); + assertEquals(55296, s.charAt(0)); + Charset.forName("UTF-8").encode(CharBuffer.wrap(s)); +// ByteBuffer buf = <result> +// for (byte o : orig) { +// byte b = 0; +// buf.get(b); +// assertEquals(o, b); +// } + } + +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetTest.java new file mode 100644 index 0000000..acc611d --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetTest.java @@ -0,0 +1,244 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.harmony.nio_char.tests.java.nio.charset; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderResult; +import java.nio.charset.IllegalCharsetNameException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; + +import junit.framework.TestCase; + +public class CharsetTest extends TestCase { + + // Will contain names of charsets registered with IANA + Set knownRegisteredCharsets = new HashSet(); + + // Will contain names of charsets not known to be registered with IANA + Set unknownRegisteredCharsets = new HashSet(); + + /** + * JUnit set-up method + */ + public void setUp() { + // Populate the known charset vars + Set names = Charset.availableCharsets().keySet(); + for (Iterator nameItr = names.iterator(); nameItr.hasNext();) { + String name = (String) nameItr.next(); + if (name.toLowerCase().startsWith("x-")) + unknownRegisteredCharsets.add(name); + else + knownRegisteredCharsets.add(name); + } + } + + /** + * @tests java.nio.charset.Charset#isRegistered() + */ + public void test_isRegistered() { + // Regression for HARMONY-45 + for (Iterator nameItr = knownRegisteredCharsets.iterator(); nameItr.hasNext();) { + String name = (String) nameItr.next(); + assertTrue("Assert 0: isRegistered() failed for " + name, + Charset.forName(name).isRegistered()); + } + for (Iterator nameItr = unknownRegisteredCharsets.iterator(); nameItr.hasNext();) { + String name = (String) nameItr.next(); + assertFalse("Assert 0: isRegistered() failed for " + name, + Charset.forName(name).isRegistered()); + } + } + + /** + * @tests java.nio.charset.Charset#isSupported(String) + */ + public void testIsSupported_EmptyString() { + // Regression for HARMONY-113 + try { + Charset.isSupported(""); + fail("Assert 0: Should throw IllegalCharsetNameException"); + } catch (IllegalCharsetNameException e) { + // Expected + } + } + + public void test_defaultCharset() { + assertEquals("UTF-8", Charset.defaultCharset().name()); + } + + public void test_forNameLjava_lang_String() { + /* + * invoke forName two times with the same canonical name, it + * should return the same reference. + */ + Charset cs1 = Charset.forName("UTF-8"); + Charset cs2 = Charset.forName("UTF-8"); + assertSame(cs1, cs2); + + /* + * test forName: invoke forName two times for the same Charset using + * canonical name and alias, it should return the same reference. + */ + Charset cs3 = Charset.forName("ASCII"); + Charset cs4 = Charset.forName("US-ASCII"); + assertSame(cs3, cs4); + } + + /* + * test cached decoder + */ +// public void test_DecodeLjava_nio_ByteBuffer() throws Exception{ +// MockCharsetForDecoder cs1 = new MockCharsetForDecoder("CachedCharset",null); +// MockCharsetForDecoder cs2 = new MockCharsetForDecoder("CachedCharset",null); +// ByteBuffer in = ByteBuffer.wrap(new byte[]{0x00}); +// cs1.decode(in); +// in.flip(); +// cs2.decode(in); +// in.flip(); +// } + /* + * Mock Charset for cached decoder test + */ + static class MockCharsetForDecoder extends Charset{ + + public MockCharsetForDecoder(String canonicalName, String[] aliases){ + super(canonicalName, aliases); + } + + public boolean contains(Charset charset) { + return false; + } + + public CharsetEncoder newEncoder() { + return null; + } + + public CharsetDecoder newDecoder() { + return new MockCachedDecoder(this); + } + + + } + /* + * Mock decoder. Only one caller is permitted. + */ + static class MockCachedDecoder extends CharsetDecoder { + static MockCachedDecoder caller = null; + + public MockCachedDecoder(Charset cs) { + super(cs, 1, 10); + } + + /* + * Only one caller is permitted. + * If there's another caller, throw RuntimeException. + */ + protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { + if(null == caller){ + caller = this; + }else{ + if(caller != this){ + // Another instance + fail("should use the same instance"); + } + } + return CoderResult.UNDERFLOW; + } + } + + /* + * test cached encoder + */ +// public void test_EncodeLjava_nio_CharBuffer() throws Exception { +// MockCharsetForEncoder cs1 = new MockCharsetForEncoder("CachedCharset", null); +// MockCharsetForEncoder cs2 = new MockCharsetForEncoder("CachedCharset", null); +// CharBuffer in = CharBuffer.wrap("A"); +// cs1.encode(in); +// in.flip(); +// cs2.encode(in); +// } + + /* + * Mock Charset for cached encoder test + */ + static class MockCharsetForEncoder extends Charset { + + public MockCharsetForEncoder(String canonicalName, String[] aliases) { + super(canonicalName, aliases); + } + + public boolean contains(Charset charset) { + return false; + } + + public CharsetDecoder newDecoder() { + return new MockDecoderForEncoder(this); + } + + public CharsetEncoder newEncoder() { + return new MockCachedEncoder(this); + } + } + + /* + * Mock encoder. Only one caller is permitted. + */ + static class MockCachedEncoder extends CharsetEncoder { + static MockCachedEncoder caller = null; + + public MockCachedEncoder(Charset cs) { + super(cs, 1, 10); + } + + /* + * Only one caller is permitted. + */ + protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { + if (null == caller) { + caller = this; + } else { + if (caller != this) { + // Another instance + fail("should use the same instance"); + } + } + return CoderResult.UNDERFLOW; + } + } + + /* + * Mock decoder for MockCachedEncoder. + */ + static class MockDecoderForEncoder extends CharsetDecoder { + public MockDecoderForEncoder(Charset cs) { + super(cs, 1, 10); + } + + protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { + in.position(in.limit()); + return CoderResult.UNDERFLOW; + } + } + +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CoderMalfunctionErrorTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CoderMalfunctionErrorTest.java new file mode 100644 index 0000000..8e6318f --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CoderMalfunctionErrorTest.java @@ -0,0 +1,62 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.harmony.nio_char.tests.java.nio.charset; + +import java.nio.charset.CoderMalfunctionError; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; + +/** + * Test java.nio.CoderMalfunctionError. + */ +public class CoderMalfunctionErrorTest extends TestCase { + + /* + * Test constructor with normal param. + */ + public void testConstructor_Normal() { + Exception ex = new Exception(); + CoderMalfunctionError e = new CoderMalfunctionError(ex); + assertSame(ex, e.getCause()); + } + + /* + * Test constructor with null param. + */ + public void testConstructor_Null() { + CoderMalfunctionError e = new CoderMalfunctionError(null); + assertNull(e.getCause()); + } + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new CoderMalfunctionError(null)); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + SerializationTest.verifyGolden(this, new CoderMalfunctionError(null)); + + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/IllegalCharsetNameExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/IllegalCharsetNameExceptionTest.java new file mode 100644 index 0000000..a514aef --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/IllegalCharsetNameExceptionTest.java @@ -0,0 +1,94 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.harmony.nio_char.tests.java.nio.charset; + +import java.io.Serializable; +import java.nio.charset.IllegalCharsetNameException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; +import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; + +/** + * Test class IllegalCharsetNameException. + */ +public class IllegalCharsetNameExceptionTest extends TestCase { + + public void testConstructor() { + IllegalCharsetNameException ex = new IllegalCharsetNameException( + "impossible"); + assertTrue(ex instanceof IllegalArgumentException); + assertNull(ex.getCause()); + assertEquals(ex.getCharsetName(), "impossible"); + assertTrue(ex.getMessage().indexOf("impossible") != -1); + + ex = new IllegalCharsetNameException("ascii"); + assertNull(ex.getCause()); + assertEquals(ex.getCharsetName(), "ascii"); + assertTrue(ex.getMessage().indexOf("ascii") != -1); + + ex = new IllegalCharsetNameException(""); + assertNull(ex.getCause()); + assertEquals(ex.getCharsetName(), ""); + ex.getMessage(); + + ex = new IllegalCharsetNameException(null); + assertNull(ex.getCause()); + assertNull(ex.getCharsetName()); + assertTrue(ex.getMessage().indexOf("null") != -1); + + } + + // comparator for IllegalCharsetNameException objects + private static final SerializableAssert COMPARATOR = new SerializableAssert() { + public void assertDeserialized(Serializable initial, + Serializable deserialized) { + + // FIXME?: getMessage() returns more helpful string but + // this leads to incompatible message in serial form + // + // do common checks for all throwable objects + // SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial, + // deserialized); + + IllegalCharsetNameException initEx = (IllegalCharsetNameException) initial; + IllegalCharsetNameException desrEx = (IllegalCharsetNameException) deserialized; + + assertEquals("CharsetName", initEx.getCharsetName(), desrEx + .getCharsetName()); + } + }; + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new IllegalCharsetNameException( + "charsetName"), COMPARATOR); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new IllegalCharsetNameException( + "charsetName"), COMPARATOR); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/MalformedInputExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/MalformedInputExceptionTest.java new file mode 100644 index 0000000..f482d9d --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/MalformedInputExceptionTest.java @@ -0,0 +1,85 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.harmony.nio_char.tests.java.nio.charset; + +import java.io.Serializable; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.MalformedInputException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; +import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; + +/** + * Test class MalformedInputException. + */ +public class MalformedInputExceptionTest extends TestCase { + + public void testConstructor() { + MalformedInputException ex = new MalformedInputException(3); + assertTrue(ex instanceof CharacterCodingException); + assertNull(ex.getCause()); + assertEquals(ex.getInputLength(), 3); + assertTrue(ex.getMessage().indexOf("3") != -1); + + ex = new MalformedInputException(-3); + assertNull(ex.getCause()); + assertEquals(ex.getInputLength(), -3); + assertTrue(ex.getMessage().indexOf("-3") != -1); + + ex = new MalformedInputException(0); + assertNull(ex.getCause()); + assertEquals(ex.getInputLength(), 0); + assertTrue(ex.getMessage().indexOf("0") != -1); + } + + // comparator for MalformedInputException objects + private static final SerializableAssert COMPARATOR = new SerializableAssert() { + public void assertDeserialized(Serializable initial, + Serializable deserialized) { + + // do common checks for all throwable objects + SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial, + deserialized); + + MalformedInputException initEx = (MalformedInputException) initial; + MalformedInputException desrEx = (MalformedInputException) deserialized; + + assertEquals("InputLength", initEx.getInputLength(), desrEx + .getInputLength()); + } + }; + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new MalformedInputException(11), + COMPARATOR); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new MalformedInputException(11), + COMPARATOR); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnmappableCharacterExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnmappableCharacterExceptionTest.java new file mode 100644 index 0000000..a6cf6a6 --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnmappableCharacterExceptionTest.java @@ -0,0 +1,86 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.harmony.nio_char.tests.java.nio.charset; + +import java.io.Serializable; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.UnmappableCharacterException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; +import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; + +/** + * Test class UnmappableCharacterException. + */ +public class UnmappableCharacterExceptionTest extends TestCase { + + public void testConstructor() { + UnmappableCharacterException ex = new UnmappableCharacterException(3); + assertTrue(ex instanceof CharacterCodingException); + assertNull(ex.getCause()); + assertEquals(ex.getInputLength(), 3); + assertTrue(ex.getMessage().indexOf("3") != -1); + + ex = new UnmappableCharacterException(-3); + assertNull(ex.getCause()); + assertEquals(ex.getInputLength(), -3); + assertTrue(ex.getMessage().indexOf("-3") != -1); + + ex = new UnmappableCharacterException(0); + assertNull(ex.getCause()); + assertEquals(ex.getInputLength(), 0); + assertTrue(ex.getMessage().indexOf("0") != -1); + + } + + // comparator for UnmappableCharacterException objects + private static final SerializableAssert COMPARATOR = new SerializableAssert() { + public void assertDeserialized(Serializable initial, + Serializable deserialized) { + + // do common checks for all throwable objects + SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial, + deserialized); + + UnmappableCharacterException initEx = (UnmappableCharacterException) initial; + UnmappableCharacterException desrEx = (UnmappableCharacterException) deserialized; + + assertEquals("InputLength", initEx.getInputLength(), desrEx + .getInputLength()); + } + }; + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new UnmappableCharacterException(11), + COMPARATOR); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new UnmappableCharacterException( + 11), COMPARATOR); + } +} diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnsupportedCharsetExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnsupportedCharsetExceptionTest.java new file mode 100644 index 0000000..57ea31c --- /dev/null +++ b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/UnsupportedCharsetExceptionTest.java @@ -0,0 +1,93 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.harmony.nio_char.tests.java.nio.charset; + +import java.io.Serializable; +import java.nio.charset.UnsupportedCharsetException; + +import junit.framework.TestCase; + +import org.apache.harmony.testframework.serialization.SerializationTest; +import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; + +/** + * Test class UnsupportedCharsetException. + */ +public class UnsupportedCharsetExceptionTest extends TestCase { + + public void testConstructor() { + UnsupportedCharsetException ex = new UnsupportedCharsetException( + "impossible"); + assertTrue(ex instanceof IllegalArgumentException); + assertNull(ex.getCause()); + assertEquals(ex.getCharsetName(), "impossible"); + assertTrue(ex.getMessage().indexOf("impossible") != -1); + + ex = new UnsupportedCharsetException("ascii"); + assertNull(ex.getCause()); + assertEquals(ex.getCharsetName(), "ascii"); + assertTrue(ex.getMessage().indexOf("ascii") != -1); + + ex = new UnsupportedCharsetException(""); + assertNull(ex.getCause()); + assertEquals(ex.getCharsetName(), ""); + ex.getMessage(); + + ex = new UnsupportedCharsetException(null); + assertNull(ex.getCause()); + assertNull(ex.getCharsetName()); + assertTrue(ex.getMessage().indexOf("null") != -1); + } + + // comparator for UnsupportedCharsetException objects + private static final SerializableAssert COMPARATOR = new SerializableAssert() { + public void assertDeserialized(Serializable initial, + Serializable deserialized) { + + // FIXME?: getMessage() returns more helpful string but + // this leads to incompatible message in serial form + // + // do common checks for all throwable objects + // SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial, + // deserialized); + + UnsupportedCharsetException initEx = (UnsupportedCharsetException) initial; + UnsupportedCharsetException desrEx = (UnsupportedCharsetException) deserialized; + + assertEquals("CharsetName", initEx.getCharsetName(), desrEx + .getCharsetName()); + } + }; + + /** + * @tests serialization/deserialization compatibility. + */ + public void testSerializationSelf() throws Exception { + + SerializationTest.verifySelf(new UnsupportedCharsetException( + "charsetName"), COMPARATOR); + } + + /** + * @tests serialization/deserialization compatibility with RI. + */ + public void testSerializationCompatibility() throws Exception { + + SerializationTest.verifyGolden(this, new UnsupportedCharsetException( + "charsetName"), COMPARATOR); + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetDecoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetDecoderTest.java new file mode 100644 index 0000000..a349b9c --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetDecoderTest.java @@ -0,0 +1,72 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +public class ASCCharsetDecoderTest extends CharsetDecoderTest { + + protected void setUp() throws Exception { + cs = Charset.forName("ascii"); + super.setUp(); + } + + /* + * @see CharsetDecoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + // FIXME: give up this tests + // public void testDefaultCharsPerByte(){ + // // assertEquals(1, decoder.averageCharsPerByte()); + // // assertEquals(1, decoder.maxCharsPerByte()); + // assertEquals(decoder.averageCharsPerByte(), 1, 0.001); + // assertEquals(decoder.maxCharsPerByte(), 2, 0.001); + // } + + ByteBuffer getUnmappedByteBuffer() { + // FIXME: different here + return null; + // ByteBuffer buffer = ByteBuffer.allocate(8); + // buffer.put((byte)-1); + // buffer.put(unibytes); + // buffer.flip(); + // return buffer; + + } + + ByteBuffer getMalformedByteBuffer() { + // FIXME: different here + ByteBuffer buffer = ByteBuffer.allocate(8); + buffer.put((byte) -1); + buffer.put(getByteBuffer()); + buffer.flip(); + return buffer; + + // TODO: how malform? + // return null; + } + + ByteBuffer getExceptionByteArray() throws UnsupportedEncodingException { + return null; + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetTest.java new file mode 100644 index 0000000..f46321e --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/ASCCharsetTest.java @@ -0,0 +1,59 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +/** + * Test charset US-ASCII. + */ +public class ASCCharsetTest extends AbstractCharsetTestCase { + + /** + * Constructor. + * + */ + public ASCCharsetTest(String arg0) { + super(arg0, "US-ASCII", new String[] { "ISO646-US", "ASCII", "cp367", + "ascii7", "ANSI_X3.4-1986", "iso-ir-6", "us", "646", + "iso_646.irv:1983", "csASCII", "ANSI_X3.4-1968", + "ISO_646.irv:1991" }, true, true); // "ibm-367" + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testEncode_Normal() + */ + public void testEncode_Normal() { + String input = "ab\u5D14\u654F"; + byte[] output = new byte[] { 97, 98, + this.testingCharset.newEncoder().replacement()[0], + this.testingCharset.newEncoder().replacement()[0] }; + internalTestEncode(input, output); + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testDecode_Normal() + */ + public void testDecode_Normal() { + byte[] input = new byte[] { 97, 98, 63, 63 }; + char[] output = "ab??".toCharArray(); + internalTestDecode(input, output); + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/AbstractCharsetTestCase.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/AbstractCharsetTestCase.java new file mode 100644 index 0000000..0ebf922 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/AbstractCharsetTestCase.java @@ -0,0 +1,175 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; + +import junit.framework.TestCase; + +/** + * Super class for concrete charset test suites. + */ +public abstract class AbstractCharsetTestCase extends TestCase { + + // the canonical name of this charset + protected final String canonicalName; + + // the aliases set + protected final String[] aliases; + + // canEncode + protected final boolean canEncode; + + // isRegistered + protected final boolean isRegistered; + + // charset instance + protected Charset testingCharset; + + /* + * Initialize the field "testingCharset" here. + * + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + this.testingCharset = Charset.forName(this.canonicalName); + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * Constructor for ConcreteCharsetTest. + * + */ + public AbstractCharsetTestCase(String arg0, String canonicalName, + String[] aliases, boolean canEncode, boolean isRegistered) { + super(arg0); + this.canonicalName = canonicalName; + this.canEncode = canEncode; + this.isRegistered = isRegistered; + this.aliases = aliases; + } + + /* + * Test canEncode. + */ + public void testCanEncode() { + assertEquals(this.canEncode, this.testingCharset.canEncode()); + } + + /* + * Test isRegistered. + */ + public void testIsRegistered() { + assertEquals(this.isRegistered, this.testingCharset.isRegistered()); + } + + /* + * Test name. + */ + public void testName() { + assertEquals(this.canonicalName, this.testingCharset.name()); + // assertEquals(this.canonicalName, this.testingCharset.displayName()); + // assertEquals(this.canonicalName, + // this.testingCharset.displayName(null)); + } + + /* + * Test aliases. + */ + public void testAliases() { + for (int i = 0; i < this.aliases.length; i++) { + Charset c = Charset.forName(this.aliases[i]); + assertEquals(this.canonicalName, c.name()); + // TODO + // assertTrue(this.testingCharset.aliases().contains(this.aliases[i])); + } + } + + /* + * Test the method encode(String) with null. + */ + public void testEncode_String_Null() { + try { + this.testingCharset.encode((String) null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the method encode(CharBuffer) with null. + */ + public void testEncode_CharBuffer_Null() { + try { + this.testingCharset.encode((CharBuffer) null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test encoding. + */ + protected void internalTestEncode(String input, byte[] output) { + ByteBuffer bb = this.testingCharset.encode(input); + int i = 0; + bb.rewind(); + while (bb.hasRemaining() && i < output.length) { + assertEquals(output[i], bb.get()); + i++; + } + assertFalse(bb.hasRemaining()); + assertEquals(output.length, i); + } + + /* + * Test encoding. + */ + public abstract void testEncode_Normal(); + + /* + * Test decoding. + */ + protected void internalTestDecode(byte[] input, char[] output) { + CharBuffer chb = this.testingCharset.decode(ByteBuffer.wrap(input)); + int i = 0; + chb.rewind(); + while (chb.hasRemaining() && i < output.length) { + assertEquals(output[i], chb.get()); + i++; + } + assertFalse(chb.hasRemaining()); + assertEquals(output.length, i); + } + + /* + * Test decoding. + */ + public abstract void testDecode_Normal(); +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CP037CharsetTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/CP037CharsetTest.java new file mode 100644 index 0000000..87918bb --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/CP037CharsetTest.java @@ -0,0 +1,30 @@ + /* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import junit.framework.TestCase; + +/** + * test case specific activity of IBM037 charset encoder/decoder + */ +public class CP037CharsetTest extends TestCase { + + public void test_0x15_CP037() throws Exception { + // Regression test for HARMONY-6308 + assertEquals(new String(new byte[] { 0x000A }, "UTF-8"), new String(new byte[] { 0x15 }, "CP037")); + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetDecoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetDecoderTest.java new file mode 100644 index 0000000..9cd59ea --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetDecoderTest.java @@ -0,0 +1,870 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CoderResult; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.MalformedInputException; +import java.nio.charset.UnmappableCharacterException; + +import junit.framework.TestCase; + +/** + * API unit test for java.nio.CharsetDecoder + */ +public class CharsetDecoderTest extends TestCase { + + protected static final int MAX_BYTES = 3; + + protected static final double AVER_BYTES = 0.5; + + // default charset + private static final Charset MOCKCS = new CharsetEncoderTest.MockCharset( + "mock", new String[0]); + + Charset cs = MOCKCS; + + // default decoder + protected static CharsetDecoder decoder; + + String bom = ""; + + protected void setUp() throws Exception { + super.setUp(); + decoder = cs.newDecoder(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + // FIXME: give up this tests + // /* + // * test default value + // */ + // public void testDefaultCharsPerByte() { + // assertTrue(decoder.averageCharsPerByte() == AVER_BYTES); + // assertTrue(decoder.maxCharsPerByte() == MAX_BYTES); + // } + + public void testDefaultValues() { + assertSame(cs, decoder.charset()); + try { + decoder.detectedCharset(); + fail("should unsupported"); + } catch (UnsupportedOperationException e) { + } + try { + assertTrue(decoder.isCharsetDetected()); + fail("should unsupported"); + } catch (UnsupportedOperationException e) { + } + assertFalse(decoder.isAutoDetecting()); + assertSame(CodingErrorAction.REPORT, decoder.malformedInputAction()); + assertSame(CodingErrorAction.REPORT, decoder + .unmappableCharacterAction()); + assertEquals(decoder.replacement(), "\ufffd"); + } + + /* + * test constructor + */ + public void testCharsetDecoder() { + // default value + decoder = new MockCharsetDecoder(cs, (float) AVER_BYTES, MAX_BYTES); + + // normal case + CharsetDecoder ec = new MockCharsetDecoder(cs, 1, MAX_BYTES); + assertSame(ec.charset(), cs); + assertEquals(1.0, ec.averageCharsPerByte(), 0.0); + assertTrue(ec.maxCharsPerByte() == MAX_BYTES); + + /* + * ------------------------ Exceptional cases ------------------------- + */ + // Normal case: null charset + ec = new MockCharsetDecoder(null, 1, MAX_BYTES); + assertNull(ec.charset()); + assertEquals(1.0, ec.averageCharsPerByte(), 0.0); + assertTrue(ec.maxCharsPerByte() == MAX_BYTES); + + ec = new MockCharsetDecoder(new CharsetEncoderTest.MockCharset("mock", + new String[0]), 1, MAX_BYTES); + + // Commented out since the comment is wrong since MAX_BYTES > 1 + // // OK: average length less than max length + // ec = new MockCharsetDecoder(cs, MAX_BYTES, 1); + // assertTrue(ec.averageCharsPerByte() == MAX_BYTES); + // assertTrue(ec.maxCharsPerByte() == 1); + + // Illegal Argument: zero length + try { + ec = new MockCharsetDecoder(cs, 0, MAX_BYTES); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + try { + ec = new MockCharsetDecoder(cs, 1, 0); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + + // Illegal Argument: negative length + try { + ec = new MockCharsetDecoder(cs, -1, MAX_BYTES); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + try { + ec = new MockCharsetDecoder(cs, 1, -1); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + } + + /* + * test onMalformedInput + */ + public void testOnMalformedInput() { + assertSame(CodingErrorAction.REPORT, decoder.malformedInputAction()); + try { + decoder.onMalformedInput(null); + fail("should throw null pointer exception"); + } catch (IllegalArgumentException e) { + } + decoder.onMalformedInput(CodingErrorAction.IGNORE); + assertSame(CodingErrorAction.IGNORE, decoder.malformedInputAction()); + } + + /* + * test unmappableCharacter + */ + public void testOnUnmappableCharacter() { + assertSame(CodingErrorAction.REPORT, decoder + .unmappableCharacterAction()); + try { + decoder.onUnmappableCharacter(null); + fail("should throw null pointer exception"); + } catch (IllegalArgumentException e) { + } + decoder.onUnmappableCharacter(CodingErrorAction.IGNORE); + assertSame(CodingErrorAction.IGNORE, decoder + .unmappableCharacterAction()); + } + + /* + * test replaceWith + */ + public void testReplaceWith() { + try { + decoder.replaceWith(null); + fail("should throw null pointer exception"); + } catch (IllegalArgumentException e) { + } + try { + decoder.replaceWith(""); + fail("should throw null pointer exception"); + } catch (IllegalArgumentException e) { + } + try { + decoder.replaceWith("testReplaceWith"); + fail("should throw illegal argument exception"); + } catch (IllegalArgumentException e) { + } + + decoder.replaceWith("a"); + assertSame("a", decoder.replacement()); + } + + /* + * Class under test for CharBuffer decode(ByteBuffer) + */ + public void testDecodeByteBuffer() throws CharacterCodingException { + implTestDecodeByteBuffer(); + } + + void implTestDecodeByteBuffer() throws CharacterCodingException { + // Null pointer + try { + decoder.decode(null); + fail("should throw null pointer exception"); + } catch (NullPointerException e) { + } + + // empty input buffer + CharBuffer out = decoder.decode(ByteBuffer.allocate(0)); + assertCharBufferValue("", out); + + // normal case + ByteBuffer in = getByteBuffer(); + out = decoder.decode(in); + assertEquals(0, out.position()); + assertEquals(getString().length(), out.limit()); + assertEquals(getString().length(), out.remaining()); + assertCharBufferValue(getString(), out); + + // normal read only case + in = getByteBuffer().asReadOnlyBuffer(); + out = decoder.decode(in); + assertEquals(out.position(), 0); + assertEquals(out.limit(), getString().length()); + assertEquals(out.remaining(), getString().length()); + assertCharBufferValue(getString(), out); + } + + public void testDecodeByteBufferException() + throws CharacterCodingException, UnsupportedEncodingException { + CharBuffer out; + ByteBuffer in; + String replaceStr = decoder.replacement() + getString(); + + // MalformedException: + decoder.onMalformedInput(CodingErrorAction.REPORT); + decoder.onUnmappableCharacter(CodingErrorAction.REPORT); + in = getMalformedByteBuffer(); + if (in != null) { + try { + CharBuffer buffer = decoder.decode(in); + assertTrue(buffer.remaining() > 0); + fail("should throw MalformedInputException"); + } catch (MalformedInputException e) { + } + + decoder.reset(); + in.rewind(); + decoder.onMalformedInput(CodingErrorAction.IGNORE); + out = decoder.decode(in); + assertCharBufferValue(getString(), out); + + decoder.reset(); + in.rewind(); + decoder.onMalformedInput(CodingErrorAction.REPLACE); + out = decoder.decode(in); + assertCharBufferValue(replaceStr, out); + } + + // Unmapped Exception: + decoder.onMalformedInput(CodingErrorAction.REPORT); + decoder.onUnmappableCharacter(CodingErrorAction.REPORT); + in = getUnmappedByteBuffer(); + if (in != null) { + try { + decoder.decode(in); + fail("should throw UnmappableCharacterException"); + } catch (UnmappableCharacterException e) { + } + + decoder.reset(); + in.rewind(); + decoder.onUnmappableCharacter(CodingErrorAction.IGNORE); + out = decoder.decode(in); + assertCharBufferValue(getString(), out); + + decoder.reset(); + in.rewind(); + decoder.onUnmappableCharacter(CodingErrorAction.REPLACE); + out = decoder.decode(in); + assertCharBufferValue(replaceStr, out); + } + + // RuntimeException + try { + decoder.decode(getExceptionByteArray()); + fail("should throw runtime exception"); + } catch (RuntimeException e) { + } + } + + /* + * Class under test for CoderResult decode(ByteBuffer, CharBuffer, boolean) + */ + public void testDecodeByteBufferCharBuffer() { + implTestDecodeByteBufferCharBuffer(getByteBuffer()); + } + + public void testDecodeByteBufferCharBufferReadOnly() { + implTestDecodeByteBufferCharBuffer(getByteBuffer()); + } + + void implTestDecodeByteBufferCharBuffer(ByteBuffer in) { + CharBuffer out = CharBuffer.allocate(100); + + // Null pointer + decoder.reset(); + try { + decoder.decode(null, out, true); + fail("NullPointerException expected"); + } catch (NullPointerException e) { + } + try { + decoder.decode(in, null, true); + fail("NullPointerException expected"); + } catch (NullPointerException e) { + } + + // normal case, one complete operation + decoder.reset(); + in.rewind(); + out.rewind(); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, true)); + assertEquals(out.limit(), 100); + assertEquals(out.position(), getString().length()); + assertEquals(out.remaining(), 100 - getString().length()); + assertEquals(out.capacity(), 100); + assertCharBufferValue(getString(), out); + decoder.flush(out); + + // normal case, one complete operation, but call twice, first time set + // endOfInput to false + decoder.reset(); + in.rewind(); + out.clear(); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, false)); + assertEquals(out.limit(), 100); + assertEquals(out.position(), getString().length()); + assertEquals(out.remaining(), 100 - getString().length()); + assertEquals(out.capacity(), 100); + assertCharBufferValue(getString(), out); + + decoder.reset(); + in.rewind(); + out.clear(); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, false)); + in = getHeadlessByteBuffer(); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, false)); + in.rewind(); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, true)); + assertEquals(out.limit(), 100); + assertTrue(out.position() > 0); + assertEquals(out.remaining(), out.capacity() - out.position()); + assertEquals(out.capacity(), 100); + assertCharBufferValue(getString() + getString() + getString(), out); + + // overflow + out = CharBuffer.allocate(4); + decoder.reset(); + in = getByteBuffer(); + out.rewind(); + assertSame(CoderResult.OVERFLOW, decoder.decode(in, out, false)); + + assertCharBufferValue(getString().substring(0, 4), out); + out = CharBuffer.allocate(100); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, false)); + assertCharBufferValue(getString().substring(4), out); + in.rewind(); + out = CharBuffer.allocate(100); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, true)); + assertCharBufferValue(bom + getString(), out); + } + + public void testDecodeCharBufferByteBufferUnmappedException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferUnmappedException( + getUnmappedByteBuffer(), true); + } + + public void testDecodeCharBufferByteIncompleteBufferUnmappedException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferUnmappedException( + getUnmappedByteBuffer(), false); + } + + public void testDecodeCharBufferByteReadOnlyBufferUnmappedException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferUnmappedException( + readOnly(getUnmappedByteBuffer()), true); + } + + public void testDecodeCharBufferByteReadOnlyIncompleteBufferUnmappedException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferUnmappedException( + readOnly(getUnmappedByteBuffer()), false); + } + + void implTestDecodeCharBufferByteBufferUnmappedException(ByteBuffer in, + boolean endOfInput) throws CharacterCodingException, + UnsupportedEncodingException { + if (null == in) { + return; + } + CharBuffer out = CharBuffer.allocate(50); + + decoder.onMalformedInput(CodingErrorAction.REPORT); + decoder.reset(); + decoder.onUnmappableCharacter(CodingErrorAction.REPORT); + CoderResult result = decoder.decode(in, out, endOfInput); + assertTrue(result.isUnmappable()); + + decoder.reset(); + out.clear(); + in.rewind(); + decoder.onUnmappableCharacter(CodingErrorAction.IGNORE); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, endOfInput)); + assertCharBufferValue(getString(), out); + + decoder.reset(); + out.clear(); + in.rewind(); + decoder.onUnmappableCharacter(CodingErrorAction.REPLACE); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, endOfInput)); + assertCharBufferValue(decoder.replacement() + getString(), out); + } + + public void testDecodeCharBufferByteBufferMalformedException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferMalformedException( + getMalformedByteBuffer(), true); + } + + public void testDecodeCharBufferByteIncompleteBufferMalformedException() + throws CharacterCodingException, UnsupportedEncodingException { + + implTestDecodeCharBufferByteBufferMalformedException( + getMalformedByteBuffer(), false); + } + + public void testDecodeCharBufferByteReadOnlyBufferMalformedException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferMalformedException( + readOnly(getMalformedByteBuffer()), true); + } + + public void testDecodeCharBufferByteReadOnlyIncompleteBufferMalformedException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferMalformedException( + readOnly(getMalformedByteBuffer()), false); + } + + void implTestDecodeCharBufferByteBufferMalformedException(ByteBuffer in, + boolean endOfInput) throws CharacterCodingException, + UnsupportedEncodingException { + if (null == in) { + return; + } + CharBuffer out = CharBuffer.allocate(getString().length() * 3); + decoder.onUnmappableCharacter(CodingErrorAction.REPORT); + decoder.reset(); + decoder.onMalformedInput(CodingErrorAction.REPORT); + CoderResult result = decoder.decode(in, out, endOfInput); + assertTrue(result.isMalformed()); + + decoder.reset(); + out.clear(); + in.rewind(); + decoder.onMalformedInput(CodingErrorAction.IGNORE); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, endOfInput)); + assertCharBufferValue(getString(), out); + + decoder.reset(); + out.clear(); + in.rewind(); + decoder.onMalformedInput(CodingErrorAction.REPLACE); + assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, endOfInput)); + assertCharBufferValue(decoder.replacement() + getString(), out); + } + + public void testDecodeCharBufferByteBufferException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferException(getExceptionByteArray(), + true); + } + + public void testDecodeCharBufferByteIncompleteBufferException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferException(getExceptionByteArray(), + false); + } + + public void testDecodeCharBufferByteReadOnlyBufferException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferException( + readOnly(getExceptionByteArray()), true); + } + + public void testDecodeCharBufferByteReadOnlyIncompleteBufferException() + throws CharacterCodingException, UnsupportedEncodingException { + implTestDecodeCharBufferByteBufferException( + readOnly(getExceptionByteArray()), false); + } + + void implTestDecodeCharBufferByteBufferException(ByteBuffer in, + boolean endOfInput) throws CharacterCodingException, + UnsupportedEncodingException { + CharBuffer out = CharBuffer.allocate(50); + decoder.reset(); + try { + decoder.decode(in, out, endOfInput); + fail("should throw runtime exception"); + } catch (RuntimeException e) { + } + } + + private ByteBuffer readOnly(ByteBuffer b) { + if (null == b) { + return null; + } + return b.asReadOnlyBuffer(); + } + + protected String getString() { + return " buffer"; + } + + protected ByteBuffer getByteBuffer() { + return ByteBuffer.wrap(new byte[] { 32, 98, 117, 102, 102, 101, 114 }); + } + + protected ByteBuffer getHeadlessByteBuffer() { + return getByteBuffer(); + } + + ByteBuffer getExceptionByteArray() throws UnsupportedEncodingException { + // "runtime" + return ByteBuffer + .wrap(new byte[] { 114, 117, 110, 116, 105, 109, 101 }); + } + + ByteBuffer getUnmappedByteBuffer() throws UnsupportedEncodingException { + // "unmap buffer" + byte[] ba = new byte[] { 117, 110, 109, 97, 112, 32, 98, 117, 102, 102, + 101, 114 }; + return ByteBuffer.wrap(ba); + } + + ByteBuffer getMalformedByteBuffer() throws UnsupportedEncodingException { + // "malform buffer" + byte[] ba = new byte[] { 109, 97, 108, 102, 111, 114, 109, 32, 98, 117, + 102, 102, 101, 114 }; + return ByteBuffer.wrap(ba); + } + + private void assertCharBufferValue(String expected, CharBuffer out) { + if (out.position() != 0) { + out.flip(); + } + assertEquals(expected, new String(out.array(), out.arrayOffset(), out + .arrayOffset() + out.limit())); + } + + /* + * test flush + */ + public void testFlush() throws CharacterCodingException { + CharBuffer out = CharBuffer.allocate(10); + ByteBuffer in = ByteBuffer.wrap(new byte[] { 12, 12 }); + decoder.decode(in, out, true); + assertSame(CoderResult.UNDERFLOW, decoder.flush(out)); + + decoder.reset(); + decoder.decode((ByteBuffer) in.rewind(), (CharBuffer) out.rewind(), + true); + assertSame(CoderResult.UNDERFLOW, decoder + .flush(CharBuffer.allocate(10))); + } + + /* + * ---------------------------------- methods to test illegal state + * ----------------------------------- + */ + // Normal case: just after reset, and it also means reset can be done + // anywhere + public void testResetIllegalState() throws CharacterCodingException { + decoder.reset(); + decoder.decode(getByteBuffer()); + decoder.reset(); + decoder.decode(getByteBuffer(), CharBuffer.allocate(3), false); + decoder.reset(); + decoder.decode(getByteBuffer(), CharBuffer.allocate(3), true); + decoder.reset(); + } + + public void testFlushIllegalState() throws CharacterCodingException { + ByteBuffer in = ByteBuffer.wrap(new byte[] { 98, 98 }); + CharBuffer out = CharBuffer.allocate(5); + // Normal case: after decode with endOfInput is true + decoder.reset(); + decoder.decode(in, out, true); + out.rewind(); + CoderResult result = decoder.flush(out); + assertSame(result, CoderResult.UNDERFLOW); + + // Illegal state: flush twice + try { + decoder.flush(out); + fail("should throw IllegalStateException"); + } catch (IllegalStateException e) { + } + + // Illegal state: flush after decode with endOfInput is false + decoder.reset(); + decoder.decode(in, out, false); + try { + decoder.flush(out); + fail("should throw IllegalStateException"); + } catch (IllegalStateException e) { + } + } + + // test illegal states for decode facade + public void testDecodeFacadeIllegalState() throws CharacterCodingException { + // decode facade can be execute in anywhere + ByteBuffer in = getByteBuffer(); + + // Normal case: just created + decoder.decode(in); + in.rewind(); + + // Normal case: just after decode facade + decoder.decode(in); + in.rewind(); + + // Normal case: just after decode with that endOfInput is true + decoder.reset(); + decoder.decode(getByteBuffer(), CharBuffer.allocate(30), true); + decoder.decode(in); + in.rewind(); + + // Normal case:just after decode with that endOfInput is false + decoder.reset(); + decoder.decode(getByteBuffer(), CharBuffer.allocate(30), false); + decoder.decode(in); + in.rewind(); + + // Normal case: just after flush + decoder.reset(); + decoder.decode(getByteBuffer(), CharBuffer.allocate(30), true); + decoder.flush(CharBuffer.allocate(10)); + decoder.decode(in); + in.rewind(); + } + + // test illegal states for two decode method with endOfInput is true + public void testDecodeTrueIllegalState() throws CharacterCodingException { + ByteBuffer in = ByteBuffer.wrap(new byte[] { 98, 98 }); + CharBuffer out = CharBuffer.allocate(100); + // Normal case: just created + decoder.decode(in, out, true); + in.rewind(); + out.rewind(); + + // Normal case: just after decode with that endOfInput is true + decoder.reset(); + decoder.decode(in, CharBuffer.allocate(30), true); + in.rewind(); + decoder.decode(in, out, true); + in.rewind(); + out.rewind(); + + // Normal case:just after decode with that endOfInput is false + decoder.reset(); + decoder.decode(in, CharBuffer.allocate(30), false); + in.rewind(); + decoder.decode(in, out, true); + in.rewind(); + out.rewind(); + + // Illegal state: just after flush + decoder.reset(); + decoder.decode(in, CharBuffer.allocate(30), true); + decoder.flush(CharBuffer.allocate(10)); + in.rewind(); + try { + decoder.decode(in, out, true); + fail("should illegal state"); + } catch (IllegalStateException e) { + } + in.rewind(); + out.rewind(); + + } + + // test illegal states for two decode method with endOfInput is false + public void testDecodeFalseIllegalState() throws CharacterCodingException { + ByteBuffer in = ByteBuffer.wrap(new byte[] { 98, 98 }); + CharBuffer out = CharBuffer.allocate(5); + // Normal case: just created + decoder.decode(in, out, false); + in.rewind(); + out.rewind(); + + // Illegal state: just after decode facade + decoder.reset(); + decoder.decode(in); + in.rewind(); + try { + decoder.decode(in, out, false); + fail("should illegal state"); + } catch (IllegalStateException e) { + } + in.rewind(); + out.rewind(); + + // Illegal state: just after decode with that endOfInput is true + decoder.reset(); + decoder.decode(in, CharBuffer.allocate(30), true); + in.rewind(); + try { + decoder.decode(in, out, false); + fail("should illegal state"); + } catch (IllegalStateException e) { + } + in.rewind(); + out.rewind(); + + // Normal case:just after decode with that endOfInput is false + decoder.reset(); + decoder.decode(in, CharBuffer.allocate(30), false); + in.rewind(); + decoder.decode(in, out, false); + in.rewind(); + out.rewind(); + + // Illegal state: just after flush + decoder.reset(); + decoder.decode(in, CharBuffer.allocate(30), true); + in.rewind(); + decoder.flush(CharBuffer.allocate(10)); + try { + decoder.decode(in, out, false); + fail("should illegal state"); + } catch (IllegalStateException e) { + } + } + + /* + * --------------------------------- illegal state test end + * --------------------------------- + */ + + public void testImplFlush() { + decoder = new MockCharsetDecoder(cs, 1, 3); + assertEquals(CoderResult.UNDERFLOW, ((MockCharsetDecoder) decoder) + .pubImplFlush(null)); + } + + public void testImplOnMalformedInput() { + decoder = new MockCharsetDecoder(cs, 1, 3); + assertEquals(CoderResult.UNDERFLOW, ((MockCharsetDecoder) decoder) + .pubImplFlush(null)); + + } + + public void testImplOnUnmappableCharacter() { + decoder = new MockCharsetDecoder(cs, 1, 3); + ((MockCharsetDecoder) decoder).pubImplOnUnmappableCharacter(null); + } + + public void testImplReplaceWith() { + decoder = new MockCharsetDecoder(cs, 1, 3); + ((MockCharsetDecoder) decoder).pubImplReplaceWith(null); + } + + public void testImplReset() { + decoder = new MockCharsetDecoder(cs, 1, 3); + ((MockCharsetDecoder) decoder).pubImplReset(); + } + + /* + * mock decoder + */ + public static class MockCharsetDecoder extends CharsetDecoder { + public MockCharsetDecoder(Charset cs, float ave, float max) { + super(cs, ave, max); + } + + protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { + int inPosition = in.position(); + byte[] input = new byte[in.remaining()]; + in.get(input); + String result; + try { + result = new String(input, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } + if (result.startsWith("malform")) { + // reset the cursor to the error position + in.position(inPosition); + // set the error length + return CoderResult.malformedForLength("malform".length()); + } else if (result.startsWith("unmap")) { + // reset the cursor to the error position + in.position(inPosition); + // set the error length + return CoderResult.unmappableForLength("unmap".length()); + } else if (result.startsWith("runtime")) { + // reset the cursor to the error position + in.position(0); + // set the error length + throw new RuntimeException("runtime"); + } + int inLeft = input.length; + int outLeft = out.remaining(); + CoderResult r = CoderResult.UNDERFLOW; + int length = inLeft; + if (outLeft < inLeft) { + r = CoderResult.OVERFLOW; + length = outLeft; + in.position(inPosition + outLeft); + } + for (int i = 0; i < length; i++) { + out.put((char) input[i]); + } + return r; + } + + protected CoderResult implFlush(CharBuffer out) { + CoderResult result = super.implFlush(out); + if (out.remaining() >= 5) { + // TODO + // out.put("flush"); + result = CoderResult.UNDERFLOW; + } else { + // out.put("flush", 0, out.remaining()); + result = CoderResult.OVERFLOW; + } + return result; + } + + public CoderResult pubImplFlush(CharBuffer out) { + return super.implFlush(out); + } + + public void pubImplOnMalformedInput(CodingErrorAction newAction) { + super.implOnMalformedInput(newAction); + } + + public void pubImplOnUnmappableCharacter(CodingErrorAction newAction) { + super.implOnUnmappableCharacter(newAction); + } + + public void pubImplReplaceWith(String newReplacement) { + super.implReplaceWith(newReplacement); + } + + public void pubImplReset() { + super.implReset(); + } + + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetEncoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetEncoderTest.java new file mode 100644 index 0000000..e48c4ef --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetEncoderTest.java @@ -0,0 +1,1118 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderResult; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.MalformedInputException; +import java.nio.charset.UnmappableCharacterException; +import java.nio.charset.UnsupportedCharsetException; +import java.util.Arrays; + +import junit.framework.TestCase; + +/** + * API unit test for java.nio.charset.CharsetEncoder + */ +public class CharsetEncoderTest extends TestCase { + + static final int MAX_BYTES = 3; + + static final float AVER_BYTES = 0.5f; + + // charset for mock class + private static final Charset MOCKCS = new MockCharset("CharsetEncoderTest_mock", new String[0]); + + Charset cs = MOCKCS; + + // default encoder + CharsetEncoder encoder; + + // default for Charset abstract class + byte[] defaultReplacement = new byte[] { 63 }; + + // specific for Charset implementation subclass + byte[] specifiedReplacement = new byte[] { 63 }; + + static final String unistr = " buffer";// \u8000\u8001\u00a5\u3000\r\n"; + + byte[] unibytes = new byte[] { 32, 98, 117, 102, 102, 101, 114 }; + + byte[] unibytesWithRep = null; + + byte[] surrogate = new byte[0]; + + protected void setUp() throws Exception { + super.setUp(); + encoder = cs.newEncoder(); + if (null == unibytesWithRep) { + byte[] replacement = encoder.replacement(); + unibytesWithRep = new byte[replacement.length + unibytes.length]; + System.arraycopy(replacement, 0, unibytesWithRep, 0, + replacement.length); + System.arraycopy(unibytes, 0, unibytesWithRep, replacement.length, + unibytes.length); + } + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testSpecificDefaultValue() { + assertTrue(encoder.averageBytesPerChar() == AVER_BYTES); + assertTrue(encoder.maxBytesPerChar() == MAX_BYTES); + } + + public void testDefaultValue() { + assertEquals(CodingErrorAction.REPORT, encoder.malformedInputAction()); + assertEquals(CodingErrorAction.REPORT, encoder + .unmappableCharacterAction()); + assertSame(encoder, encoder.onMalformedInput(CodingErrorAction.IGNORE)); + assertSame(encoder, encoder + .onUnmappableCharacter(CodingErrorAction.IGNORE)); + if (encoder instanceof MockCharsetEncoder) { + assertTrue(Arrays.equals(encoder.replacement(), defaultReplacement)); + } else { + assertTrue(Arrays.equals(encoder.replacement(), + specifiedReplacement)); + } + + } + + /* + * Class under test for constructor CharsetEncoder(Charset, float, float) + */ + public void testCharsetEncoderCharsetfloatfloat() { + // default value + encoder = new MockCharsetEncoder(cs, (float) AVER_BYTES, MAX_BYTES); + assertSame(encoder.charset(), cs); + assertTrue(encoder.averageBytesPerChar() == AVER_BYTES); + assertTrue(encoder.maxBytesPerChar() == MAX_BYTES); + assertEquals(CodingErrorAction.REPORT, encoder.malformedInputAction()); + assertEquals(CodingErrorAction.REPORT, encoder + .unmappableCharacterAction()); + assertEquals(new String(encoder.replacement()), new String( + defaultReplacement)); + assertSame(encoder, encoder.onMalformedInput(CodingErrorAction.IGNORE)); + assertSame(encoder, encoder + .onUnmappableCharacter(CodingErrorAction.IGNORE)); + + // normal case + CharsetEncoder ec = new MockCharsetEncoder(cs, 1, MAX_BYTES); + assertSame(ec.charset(), cs); + assertEquals(1.0, ec.averageBytesPerChar(), 0); + assertTrue(ec.maxBytesPerChar() == MAX_BYTES); + + /* + * ------------------------ Exceptional cases ------------------------- + */ + // NullPointerException: null charset + try { + ec = new MockCharsetEncoder(null, 1, MAX_BYTES); + fail("should throw null pointer exception"); + } catch (NullPointerException e) { + } + + ec = new MockCharsetEncoder(new MockCharset("mock", new String[0]), 1, + MAX_BYTES); + + // Commented out since the comment is wrong since MAX_BYTES > 1 + // // OK: average length less than max length + // ec = new MockCharsetEncoder(cs, MAX_BYTES, 1); + // assertTrue(ec.averageBytesPerChar() == MAX_BYTES); + // assertTrue(ec.maxBytesPerChar() == 1); + + // Illegal Argument: zero length + try { + ec = new MockCharsetEncoder(cs, 0, MAX_BYTES); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + try { + ec = new MockCharsetEncoder(cs, 1, 0); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + + // Illegal Argument: negative length + try { + ec = new MockCharsetEncoder(cs, -1, MAX_BYTES); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + try { + ec = new MockCharsetEncoder(cs, 1, -1); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + } + + /* + * Class under test for constructor CharsetEncoder(Charset, float, float, + * byte[]) + */ + public void testCharsetEncoderCharsetfloatfloatbyteArray() { + byte[] ba = getLegalByteArray(); + // normal case + CharsetEncoder ec = new MockCharsetEncoder(cs, 1, MAX_BYTES, ba); + assertSame(ec.charset(), cs); + assertEquals(1.0, ec.averageBytesPerChar(), 0.0); + assertTrue(ec.maxBytesPerChar() == MAX_BYTES); + assertSame(ba, ec.replacement()); + + /* + * ------------------------ Exceptional cases ------------------------- + */ + // NullPointerException: null charset + try { + ec = new MockCharsetEncoder(null, 1, MAX_BYTES, ba); + fail("should throw null pointer exception"); + } catch (NullPointerException e) { + } + + // Illegal Argument: null byte array + try { + ec = new MockCharsetEncoder(cs, 1, MAX_BYTES, null); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + // Illegal Argument: empty byte array + try { + ec = new MockCharsetEncoder(cs, 1, MAX_BYTES, new byte[0]); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + // Illegal Argument: byte array is longer than max length + try { + ec = new MockCharsetEncoder(cs, 1, MAX_BYTES, new byte[] { 1, 2, + MAX_BYTES, 4 }); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + + // Commented out since the comment is wrong since MAX_BYTES > 1 + // This test throws IllegalArgumentException on Harmony and RI + // // OK: average length less than max length + // ec = new MockCharsetEncoder(cs, MAX_BYTES, ba.length, ba); + // assertTrue(ec.averageBytesPerChar() == MAX_BYTES); + // assertTrue(ec.maxBytesPerChar() == ba.length); + + // Illegal Argument: zero length + try { + ec = new MockCharsetEncoder(cs, 0, MAX_BYTES, ba); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + try { + ec = new MockCharsetEncoder(cs, 1, 0, ba); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + + // Illegal Argument: negative length + try { + ec = new MockCharsetEncoder(cs, -1, MAX_BYTES, ba); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + try { + ec = new MockCharsetEncoder(cs, 1, -1, ba); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + } + + /* + * Class under test for boolean canEncode(char) + */ + public void testCanEncodechar() throws CharacterCodingException { + // for non-mapped char + assertTrue(encoder.canEncode('\uc2c0')); + // surrogate char for unicode + // 1st byte: d800-dbff + // 2nd byte: dc00-dfff + assertTrue(encoder.canEncode('\ud800')); + // valid surrogate pair + assertTrue(encoder.canEncode('\udc00')); + } + + /*----------------------------------------- + * Class under test for illegal state case + * methods which can change internal states are two encode, flush, two canEncode, reset + * ----------------------------------------- + */ + + // Normal case: just after reset, and it also means reset can be done + // anywhere + public void testResetIllegalState() throws CharacterCodingException { + assertSame(encoder, encoder.reset()); + encoder.canEncode('\ud901'); + assertSame(encoder, encoder.reset()); + encoder.canEncode("\ud901\udc00"); + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("aaa")); + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("aaa"), ByteBuffer.allocate(3), false); + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("aaa"), ByteBuffer.allocate(3), true); + assertSame(encoder, encoder.reset()); + } + + public void testFlushIllegalState() throws CharacterCodingException { + CharBuffer in = CharBuffer.wrap("aaa"); + ByteBuffer out = ByteBuffer.allocate(5); + + // Normal case: after encode with endOfInput is true + assertSame(encoder, encoder.reset()); + encoder.encode(in, out, true); + out.rewind(); + CoderResult result = encoder.flush(out); + + // Illegal state: flush twice + try { + encoder.flush(out); + fail("should throw IllegalStateException"); + } catch (IllegalStateException e) { + // Expected + } + + // Illegal state: flush after encode with endOfInput is false + assertSame(encoder, encoder.reset()); + encoder.encode(in, out, false); + try { + encoder.flush(out); + fail("should throw IllegalStateException"); + } catch (IllegalStateException e) { + // Expected + } + } + + public void testFlushAfterConstructing() { + ByteBuffer out = ByteBuffer.allocate(5); + + //Illegal state: flush after instance created + try { + encoder.flush(out); + fail("should throw IllegalStateException"); + } catch (IllegalStateException e) { + // Expected + } + + } + + // test illegal states for encode facade + public void testEncodeFacadeIllegalState() throws CharacterCodingException { + // encode facade can be execute in anywhere + CharBuffer in = CharBuffer.wrap("aaa"); + // Normal case: just created + encoder.encode(in); + in.rewind(); + + // Normal case: just after encode facade + encoder.encode(in); + in.rewind(); + + // Normal case: just after canEncode + assertSame(encoder, encoder.reset()); + encoder.canEncode("\ud902\udc00"); + encoder.encode(in); + in.rewind(); + assertSame(encoder, encoder.reset()); + encoder.canEncode('\ud902'); + encoder.encode(in); + in.rewind(); + + // Normal case: just after encode with that endOfInput is true + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"), + ByteBuffer.allocate(30), true); + encoder.encode(in); + in.rewind(); + + // Normal case:just after encode with that endOfInput is false + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"), + ByteBuffer.allocate(30), false); + encoder.encode(in); + in.rewind(); + + // Normal case: just after flush + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"), + ByteBuffer.allocate(30), true); + encoder.flush(ByteBuffer.allocate(10)); + encoder.encode(in); + in.rewind(); + } + + // test illegal states for two encode method with endOfInput is true + public void testEncodeTrueIllegalState() throws CharacterCodingException { + CharBuffer in = CharBuffer.wrap("aaa"); + ByteBuffer out = ByteBuffer.allocate(5); + // Normal case: just created + encoder.encode(in, out, true); + in.rewind(); + out.rewind(); + + in.rewind(); + out.rewind(); + + // Normal case: just after encode with that endOfInput is true + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"), + ByteBuffer.allocate(30), true); + encoder.encode(in, out, true); + in.rewind(); + out.rewind(); + + // Normal case:just after encode with that endOfInput is false + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"), + ByteBuffer.allocate(30), false); + encoder.encode(in, out, true); + in.rewind(); + out.rewind(); + + // Illegal state: just after flush + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"), + ByteBuffer.allocate(30), true); + encoder.flush(ByteBuffer.allocate(10)); + try { + encoder.encode(in, out, true); + fail("should illegal state"); + } catch (IllegalStateException e) { + } + + // Normal case: after canEncode + assertSame(encoder, encoder.reset()); + encoder.canEncode("\ud906\udc00"); + encoder.encode(in, out, true); + in.rewind(); + out.rewind(); + assertSame(encoder, encoder.reset()); + encoder.canEncode('\ud905'); + encoder.encode(in, out, true); + } + + // test illegal states for two encode method with endOfInput is false + public void testEncodeFalseIllegalState() throws CharacterCodingException { + CharBuffer in = CharBuffer.wrap("aaa"); + ByteBuffer out = ByteBuffer.allocate(5); + // Normal case: just created + encoder.encode(in, out, false); + in.rewind(); + out.rewind(); + + // Illegal state: just after encode facade + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState1")); + try { + encoder.encode(in, out, false); + fail("should illegal state"); + } catch (IllegalStateException e) { + } + + // Illegal state: just after encode with that endOfInput is true + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"), + ByteBuffer.allocate(30), true); + try { + encoder.encode(in, out, false); + fail("should illegal state"); + } catch (IllegalStateException e) { + } + + // Normal case:just after encode with that endOfInput is false + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"), + ByteBuffer.allocate(30), false); + encoder.encode(in, out, false); + in.rewind(); + out.rewind(); + + // Illegal state: just after flush + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"), + ByteBuffer.allocate(30), true); + encoder.flush(ByteBuffer.allocate(10)); + try { + encoder.encode(in, out, false); + fail("should illegal state"); + } catch (IllegalStateException e) { + } + + // Normal case: after canEncode + assertSame(encoder, encoder.reset()); + encoder.canEncode("\ud906\udc00"); + encoder.encode(in, out, false); + in.rewind(); + out.rewind(); + assertSame(encoder, encoder.reset()); + encoder.canEncode('\ud905'); + encoder.encode(in, out, false); + } + + // test illegal states for two canEncode methods + public void testCanEncodeIllegalState() throws CharacterCodingException { + // Normal case: just created + encoder.canEncode("\ud900\udc00"); + encoder.canEncode('\ud900'); + + // Illegal state: just after encode with that endOfInput is true + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"), + ByteBuffer.allocate(30), true); + try { + encoder.canEncode("\ud903\udc00"); + fail("should throw illegal state exception"); + } catch (IllegalStateException e) { + } + + // Illegal state:just after encode with that endOfInput is false + assertSame(encoder, encoder.reset()); + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"), + ByteBuffer.allocate(30), false); + try { + encoder.canEncode("\ud904\udc00"); + fail("should throw illegal state exception"); + } catch (IllegalStateException e) { + } + + // Normal case: just after flush + encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"), + ByteBuffer.allocate(30), true); + encoder.flush(ByteBuffer.allocate(10)); + encoder.canEncode("\ud905\udc00"); + encoder.canEncode('\ud906'); + + // Normal case: after reset again + assertSame(encoder, encoder.reset()); + encoder.canEncode("\ud906\udc00"); + encoder.canEncode('\ud905'); + } + + /* + * --------------------------------- illegal state test end + * --------------------------------- + */ + + /* + * Class under test for boolean canEncode(CharSequence) + */ + public void testCanEncodeCharSequence() { + // for non-mapped char + assertTrue(encoder.canEncode("\uc2c0")); + // surrogate char for unicode + // 1st byte: d800-dbff + // 2nd byte: dc00-dfff + assertTrue(encoder.canEncode("\ud800")); + // valid surrogate pair + assertTrue(encoder.canEncode("\ud800\udc00")); + // invalid surrogate pair + assertTrue(encoder.canEncode("\ud800\udb00")); + } + + /* + * Class under test for Charset charset() + */ + public void testCharset() { + try { + encoder = new MockCharsetEncoder(Charset.forName("gbk"), 1, + MAX_BYTES); + // assertSame(encoder.charset(), Charset.forName("gbk")); + } catch (UnsupportedCharsetException e) { + System.err + .println("Don't support GBK encoding, ignore current test"); + } + } + + /* + * Class under test for ByteBuffer encode(CharBuffer) + */ + public void testEncodeCharBuffer() throws CharacterCodingException { + // Null pointer + try { + encoder.encode(null); + fail("should throw null pointer exception"); + } catch (NullPointerException e) { + } + + // empty input buffer + ByteBuffer out = encoder.encode(CharBuffer.wrap("")); + assertEquals(out.position(), 0); + assertByteArray(out, new byte[0]); + // assertByteArray(out, surrogate); + + // normal case + out = encoder.encode(CharBuffer.wrap(unistr)); + assertEquals(out.position(), 0); + assertByteArray(out, addSurrogate(unibytes)); + + // Regression test for harmony-3378 + Charset cs = Charset.forName("UTF-8"); + CharsetEncoder encoder = cs.newEncoder(); + encoder.onMalformedInput(CodingErrorAction.REPLACE); + encoder = encoder.replaceWith(new byte[] { (byte) 0xef, (byte) 0xbf, + (byte) 0xbd, }); + CharBuffer in = CharBuffer.wrap("\ud800"); + out = encoder.encode(in); + assertNotNull(out); + } + + private byte[] addSurrogate(byte[] expected) { + if (surrogate.length > 0) { + byte[] temp = new byte[surrogate.length + expected.length]; + System.arraycopy(surrogate, 0, temp, 0, surrogate.length); + System.arraycopy(expected, 0, temp, surrogate.length, + expected.length); + expected = temp; + } + return expected; + } + + /** + * @return + */ + protected byte[] getEmptyByteArray() { + return new byte[0]; + } + + CharBuffer getMalformedCharBuffer() { + return CharBuffer.wrap("malform buffer"); + } + + CharBuffer getUnmapCharBuffer() { + return CharBuffer.wrap("unmap buffer"); + } + + CharBuffer getExceptionCharBuffer() { + return CharBuffer.wrap("runtime buffer"); + } + + public void testEncodeCharBufferException() throws CharacterCodingException { + ByteBuffer out; + CharBuffer in; + // MalformedException: + in = getMalformedCharBuffer(); + encoder.onMalformedInput(CodingErrorAction.REPORT); + encoder.onUnmappableCharacter(CodingErrorAction.REPORT); + if (in != null) { + try { + // regression test for Harmony-1379 + encoder.encode(in); + fail("should throw MalformedInputException"); + } catch (MalformedInputException e) { + } + + encoder.reset(); + in.rewind(); + encoder.onMalformedInput(CodingErrorAction.IGNORE); + out = encoder.encode(in); + assertByteArray(out, addSurrogate(unibytes)); + + encoder.reset(); + in.rewind(); + encoder.onMalformedInput(CodingErrorAction.REPLACE); + out = encoder.encode(in); + assertByteArray(out, addSurrogate(unibytesWithRep)); + } + + // Unmapped Exception: + in = getUnmapCharBuffer(); + encoder.onMalformedInput(CodingErrorAction.REPORT); + encoder.onUnmappableCharacter(CodingErrorAction.REPORT); + if (in != null) { + encoder.reset(); + try { + encoder.encode(in); + fail("should throw UnmappableCharacterException"); + } catch (UnmappableCharacterException e) { + } + + encoder.reset(); + in.rewind(); + encoder.onUnmappableCharacter(CodingErrorAction.IGNORE); + out = encoder.encode(in); + assertByteArray(out, unibytes); + + encoder.reset(); + in.rewind(); + encoder.onUnmappableCharacter(CodingErrorAction.REPLACE); + out = encoder.encode(in); + assertByteArray(out, unibytesWithRep); + } + + // RuntimeException + try { + encoder.encode(getExceptionCharBuffer()); + fail("should throw runtime exception"); + } catch (RuntimeException e) { + } + } + + /* + * utility method, extract given bytebuffer to a string and compare with + * give string + */ + void assertByteArray(ByteBuffer out, byte[] expected) { + out = out.duplicate(); + if (out.position() != 0) { + out.flip(); + } + byte[] ba = new byte[out.limit() - out.position()]; + out.get(ba); + // byte[] ba = out.array(); + assertTrue(Arrays.equals(ba, expected)); + } + + /* + * Class under test for CoderResult encode(CharBuffer, ByteBuffer, boolean) + */ + public void testEncodeCharBufferByteBufferboolean() + throws CharacterCodingException { + ByteBuffer out = ByteBuffer.allocate(200); + CharBuffer in = CharBuffer.wrap(unistr); + // Null pointer + try { + encoder.encode(null, out, true); + fail("should throw null pointer exception"); + } catch (NullPointerException e) { + } + try { + encoder.encode(in, null, true); + fail("should throw null pointer exception"); + } catch (NullPointerException e) { + } + + // normal case, one complete operation + assertSame(encoder, encoder.reset()); + in.rewind(); + out.rewind(); + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true)); + assertEquals(out.limit(), 200); + assertTrue(out.position() > 0); + assertTrue(out.remaining() > 0); + assertEquals(out.capacity(), 200); + assertByteArray(out, addSurrogate(unibytes)); + in.rewind(); + + encoder.flush(out); + + // normal case, one complete operation, but call twice, first time set + // endOfInput to false + assertSame(encoder, encoder.reset()); + in.rewind(); + out = ByteBuffer.allocate(200); + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, false)); + assertEquals(out.limit(), 200); + assertTrue(out.position() > 0); + assertTrue(out.remaining() > 0); + assertEquals(out.capacity(), 200); + assertByteArray(out, addSurrogate(unibytes)); + + in.rewind(); + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, false)); + in.rewind(); + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true)); + assertEquals(out.limit(), 200); + assertTrue(out.position() > 0); + assertTrue(out.remaining() > 0); + assertEquals(out.capacity(), 200); + + assertByteArray(out, addSurrogate(duplicateByteArray(unibytes, 3))); + + // overflow + out = ByteBuffer.allocate(4); + assertSame(encoder, encoder.reset()); + in.rewind(); + out.rewind(); + assertSame(CoderResult.OVERFLOW, encoder.encode(in, out, true)); + assertEquals(out.limit(), 4); + assertEquals(out.position(), 4); + assertEquals(out.remaining(), 0); + assertEquals(out.capacity(), 4); + ByteBuffer temp = ByteBuffer.allocate(200); + out.flip(); + temp.put(out); + out = temp; + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true)); + assertEquals(out.limit(), 200); + assertTrue(out.position() > 0); + assertTrue(out.remaining() > 0); + assertEquals(out.capacity(), 200); + assertByteArray(out, addSurrogate(unibytes)); + + assertSame(encoder, encoder.reset()); + in.rewind(); + out = ByteBuffer.allocate(4); + assertSame(CoderResult.OVERFLOW, encoder.encode(in, out, false)); + assertEquals(out.limit(), 4); + assertEquals(out.position(), 4); + assertEquals(out.remaining(), 0); + assertEquals(out.capacity(), 4); + temp = ByteBuffer.allocate(200); + out.flip(); + temp.put(out); + out = temp; + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, false)); + assertEquals(out.limit(), 200); + assertTrue(out.position() > 0); + assertTrue(out.remaining() > 0); + assertEquals(out.capacity(), 200); + assertByteArray(out, addSurrogate(unibytes)); + } + + void printByteBuffer(ByteBuffer buffer) { + System.out.println("print buffer"); + if (buffer.position() != 0) { + buffer.flip(); + } + byte[] ba = buffer.array(); + for (int i = 0; i < ba.length; i++) { + System.out.println(Integer.toHexString(ba[i])); + } + } + + public void testEncodeCharBufferByteBufferbooleanExceptionFalse() + throws CharacterCodingException { + implTestEncodeCharBufferByteBufferbooleanException(false); + } + + public void testEncodeCharBufferByteBufferbooleanExceptionTrue() + throws CharacterCodingException { + implTestEncodeCharBufferByteBufferbooleanException(true); + } + + private byte[] duplicateByteArray(byte[] ba, int times) { + byte[] result = new byte[ba.length * times]; + for (int i = 0; i < times; i++) { + System.arraycopy(ba, 0, result, i * ba.length, ba.length); + } + return result; + } + + protected void implTestEncodeCharBufferByteBufferbooleanException( + boolean endOfInput) throws CharacterCodingException { + ByteBuffer out = ByteBuffer.allocate(100); + + // MalformedException: + CharBuffer in = getMalformedCharBuffer(); + encoder.onMalformedInput(CodingErrorAction.REPORT); + encoder.onUnmappableCharacter(CodingErrorAction.REPORT); + if (in != null) { + encoder.reset(); + CoderResult r = encoder.encode(in, out, endOfInput); + assertTrue(r.isMalformed()); + + encoder.reset(); + out.clear(); + in.rewind(); + encoder.onMalformedInput(CodingErrorAction.IGNORE); + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, + endOfInput)); + assertCodingErrorAction(endOfInput, out, in, unibytes); + + encoder.reset(); + out.clear(); + in.rewind(); + encoder.onMalformedInput(CodingErrorAction.REPLACE); + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, + endOfInput)); + assertCodingErrorAction(endOfInput, out, in, unibytesWithRep); + } else { + System.out.println("Cannot find malformed char buffer for " + + cs.name()); + } + + // Unmapped Exception: + in = getUnmapCharBuffer(); + encoder.onMalformedInput(CodingErrorAction.REPORT); + encoder.onUnmappableCharacter(CodingErrorAction.REPORT); + if (in != null) { + encoder.reset(); + out.clear(); + assertTrue(encoder.encode(in, out, endOfInput).isUnmappable()); + + encoder.reset(); + out.clear(); + in.rewind(); + encoder.onUnmappableCharacter(CodingErrorAction.IGNORE); + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, + endOfInput)); + assertCodingErrorAction(endOfInput, out, in, unibytes); + + encoder.reset(); + out.clear(); + in.rewind(); + encoder.onUnmappableCharacter(CodingErrorAction.REPLACE); + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, + endOfInput)); + assertCodingErrorAction(endOfInput, out, in, unibytesWithRep); + } else { + System.out.println("Cannot find unmapped char buffer for " + + cs.name()); + } + + // RuntimeException + try { + encoder.encode(getExceptionCharBuffer()); + fail("should throw runtime exception"); + } catch (RuntimeException e) { + } + } + + private void assertCodingErrorAction(boolean endOfInput, ByteBuffer out, + CharBuffer in, byte[] expect) { + if (endOfInput) { + assertByteArray(out, addSurrogate(expect)); + } else { + in.rewind(); + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, + endOfInput)); + in.rewind(); + assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true)); + assertByteArray(out, addSurrogate(duplicateByteArray(expect, 3))); + } + } + + /* + * Class under test for CoderResult flush(ByteBuffer) + */ + public void testFlush() throws CharacterCodingException { + ByteBuffer out = ByteBuffer.allocate(6); + CharBuffer in = CharBuffer.wrap("aaa"); + assertEquals(in.remaining(), 3); + + // by encode facade, so that internal state will be wrong + encoder.encode(CharBuffer.wrap("testFlush"), ByteBuffer.allocate(20), + true); + assertSame(CoderResult.UNDERFLOW, encoder + .flush(ByteBuffer.allocate(50))); + } + + /* + * test isLegalReplacement(byte[]) + */ + public void testIsLegalReplacement() { + try { + encoder.isLegalReplacement(null); + fail("should throw null pointer exception"); + } catch (NullPointerException e) { + } + assertTrue(encoder.isLegalReplacement(specifiedReplacement)); + + assertTrue(encoder.isLegalReplacement(new byte[200])); + byte[] ba = getIllegalByteArray(); + if (ba != null) { + assertFalse(encoder.isLegalReplacement(ba)); + } + } + + public void testIsLegalReplacementEmptyArray() { + // ISO, ASC, GB, UTF8 encoder will throw exception in RI + // others will pass + // try { + assertTrue(encoder.isLegalReplacement(new byte[0])); + // fail("should throw ArrayIndexOutOfBoundsException"); + // } catch (ArrayIndexOutOfBoundsException e) { + // } + } + + public void testOnMalformedInput() { + assertSame(CodingErrorAction.REPORT, encoder.malformedInputAction()); + try { + encoder.onMalformedInput(null); + fail("should throw null pointer exception"); + } catch (IllegalArgumentException e) { + } + encoder.onMalformedInput(CodingErrorAction.IGNORE); + assertSame(CodingErrorAction.IGNORE, encoder.malformedInputAction()); + } + + public void testOnUnmappableCharacter() { + assertSame(CodingErrorAction.REPORT, encoder + .unmappableCharacterAction()); + try { + encoder.onUnmappableCharacter(null); + fail("should throw null pointer exception"); + } catch (IllegalArgumentException e) { + } + encoder.onUnmappableCharacter(CodingErrorAction.IGNORE); + assertSame(CodingErrorAction.IGNORE, encoder + .unmappableCharacterAction()); + } + + public void testReplacement() { + try { + encoder.replaceWith(null); + fail("should throw null pointer exception"); + } catch (IllegalArgumentException e) { + } + try { + encoder.replaceWith(new byte[0]); + fail("should throw null pointer exception"); + } catch (IllegalArgumentException e) { + } + try { + encoder.replaceWith(new byte[100]); + fail("should throw null pointer exception"); + } catch (IllegalArgumentException e) { + } + + byte[] nr = getLegalByteArray(); + assertSame(encoder, encoder.replaceWith(nr)); + assertSame(nr, encoder.replacement()); + + nr = getIllegalByteArray(); + try { + encoder.replaceWith(new byte[100]); + fail("should throw null pointer exception"); + } catch (IllegalArgumentException e) { + } + } + + protected byte[] getLegalByteArray() { + return new byte[] { 'a' }; + } + + protected byte[] getIllegalByteArray() { + return new byte[155]; + } + + /* + * Mock subclass of CharsetEncoder For protected method test + */ + public static class MockCharsetEncoder extends CharsetEncoder { + + boolean flushed = false; + + public boolean isFlushed() { + boolean result = flushed; + flushed = false; + return result; + } + + public boolean isLegalReplacement(byte[] ba) { + if (ba.length == 155) {// specified magic number, return false + return false; + } + return super.isLegalReplacement(ba); + } + + public MockCharsetEncoder(Charset cs, float aver, float max) { + super(cs, aver, max); + } + + public MockCharsetEncoder(Charset cs, float aver, float max, + byte[] replacement) { + super(cs, aver, max, replacement); + } + + protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { + int inPosition = in.position(); + char[] input = new char[in.remaining()]; + in.get(input); + String result = new String(input); + if (result.startsWith("malform")) { + // reset the cursor to the error position + in.position(inPosition); + // in.position(0); + // set the error length + return CoderResult.malformedForLength("malform".length()); + } else if (result.startsWith("unmap")) { + // reset the cursor to the error position + in.position(inPosition); + // in.position(0); + // set the error length + return CoderResult.unmappableForLength("unmap".length()); + } else if (result.startsWith("runtime")) { + // reset the cursor to the error position + in.position(0); + // set the error length + throw new RuntimeException("runtime"); + } + int inLeft = input.length; + int outLeft = out.remaining(); + CoderResult r = CoderResult.UNDERFLOW; + int length = inLeft; + if (outLeft < inLeft) { + r = CoderResult.OVERFLOW; + length = outLeft; + in.position(inPosition + outLeft); + } + for (int i = 0; i < length; i++) { + out.put((byte) input[i]); + } + return r; + } + + protected CoderResult implFlush(ByteBuffer out) { + CoderResult result = super.implFlush(out); + int length = 0; + if (out.remaining() >= 5) { + length = 5; + result = CoderResult.UNDERFLOW; + flushed = true; + // for (int i = 0; i < length; i++) { + // out.put((byte)'f'); + // } + } else { + length = out.remaining(); + result = CoderResult.OVERFLOW; + } + return result; + } + + protected void implReplaceWith(byte[] ba) { + assertSame(ba, replacement()); + } + + } + + /* + * mock charset for test encoder initialization + */ + public static class MockCharset extends Charset { + protected MockCharset(String arg0, String[] arg1) { + super(arg0, arg1); + } + + public boolean contains(Charset arg0) { + return false; + } + + public CharsetDecoder newDecoder() { + return new CharsetDecoderTest.MockCharsetDecoder(this, + (float) AVER_BYTES, MAX_BYTES); + } + + public CharsetEncoder newEncoder() { + return new MockCharsetEncoder(this, (float) AVER_BYTES, MAX_BYTES); + } + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetProviderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetProviderTest.java new file mode 100644 index 0000000..06d4f20 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetProviderTest.java @@ -0,0 +1,409 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.Charset; +import java.nio.charset.UnsupportedCharsetException; +import java.nio.charset.spi.CharsetProvider; +import java.util.Iterator; +import java.util.Vector; + +import junit.framework.TestCase; +import tests.api.java.nio.charset.CharsetTest.MockCharset; + +/** + * Test charset providers managed by Charset. + */ +public class CharsetProviderTest extends TestCase { + + // need to be modified, e.g., read from system property + static String PROP_CONFIG_FILE1 = "clear.tests.cp1"; + + static String CONFIG_FILE1 = null; + + + static MockCharset charset1 = new MockCharset("mockCharset00", + new String[] { "mockCharset01", "mockCharset02" }); + + static MockCharset charset2 = new MockCharset("mockCharset10", + new String[] { "mockCharset11", "mockCharset12" }); + + /** + * @param arg0 + */ + public CharsetProviderTest(String arg0) { + super(arg0); + CONFIG_FILE1 = System.getProperty("user.dir") + "/resources"; + + String sep = System.getProperty("file.separator"); + + if (!CONFIG_FILE1.endsWith(sep)) { + CONFIG_FILE1 += sep; + } + CONFIG_FILE1 += "META-INF" + sep + "services" + sep + + "java.nio.charset.spi.CharsetProvider"; + } + + /* + * Write the string to the config file. + */ + private void setupFile(String path, String content) throws Exception { + String sep = System.getProperty("file.separator"); + int sepIndex = path.lastIndexOf(sep); + File f = new File(path.substring(0, sepIndex)); + f.mkdirs(); + + FileOutputStream fos = new FileOutputStream(path); + OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8"); + try { + writer.write(content); + } finally { + writer.close(); + } + } + + /* + * Write the string to the config file. + */ + private void cleanupFile(String path) throws Exception { + File f = new File(path); + f.delete(); + } + + /* + * Test the method isSupported(String) with charset supported by some + * providers (multiple). + */ + public void testIsSupported_And_ForName_NormalProvider() throws Exception { + try { + assertFalse(Charset.isSupported("mockCharset10")); + assertFalse(Charset.isSupported("mockCharset11")); + assertFalse(Charset.isSupported("mockCharset12")); + try { + Charset.forName("mockCharset10"); + fail("Should throw UnsupportedCharsetException!"); + } catch (UnsupportedCharsetException e) { + // expected + } + try { + Charset.forName("mockCharset11"); + fail("Should throw UnsupportedCharsetException!"); + } catch (UnsupportedCharsetException e) { + // expected + } + try { + Charset.forName("mockCharset12"); + fail("Should throw UnsupportedCharsetException!"); + } catch (UnsupportedCharsetException e) { + // expected + } + + StringBuffer sb = new StringBuffer(); + sb.append("#comment\r"); + sb.append("\n"); + sb.append("\r\n"); + sb + .append(" \ttests.api.java.nio.charset.CharsetTest$MockCharsetProvider \t\n\r"); + sb + .append(" \ttests.api.java.nio.charset.CharsetTest$MockCharsetProvider \t"); + setupFile(CONFIG_FILE1, sb.toString()); + + sb = new StringBuffer(); + sb.append(" #comment\r"); + sb.append("\n"); + sb.append("\r\n"); + sb + .append(" \ttests.api.java.nio.charset.CharsetProviderTest$MockCharsetProvider \t\n\r"); + setupFile(CONFIG_FILE1, sb.toString()); + + assertTrue(Charset.isSupported("mockCharset10")); + // ignore case problem in mock, intended + assertTrue(Charset.isSupported("MockCharset11")); + assertTrue(Charset.isSupported("MockCharset12")); + assertTrue(Charset.isSupported("MOCKCharset10")); + // intended case problem in mock + assertTrue(Charset.isSupported("MOCKCharset11")); + assertTrue(Charset.isSupported("MOCKCharset12")); + + assertTrue(Charset.forName("mockCharset10") instanceof MockCharset); + assertTrue(Charset.forName("mockCharset11") instanceof MockCharset); + assertTrue(Charset.forName("mockCharset12") instanceof MockCharset); + + assertTrue(Charset.forName("mockCharset10") == charset2); + // intended case problem in mock + Charset.forName("mockCharset11"); + assertTrue(Charset.forName("mockCharset12") == charset2); + } finally { + cleanupFile(CONFIG_FILE1); + } + } + + /* + * Test the method isSupported(String) when the configuration file contains + * a non-existing class name. + */ + public void testIsSupported_NonExistingClass() throws Exception { + try { + StringBuffer sb = new StringBuffer(); + sb.append("impossible\r"); + setupFile(CONFIG_FILE1, sb.toString()); + + Charset.isSupported("impossible"); + fail("Should throw Error!"); + } catch (Error e) { + // expected + } finally { + cleanupFile(CONFIG_FILE1); + } + } + + /* + * Test the method isSupported(String) when the configuration file contains + * a non-CharsetProvider class name. + */ + public void testIsSupported_NotCharsetProviderClass() throws Exception { + try { + StringBuffer sb = new StringBuffer(); + sb.append("java.lang.String\r"); + setupFile(CONFIG_FILE1, sb.toString()); + + Charset.isSupported("impossible"); + fail("Should throw ClassCastException!"); + } catch (ClassCastException e) { + // expected + } finally { + cleanupFile(CONFIG_FILE1); + } + } + + /* + * Test the method forName(String) when the charset provider supports a + * built-in charset. + */ + public void testForName_DuplicateWithBuiltInCharset() throws Exception { + try { + StringBuffer sb = new StringBuffer(); + sb + .append("tests.api.java.nio.charset.CharsetProviderTest$MockCharsetProviderACSII\r"); + setupFile(CONFIG_FILE1, sb.toString()); + + assertFalse(Charset.forName("us-ascii") instanceof MockCharset); + assertFalse(Charset.availableCharsets().get("us-ascii") instanceof MockCharset); + } finally { + cleanupFile(CONFIG_FILE1); + } + } + + /* + * Test the method forName(String) when the configuration file contains a + * non-existing class name. + */ + public void testForName_NonExistingClass() throws Exception { + try { + StringBuffer sb = new StringBuffer(); + sb.append("impossible\r"); + setupFile(CONFIG_FILE1, sb.toString()); + + Charset.forName("impossible"); + fail("Should throw Error!"); + } catch (Error e) { + // expected + } finally { + cleanupFile(CONFIG_FILE1); + } + } + + /* + * Test the method forName(String) when the configuration file contains a + * non-CharsetProvider class name. + */ + public void testForName_NotCharsetProviderClass() throws Exception { + try { + StringBuffer sb = new StringBuffer(); + sb.append("java.lang.String\r"); + setupFile(CONFIG_FILE1, sb.toString()); + + Charset.forName("impossible"); + fail("Should throw ClassCastException!"); + } catch (ClassCastException e) { + // expected + } finally { + cleanupFile(CONFIG_FILE1); + } + } + + /* + * Test the method availableCharsets() with charset supported by some + * providers (multiple). + */ + public void testAvailableCharsets_NormalProvider() throws Exception { + try { + assertFalse(Charset.availableCharsets() + .containsKey("mockCharset10")); + assertFalse(Charset.availableCharsets() + .containsKey("mockCharset11")); + assertFalse(Charset.availableCharsets() + .containsKey("mockCharset12")); + + StringBuffer sb = new StringBuffer(); + sb.append("#comment\r"); + sb.append("\n"); + sb.append("\r\n"); + sb + .append(" \ttests.api.java.nio.charset.CharsetTest$MockCharsetProvider \t\n\r"); + sb + .append(" \ttests.api.java.nio.charset.CharsetTest$MockCharsetProvider \t"); + setupFile(CONFIG_FILE1, sb.toString()); + + sb = new StringBuffer(); + sb.append("#comment\r"); + sb.append("\n"); + sb.append("\r\n"); + sb + .append(" \ttests.api.java.nio.charset.CharsetProviderTest$MockCharsetProvider \t\n\r"); + setupFile(CONFIG_FILE1, sb.toString()); + + assertTrue(Charset.availableCharsets().containsKey("mockCharset00")); + assertTrue(Charset.availableCharsets().containsKey("MOCKCharset00")); + assertTrue(Charset.availableCharsets().get("mockCharset00") instanceof MockCharset); + assertTrue(Charset.availableCharsets().get("MOCKCharset00") instanceof MockCharset); + assertFalse(Charset.availableCharsets() + .containsKey("mockCharset01")); + assertFalse(Charset.availableCharsets() + .containsKey("mockCharset02")); + + assertTrue(Charset.availableCharsets().get("mockCharset10") == charset2); + assertTrue(Charset.availableCharsets().get("MOCKCharset10") == charset2); + assertFalse(Charset.availableCharsets() + .containsKey("mockCharset11")); + assertFalse(Charset.availableCharsets() + .containsKey("mockCharset12")); + + assertTrue(Charset.availableCharsets().containsKey("mockCharset10")); + assertTrue(Charset.availableCharsets().containsKey("MOCKCharset10")); + assertTrue(Charset.availableCharsets().get("mockCharset10") == charset2); + assertFalse(Charset.availableCharsets() + .containsKey("mockCharset11")); + assertFalse(Charset.availableCharsets() + .containsKey("mockCharset12")); + } finally { + cleanupFile(CONFIG_FILE1); + } + } + + /* + * Test the method availableCharsets(String) when the configuration file + * contains a non-existing class name. + */ + public void testAvailableCharsets_NonExistingClass() throws Exception { + try { + StringBuffer sb = new StringBuffer(); + sb.append("impossible\r"); + setupFile(CONFIG_FILE1, sb.toString()); + + Charset.availableCharsets(); + fail("Should throw Error!"); + } catch (Error e) { + // expected + } finally { + cleanupFile(CONFIG_FILE1); + } + } + + /* + * Test the method availableCharsets(String) when the configuration file + * contains a non-CharsetProvider class name. + */ + public void testAvailableCharsets_NotCharsetProviderClass() + throws Exception { + try { + StringBuffer sb = new StringBuffer(); + sb.append("java.lang.String\r"); + setupFile(CONFIG_FILE1, sb.toString()); + + Charset.availableCharsets(); + fail("Should throw ClassCastException!"); + } catch (ClassCastException e) { + // expected + } finally { + cleanupFile(CONFIG_FILE1); + } + } + + /* + * Test the method availableCharsets(String) when the configuration file + * contains an illegal string. + */ + public void testAvailableCharsets_IllegalString() throws Exception { + try { + StringBuffer sb = new StringBuffer(); + sb.append("java String\r"); + setupFile(CONFIG_FILE1, sb.toString()); + + Charset.availableCharsets(); + fail("Should throw Error!"); + } catch (Error e) { + // expected + } finally { + cleanupFile(CONFIG_FILE1); + } + } + + /* + * Mock charset provider. + */ + public static class MockCharsetProvider extends CharsetProvider { + + public Charset charsetForName(String charsetName) { + if ("MockCharset10".equalsIgnoreCase(charsetName) + || "MockCharset11".equalsIgnoreCase(charsetName) + || "MockCharset12".equalsIgnoreCase(charsetName)) { + return charset2; + } + return null; + } + + public Iterator charsets() { + Vector v = new Vector(); + v.add(charset2); + return v.iterator(); + } + } + + /* + * Another mock charset provider providing build-in charset "ascii". + */ + public static class MockCharsetProviderACSII extends CharsetProvider { + + public Charset charsetForName(String charsetName) { + if ("US-ASCII".equalsIgnoreCase(charsetName) + || "ASCII".equalsIgnoreCase(charsetName)) { + return new MockCharset("US-ASCII", new String[] { "ASCII" }); + } + return null; + } + + public Iterator charsets() { + Vector v = new Vector(); + v.add(new MockCharset("US-ASCII", new String[] { "ASCII" })); + return v.iterator(); + } + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetTest.java new file mode 100644 index 0000000..34d84ba --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetTest.java @@ -0,0 +1,840 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderResult; +import java.nio.charset.IllegalCharsetNameException; +import java.nio.charset.UnsupportedCharsetException; +import java.nio.charset.spi.CharsetProvider; +import java.security.Permission; +import java.util.Iterator; +import java.util.Locale; +import java.util.SortedMap; +import java.util.Vector; + +import junit.framework.TestCase; + +/** + * Test class java.nio.Charset. + */ +public class CharsetTest extends TestCase { + + static MockCharset charset1 = new MockCharset("mockCharset00", + new String[] { "mockCharset01", "mockCharset02" }); + + static MockCharset charset2 = new MockCharset("mockCharset10", + new String[] { "mockCharset11", "mockCharset12" }); + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + /* + * Test the required 6 charsets are supported. + */ + public void testRequiredCharsetSupported() { + assertTrue(Charset.isSupported("US-ASCII")); + assertTrue(Charset.isSupported("ASCII")); + assertTrue(Charset.isSupported("ISO-8859-1")); + assertTrue(Charset.isSupported("ISO8859_1")); + assertTrue(Charset.isSupported("UTF-8")); + assertTrue(Charset.isSupported("UTF8")); + assertTrue(Charset.isSupported("UTF-16")); + assertTrue(Charset.isSupported("UTF-16BE")); + assertTrue(Charset.isSupported("UTF-16LE")); + + Charset c1 = Charset.forName("US-ASCII"); + assertEquals("US-ASCII", Charset.forName("US-ASCII").name()); + assertEquals("US-ASCII", Charset.forName("ASCII").name()); + assertEquals("ISO-8859-1", Charset.forName("ISO-8859-1").name()); + assertEquals("ISO-8859-1", Charset.forName("ISO8859_1").name()); + assertEquals("UTF-8", Charset.forName("UTF-8").name()); + assertEquals("UTF-8", Charset.forName("UTF8").name()); + assertEquals("UTF-16", Charset.forName("UTF-16").name()); + assertEquals("UTF-16BE", Charset.forName("UTF-16BE").name()); + assertEquals("UTF-16LE", Charset.forName("UTF-16LE").name()); + + assertNotSame(Charset.availableCharsets(), Charset.availableCharsets()); + // assertSame(Charset.forName("US-ASCII"), Charset.availableCharsets() + // .get("US-ASCII")); + // assertSame(Charset.forName("US-ASCII"), c1); + assertTrue(Charset.availableCharsets().containsKey("US-ASCII")); + assertTrue(Charset.availableCharsets().containsKey("ISO-8859-1")); + assertTrue(Charset.availableCharsets().containsKey("UTF-8")); + assertTrue(Charset.availableCharsets().containsKey("UTF-16")); + assertTrue(Charset.availableCharsets().containsKey("UTF-16BE")); + assertTrue(Charset.availableCharsets().containsKey("UTF-16LE")); + } + + /* + * Test the method isSupported(String) with null. + */ + public void testIsSupported_Null() { + try { + Charset.isSupported(null); + fail("Should throw IllegalArgumentException!"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /* + * Test the method isSupported(String) with empty string. + * + */ + public void testIsSupported_EmptyString() { + try { + Charset.isSupported(""); + } catch (IllegalArgumentException e) { + // FIXME: Commented out since RI does throw IAE + // fail("Should not throw IllegalArgumentException!"); + } + } + + /* + * Test the method isSupported(String) with a string starting with ".". + * + */ + public void testIsSupported_InvalidInitialCharacter() { + try { + Charset.isSupported(".char"); + } catch (IllegalArgumentException e) { + fail("Should not throw IllegalArgumentException!"); + } + } + + /* + * Test the method isSupported(String) with illegal charset name. + */ + public void testIsSupported_IllegalName() { + try { + Charset.isSupported(" ///#$$"); + fail("Should throw IllegalCharsetNameException!"); + } catch (IllegalCharsetNameException e) { + // expected + } + } + + /* + * Test the method isSupported(String) with not supported charset name. + */ + public void testIsSupported_NotSupported() { + assertFalse(Charset.isSupported("impossible")); + } + + /* + * Test the method forName(String) with null. + */ + public void testForName_Null() { + try { + Charset.forName(null); + fail("Should throw IllegalArgumentException!"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /* + * Test the method forName(String) with empty string. + */ + public void testForName_EmptyString() { + try { + Charset.forName(""); + fail("Should throw IllegalArgumentException!"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /* + * Test the method forName(String) with a string starting with ".". + */ + public void testForName_InvalidInitialCharacter() { + try { + Charset.forName(".char"); + fail("Should throw IllegalArgumentException!"); + } catch (IllegalArgumentException e) { + // expected + } + } + + /* + * Test the method forName(String) with illegal charset name. + */ + public void testForName_IllegalName() { + try { + Charset.forName(" ///#$$"); + fail("Should throw IllegalCharsetNameException!"); + } catch (IllegalCharsetNameException e) { + // expected + } + } + + /* + * Test the method forName(String) with not supported charset name. + */ + public void testForName_NotSupported() { + try { + Charset.forName("impossible"); + fail("Should throw UnsupportedCharsetException!"); + } catch (UnsupportedCharsetException e) { + // expected + } + } + + /* + * Test the constructor with normal parameter values. + */ + public void testConstructor_Normal() { + final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_"; + MockCharset c = new MockCharset(mockName, new String[] { "mock" }); + assertEquals(mockName, c.name()); + assertEquals(mockName, c.displayName()); + assertEquals(mockName, c.displayName(Locale.getDefault())); + assertEquals("mock", c.aliases().toArray()[0]); + assertEquals(1, c.aliases().toArray().length); + } + + /* + * Test the constructor with empty canonical name. + * + */ + public void testConstructor_EmptyCanonicalName() { + try { + new MockCharset("", new String[0]); + } catch (IllegalCharsetNameException e) { + // FIXME: Commented out since RI does throw IAE + // fail("Should not throw IllegalArgumentException!"); + } + } + + /* + * Test the constructor with illegal canonical name: starting with neither a + * digit nor a letter. + * + */ + public void testConstructor_IllegalCanonicalName_Initial() { + try { + new MockCharset("-123", new String[] { "mock" }); + } catch (IllegalCharsetNameException e) { + fail("Should not throw IllegalArgumentException!"); + } + } + + /* + * Test the constructor with illegal canonical name, illegal character in + * the middle. + */ + public void testConstructor_IllegalCanonicalName_Middle() { + try { + new MockCharset("1%%23", new String[] { "mock" }); + fail("Should throw IllegalCharsetNameException!"); + } catch (IllegalCharsetNameException e) { + // expected + } + try { + new MockCharset("1//23", new String[] { "mock" }); + fail("Should throw IllegalCharsetNameException!"); + } catch (IllegalCharsetNameException e) { + // expected + } + } + + /* + * Test the constructor with null canonical name. + */ + public void testConstructor_NullCanonicalName() { + try { + MockCharset c = new MockCharset(null, new String[] { "mock" }); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the constructor with null aliases. + */ + public void testConstructor_NullAliases() { + MockCharset c = new MockCharset("mockChar", null); + assertEquals("mockChar", c.name()); + assertEquals("mockChar", c.displayName()); + assertEquals("mockChar", c.displayName(Locale.getDefault())); + assertEquals(0, c.aliases().toArray().length); + } + + /* + * Test the constructor with a null aliases. + */ + public void testConstructor_NullAliase() { + try { + new MockCharset("mockChar", new String[] { "mock", null }); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the constructor with no aliases. + */ + public void testConstructor_NoAliases() { + MockCharset c = new MockCharset("mockChar", new String[0]); + assertEquals("mockChar", c.name()); + assertEquals("mockChar", c.displayName()); + assertEquals("mockChar", c.displayName(Locale.getDefault())); + assertEquals(0, c.aliases().toArray().length); + } + + /* + * Test the constructor with empty aliases. + * + */ + public void testConstructor_EmptyAliases() { + try { + new MockCharset("mockChar", new String[] { "" }); + } catch (IllegalCharsetNameException e) { + // FIXME: Commented out since RI does throw IAE + // fail("Should not throw IllegalArgumentException!"); + } + } + + /* + * Test the constructor with illegal aliases: starting with neither a digit + * nor a letter. + * + */ + public void testConstructor_IllegalAliases_Initial() { + try { + new MockCharset("mockChar", new String[] { "mock", "-123" }); + } catch (IllegalCharsetNameException e) { + fail("Should not throw IllegalArgumentException!"); + } + } + + /* + * Test the constructor with illegal aliase, illegal character in the + * middle. + */ + public void testConstructor_IllegalAliases_Middle() { + try { + new MockCharset("mockChar", new String[] { "mock", "22##ab" }); + fail("Should throw IllegalCharsetNameException!"); + } catch (IllegalCharsetNameException e) { + // expected + } + try { + new MockCharset("mockChar", new String[] { "mock", "22%%ab" }); + fail("Should throw IllegalCharsetNameException!"); + } catch (IllegalCharsetNameException e) { + // expected + } + } + + /* + * Test the method aliases() with multiple aliases. Most conditions have + * been tested in the testcases for the constructors. + */ + public void testAliases_Multiple() { + final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_"; + MockCharset c = new MockCharset("mockChar", new String[] { "mock", + mockName, "mock2" }); + assertEquals("mockChar", c.name()); + assertEquals(3, c.aliases().size()); + assertTrue(c.aliases().contains("mock")); + assertTrue(c.aliases().contains(mockName)); + assertTrue(c.aliases().contains("mock2")); + + try { + c.aliases().clear(); + fail("Should throw UnsupportedOperationException!"); + } catch (UnsupportedOperationException e) { + // expected + } + } + + /* + * Test the method aliases() with duplicate aliases, one same with its + * canonical name. + */ + public void testAliases_Duplicate() { + final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_"; + MockCharset c = new MockCharset("mockChar", new String[] { "mockChar", + "mock", mockName, "mock", "mockChar", "mock", "mock2" }); + assertEquals("mockChar", c.name()); + assertEquals(4, c.aliases().size()); + assertTrue(c.aliases().contains("mockChar")); + assertTrue(c.aliases().contains("mock")); + assertTrue(c.aliases().contains(mockName)); + assertTrue(c.aliases().contains("mock2")); + } + + /* + * Test the method canEncode(). Test the default return value. + */ + public void testCanEncode() { + MockCharset c = new MockCharset("mock", null); + assertTrue(c.canEncode()); + } + + /* + * Test the method isRegistered(). Test the default return value. + */ + public void testIsRegistered() { + MockCharset c = new MockCharset("mock", null); + assertTrue(c.isRegistered()); + } + + /* + * The name() method has been tested by the testcases for the constructor. + */ + public void testName() { + // already covered by testConstructor_XXX series + } + + /* + * The displayName() method have been tested by the testcases for the + * constructor. + */ + public void testDisplayName() { + // already covered by testConstructor_XXX series + } + + /* + * Test displayName(Locale) with null. + */ + public void testDisplayName_Locale_Null() { + MockCharset c = new MockCharset("mock", null); + assertEquals("mock", c.displayName(null)); + } + + /* + * Test the method compareTo(Object) with normal conditions. + */ + public void testCompareTo_Normal() { + MockCharset c1 = new MockCharset("mock", null); + assertEquals(0, c1.compareTo(c1)); + + MockCharset c2 = new MockCharset("Mock", null); + assertEquals(0, c1.compareTo(c2)); + + c2 = new MockCharset("mock2", null); + assertTrue(c1.compareTo(c2) < 0); + assertTrue(c2.compareTo(c1) > 0); + + c2 = new MockCharset("mack", null); + assertTrue(c1.compareTo(c2) > 0); + assertTrue(c2.compareTo(c1) < 0); + + c2 = new MockCharset("m.", null); + assertTrue(c1.compareTo(c2) > 0); + assertTrue(c2.compareTo(c1) < 0); + + c2 = new MockCharset("m:", null); + assertEquals("mock".compareToIgnoreCase("m:"), c1.compareTo(c2)); + assertEquals("m:".compareToIgnoreCase("mock"), c2.compareTo(c1)); + + c2 = new MockCharset("m-", null); + assertTrue(c1.compareTo(c2) > 0); + assertTrue(c2.compareTo(c1) < 0); + + c2 = new MockCharset("m_", null); + assertTrue(c1.compareTo(c2) > 0); + assertTrue(c2.compareTo(c1) < 0); + } + + /* + * Test the method compareTo(Object) with null param. + */ + public void testCompareTo_Null() { + MockCharset c1 = new MockCharset("mock", null); + try { + c1.compareTo(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the method compareTo(Object) with another kind of charset object. + */ + public void testCompareTo_DiffCharsetClass() { + MockCharset c1 = new MockCharset("mock", null); + MockCharset2 c2 = new MockCharset2("Mock", new String[] { "myname" }); + assertEquals(0, c1.compareTo(c2)); + assertEquals(0, c2.compareTo(c1)); + } + + /* + * Test the method equals(Object) with null param. + */ + public void testEquals_Normal() { + MockCharset c1 = new MockCharset("mock", null); + MockCharset2 c2 = new MockCharset2("mock", null); + assertTrue(c1.equals(c2)); + assertTrue(c2.equals(c1)); + + c2 = new MockCharset2("Mock", null); + assertFalse(c1.equals(c2)); + assertFalse(c2.equals(c1)); + } + + /* + * Test the method equals(Object) with normal conditions. + */ + public void testEquals_Null() { + MockCharset c1 = new MockCharset("mock", null); + assertFalse(c1.equals(null)); + } + + /* + * Test the method equals(Object) with another kind of charset object. + */ + public void testEquals_NonCharsetObject() { + MockCharset c1 = new MockCharset("mock", null); + assertFalse(c1.equals("test")); + } + + /* + * Test the method equals(Object) with another kind of charset object. + */ + public void testEquals_DiffCharsetClass() { + MockCharset c1 = new MockCharset("mock", null); + MockCharset2 c2 = new MockCharset2("mock", null); + assertTrue(c1.equals(c2)); + assertTrue(c2.equals(c1)); + } + + /* + * Test the method hashCode(). + */ + public void testHashCode_DiffCharsetClass() { + MockCharset c1 = new MockCharset("mock", null); + assertEquals(c1.hashCode(), "mock".hashCode()); + + final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_"; + c1 = new MockCharset(mockName, new String[] { "mockChar", "mock", + mockName, "mock", "mockChar", "mock", "mock2" }); + assertEquals(mockName.hashCode(), c1.hashCode()); + } + + /* + * Test the method encode(CharBuffer) under normal condition. + */ + public void testEncode_CharBuffer_Normal() throws Exception { + MockCharset c1 = new MockCharset("testEncode_CharBuffer_Normal_mock", null); + ByteBuffer bb = c1.encode(CharBuffer.wrap("abcdefg")); + assertEquals("abcdefg", new String(bb.array(), "iso8859-1")); + bb = c1.encode(CharBuffer.wrap("")); + assertEquals("", new String(bb.array(), "iso8859-1")); + } + + /* + * Test the method encode(CharBuffer) with an unmappable char. + */ + public void testEncode_CharBuffer_Unmappable() throws Exception { + Charset c1 = Charset.forName("iso8859-1"); + ByteBuffer bb = c1.encode(CharBuffer.wrap("abcd\u5D14efg")); + assertEquals(new String(bb.array(), "iso8859-1"), "abcd" + + new String(c1.newEncoder().replacement(), "iso8859-1") + + "efg"); + } + + /* + * Test the method encode(CharBuffer) with null CharBuffer. + */ + public void testEncode_CharBuffer_NullCharBuffer() { + MockCharset c = new MockCharset("mock", null); + try { + c.encode((CharBuffer) null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the method encode(CharBuffer) with null encoder. + */ + public void testEncode_CharBuffer_NullEncoder() { + MockCharset2 c = new MockCharset2("mock2", null); + try { + c.encode(CharBuffer.wrap("hehe")); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the method encode(String) under normal condition. + */ + public void testEncode_String_Normal() throws Exception { + MockCharset c1 = new MockCharset("testEncode_String_Normal_mock", null); + ByteBuffer bb = c1.encode("abcdefg"); + assertEquals("abcdefg", new String(bb.array(), "iso8859-1")); + bb = c1.encode(""); + assertEquals("", new String(bb.array(), "iso8859-1")); + } + + /* + * Test the method encode(String) with an unmappable char. + */ + public void testEncode_String_Unmappable() throws Exception { + Charset c1 = Charset.forName("iso8859-1"); + ByteBuffer bb = c1.encode("abcd\u5D14efg"); + assertEquals(new String(bb.array(), "iso8859-1"), "abcd" + + new String(c1.newEncoder().replacement(), "iso8859-1") + + "efg"); + } + + /* + * Test the method encode(String) with null CharBuffer. + */ + public void testEncode_String_NullString() { + MockCharset c = new MockCharset("mock", null); + try { + c.encode((String) null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the method encode(String) with null encoder. + */ + public void testEncode_String_NullEncoder() { + + MockCharset2 c = new MockCharset2("mock2", null); + try { + c.encode("hehe"); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the method decode(ByteBuffer) under normal condition. + */ + public void testDecode_Normal() throws Exception { + MockCharset c1 = new MockCharset("mock", null); + CharBuffer cb = c1.decode(ByteBuffer.wrap("abcdefg" + .getBytes("iso8859-1"))); + assertEquals("abcdefg", new String(cb.array())); + cb = c1.decode(ByteBuffer.wrap("".getBytes("iso8859-1"))); + assertEquals("", new String(cb.array())); + } + + /* + * Test the method decode(ByteBuffer) with a malformed input. + */ + public void testDecode_Malformed() throws Exception { + Charset c1 = Charset.forName("iso8859-1"); + CharBuffer cb = c1.decode(ByteBuffer.wrap("abcd\u5D14efg" + .getBytes("iso8859-1"))); + byte[] replacement = c1.newEncoder().replacement(); + assertEquals(new String(cb.array()).trim(), "abcd" + new String(replacement, "iso8859-1") + + "efg"); + } + + /* + * Test the method decode(ByteBuffer) with null CharBuffer. + */ + public void testDecode_NullByteBuffer() { + MockCharset c = new MockCharset("mock", null); + try { + c.decode(null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the method decode(ByteBuffer) with null encoder. + */ + public void testDecode_NullDecoder() { + MockCharset2 c = new MockCharset2("mock2", null); + try { + c.decode(ByteBuffer.wrap("hehe".getBytes())); + fail("Should throw NullPointerException!"); + } catch (NullPointerException e) { + // expected + } + } + + /* + * Test the method toString(). + */ + public void testToString() { + MockCharset c1 = new MockCharset("mock", null); + assertTrue(-1 != c1.toString().indexOf("mock")); + } + + /** + * @tests java.nio.charset.Charset#availableCharsets() + */ + public void test_availableCharsets() throws Exception { + // regression test for Harmony-1051 + ClassLoader originalClassLoader = Thread.currentThread() + .getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(null); + SortedMap<String, Charset> charsets = Charset.availableCharsets(); + // make sure "mockCharset00" is loaded by MockCharsetProvider + assertTrue(charsets.containsKey("mockCharset00")); + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + } + + /** + * @tests java.nio.charset.Charset#availableCharsets() + */ + public void test_forNameLString() throws Exception { + // regression test for Harmony-1051 + ClassLoader originalClassLoader = Thread.currentThread() + .getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(null); + // make sure "mockCharset00" is loaded by MockCharsetProvider + assertNotNull(Charset.forName("mockCharset00")); + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + } + + /* + * Mock charset class. + */ + static final class MockCharset extends Charset { + + public MockCharset(String canonicalName, String[] aliases) { + super(canonicalName, aliases); + } + + public boolean contains(Charset cs) { + return false; + } + + public CharsetDecoder newDecoder() { + return new MockDecoder(this); + } + + public CharsetEncoder newEncoder() { + return new MockEncoder(this); + } + } + + /* + * Another mock charset class. + */ + static class MockCharset2 extends Charset { + + public MockCharset2(String canonicalName, String[] aliases) { + super(canonicalName, aliases); + } + + public boolean contains(Charset cs) { + return false; + } + + public CharsetDecoder newDecoder() { + return null; + } + + public CharsetEncoder newEncoder() { + return null; + } + } + + /* + * Mock encoder. + */ + static class MockEncoder extends java.nio.charset.CharsetEncoder { + + public MockEncoder(Charset cs) { + super(cs, 1, 3, new byte[] { (byte) '?' }); + } + + protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { + while (in.remaining() > 0) { + out.put((byte) in.get()); + // out.put((byte) '!'); + } + return CoderResult.UNDERFLOW; + } + } + + /* + * Mock decoder. + */ + static class MockDecoder extends java.nio.charset.CharsetDecoder { + + public MockDecoder(Charset cs) { + super(cs, 1, 10); + } + + protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { + while (in.remaining() > 0) { + out.put((char) in.get()); + } + return CoderResult.UNDERFLOW; + } + } + + /* + * Mock charset provider. + */ + public static class MockCharsetProvider extends CharsetProvider { + + public Charset charsetForName(String charsetName) { + if ("MockCharset00".equalsIgnoreCase(charsetName) + || "MockCharset01".equalsIgnoreCase(charsetName) + || "MockCharset02".equalsIgnoreCase(charsetName)) { + return new MockCharset("mockCharset00", new String[] { + "mockCharset01", "mockCharset02" }); + } + return null; + } + + public Iterator charsets() { + Vector v = new Vector(); + v.add(new MockCharset("mockCharset00", new String[] { + "mockCharset01", "mockCharset02" })); + return v.iterator(); + } + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CoderResultTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/CoderResultTest.java new file mode 100644 index 0000000..469fc98 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/CoderResultTest.java @@ -0,0 +1,265 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.charset.CoderResult; +import java.nio.charset.MalformedInputException; +import java.nio.charset.UnmappableCharacterException; + +import junit.framework.TestCase; + +/** + * Test class java.nio.charset.CoderResult. + */ +public class CoderResultTest extends TestCase { + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + /* + * Test the constant OVERFLOW and UNDERFLOW. + */ + public void testConstants() throws Exception { + assertNotSame(CoderResult.OVERFLOW, CoderResult.UNDERFLOW); + + assertNotNull(CoderResult.OVERFLOW); + assertFalse(CoderResult.OVERFLOW.isError()); + assertFalse(CoderResult.OVERFLOW.isMalformed()); + assertFalse(CoderResult.OVERFLOW.isUnderflow()); + assertFalse(CoderResult.OVERFLOW.isUnmappable()); + assertTrue(CoderResult.OVERFLOW.isOverflow()); + assertTrue(CoderResult.OVERFLOW.toString().indexOf("OVERFLOW") != -1); + try { + CoderResult.OVERFLOW.throwException(); + fail("Should throw BufferOverflowException"); + } catch (BufferOverflowException ex) { + // expected + } + try { + CoderResult.OVERFLOW.length(); + fail("Should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException ex) { + // expected + } + + assertNotNull(CoderResult.UNDERFLOW); + assertFalse(CoderResult.UNDERFLOW.isError()); + assertFalse(CoderResult.UNDERFLOW.isMalformed()); + assertTrue(CoderResult.UNDERFLOW.isUnderflow()); + assertFalse(CoderResult.UNDERFLOW.isUnmappable()); + assertFalse(CoderResult.UNDERFLOW.isOverflow()); + assertTrue(CoderResult.UNDERFLOW.toString().indexOf("UNDERFLOW") != -1); + try { + CoderResult.UNDERFLOW.throwException(); + fail("Should throw BufferOverflowException"); + } catch (BufferUnderflowException ex) { + // expected + } + try { + CoderResult.UNDERFLOW.length(); + fail("Should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException ex) { + // expected + } + } + + /** + * Test method isError(). + * + */ + public void testIsError() { + assertFalse(CoderResult.UNDERFLOW.isError()); + assertFalse(CoderResult.OVERFLOW.isError()); + assertTrue(CoderResult.malformedForLength(1).isError()); + assertTrue(CoderResult.unmappableForLength(1).isError()); + } + + /** + * Test method isMalformed(). + * + */ + public void testIsMalformed() { + assertFalse(CoderResult.UNDERFLOW.isMalformed()); + assertFalse(CoderResult.OVERFLOW.isMalformed()); + assertTrue(CoderResult.malformedForLength(1).isMalformed()); + assertFalse(CoderResult.unmappableForLength(1).isMalformed()); + } + + /** + * Test method isMalformed(). + * + */ + public void testIsUnmappable() { + assertFalse(CoderResult.UNDERFLOW.isUnmappable()); + assertFalse(CoderResult.OVERFLOW.isUnmappable()); + assertFalse(CoderResult.malformedForLength(1).isUnmappable()); + assertTrue(CoderResult.unmappableForLength(1).isUnmappable()); + } + + /** + * Test method isOverflow(). + * + */ + public void testIsOverflow() { + assertFalse(CoderResult.UNDERFLOW.isOverflow()); + assertTrue(CoderResult.OVERFLOW.isOverflow()); + assertFalse(CoderResult.malformedForLength(1).isOverflow()); + assertFalse(CoderResult.unmappableForLength(1).isOverflow()); + } + + /** + * Test method isUnderflow(). + * + */ + public void testIsUnderflow() { + assertTrue(CoderResult.UNDERFLOW.isUnderflow()); + assertFalse(CoderResult.OVERFLOW.isUnderflow()); + assertFalse(CoderResult.malformedForLength(1).isUnderflow()); + assertFalse(CoderResult.unmappableForLength(1).isUnderflow()); + } + + /** + * Test method length(). + * + */ + public void testLength() { + try { + CoderResult.UNDERFLOW.length(); + fail("Should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException ex) { + // expected + } + try { + CoderResult.OVERFLOW.length(); + fail("Should throw UnsupportedOperationException"); + } catch (UnsupportedOperationException ex) { + // expected + } + + assertEquals(CoderResult.malformedForLength(1).length(), 1); + assertEquals(CoderResult.unmappableForLength(1).length(), 1); + } + + /** + * Test method malformedForLength(int). + * + */ + public void testMalformedForLength() { + assertNotNull(CoderResult.malformedForLength(Integer.MAX_VALUE)); + assertNotNull(CoderResult.malformedForLength(1)); + assertSame(CoderResult.malformedForLength(1), CoderResult + .malformedForLength(1)); + assertNotSame(CoderResult.malformedForLength(1), CoderResult + .unmappableForLength(1)); + assertNotSame(CoderResult.malformedForLength(2), CoderResult + .malformedForLength(1)); + try { + CoderResult.malformedForLength(-1); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException ex) { + // expected + } + try { + CoderResult.malformedForLength(0); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException ex) { + // expected + } + } + + /** + * Test method unmappableForLength(int). + * + */ + public void testUnmappableForLength() { + assertNotNull(CoderResult.unmappableForLength(Integer.MAX_VALUE)); + assertNotNull(CoderResult.unmappableForLength(1)); + assertSame(CoderResult.unmappableForLength(1), CoderResult + .unmappableForLength(1)); + assertNotSame(CoderResult.unmappableForLength(2), CoderResult + .unmappableForLength(1)); + try { + CoderResult.unmappableForLength(-1); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException ex) { + // expected + } + try { + CoderResult.unmappableForLength(0); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException ex) { + // expected + } + } + + /** + * Test method throwException(). + * + */ + public void testThrowException() throws Exception { + try { + CoderResult.OVERFLOW.throwException(); + fail("Should throw BufferOverflowException"); + } catch (BufferOverflowException ex) { + // expected + } + try { + CoderResult.UNDERFLOW.throwException(); + fail("Should throw BufferOverflowException"); + } catch (BufferUnderflowException ex) { + // expected + } + try { + CoderResult.malformedForLength(1).throwException(); + fail("Should throw MalformedInputException"); + } catch (MalformedInputException ex) { + assertEquals(ex.getInputLength(), 1); + } + try { + CoderResult.unmappableForLength(1).throwException(); + fail("Should throw UnmappableCharacterException"); + } catch (UnmappableCharacterException ex) { + assertEquals(ex.getInputLength(), 1); + } + } + + /** + * Test method toString(). + * + */ + public void testToString() throws Exception { + assertTrue(CoderResult.OVERFLOW.toString().indexOf("OVERFLOW") != -1); + assertTrue(CoderResult.UNDERFLOW.toString().indexOf("UNDERFLOW") != -1); + assertTrue(CoderResult.malformedForLength(666).toString() + .indexOf("666") != -1); + assertTrue(CoderResult.unmappableForLength(666).toString().indexOf( + "666") != -1); + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CodingErrorActionTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/CodingErrorActionTest.java new file mode 100644 index 0000000..da293bb --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/CodingErrorActionTest.java @@ -0,0 +1,62 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.charset.CodingErrorAction; + +import junit.framework.TestCase; + +/** + * Test class java.nio.charset.CodingErrorAction + */ +public class CodingErrorActionTest extends TestCase { + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + /* + * Test the constants. + */ + public void testIGNORE() { + assertNotNull(CodingErrorAction.IGNORE); + assertNotNull(CodingErrorAction.REPLACE); + assertNotNull(CodingErrorAction.REPORT); + assertNotSame(CodingErrorAction.IGNORE, CodingErrorAction.REPLACE); + assertNotSame(CodingErrorAction.IGNORE, CodingErrorAction.REPORT); + assertNotSame(CodingErrorAction.REPLACE, CodingErrorAction.REPORT); + } + + /* + * Test the method toString(). + */ + public void testToString() { + assertTrue(CodingErrorAction.IGNORE.toString().indexOf("IGNORE") != -1); + assertTrue(CodingErrorAction.REPLACE.toString().indexOf("REPLACE") != -1); + assertTrue(CodingErrorAction.REPORT.toString().indexOf("REPORT") != -1); + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetDecoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetDecoderTest.java new file mode 100644 index 0000000..e129c54 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetDecoderTest.java @@ -0,0 +1,64 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +/** + * test gb18030 decoder + */ +public class GBCharsetDecoderTest extends CharsetDecoderTest { + + protected void setUp() throws Exception { + cs = Charset.forName("gb18030"); + super.setUp(); + } + + /* + * @see CharsetDecoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + // // FIXME: give up this tests + // public void testDefaultCharsPerByte(){ + // //assertEquals(1, decoder.averageCharsPerByte()); + // //assertEquals(1, decoder.maxCharsPerByte()); + // assertEquals(decoder.averageCharsPerByte(), 0.25, 0.001); + // assertEquals(decoder.maxCharsPerByte(), 2, 0.001); + // } + + ByteBuffer getUnmappedByteBuffer() throws UnsupportedEncodingException { + return null; + } + + ByteBuffer getMalformedByteBuffer() throws UnsupportedEncodingException { + ByteBuffer buffer = ByteBuffer.allocate(20); + buffer.put(new byte[] { (byte) 0xd8 }); + buffer.put(getByteBuffer()); + buffer.flip(); + return buffer; + } + + ByteBuffer getExceptionByteArray() throws UnsupportedEncodingException { + return null; + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetEncoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetEncoderTest.java new file mode 100644 index 0000000..9ce07a2 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/GBCharsetEncoderTest.java @@ -0,0 +1,95 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; + +/** + * test case specific activity of gb18030 charset encoder + */ +public class GBCharsetEncoderTest extends CharsetEncoderTest { + + // charset for gb180303 + private static final Charset CS = Charset.forName("gb18030"); + + /* + * @see CharsetEncoderTest#setUp() + */ + protected void setUp() throws Exception { + cs = CS; + super.setUp(); + } + + /* + * @see CharsetEncoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testCanEncodechar() { + // normal case for utfCS + assertTrue(encoder.canEncode('\u0077')); + assertTrue(encoder.canEncode('\uc2a3')); + + // for non-mapped char + assertTrue(encoder.canEncode('\uc2c0')); + } + + /* + * Class under test for boolean canEncode(CharSequence) + */ + public void testCanEncodeCharSequence() { + assertTrue(encoder.canEncode("")); + // surrogate char + + // valid surrogate pair + //assertTrue(encoder.canEncode("\ud800\udc00")); + // invalid surrogate pair + assertFalse(encoder.canEncode("\ud800\udb00")); + assertFalse(encoder.canEncode("\ud800")); + } + + public void testSpecificDefaultValue() { + // FIXME: different here! + assertEquals(4.0, encoder.maxBytesPerChar(), 0.0); + assertEquals(4.0, encoder.averageBytesPerChar(), 0.0); + + // assertTrue(encoder.averageBytesPerChar() == 3); + // assertTrue(encoder.maxBytesPerChar() == 2); + + } + + CharBuffer getMalformedCharBuffer() { + return CharBuffer.wrap("\ud800 buffer"); + } + + CharBuffer getUnmapCharBuffer() { + return null; + } + + CharBuffer getExceptionCharBuffer() { + return null; + } + + protected byte[] getIllegalByteArray() { + return new byte[] { (byte) 0xd8, (byte) 0x00 }; + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetDecoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetDecoderTest.java new file mode 100644 index 0000000..82ba9b3 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetDecoderTest.java @@ -0,0 +1,61 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +/** + * test ISO-8859-1 decoder + */ +public class ISOCharsetDecoderTest extends CharsetDecoderTest { + + protected void setUp() throws Exception { + cs = Charset.forName("iso-8859-1"); + super.setUp(); + } + + /* + * @see CharsetDecoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + // FIXME: give up this tests + // public void testDefaultCharsPerByte(){ + // assertEquals(1, decoder.averageCharsPerByte()); + // assertEquals(decoder.maxCharsPerByte(), 2, 0.001); + // } + + ByteBuffer getUnmappedByteBuffer() throws UnsupportedEncodingException { + // TODO how on map? + return null; + + } + + ByteBuffer getMalformedByteBuffer() throws UnsupportedEncodingException { + // TODO how malform + return null; + } + + ByteBuffer getExceptionByteArray() throws UnsupportedEncodingException { + return null; + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetEncoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetEncoderTest.java new file mode 100644 index 0000000..7d7bca3 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetEncoderTest.java @@ -0,0 +1,112 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CoderResult; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.UnmappableCharacterException; + +/** + * test case specific activity of iso-8859-1 charset encoder + */ +public class ISOCharsetEncoderTest extends CharsetEncoderTest { + + // charset for iso-8859-1 + private static final Charset CS = Charset.forName("iso-8859-1"); + + /* + * @see CharsetEncoderTest#setUp() + */ + protected void setUp() throws Exception { + cs = CS; + super.setUp(); + } + + /* + * @see CharsetEncoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testCanEncodeCharSequence() { + // normal case for isoCS + assertTrue(encoder.canEncode("\u0077")); + assertFalse(encoder.canEncode("\uc2a3")); + assertFalse(encoder.canEncode("\ud800\udc00")); + try { + encoder.canEncode(null); + } catch (NullPointerException e) { + } + assertTrue(encoder.canEncode("")); + } + + public void testCanEncodeICUBug() { + assertFalse(encoder.canEncode((char) '\ud800')); + assertFalse(encoder.canEncode((String) "\ud800")); + } + + public void testCanEncodechar() throws CharacterCodingException { + assertTrue(encoder.canEncode('\u0077')); + assertFalse(encoder.canEncode('\uc2a3')); + } + + public void testSpecificDefaultValue() { + assertEquals(1, encoder.averageBytesPerChar(), 0.001); + assertEquals(1, encoder.maxBytesPerChar(), 0.001); + } + + CharBuffer getMalformedCharBuffer() { + return CharBuffer.wrap("\ud800 buffer"); + } + + CharBuffer getUnmapCharBuffer() { + return CharBuffer.wrap("\ud800\udc00 buffer"); + } + + CharBuffer getExceptionCharBuffer() { + return null; + } + + protected byte[] getIllegalByteArray() { + return null; + } + + public void testMultiStepEncode() throws CharacterCodingException { + encoder.onMalformedInput(CodingErrorAction.REPORT); + encoder.onUnmappableCharacter(CodingErrorAction.REPORT); + try { + encoder.encode(CharBuffer.wrap("\ud800\udc00")); + fail("should unmappable"); + } catch (UnmappableCharacterException e) { + } + encoder.reset(); + ByteBuffer out = ByteBuffer.allocate(10); + assertTrue(encoder.encode(CharBuffer.wrap("\ud800"), out, true) + .isMalformed()); + encoder.flush(out); + encoder.reset(); + out = ByteBuffer.allocate(10); + assertSame(CoderResult.UNDERFLOW, encoder.encode(CharBuffer + .wrap("\ud800"), out, false)); + assertTrue(encoder.encode(CharBuffer.wrap("\udc00"), out, true) + .isMalformed()); + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetTest.java new file mode 100644 index 0000000..689dbf3 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/ISOCharsetTest.java @@ -0,0 +1,58 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +/** + * Test ISO-8859-1. + */ +public class ISOCharsetTest extends AbstractCharsetTestCase { + + /** + * Constructor. + */ + public ISOCharsetTest(String arg0) { + super(arg0, "ISO-8859-1", new String[] { "iso-ir-100", "8859_1", + "ISO_8859-1", "ISO8859_1", "819", "csISOLatin1", "IBM-819", + "ISO_8859-1:1987", "latin1", "cp819", "ISO8859-1", "IBM819", + "ISO_8859_1", "l1" }, true, true); + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testEncode_Normal() + */ + public void testEncode_Normal() { + String input = "ab\u5D14\u654F"; + byte[] output = new byte[] { 97, 98, + this.testingCharset.newEncoder().replacement()[0], + this.testingCharset.newEncoder().replacement()[0] }; + internalTestEncode(input, output); + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testDecode_Normal() + */ + public void testDecode_Normal() { + byte[] input = new byte[] { 97, 98, 63, 63 }; + char[] output = "ab??".toCharArray(); + internalTestDecode(input, output); + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetDecoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetDecoderTest.java new file mode 100644 index 0000000..a8e1343 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetDecoderTest.java @@ -0,0 +1,72 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +/** + * + */ +public class UTF16BECharsetDecoderTest extends CharsetDecoderTest { + + protected void setUp() throws Exception { + cs = Charset.forName("utf-16be"); + super.setUp(); + } + + /* + * @see CharsetDecoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + // FIXME: give up this tests + // public void testDefaultCharsPerByte() { + // // assertEquals(1, decoder.averageCharsPerByte()); + // // assertEquals(1, decoder.maxCharsPerByte()); + // assertEquals(decoder.averageCharsPerByte(), 0.5, 0.001); + // assertEquals(decoder.maxCharsPerByte(), 2, 0.001); + // } + + ByteBuffer getUnmappedByteBuffer() throws UnsupportedEncodingException { + // no unmap byte buffer + return null; + } + + ByteBuffer getMalformedByteBuffer() throws UnsupportedEncodingException { + // FIXME: different here, RI can parse 0xd8d8 + // ByteBuffer buffer = ByteBuffer.allocate(100); + // buffer.put((byte)0xd8); + // buffer.put((byte)0xd8); + // buffer.put(unibytes); + // buffer.flip(); + // return buffer; + return null; + } + + ByteBuffer getExceptionByteArray() throws UnsupportedEncodingException { + return null; + } + + protected ByteBuffer getByteBuffer() { + return ByteBuffer.wrap(new byte[] { 0, 32, 0, 98, 0, 117, 0, 102, 0, + 102, 0, 101, 0, 114 }); + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetEncoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetEncoderTest.java new file mode 100644 index 0000000..70a1786 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetEncoderTest.java @@ -0,0 +1,120 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; + +/** + * TODO type def + */ +public class UTF16BECharsetEncoderTest extends CharsetEncoderTest { + + // charset for utf-16be + private static final Charset CS = Charset.forName("utf-16be"); + + /* + * @see CharsetEncoderTest#setUp() + */ + protected void setUp() throws Exception { + cs = CS; + specifiedReplacement = new byte[] { -1, -3 }; + unibytes = new byte[] { 0, 32, 0, 98, 0, 117, 0, 102, 0, 102, 0, 101, + 0, 114 }; + + // unibytesWithRep = new byte[] {(byte)0xff, (byte)0xfd,0, 32, 0, 98, 0, + // 117, 0, 102, 0, 102, 0, 101, 0, 114}; + + super.setUp(); + } + + /* + * @see CharsetEncoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testCharsetEncoderCharsetfloatfloat() { + // this constructor is invalid for UTF16LE CharsetEncoder + } + + public void testCanEncodechar() throws CharacterCodingException { + // normal case for utfCS + assertTrue(encoder.canEncode('\u0077')); + assertTrue(encoder.canEncode('\uc2a3')); + + // for non-mapped char + assertTrue(encoder.canEncode('\uc2c0')); + + } + + public void testCanEncodeCharSequence() { + // normal case for utfCS + assertTrue(encoder.canEncode("\u0077")); + assertTrue(encoder.canEncode("\uc2a3")); + assertTrue(encoder.canEncode("")); + + // for non-mapped char + assertTrue(encoder.canEncode("\uc2c0")); + + // surrogate char for unicode + // 1st byte: d800-dbff + // 2nd byte: dc00-dfff + // valid surrogate pair + assertTrue(encoder.canEncode("\ud800\udc00")); + // invalid surrogate pair + assertFalse(encoder.canEncode("\ud800\udb00")); + } + + public void testCanEncodeICUBug() { + assertFalse(encoder.canEncode("\ud800")); + } + + public void testSpecificDefaultValue() { + assertEquals(2, encoder.averageBytesPerChar(), 0.001); + assertEquals(2, encoder.maxBytesPerChar(), 0.001); + } + + CharBuffer getMalformedCharBuffer() { + return CharBuffer.wrap("\ud800 buffer"); + } + + CharBuffer getUnmapCharBuffer() { + return null; + } + + CharBuffer getExceptionCharBuffer() { + return null; + } + + public void testIsLegalReplacementEmptyArray() { + assertTrue(encoder.isLegalReplacement(new byte[0])); + } + + protected byte[] getIllegalByteArray() { + // FIXME: different here + // cannot replace by 0xd8d8, but RI can + // return new byte[]{(byte)0xd8, (byte)0xd8}; + return new byte[] { 0 }; + } + + protected byte[] getLegalByteArray() { + return new byte[] { (byte) 0x00, (byte) 0xd8 }; + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetTest.java new file mode 100644 index 0000000..52cee90 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16BECharsetTest.java @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +/** + * Test UTF-16BE. + */ +public class UTF16BECharsetTest extends AbstractCharsetTestCase { + + /** + * Constructor. + */ + public UTF16BECharsetTest(String arg0) { + super(arg0, "UTF-16BE", new String[] { "X-UTF-16BE", "UTF_16BE" }, + true, true); // "ISO-10646-UCS-2" + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testEncode_Normal() + */ + public void testEncode_Normal() { + String input = "ab\u5D14\u654F"; + byte[] output = new byte[] { 0, 97, 0, 98, 93, 20, 101, 79 }; + internalTestEncode(input, output); + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testDecode_Normal() + */ + public void testDecode_Normal() { + byte[] input = new byte[] { 0, 97, 0, 98, 93, 20, 101, 79 }; + char[] output = "ab\u5D14\u654F".toCharArray(); + internalTestDecode(input, output); + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetDecoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetDecoderTest.java new file mode 100644 index 0000000..51daaf6 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetDecoderTest.java @@ -0,0 +1,161 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CoderResult; +import java.nio.charset.CodingErrorAction; + +/** + * + */ +public class UTF16CharsetDecoderTest extends CharsetDecoderTest { + + boolean bigEndian = true; + + protected void setUp() throws Exception { + cs = Charset.forName("utf-16"); + bom = "\ufeff"; + super.setUp(); + } + + /* + * @see CharsetDecoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + protected ByteBuffer getByteBuffer() { + // FIXME: different here + // if don't specified BOM + // ICU default is LE + // JDK default is BE + + // maybe start with 0xFEFF, which means big endian + // 0xFFFE, which means little endian + byte[] b = (bigEndian) ? new byte[] { -1, -2, 32, 0, 98, 0, 117, 0, + 102, 0, 102, 0, 101, 0, 114, 0 } : new byte[] { -2, -1, 0, 32, + 0, 98, 0, 117, 0, 102, 0, 102, 0, 101, 0, 114 }; + return ByteBuffer.wrap(b); + } + + protected ByteBuffer getHeadlessByteBuffer() { + ByteBuffer b = getByteBuffer(); + b.position(2); + byte[] bytes = new byte[b.remaining()]; + b.get(bytes); + return ByteBuffer.wrap(bytes); + } + + public void testMultiStepDecode() throws CharacterCodingException { + if (!cs.name().equals("mock")) { + decoder.onMalformedInput(CodingErrorAction.REPORT); + decoder.onUnmappableCharacter(CodingErrorAction.REPORT); + CharBuffer out = CharBuffer.allocate(10); + assertTrue(decoder.decode( + ByteBuffer.wrap(new byte[] { -1, -2, 32, 0, 98 }), out, + true).isMalformed()); + + decoder.flush(out); + decoder.reset(); + out.clear(); + assertSame(CoderResult.UNDERFLOW, decoder.decode(ByteBuffer + .wrap(new byte[] { -1, -2, 32, 0 }), out, false)); + assertTrue(decoder.decode(ByteBuffer.wrap(new byte[] { 98 }), out, + true).isMalformed()); + + decoder.flush(out); + decoder.reset(); + out.clear(); + assertSame(CoderResult.UNDERFLOW, decoder.decode(ByteBuffer + .wrap(new byte[] { -1, -2, 32, 0, 98 }), out, false)); + assertFalse(decoder.decode(ByteBuffer.wrap(new byte[] {}), out, + true).isMalformed()); + + decoder.flush(out); + decoder.reset(); + out.clear(); + assertFalse(decoder.decode( + ByteBuffer.wrap(new byte[] { -1, -2, 32, 0, 98, 0 }), out, + true).isError()); + + decoder.flush(out); + decoder.reset(); + out.clear(); + assertSame(CoderResult.UNDERFLOW, decoder.decode(ByteBuffer + .wrap(new byte[] { -1, -2, 32, 0, 98 }), out, false)); + assertTrue(decoder.decode(ByteBuffer.wrap(new byte[] { 0 }), out, + true).isMalformed()); + + } + } + + public void testLittleEndianByteBufferCharBuffer() + throws CharacterCodingException, UnsupportedEncodingException { + bigEndian = false; + implTestDecodeByteBufferCharBuffer(getByteBuffer()); + bigEndian = true; + } + + public void testLittleEndianReadOnlyByteBufferCharBuffer() + throws CharacterCodingException, UnsupportedEncodingException { + bigEndian = false; + implTestDecodeByteBufferCharBuffer(getByteBuffer().asReadOnlyBuffer()); + bigEndian = true; + } + + public void testLittleEndian() throws CharacterCodingException, + UnsupportedEncodingException { + bigEndian = false; + implTestDecodeByteBuffer(); + bigEndian = true; + } + + // FIXME: give up this tests + // public void testDefaultCharsPerByte() { + // // assertEquals(1, decoder.averageCharsPerByte()); + // // assertEquals(1, decoder.maxCharsPerByte()); + // assertEquals(decoder.averageCharsPerByte(), 0.5, 0.001); + // assertEquals(decoder.maxCharsPerByte(), 2, 0.001); + // } + + ByteBuffer getUnmappedByteBuffer() throws UnsupportedEncodingException { + return null; + } + + ByteBuffer getMalformedByteBuffer() throws UnsupportedEncodingException { + return null; + // FIXME: different here, RI can parse 0xd8d8 + // ByteBuffer buffer = ByteBuffer.allocate(100); + // buffer.put((byte) -1); + // buffer.put((byte) -2); + // buffer.put((byte) 0xdc); + // buffer.put((byte) 0xdc); + // buffer.put(unibytes); + // buffer.flip(); + // return buffer; + } + + ByteBuffer getExceptionByteArray() throws UnsupportedEncodingException { + return null; + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetEncoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetEncoderTest.java new file mode 100644 index 0000000..c113c08 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetEncoderTest.java @@ -0,0 +1,138 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; + +/** + * TODO type def + */ +public class UTF16CharsetEncoderTest extends CharsetEncoderTest { + + // charset for utf-16 + // charset for utf-16be + private static final Charset CS = Charset.forName("utf-16"); + + private static final CharsetDecoder decoder = CS.newDecoder(); + + /* + * @see CharsetEncoderTest#setUp() + */ + protected void setUp() throws Exception { + cs = CS; + specifiedReplacement = new byte[] { -1, -3 }; + surrogate = new byte[] { -1, -2 }; + unibytes = new byte[] { 32, 0, 98, 0, 117, 0, 102, 0, 102, 0, 101, 0, + 114, 0 }; + unibytesWithRep = new byte[] { -3, -1, 32, 0, 98, 0, 117, 0, 102, 0, + 102, 0, 101, 0, 114, 0 }; + super.setUp(); + } + + /* + * @see CharsetEncoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testCharsetEncoderCharsetfloatfloat() { + // this constructor is invalid for UTF16LE CharsetEncoder + } + + public void testCanEncodechar() throws CharacterCodingException { + // normal case for utfCS + assertTrue(encoder.canEncode('\u0077')); + assertTrue(encoder.canEncode('\uc2a3')); + + // for non-mapped char + assertTrue(encoder.canEncode('\uc2c0')); + } + + public void testCanEncodeCharSequence() { + // normal case for utfCS + assertTrue(encoder.canEncode("\u0077")); + assertTrue(encoder.canEncode("\uc2a3")); + assertTrue(encoder.canEncode("")); + + // for non-mapped char + assertTrue(encoder.canEncode("\uc2c0")); + + // surrogate char for unicode + // 1st byte: d800-dbff + // 2nd byte: dc00-dfff + // valid surrogate pair + assertTrue(encoder.canEncode("\ud800\udc00")); + // invalid surrogate pair + assertFalse(encoder.canEncode("\ud800\udb00")); + } + + public void testCanEncodeICUBug() { + assertFalse(encoder.canEncode('\ud800')); + assertFalse(encoder.canEncode("\ud800")); + } + + public void testSpecificDefaultValue() { + assertEquals(encoder.averageBytesPerChar(), 2, 0.001); + // assertEquals(4, encoder.maxBytesPerChar()); + // FIXME: different here! + assertEquals(encoder.maxBytesPerChar(), 2, 0.001); + } + + CharBuffer getMalformedCharBuffer() { + return CharBuffer.wrap("\ud800 buffer"); + } + + CharBuffer getUnmapCharBuffer() { + return null; + } + + CharBuffer getExceptionCharBuffer() { + return null; + } + + public void testIsLegalReplacementEmptyArray() { + assertTrue(encoder.isLegalReplacement(new byte[0])); + } + + protected byte[] getIllegalByteArray() { + return new byte[] { 0x00 }; + } + + protected byte[] getLegalByteArray() { + // FIXME: Different Here! + // return new byte[]{(byte)0xd8, 0x00}; + return new byte[] { (byte) 0x00, (byte) 0xd8 }; + } + + void assertByteArray(ByteBuffer out, byte[] expected) { + out = out.duplicate(); + if (out.position() > 0) { + out.flip(); + } + try { + assertEquals(decoder.decode(out), decoder.decode(ByteBuffer + .wrap(expected))); + } catch (CharacterCodingException e) { + fail(e.toString()); + } + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetTest.java new file mode 100644 index 0000000..61dcf49 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16CharsetTest.java @@ -0,0 +1,51 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +/** + * Test UTF-16. + */ +public class UTF16CharsetTest extends AbstractCharsetTestCase { + + /** + * Constructor. + */ + public UTF16CharsetTest(String arg0) { + super(arg0, "UTF-16", new String[] { "UTF_16" }, true, true); + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testEncode_Normal() + */ + public void testEncode_Normal() { + // TODO Auto-generated method stub + + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testDecode_Normal() + */ + public void testDecode_Normal() { + // TODO Auto-generated method stub + + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetDecoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetDecoderTest.java new file mode 100644 index 0000000..e9a8e56 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetDecoderTest.java @@ -0,0 +1,72 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +/** + * TODO typedef + */ +public class UTF16LECharsetDecoderTest extends CharsetDecoderTest { + + protected void setUp() throws Exception { + cs = Charset.forName("utf-16le"); + super.setUp(); + } + + /* + * @see CharsetDecoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + // // FIXME: give up this tests + // public void testDefaultCharsPerByte(){ + // // assertEquals(1, decoder.averageCharsPerByte()); + // // assertEquals(1, decoder.maxCharsPerByte()); + // assertEquals(decoder.averageCharsPerByte(), 0.5, 0.001); + // assertEquals(decoder.maxCharsPerByte(), 2, 0.001); + // } + + ByteBuffer getUnmappedByteBuffer() throws UnsupportedEncodingException { + // no unmap byte buffer + return null; + } + + ByteBuffer getMalformedByteBuffer() throws UnsupportedEncodingException { + // FIXME: different here, JDK can parse 0xd8d8 + // ByteBuffer buffer = ByteBuffer.allocate(100); + // buffer.put((byte)0xd8); + // buffer.put((byte)0xd8); + // buffer.put(unibytes); + // buffer.flip(); + // return buffer; + return null; + } + + ByteBuffer getExceptionByteArray() throws UnsupportedEncodingException { + return null; + } + + protected ByteBuffer getByteBuffer() { + return ByteBuffer.wrap(new byte[] { 32, 0, 98, 0, 117, 0, 102, 0, 102, + 0, 101, 0, 114, 0 }); + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetEncoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetEncoderTest.java new file mode 100644 index 0000000..26bae5c --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetEncoderTest.java @@ -0,0 +1,118 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; + +/** + * TODO type def + */ +public class UTF16LECharsetEncoderTest extends CharsetEncoderTest { + + // charset for utf-16le + private static final Charset CS = Charset.forName("utf-16le"); + + /* + * @see CharsetEncoderTest#setUp() + */ + protected void setUp() throws Exception { + cs = CS; + specifiedReplacement = new byte[] { -3, -1 }; + + unibytes = new byte[] { 32, 0, 98, 0, 117, 0, 102, 0, 102, 0, 101, 0, + 114, 0 }; + + // unibytesWithRep = new byte[] {(byte)0xfd, (byte)0xff, 32, 0, 98, 0, + // 117, 0, 102, 0, 102, 0, 101, 0, 114 ,0}; + + super.setUp(); + } + + /* + * @see CharsetEncoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testCharsetEncoderCharsetfloatfloat() { + // this constructor is invalid for UTF16LE CharsetEncoder + } + + public void testCanEncodechar() throws CharacterCodingException { + // normal case for utfCS + assertTrue(encoder.canEncode('\u0077')); + assertTrue(encoder.canEncode('\uc2a3')); + + // for non-mapped char + assertTrue(encoder.canEncode('\uc2c0')); + } + + public void testCanEncodeCharSequence() { + // normal case for utfCS + assertTrue(encoder.canEncode("\u0077")); + assertTrue(encoder.canEncode("\uc2a3")); + assertTrue(encoder.canEncode("")); + + // for non-mapped char + assertTrue(encoder.canEncode("\uc2c0")); + + // surrogate char for unicode + // 1st byte: d800-dbff + // 2nd byte: dc00-dfff + // valid surrogate pair + assertTrue(encoder.canEncode("\ud800\udc00")); + // invalid surrogate pair + assertFalse(encoder.canEncode("\ud800\udb00")); + } + + public void testCanEncodeICUBug() { + assertFalse(encoder.canEncode("\ud800")); + } + + public void testSpecificDefaultValue() { + assertEquals(2, encoder.averageBytesPerChar(), 0.001); + assertEquals(2, encoder.maxBytesPerChar(), 0.001); + } + + public void testIsLegalReplacementEmptyArray() { + assertTrue(encoder.isLegalReplacement(new byte[0])); + } + + CharBuffer getMalformedCharBuffer() { + return CharBuffer.wrap("\ud800 buffer"); + } + + CharBuffer getUnmapCharBuffer() { + return null; + } + + CharBuffer getExceptionCharBuffer() { + return null; + } + + protected byte[] getIllegalByteArray() { + return new byte[] { 0x00 }; + } + + protected byte[] getLegalByteArray() { + return new byte[] { (byte) 0xd8, 0x00 }; + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetTest.java new file mode 100644 index 0000000..d795773 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF16LECharsetTest.java @@ -0,0 +1,54 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +/** + * Test UTF-16LE. + */ +public class UTF16LECharsetTest extends AbstractCharsetTestCase { + + /** + * Constructor. + */ + public UTF16LECharsetTest(String arg0) { + super(arg0, "UTF-16LE", new String[] { "UTF_16LE", "X-UTF-16LE" }, + true, true); + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testEncode_Normal() + */ + public void testEncode_Normal() { + String input = "ab\u5D14\u654F"; + byte[] output = new byte[] { 97, 0, 98, 0, 20, 93, 79, 101 }; + internalTestEncode(input, output); + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testDecode_Normal() + */ + public void testDecode_Normal() { + byte[] input = new byte[] { 97, 0, 98, 0, 20, 93, 79, 101 }; + char[] output = "ab\u5D14\u654F".toCharArray(); + internalTestDecode(input, output); + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF8CharsetTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF8CharsetTest.java new file mode 100644 index 0000000..8ab8b5c --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTF8CharsetTest.java @@ -0,0 +1,62 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.io.UnsupportedEncodingException; + +/** + * Test UTF-8 charset. + */ +public class UTF8CharsetTest extends AbstractCharsetTestCase { + + /** + * Constructor for UTF8CharsetTest. + * + */ + public UTF8CharsetTest(String arg0) { + super(arg0, "UTF-8", new String[] { "UTF8" }, true, true); + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testDecode_Normal() + */ + public void testDecode_Normal() { + byte[] input = new byte[] { 97, 98, -27, -76, -108, -26, -107, -113 }; + char[] output = "ab\u5D14\u654F".toCharArray(); + internalTestDecode(input, output); + } + + /* + * (non-Javadoc) + * + * @see tests.api.java.nio.charset.ConcreteCharsetTest#testEncode_Normal() + */ + public void testEncode_Normal() { + String input = "ab\u5D14\u654F"; + byte[] output = new byte[] { 97, 98, -27, -76, -108, -26, -107, -113 }; + internalTestEncode(input, output); + } + + public void test_surrogate() throws UnsupportedEncodingException { + // U+1D11E: MUSICAL SYMBOL G CLEF + String s = new StringBuilder().appendCodePoint(0x1D11E).toString(); + byte utf8[] = s.getBytes("UTF-8"); + assertEquals(s, new String(utf8, 0, utf8.length, "UTF-8")); + } +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetDecoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetDecoderTest.java new file mode 100644 index 0000000..b8ed9fd --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetDecoderTest.java @@ -0,0 +1,76 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +/** + * test utf-8 decoder + */ +public class UTFCharsetDecoderTest extends CharsetDecoderTest { + + protected void setUp() throws Exception { + cs = Charset.forName("utf-8"); + super.setUp(); + } + + /* + * @see CharsetDecoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + // FIXME: give up this tests + // public void testDefaultCharsPerByte(){ + // assertEquals(decoder.averageCharsPerByte(), 0.333, 0.001); + // assertEquals(decoder.maxCharsPerByte(), 2, 0.001); + // // assertEquals(1, decoder.averageCharsPerByte()); + // // assertEquals(1, decoder.maxCharsPerByte()); + // } + + ByteBuffer getUnmappedByteBuffer() throws UnsupportedEncodingException { + return null; + } + + ByteBuffer getMalformedByteBuffer() throws UnsupportedEncodingException { + ByteBuffer buffer = ByteBuffer.allocate(getByteBuffer().remaining() + 1); + buffer.put((byte) 0xd8); + buffer.put(getByteBuffer()); + buffer.flip(); + return buffer; + } + + ByteBuffer getExceptionByteArray() throws UnsupportedEncodingException { + return null; + } + + protected String getString() { + return " buffer \u041c\u0430\u0441\u044e\u043b\u044f \u611b"; + } + + protected ByteBuffer getByteBuffer() { + return ByteBuffer.wrap(new byte[] { 32, 98, 117, 102, 102, 101, 114, + 32, (byte) 0xd0, (byte) 0x9c, (byte) 0xd0, (byte) 0xb0, + (byte) 0xd1, (byte) 0x81, (byte) 0xd1, (byte) 0x8e, + (byte) 0xd0, (byte) 0xbb, (byte) 0xd1, (byte) 0x8f, 32, + (byte) 0xe6, (byte) 0x84, (byte) 0x9b }); + } + +} diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetEncoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetEncoderTest.java new file mode 100644 index 0000000..0096856 --- /dev/null +++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetEncoderTest.java @@ -0,0 +1,103 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.nio.charset; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; + +/** + * test case specific activity of utf-8 charset encoder + */ +public class UTFCharsetEncoderTest extends CharsetEncoderTest { + + // charset for UTF-8 + private static final Charset CS = Charset.forName("utf-8"); + + /* + * @see CharsetEncoderTest#setUp() + */ + protected void setUp() throws Exception { + cs = CS; + specifiedReplacement = new byte[] { 63 }; + super.setUp(); + } + + /* + * @see CharsetEncoderTest#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testCanEncodechar() throws CharacterCodingException { + // normal case for utfCS + assertTrue(encoder.canEncode('\u0077')); + assertTrue(encoder.canEncode('\uc2a3')); + + // for non-mapped char + assertTrue(encoder.canEncode('\uc2c0')); + } + + public void testCanEncodeCharSequence() { + // normal case for utfCS + assertTrue(encoder.canEncode("\u0077")); + assertTrue(encoder.canEncode("\uc2a3")); + assertTrue(encoder.canEncode("")); + + // for non-mapped char + assertTrue(encoder.canEncode("\uc2c0")); + + // surrogate char for unicode + // 1st byte: d800-dbff + // 2nd byte: dc00-dfff + // valid surrogate pair + assertTrue(encoder.canEncode("\ud800\udc00")); + // invalid surrogate pair + assertFalse(encoder.canEncode("\ud800\udb00")); + } + + public void testCanEncodeICUBug() { + assertFalse(encoder.canEncode("\ud800")); + } + + public void testSpecificDefaultValue() { + assertEquals(1.1, encoder.averageBytesPerChar(), 0.0001); + // assertEquals(2, encoder.averageBytesPerChar(), 0.0001); + assertEquals(4, encoder.maxBytesPerChar(), 0); + // assertEquals(3, encoder.maxBytesPerChar(), 0); + } + + CharBuffer getMalformedCharBuffer() { + return CharBuffer.wrap("\ud800 buffer"); + } + + CharBuffer getUnmapCharBuffer() { + return null; + } + + CharBuffer getExceptionCharBuffer() { + return null; + } + + protected byte[] getIllegalByteArray() { + return new byte[] { (byte) 0xd8, (byte) 0x00 }; + } + + protected void assertFlushed() { + } +} |