diff options
Diffstat (limited to 'tests/src/com/android/inputmethod/latin/utils')
13 files changed, 2674 insertions, 0 deletions
diff --git a/tests/src/com/android/inputmethod/latin/utils/AsyncResultHolderTests.java b/tests/src/com/android/inputmethod/latin/utils/AsyncResultHolderTests.java new file mode 100644 index 000000000..7fd167977 --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/AsyncResultHolderTests.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.MediumTest; +import android.util.Log; + +@MediumTest +public class AsyncResultHolderTests extends AndroidTestCase { + private static final String TAG = AsyncResultHolderTests.class.getSimpleName(); + + private static final int TIMEOUT_IN_MILLISECONDS = 500; + private static final int MARGIN_IN_MILLISECONDS = 250; + private static final int DEFAULT_VALUE = 2; + private static final int SET_VALUE = 1; + + private <T> void setAfterGivenTime(final AsyncResultHolder<T> holder, final T value, + final long time) { + new Thread(new Runnable() { + @Override + public void run() { + try { + Thread.sleep(time); + } catch (InterruptedException e) { + Log.d(TAG, "Exception while sleeping", e); + } + holder.set(value); + } + }).start(); + } + + public void testGetWithoutSet() { + final AsyncResultHolder<Integer> holder = new AsyncResultHolder<Integer>(); + final int resultValue = holder.get(DEFAULT_VALUE, TIMEOUT_IN_MILLISECONDS); + assertEquals(DEFAULT_VALUE, resultValue); + } + + public void testGetBeforeSet() { + final AsyncResultHolder<Integer> holder = new AsyncResultHolder<Integer>(); + setAfterGivenTime(holder, SET_VALUE, TIMEOUT_IN_MILLISECONDS + MARGIN_IN_MILLISECONDS); + final int resultValue = holder.get(DEFAULT_VALUE, TIMEOUT_IN_MILLISECONDS); + assertEquals(DEFAULT_VALUE, resultValue); + } + + public void testGetAfterSet() { + final AsyncResultHolder<Integer> holder = new AsyncResultHolder<Integer>(); + holder.set(SET_VALUE); + final int resultValue = holder.get(DEFAULT_VALUE, TIMEOUT_IN_MILLISECONDS); + assertEquals(SET_VALUE, resultValue); + } + + public void testGetBeforeTimeout() { + final AsyncResultHolder<Integer> holder = new AsyncResultHolder<Integer>(); + setAfterGivenTime(holder, SET_VALUE, TIMEOUT_IN_MILLISECONDS - MARGIN_IN_MILLISECONDS); + final int resultValue = holder.get(DEFAULT_VALUE, TIMEOUT_IN_MILLISECONDS); + assertEquals(SET_VALUE, resultValue); + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/Base64ReaderTests.java b/tests/src/com/android/inputmethod/latin/utils/Base64ReaderTests.java new file mode 100644 index 000000000..b311f5d37 --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/Base64ReaderTests.java @@ -0,0 +1,225 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +import java.io.EOFException; +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.StringReader; + +@SmallTest +public class Base64ReaderTests extends AndroidTestCase { + private static final String EMPTY_STRING = ""; + private static final String INCOMPLETE_CHAR1 = "Q"; + // Encode 'A'. + private static final String INCOMPLETE_CHAR2 = "QQ"; + // Encode 'A', 'B' + private static final String INCOMPLETE_CHAR3 = "QUI"; + // Encode 'A', 'B', 'C' + private static final String COMPLETE_CHAR4 = "QUJD"; + private static final String ALL_BYTE_PATTERN = + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIj\n" + + "JCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZH\n" + + "SElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\n" + + "bG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6P\n" + + "kJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKz\n" + + "tLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX\n" + + "2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7\n" + + "/P3+/w=="; + + public void test0CharInt8() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(EMPTY_STRING))); + try { + reader.readUint8(); + fail("0 char"); + } catch (final EOFException e) { + assertEquals("0 char", 0, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void test1CharInt8() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(INCOMPLETE_CHAR1))); + try { + reader.readUint8(); + fail("1 char"); + } catch (final EOFException e) { + assertEquals("1 char", 0, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void test2CharsInt8() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(INCOMPLETE_CHAR2))); + try { + final int v1 = reader.readUint8(); + assertEquals("2 chars pos 0", 'A', v1); + reader.readUint8(); + fail("2 chars"); + } catch (final EOFException e) { + assertEquals("2 chars", 1, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void test3CharsInt8() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(INCOMPLETE_CHAR3))); + try { + final int v1 = reader.readUint8(); + assertEquals("3 chars pos 0", 'A', v1); + final int v2 = reader.readUint8(); + assertEquals("3 chars pos 1", 'B', v2); + reader.readUint8(); + fail("3 chars"); + } catch (final EOFException e) { + assertEquals("3 chars", 2, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void test4CharsInt8() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(COMPLETE_CHAR4))); + try { + final int v1 = reader.readUint8(); + assertEquals("4 chars pos 0", 'A', v1); + final int v2 = reader.readUint8(); + assertEquals("4 chars pos 1", 'B', v2); + final int v3 = reader.readUint8(); + assertEquals("4 chars pos 2", 'C', v3); + reader.readUint8(); + fail("4 chars"); + } catch (final EOFException e) { + assertEquals("4 chars", 3, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void testAllBytePatternInt8() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(ALL_BYTE_PATTERN))); + try { + for (int i = 0; i <= 0xff; i++) { + final int v = reader.readUint8(); + assertEquals("value: all byte pattern: pos " + i, i, v); + assertEquals("count: all byte pattern: pos " + i, i + 1, reader.getByteCount()); + } + } catch (final EOFException e) { + assertEquals("all byte pattern", 256, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void test0CharInt16() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(EMPTY_STRING))); + try { + reader.readInt16(); + fail("0 char"); + } catch (final EOFException e) { + assertEquals("0 char", 0, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void test1CharInt16() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(INCOMPLETE_CHAR1))); + try { + reader.readInt16(); + fail("1 char"); + } catch (final EOFException e) { + assertEquals("1 char", 0, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void test2CharsInt16() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(INCOMPLETE_CHAR2))); + try { + reader.readInt16(); + fail("2 chars"); + } catch (final EOFException e) { + assertEquals("2 chars", 1, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void test3CharsInt16() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(INCOMPLETE_CHAR3))); + try { + final short v1 = reader.readInt16(); + assertEquals("3 chars pos 0", 'A' << 8 | 'B', v1); + reader.readInt16(); + fail("3 chars"); + } catch (final EOFException e) { + assertEquals("3 chars", 2, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void test4CharsInt16() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(COMPLETE_CHAR4))); + try { + final short v1 = reader.readInt16(); + assertEquals("4 chars pos 0", 'A' << 8 | 'B', v1); + reader.readInt16(); + fail("4 chars"); + } catch (final EOFException e) { + assertEquals("4 chars", 3, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } + + public void testAllBytePatternInt16() { + final Base64Reader reader = new Base64Reader( + new LineNumberReader(new StringReader(ALL_BYTE_PATTERN))); + try { + for (int i = 0; i <= 0xff; i += 2) { + final short v = reader.readInt16(); + final short expected = (short)(i << 8 | (i + 1)); + assertEquals("value: all byte pattern: pos " + i, expected, v); + assertEquals("count: all byte pattern: pos " + i, i + 2, reader.getByteCount()); + } + } catch (final EOFException e) { + assertEquals("all byte pattern", 256, reader.getByteCount()); + } catch (final IOException e) { + fail("IOException: " + e); + } + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/CapsModeUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/CapsModeUtilsTests.java new file mode 100644 index 000000000..cf3bdd680 --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/CapsModeUtilsTests.java @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; +import android.text.TextUtils; + +import java.util.Locale; + +@SmallTest +public class CapsModeUtilsTests extends AndroidTestCase { + private static void onePathForCaps(final CharSequence cs, final int expectedResult, + final int mask, final Locale l, final boolean hasSpaceBefore) { + int oneTimeResult = expectedResult & mask; + assertEquals("After >" + cs + "<", oneTimeResult, + CapsModeUtils.getCapsMode(cs, mask, l, hasSpaceBefore)); + } + + private static void allPathsForCaps(final CharSequence cs, final int expectedResult, + final Locale l, final boolean hasSpaceBefore) { + final int c = TextUtils.CAP_MODE_CHARACTERS; + final int w = TextUtils.CAP_MODE_WORDS; + final int s = TextUtils.CAP_MODE_SENTENCES; + onePathForCaps(cs, expectedResult, c | w | s, l, hasSpaceBefore); + onePathForCaps(cs, expectedResult, w | s, l, hasSpaceBefore); + onePathForCaps(cs, expectedResult, c | s, l, hasSpaceBefore); + onePathForCaps(cs, expectedResult, c | w, l, hasSpaceBefore); + onePathForCaps(cs, expectedResult, c, l, hasSpaceBefore); + onePathForCaps(cs, expectedResult, w, l, hasSpaceBefore); + onePathForCaps(cs, expectedResult, s, l, hasSpaceBefore); + } + + public void testGetCapsMode() { + final int c = TextUtils.CAP_MODE_CHARACTERS; + final int w = TextUtils.CAP_MODE_WORDS; + final int s = TextUtils.CAP_MODE_SENTENCES; + Locale l = Locale.ENGLISH; + allPathsForCaps("", c | w | s, l, false); + allPathsForCaps("Word", c, l, false); + allPathsForCaps("Word.", c, l, false); + allPathsForCaps("Word ", c | w, l, false); + allPathsForCaps("Word. ", c | w | s, l, false); + allPathsForCaps("Word..", c, l, false); + allPathsForCaps("Word.. ", c | w | s, l, false); + allPathsForCaps("Word... ", c | w | s, l, false); + allPathsForCaps("Word ... ", c | w | s, l, false); + allPathsForCaps("Word . ", c | w, l, false); + allPathsForCaps("In the U.S ", c | w, l, false); + allPathsForCaps("In the U.S. ", c | w, l, false); + allPathsForCaps("Some stuff (e.g. ", c | w, l, false); + allPathsForCaps("In the U.S.. ", c | w | s, l, false); + allPathsForCaps("\"Word.\" ", c | w | s, l, false); + allPathsForCaps("\"Word\". ", c | w | s, l, false); + allPathsForCaps("\"Word\" ", c | w, l, false); + + // Test for phantom space + allPathsForCaps("Word", c | w, l, true); + allPathsForCaps("Word.", c | w | s, l, true); + + // Tests after some whitespace + allPathsForCaps("Word\n", c | w | s, l, false); + allPathsForCaps("Word\n", c | w | s, l, true); + allPathsForCaps("Word\n ", c | w | s, l, true); + allPathsForCaps("Word.\n", c | w | s, l, false); + allPathsForCaps("Word.\n", c | w | s, l, true); + allPathsForCaps("Word.\n ", c | w | s, l, true); + + l = Locale.FRENCH; + allPathsForCaps("\"Word.\" ", c | w, l, false); + allPathsForCaps("\"Word\". ", c | w | s, l, false); + allPathsForCaps("\"Word\" ", c | w, l, false); + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/CsvUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/CsvUtilsTests.java new file mode 100644 index 000000000..a0fa8fe4b --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/CsvUtilsTests.java @@ -0,0 +1,424 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +import com.android.inputmethod.latin.utils.CsvUtils.CsvParseException; + +import java.util.Arrays; + +@SmallTest +public class CsvUtilsTests extends AndroidTestCase { + public void testUnescape() { + assertEquals("", CsvUtils.unescapeField("")); + assertEquals("text", CsvUtils.unescapeField("text")); // text + assertEquals("", CsvUtils.unescapeField("\"\"")); // "" + assertEquals("\"", CsvUtils.unescapeField("\"\"\"\"")); // """" -> " + assertEquals("text", CsvUtils.unescapeField("\"text\"")); // "text" -> text + assertEquals("\"text", CsvUtils.unescapeField("\"\"\"text\"")); // """text" -> "text + assertEquals("text\"", CsvUtils.unescapeField("\"text\"\"\"")); // "text""" -> text" + assertEquals("te\"xt", CsvUtils.unescapeField("\"te\"\"xt\"")); // "te""xt" -> te"xt + assertEquals("\"text\"", + CsvUtils.unescapeField("\"\"\"text\"\"\"")); // """text""" -> "text" + assertEquals("t\"e\"x\"t", + CsvUtils.unescapeField("\"t\"\"e\"\"x\"\"t\"")); // "t""e""x""t" -> t"e"x"t + } + + public void testUnescapeException() { + try { + final String text = CsvUtils.unescapeField("\""); // " + fail("Unterminated quote: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Unterminated quote", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("\"\"\""); // """ + fail("Unterminated quote: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Unterminated quote", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("\"\"\"\"\""); // """"" + fail("Unterminated quote: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Unterminated quote", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("\"text"); // "text + fail("Unterminated quote: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Unterminated quote", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("text\""); // text" + fail("Raw quote in text: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Raw quote in text", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("te\"xt"); // te"xt + fail("Raw quote in text: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Raw quote in text", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("\"\"text"); // ""text + fail("Raw quote in quoted text: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Raw quote in quoted text", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("text\"\""); // text"" + fail("Escaped quote in text: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Escaped quote in text", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("te\"\"xt"); // te""xt + fail("Escaped quote in text: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Escaped quote in text", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("\"\"text\""); // ""text" + fail("Raw quote in quoted text: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Raw quote in quoted text", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("\"text\"\""); // "text"" + fail("Unterminated quote: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Unterminated quote", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("\"te\"xt\""); // "te"xt" + fail("Raw quote in quoted text: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Raw quote in quoted text", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("\"b,c"); // "b,c + fail("Unterminated quote: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Unterminated quote", success.getMessage()); + } + try { + final String text = CsvUtils.unescapeField("\",\"a\""); // ","a" + fail("Raw quote in quoted text: text=" + text); + } catch (final CsvParseException success) { + assertEquals("Raw quote in quoted text", success.getMessage()); + } + } + + private static <T> void assertArrayEquals(final T[] expected, final T[] actual) { + if (expected == actual) { + return; + } + if (expected == null || actual == null) { + assertEquals(Arrays.toString(expected), Arrays.toString(actual)); + return; + } + if (expected.length != actual.length) { + assertEquals("[length]", Arrays.toString(expected), Arrays.toString(actual)); + return; + } + for (int i = 0; i < expected.length; i++) { + final T e = expected[i]; + final T a = actual[i]; + if (e == a) { + continue; + } + assertEquals("["+i+"]", expected[i], actual[i]); + } + } + + public void testSplit() { + assertArrayEquals(new String[]{""}, CsvUtils.split("")); + assertArrayEquals(new String[]{" "}, CsvUtils.split(" ")); + assertArrayEquals(new String[]{"text"}, CsvUtils.split("text")); + assertArrayEquals(new String[]{" a b "}, CsvUtils.split(" a b ")); + + assertArrayEquals(new String[]{"", ""}, CsvUtils.split(",")); + assertArrayEquals(new String[]{"", "", ""}, CsvUtils.split(",,")); + assertArrayEquals(new String[]{" ", " "}, CsvUtils.split(" , ")); + assertArrayEquals(new String[]{" ", " ", " "}, CsvUtils.split(" , , ")); + assertArrayEquals(new String[]{"a", "b"}, CsvUtils.split("a,b")); + assertArrayEquals(new String[]{" a ", " b "}, CsvUtils.split(" a , b ")); + + assertArrayEquals(new String[]{"text"}, + CsvUtils.split("\"text\"")); // "text" + assertArrayEquals(new String[]{" text "}, + CsvUtils.split("\" text \"")); // "_text_" + + assertArrayEquals(new String[]{""}, + CsvUtils.split("\"\"")); // "" + assertArrayEquals(new String[]{"\""}, + CsvUtils.split("\"\"\"\"")); // """" + assertArrayEquals(new String[]{"", ""}, + CsvUtils.split("\"\",\"\"")); // "","" + assertArrayEquals(new String[]{"\",\""}, + CsvUtils.split("\"\"\",\"\"\"")); // """,""" + assertArrayEquals(new String[]{"\"", "\""}, + CsvUtils.split("\"\"\"\",\"\"\"\"")); // """","""" + assertArrayEquals(new String[]{"\"", "\",\""}, + CsvUtils.split("\"\"\"\",\"\"\",\"\"\"")); // """",""",""" + assertArrayEquals(new String[]{"\",\"", "\""}, + CsvUtils.split("\"\"\",\"\"\",\"\"\"\"")); // """,""","""" + + assertArrayEquals(new String[]{" a ", " b , c "}, + CsvUtils.split(" a ,\" b , c \"")); // _a_,"_b_,_c_" + assertArrayEquals(new String[]{" a ", " b , c ", " d "}, + CsvUtils.split(" a ,\" b , c \", d ")); // _a_,"_b_,_c_",_d_ + } + + public void testSplitException() { + try { + final String[] fields = CsvUtils.split(" \"text\" "); // _"text"_ + fail("Raw quote in text: fields=" + Arrays.toString(fields)); + } catch (final CsvParseException success) { + assertEquals("Raw quote in text", success.getMessage()); + } + try { + final String[] fields = CsvUtils.split(" \" text \" "); // _"_text_"_ + fail("Raw quote in text: fields=" + Arrays.toString(fields)); + } catch (final CsvParseException success) { + assertEquals("Raw quote in text", success.getMessage()); + } + + try { + final String[] fields = CsvUtils.split("a,\"b,"); // a,",b + fail("Unterminated quote: fields=" + Arrays.toString(fields)); + } catch (final CsvParseException success) { + assertEquals("Unterminated quote", success.getMessage()); + } + try { + final String[] fields = CsvUtils.split("a,\"\"\",b"); // a,""",b + fail("Unterminated quote: fields=" + Arrays.toString(fields)); + } catch (final CsvParseException success) { + assertEquals("Unterminated quote", success.getMessage()); + } + try { + final String[] fields = CsvUtils.split("a,\"\"\"\"\",b"); // a,""""",b + fail("Unterminated quote: fields=" + Arrays.toString(fields)); + } catch (final CsvParseException success) { + assertEquals("Unterminated quote", success.getMessage()); + } + try { + final String[] fields = CsvUtils.split("a,\"b,c"); // a,"b,c + fail("Unterminated quote: fields=" + Arrays.toString(fields)); + } catch (final CsvParseException success) { + assertEquals("Unterminated quote", success.getMessage()); + } + try { + final String[] fields = CsvUtils.split("a,\",\"b,c"); // a,","b,c + fail("Raw quote in quoted text: fields=" + Arrays.toString(fields)); + } catch (final CsvParseException success) { + assertEquals("Raw quote in quoted text", success.getMessage()); + } + try { + final String[] fields = CsvUtils.split("a,\",\"b\",\",c"); // a,","b",",c + fail("Raw quote in quoted text: fields=" + Arrays.toString(fields)); + } catch (final CsvParseException success) { + assertEquals("Raw quote in quoted text", success.getMessage()); + } + } + + public void testSplitWithTrimSpaces() { + final int trimSpaces = CsvUtils.SPLIT_FLAGS_TRIM_SPACES; + assertArrayEquals(new String[]{""}, CsvUtils.split(trimSpaces, "")); + assertArrayEquals(new String[]{""}, CsvUtils.split(trimSpaces, " ")); + assertArrayEquals(new String[]{"text"}, CsvUtils.split(trimSpaces, "text")); + assertArrayEquals(new String[]{"a b"}, CsvUtils.split(trimSpaces, " a b ")); + + assertArrayEquals(new String[]{"", ""}, CsvUtils.split(trimSpaces, ",")); + assertArrayEquals(new String[]{"", "", ""}, CsvUtils.split(trimSpaces, ",,")); + assertArrayEquals(new String[]{"", ""}, CsvUtils.split(trimSpaces, " , ")); + assertArrayEquals(new String[]{"", "", ""}, CsvUtils.split(trimSpaces, " , , ")); + assertArrayEquals(new String[]{"a", "b"}, CsvUtils.split(trimSpaces, "a,b")); + assertArrayEquals(new String[]{"a", "b"}, CsvUtils.split(trimSpaces, " a , b ")); + + assertArrayEquals(new String[]{"text"}, + CsvUtils.split(trimSpaces, "\"text\"")); // "text" + assertArrayEquals(new String[]{"text"}, + CsvUtils.split(trimSpaces, " \"text\" ")); // _"text"_ + assertArrayEquals(new String[]{" text "}, + CsvUtils.split(trimSpaces, "\" text \"")); // "_text_" + assertArrayEquals(new String[]{" text "}, + CsvUtils.split(trimSpaces, " \" text \" ")); // _"_text_"_ + assertArrayEquals(new String[]{"a", "b"}, + CsvUtils.split(trimSpaces, " \"a\" , \"b\" ")); // _"a"_,_"b"_ + + assertArrayEquals(new String[]{""}, + CsvUtils.split(trimSpaces, " \"\" ")); // _""_ + assertArrayEquals(new String[]{"\""}, + CsvUtils.split(trimSpaces, " \"\"\"\" ")); // _""""_ + assertArrayEquals(new String[]{"", ""}, + CsvUtils.split(trimSpaces, " \"\" , \"\" ")); // _""_,_""_ + assertArrayEquals(new String[]{"\" , \""}, + CsvUtils.split(trimSpaces, " \"\"\" , \"\"\" ")); // _"""_,_"""_ + assertArrayEquals(new String[]{"\"", "\""}, + CsvUtils.split(trimSpaces, " \"\"\"\" , \"\"\"\" ")); // _""""_,_""""_ + assertArrayEquals(new String[]{"\"", "\" , \""}, + CsvUtils.split(trimSpaces, " \"\"\"\" , \"\"\" , \"\"\" ")); // _""""_,_"""_,_"""_ + assertArrayEquals(new String[]{"\" , \"", "\""}, + CsvUtils.split(trimSpaces, " \"\"\" , \"\"\" , \"\"\"\" ")); // _"""_,_"""_,_""""_ + + assertArrayEquals(new String[]{"a", " b , c "}, + CsvUtils.split(trimSpaces, " a , \" b , c \" ")); // _a_,_"_b_,_c_"_ + assertArrayEquals(new String[]{"a", " b , c ", "d"}, + CsvUtils.split(trimSpaces, " a, \" b , c \" , d ")); // _a,_"_b_,_c_"_,_d_ + } + + public void testEscape() { + assertEquals("", CsvUtils.escapeField("", false)); + assertEquals("plain", CsvUtils.escapeField("plain", false)); + assertEquals(" ", CsvUtils.escapeField(" ", false)); + assertEquals(" ", CsvUtils.escapeField(" ", false)); + assertEquals("a space", CsvUtils.escapeField("a space", false)); + assertEquals(" space-at-start", CsvUtils.escapeField(" space-at-start", false)); + assertEquals("space-at-end ", CsvUtils.escapeField("space-at-end ", false)); + assertEquals("a lot of spaces", CsvUtils.escapeField("a lot of spaces", false)); + assertEquals("\",\"", CsvUtils.escapeField(",", false)); + assertEquals("\",,\"", CsvUtils.escapeField(",,", false)); + assertEquals("\"a,comma\"", CsvUtils.escapeField("a,comma", false)); + assertEquals("\",comma-at-begin\"", CsvUtils.escapeField(",comma-at-begin", false)); + assertEquals("\"comma-at-end,\"", CsvUtils.escapeField("comma-at-end,", false)); + assertEquals("\",,a,lot,,,of,commas,,\"", + CsvUtils.escapeField(",,a,lot,,,of,commas,,", false)); + assertEquals("\"a comma,and a space\"", CsvUtils.escapeField("a comma,and a space", false)); + assertEquals("\"\"\"\"", CsvUtils.escapeField("\"", false)); // " -> """" + assertEquals("\"\"\"\"\"\"", CsvUtils.escapeField("\"\"", false)); // "" -> """""" + assertEquals("\"\"\"\"\"\"\"\"", CsvUtils.escapeField("\"\"\"", false)); // """ -> """""""" + assertEquals("\"\"\"text\"\"\"", + CsvUtils.escapeField("\"text\"", false)); // "text" -> """text""" + assertEquals("\"text has \"\" in middle\"", + CsvUtils.escapeField("text has \" in middle", false)); + assertEquals("\"\"\"quote,at begin\"", CsvUtils.escapeField("\"quote,at begin", false)); + assertEquals("\"quote at,end\"\"\"", CsvUtils.escapeField("quote at,end\"", false)); + assertEquals("\"\"\"quote at begin\"", CsvUtils.escapeField("\"quote at begin", false)); + assertEquals("\"quote at end\"\"\"", CsvUtils.escapeField("quote at end\"", false)); + } + + public void testEscapeWithAlwaysQuoted() { + assertEquals("\"\"", CsvUtils.escapeField("", true)); + assertEquals("\"plain\"", CsvUtils.escapeField("plain", true)); + assertEquals("\" \"", CsvUtils.escapeField(" ", true)); + assertEquals("\" \"", CsvUtils.escapeField(" ", true)); + assertEquals("\"a space\"", CsvUtils.escapeField("a space", true)); + assertEquals("\" space-at-start\"", CsvUtils.escapeField(" space-at-start", true)); + assertEquals("\"space-at-end \"", CsvUtils.escapeField("space-at-end ", true)); + assertEquals("\"a lot of spaces\"", CsvUtils.escapeField("a lot of spaces", true)); + assertEquals("\",\"", CsvUtils.escapeField(",", true)); + assertEquals("\",,\"", CsvUtils.escapeField(",,", true)); + assertEquals("\"a,comma\"", CsvUtils.escapeField("a,comma", true)); + assertEquals("\",comma-at-begin\"", CsvUtils.escapeField(",comma-at-begin", true)); + assertEquals("\"comma-at-end,\"", CsvUtils.escapeField("comma-at-end,", true)); + assertEquals("\",,a,lot,,,of,commas,,\"", + CsvUtils.escapeField(",,a,lot,,,of,commas,,", true)); + assertEquals("\"a comma,and a space\"", CsvUtils.escapeField("a comma,and a space", true)); + assertEquals("\"\"\"\"", CsvUtils.escapeField("\"", true)); // " -> """" + assertEquals("\"\"\"\"\"\"", CsvUtils.escapeField("\"\"", true)); // "" -> """""" + assertEquals("\"\"\"\"\"\"\"\"", CsvUtils.escapeField("\"\"\"", true)); // """ -> """""""" + assertEquals("\"\"\"text\"\"\"", + CsvUtils.escapeField("\"text\"", true)); // "text" -> """text""" + assertEquals("\"text has \"\" in middle\"", + CsvUtils.escapeField("text has \" in middle", true)); + assertEquals("\"\"\"quote,at begin\"", CsvUtils.escapeField("\"quote,at begin", true)); + assertEquals("\"quote at,end\"\"\"", CsvUtils.escapeField("quote at,end\"", true)); + assertEquals("\"\"\"quote at begin\"", CsvUtils.escapeField("\"quote at begin", true)); + assertEquals("\"quote at end\"\"\"", CsvUtils.escapeField("quote at end\"", true)); + } + + public void testJoinWithoutColumnPositions() { + assertEquals("", CsvUtils.join()); + assertEquals("", CsvUtils.join("")); + assertEquals(",", CsvUtils.join("", "")); + + assertEquals("text, text,text ", + CsvUtils.join("text", " text", "text ")); + assertEquals("\"\"\"\",\"\"\"\"\"\",\"\"\"text\"\"\"", + CsvUtils.join("\"", "\"\"", "\"text\"")); + assertEquals("a b,\"c,d\",\"e\"\"f\"", + CsvUtils.join("a b", "c,d", "e\"f")); + } + + public void testJoinWithoutColumnPositionsWithExtraSpace() { + final int extraSpace = CsvUtils.JOIN_FLAGS_EXTRA_SPACE; + assertEquals("", CsvUtils.join(extraSpace)); + assertEquals("", CsvUtils.join(extraSpace, "")); + assertEquals(", ", CsvUtils.join(extraSpace, "", "")); + + assertEquals("text, text, text ", + CsvUtils.join(extraSpace, "text", " text", "text ")); + // ","","text" -> """","""""","""text""" + assertEquals("\"\"\"\", \"\"\"\"\"\", \"\"\"text\"\"\"", + CsvUtils.join(extraSpace, "\"", "\"\"", "\"text\"")); + assertEquals("a b, \"c,d\", \"e\"\"f\"", + CsvUtils.join(extraSpace, "a b", "c,d", "e\"f")); + } + + public void testJoinWithoutColumnPositionsWithExtraSpaceAndAlwaysQuoted() { + final int extrSpaceAndQuoted = + CsvUtils.JOIN_FLAGS_EXTRA_SPACE | CsvUtils.JOIN_FLAGS_ALWAYS_QUOTED; + assertEquals("", CsvUtils.join(extrSpaceAndQuoted)); + assertEquals("\"\"", CsvUtils.join(extrSpaceAndQuoted, "")); + assertEquals("\"\", \"\"", CsvUtils.join(extrSpaceAndQuoted, "", "")); + + assertEquals("\"text\", \" text\", \"text \"", + CsvUtils.join(extrSpaceAndQuoted, "text", " text", "text ")); + // ","","text" -> """", """""", """text""" + assertEquals("\"\"\"\", \"\"\"\"\"\", \"\"\"text\"\"\"", + CsvUtils.join(extrSpaceAndQuoted, "\"", "\"\"", "\"text\"")); + assertEquals("\"a b\", \"c,d\", \"e\"\"f\"", + CsvUtils.join(extrSpaceAndQuoted, "a b", "c,d", "e\"f")); + } + + public void testJoinWithColumnPositions() { + final int noFlags = CsvUtils.JOIN_FLAGS_NONE; + assertEquals("", CsvUtils.join(noFlags, new int[]{})); + assertEquals(" ", CsvUtils.join(noFlags, new int[]{3}, "")); + assertEquals(" ,", CsvUtils.join(noFlags, new int[]{1}, "", "")); + assertEquals(", ", CsvUtils.join(noFlags, new int[]{0, 3}, "", "")); + + assertEquals("text, text, text ", + CsvUtils.join(noFlags, new int[]{0, 8, 15}, "text", " text", "text ")); + // ","","text" -> """", """""","""text""" + assertEquals("\"\"\"\", \"\"\"\"\"\",\"\"\"text\"\"\"", + CsvUtils.join(noFlags, new int[]{0, 8, 15}, "\"", "\"\"", "\"text\"")); + assertEquals("a b, \"c,d\", \"e\"\"f\"", + CsvUtils.join(noFlags, new int[]{0, 8, 15}, "a b", "c,d", "e\"f")); + } + + public void testJoinWithColumnPositionsWithExtraSpace() { + final int extraSpace = CsvUtils.JOIN_FLAGS_EXTRA_SPACE; + assertEquals("", CsvUtils.join(extraSpace, new int[]{})); + assertEquals(" ", CsvUtils.join(extraSpace, new int[]{3}, "")); + assertEquals(" , ", CsvUtils.join(extraSpace, new int[]{1}, "", "")); + assertEquals(", ", CsvUtils.join(extraSpace, new int[]{0, 3}, "", "")); + + assertEquals("text, text, text ", + CsvUtils.join(extraSpace, new int[]{0, 8, 15}, "text", " text", "text ")); + // ","","text" -> """", """""", """text""" + assertEquals("\"\"\"\", \"\"\"\"\"\", \"\"\"text\"\"\"", + CsvUtils.join(extraSpace, new int[]{0, 8, 15}, "\"", "\"\"", "\"text\"")); + assertEquals("a b, \"c,d\", \"e\"\"f\"", + CsvUtils.join(extraSpace, new int[]{0, 8, 15}, "a b", "c,d", "e\"f")); + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/ForgettingCurveTests.java b/tests/src/com/android/inputmethod/latin/utils/ForgettingCurveTests.java new file mode 100644 index 000000000..823bd5d7d --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/ForgettingCurveTests.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +@SmallTest +public class ForgettingCurveTests extends AndroidTestCase { + public void testFcToFreq() { + for (int i = 0; i < Byte.MAX_VALUE; ++i) { + final byte fc = (byte)i; + final int e = UserHistoryForgettingCurveUtils.fcToElapsedTime(fc); + final int c = UserHistoryForgettingCurveUtils.fcToCount(fc); + final int l = UserHistoryForgettingCurveUtils.fcToLevel(fc); + final byte fc2 = UserHistoryForgettingCurveUtils.calcFc(e, c, l); + assertEquals(fc, fc2); + } + byte fc = 0; + int l; + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < (UserHistoryForgettingCurveUtils.COUNT_MAX + 1); ++j) { + fc = UserHistoryForgettingCurveUtils.pushCount(fc, true); + } + l = UserHistoryForgettingCurveUtils.fcToLevel(fc); + assertEquals(l, Math.max(1, Math.min(i + 1, 3))); + } + fc = 0; + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < (UserHistoryForgettingCurveUtils.COUNT_MAX + 1); ++j) { + fc = UserHistoryForgettingCurveUtils.pushCount(fc, false); + } + l = UserHistoryForgettingCurveUtils.fcToLevel(fc); + assertEquals(l, Math.min(i + 1, 3)); + } + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < (UserHistoryForgettingCurveUtils.ELAPSED_TIME_MAX + 1); ++j) { + fc = UserHistoryForgettingCurveUtils.pushElapsedTime(fc); + } + l = UserHistoryForgettingCurveUtils.fcToLevel(fc); + assertEquals(l, Math.max(0, 2 - i)); + } + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/PrioritizedSerialExecutorTests.java b/tests/src/com/android/inputmethod/latin/utils/PrioritizedSerialExecutorTests.java new file mode 100644 index 000000000..e0755483c --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/PrioritizedSerialExecutorTests.java @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.MediumTest; +import android.util.Log; + +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Unit tests for PrioritizedSerialExecutor. + * TODO: Add more detailed tests to make use of priorities, etc. + */ +@MediumTest +public class PrioritizedSerialExecutorTests extends AndroidTestCase { + private static final String TAG = PrioritizedSerialExecutorTests.class.getSimpleName(); + + private static final int NUM_OF_TASKS = 10; + private static final int DELAY_FOR_WAITING_TASKS_MILLISECONDS = 500; + + public void testExecute() { + final PrioritizedSerialExecutor executor = new PrioritizedSerialExecutor(); + final AtomicInteger v = new AtomicInteger(0); + for (int i = 0; i < NUM_OF_TASKS; ++i) { + executor.execute(new Runnable() { + @Override + public void run() { + v.incrementAndGet(); + } + }); + } + try { + Thread.sleep(DELAY_FOR_WAITING_TASKS_MILLISECONDS); + } catch (InterruptedException e) { + Log.d(TAG, "Exception while sleeping.", e); + } + + assertEquals(NUM_OF_TASKS, v.get()); + } + + public void testExecutePrioritized() { + final PrioritizedSerialExecutor executor = new PrioritizedSerialExecutor(); + final AtomicInteger v = new AtomicInteger(0); + for (int i = 0; i < NUM_OF_TASKS; ++i) { + executor.executePrioritized(new Runnable() { + @Override + public void run() { + v.incrementAndGet(); + } + }); + } + try { + Thread.sleep(DELAY_FOR_WAITING_TASKS_MILLISECONDS); + } catch (InterruptedException e) { + Log.d(TAG, "Exception while sleeping.", e); + } + + assertEquals(NUM_OF_TASKS, v.get()); + } + + public void testExecuteCombined() { + final PrioritizedSerialExecutor executor = new PrioritizedSerialExecutor(); + final AtomicInteger v = new AtomicInteger(0); + for (int i = 0; i < NUM_OF_TASKS; ++i) { + executor.execute(new Runnable() { + @Override + public void run() { + v.incrementAndGet(); + } + }); + } + + for (int i = 0; i < NUM_OF_TASKS; ++i) { + executor.executePrioritized(new Runnable() { + @Override + public void run() { + v.incrementAndGet(); + } + }); + } + + try { + Thread.sleep(DELAY_FOR_WAITING_TASKS_MILLISECONDS); + } catch (InterruptedException e) { + Log.d(TAG, "Exception while sleeping.", e); + } + + assertEquals(2 * NUM_OF_TASKS, v.get()); + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/RecapitalizeStatusTests.java b/tests/src/com/android/inputmethod/latin/utils/RecapitalizeStatusTests.java new file mode 100644 index 000000000..a52041264 --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/RecapitalizeStatusTests.java @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +import java.util.Locale; + +@SmallTest +public class RecapitalizeStatusTests extends AndroidTestCase { + public void testTrim() { + final RecapitalizeStatus status = new RecapitalizeStatus(); + status.initialize(30, 40, "abcdefghij", Locale.ENGLISH, " "); + status.trim(); + assertEquals("abcdefghij", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(40, status.getNewCursorEnd()); + + status.initialize(30, 44, " abcdefghij", Locale.ENGLISH, " "); + status.trim(); + assertEquals("abcdefghij", status.getRecapitalizedString()); + assertEquals(34, status.getNewCursorStart()); + assertEquals(44, status.getNewCursorEnd()); + + status.initialize(30, 40, "abcdefgh ", Locale.ENGLISH, " "); + status.trim(); + assertEquals("abcdefgh", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(38, status.getNewCursorEnd()); + + status.initialize(30, 45, " abcdefghij ", Locale.ENGLISH, " "); + status.trim(); + assertEquals("abcdefghij", status.getRecapitalizedString()); + assertEquals(33, status.getNewCursorStart()); + assertEquals(43, status.getNewCursorEnd()); + } + + public void testRotate() { + final RecapitalizeStatus status = new RecapitalizeStatus(); + status.initialize(29, 40, "abcd efghij", Locale.ENGLISH, " "); + status.rotate(); + assertEquals("Abcd Efghij", status.getRecapitalizedString()); + assertEquals(29, status.getNewCursorStart()); + assertEquals(40, status.getNewCursorEnd()); + status.rotate(); + assertEquals("ABCD EFGHIJ", status.getRecapitalizedString()); + status.rotate(); + assertEquals("abcd efghij", status.getRecapitalizedString()); + status.rotate(); + assertEquals("Abcd Efghij", status.getRecapitalizedString()); + + status.initialize(29, 40, "Abcd Efghij", Locale.ENGLISH, " "); + status.rotate(); + assertEquals("ABCD EFGHIJ", status.getRecapitalizedString()); + assertEquals(29, status.getNewCursorStart()); + assertEquals(40, status.getNewCursorEnd()); + status.rotate(); + assertEquals("abcd efghij", status.getRecapitalizedString()); + status.rotate(); + assertEquals("Abcd Efghij", status.getRecapitalizedString()); + status.rotate(); + assertEquals("ABCD EFGHIJ", status.getRecapitalizedString()); + + status.initialize(29, 40, "ABCD EFGHIJ", Locale.ENGLISH, " "); + status.rotate(); + assertEquals("abcd efghij", status.getRecapitalizedString()); + assertEquals(29, status.getNewCursorStart()); + assertEquals(40, status.getNewCursorEnd()); + status.rotate(); + assertEquals("Abcd Efghij", status.getRecapitalizedString()); + status.rotate(); + assertEquals("ABCD EFGHIJ", status.getRecapitalizedString()); + status.rotate(); + assertEquals("abcd efghij", status.getRecapitalizedString()); + + status.initialize(29, 39, "AbCDefghij", Locale.ENGLISH, " "); + status.rotate(); + assertEquals("abcdefghij", status.getRecapitalizedString()); + assertEquals(29, status.getNewCursorStart()); + assertEquals(39, status.getNewCursorEnd()); + status.rotate(); + assertEquals("Abcdefghij", status.getRecapitalizedString()); + status.rotate(); + assertEquals("ABCDEFGHIJ", status.getRecapitalizedString()); + status.rotate(); + assertEquals("AbCDefghij", status.getRecapitalizedString()); + status.rotate(); + assertEquals("abcdefghij", status.getRecapitalizedString()); + + status.initialize(29, 40, "Abcd efghij", Locale.ENGLISH, " "); + status.rotate(); + assertEquals("abcd efghij", status.getRecapitalizedString()); + assertEquals(29, status.getNewCursorStart()); + assertEquals(40, status.getNewCursorEnd()); + status.rotate(); + assertEquals("Abcd Efghij", status.getRecapitalizedString()); + status.rotate(); + assertEquals("ABCD EFGHIJ", status.getRecapitalizedString()); + status.rotate(); + assertEquals("Abcd efghij", status.getRecapitalizedString()); + status.rotate(); + assertEquals("abcd efghij", status.getRecapitalizedString()); + + status.initialize(30, 34, "grüß", Locale.GERMAN, " "); status.rotate(); + assertEquals("Grüß", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(34, status.getNewCursorEnd()); + status.rotate(); + assertEquals("GRÜSS", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(35, status.getNewCursorEnd()); + status.rotate(); + assertEquals("grüß", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(34, status.getNewCursorEnd()); + status.rotate(); + assertEquals("Grüß", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(34, status.getNewCursorEnd()); + + status.initialize(30, 33, "œuf", Locale.FRENCH, " "); status.rotate(); + assertEquals("Œuf", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(33, status.getNewCursorEnd()); + status.rotate(); + assertEquals("ŒUF", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(33, status.getNewCursorEnd()); + status.rotate(); + assertEquals("œuf", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(33, status.getNewCursorEnd()); + status.rotate(); + assertEquals("Œuf", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(33, status.getNewCursorEnd()); + + status.initialize(30, 33, "œUf", Locale.FRENCH, " "); status.rotate(); + assertEquals("œuf", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(33, status.getNewCursorEnd()); + status.rotate(); + assertEquals("Œuf", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(33, status.getNewCursorEnd()); + status.rotate(); + assertEquals("ŒUF", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(33, status.getNewCursorEnd()); + status.rotate(); + assertEquals("œUf", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(33, status.getNewCursorEnd()); + status.rotate(); + assertEquals("œuf", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(33, status.getNewCursorEnd()); + + status.initialize(30, 35, "école", Locale.FRENCH, " "); status.rotate(); + assertEquals("École", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(35, status.getNewCursorEnd()); + status.rotate(); + assertEquals("ÉCOLE", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(35, status.getNewCursorEnd()); + status.rotate(); + assertEquals("école", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(35, status.getNewCursorEnd()); + status.rotate(); + assertEquals("École", status.getRecapitalizedString()); + assertEquals(30, status.getNewCursorStart()); + assertEquals(35, status.getNewCursorEnd()); + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/ResizableIntArrayTests.java b/tests/src/com/android/inputmethod/latin/utils/ResizableIntArrayTests.java new file mode 100644 index 000000000..cad80d5ce --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/ResizableIntArrayTests.java @@ -0,0 +1,357 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +import java.util.Arrays; + +@SmallTest +public class ResizableIntArrayTests extends AndroidTestCase { + private static final int DEFAULT_CAPACITY = 48; + + public void testNewInstance() { + final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); + final int[] array = src.getPrimitiveArray(); + assertEquals("new instance length", 0, src.getLength()); + assertNotNull("new instance array", array); + assertEquals("new instance array length", DEFAULT_CAPACITY, array.length); + } + + public void testAdd() { + final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); + final int[] array = src.getPrimitiveArray(); + int[] array2 = null, array3 = null; + final int limit = DEFAULT_CAPACITY * 2 + 10; + for (int i = 0; i < limit; i++) { + src.add(i); + assertEquals("length after add " + i, i + 1, src.getLength()); + if (i == DEFAULT_CAPACITY) { + array2 = src.getPrimitiveArray(); + } + if (i == DEFAULT_CAPACITY * 2) { + array3 = src.getPrimitiveArray(); + } + if (i < DEFAULT_CAPACITY) { + assertSame("array after add " + i, array, src.getPrimitiveArray()); + } else if (i < DEFAULT_CAPACITY * 2) { + assertSame("array after add " + i, array2, src.getPrimitiveArray()); + } else if (i < DEFAULT_CAPACITY * 3) { + assertSame("array after add " + i, array3, src.getPrimitiveArray()); + } + } + for (int i = 0; i < limit; i++) { + assertEquals("value at " + i, i, src.get(i)); + } + } + + public void testAddAt() { + final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); + final int limit = DEFAULT_CAPACITY * 10, step = DEFAULT_CAPACITY * 2; + for (int i = 0; i < limit; i += step) { + src.add(i, i); + assertEquals("length after add at " + i, i + 1, src.getLength()); + } + for (int i = 0; i < limit; i += step) { + assertEquals("value at " + i, i, src.get(i)); + } + } + + public void testGet() { + final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); + try { + final int value = src.get(0); + fail("get(0) shouldn't succeed"); + } catch (ArrayIndexOutOfBoundsException e) { + // success + } + try { + final int value = src.get(DEFAULT_CAPACITY); + fail("get(DEFAULT_CAPACITY) shouldn't succeed"); + } catch (ArrayIndexOutOfBoundsException e) { + // success + } + + final int index = DEFAULT_CAPACITY / 2; + src.add(index, 100); + assertEquals("legth after add at " + index, index + 1, src.getLength()); + assertEquals("value after add at " + index, 100, src.get(index)); + assertEquals("value after add at 0", 0, src.get(0)); + try { + final int value = src.get(src.getLength()); + fail("get(length) shouldn't succeed"); + } catch (ArrayIndexOutOfBoundsException e) { + // success + } + } + + public void testReset() { + final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); + final int[] array = src.getPrimitiveArray(); + for (int i = 0; i < DEFAULT_CAPACITY; i++) { + src.add(i); + assertEquals("length after add " + i, i + 1, src.getLength()); + } + + final int smallerLength = DEFAULT_CAPACITY / 2; + src.reset(smallerLength); + final int[] array2 = src.getPrimitiveArray(); + assertEquals("length after reset", 0, src.getLength()); + assertNotSame("array after reset", array, array2); + + int[] array3 = null; + for (int i = 0; i < DEFAULT_CAPACITY; i++) { + src.add(i); + assertEquals("length after add " + i, i + 1, src.getLength()); + if (i == smallerLength) { + array3 = src.getPrimitiveArray(); + } + if (i < smallerLength) { + assertSame("array after add " + i, array2, src.getPrimitiveArray()); + } else if (i < smallerLength * 2) { + assertSame("array after add " + i, array3, src.getPrimitiveArray()); + } + } + } + + public void testSetLength() { + final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); + final int[] array = src.getPrimitiveArray(); + for (int i = 0; i < DEFAULT_CAPACITY; i++) { + src.add(i); + assertEquals("length after add " + i, i + 1, src.getLength()); + } + + final int largerLength = DEFAULT_CAPACITY * 2; + src.setLength(largerLength); + final int[] array2 = src.getPrimitiveArray(); + assertEquals("length after larger setLength", largerLength, src.getLength()); + assertNotSame("array after larger setLength", array, array2); + assertEquals("array length after larger setLength", largerLength, array2.length); + for (int i = 0; i < largerLength; i++) { + final int v = src.get(i); + if (i < DEFAULT_CAPACITY) { + assertEquals("value at " + i, i, v); + } else { + assertEquals("value at " + i, 0, v); + } + } + + final int smallerLength = DEFAULT_CAPACITY / 2; + src.setLength(smallerLength); + final int[] array3 = src.getPrimitiveArray(); + assertEquals("length after smaller setLength", smallerLength, src.getLength()); + assertSame("array after smaller setLength", array2, array3); + assertEquals("array length after smaller setLength", largerLength, array3.length); + for (int i = 0; i < smallerLength; i++) { + assertEquals("value at " + i, i, src.get(i)); + } + } + + public void testSet() { + final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); + final int limit = DEFAULT_CAPACITY * 2 + 10; + for (int i = 0; i < limit; i++) { + src.add(i); + } + + final ResizableIntArray dst = new ResizableIntArray(DEFAULT_CAPACITY); + dst.set(src); + assertEquals("length after set", dst.getLength(), src.getLength()); + assertSame("array after set", dst.getPrimitiveArray(), src.getPrimitiveArray()); + } + + public void testCopy() { + final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); + for (int i = 0; i < DEFAULT_CAPACITY; i++) { + src.add(i); + } + + final ResizableIntArray dst = new ResizableIntArray(DEFAULT_CAPACITY); + final int[] array = dst.getPrimitiveArray(); + dst.copy(src); + assertEquals("length after copy", dst.getLength(), src.getLength()); + assertSame("array after copy", array, dst.getPrimitiveArray()); + assertNotSame("array after copy", dst.getPrimitiveArray(), src.getPrimitiveArray()); + assertIntArrayEquals("values after copy", + dst.getPrimitiveArray(), 0, src.getPrimitiveArray(), 0, dst.getLength()); + + final int smallerLength = DEFAULT_CAPACITY / 2; + dst.reset(smallerLength); + final int[] array2 = dst.getPrimitiveArray(); + dst.copy(src); + final int[] array3 = dst.getPrimitiveArray(); + assertEquals("length after copy to smaller", dst.getLength(), src.getLength()); + assertNotSame("array after copy to smaller", array2, array3); + assertNotSame("array after copy to smaller", array3, src.getPrimitiveArray()); + assertIntArrayEquals("values after copy to smaller", + dst.getPrimitiveArray(), 0, src.getPrimitiveArray(), 0, dst.getLength()); + } + + public void testAppend() { + final int srcLen = DEFAULT_CAPACITY; + final ResizableIntArray src = new ResizableIntArray(srcLen); + for (int i = 0; i < srcLen; i++) { + src.add(i); + } + final ResizableIntArray dst = new ResizableIntArray(DEFAULT_CAPACITY * 2); + final int[] array = dst.getPrimitiveArray(); + final int dstLen = DEFAULT_CAPACITY / 2; + for (int i = 0; i < dstLen; i++) { + final int value = -i - 1; + dst.add(value); + } + final ResizableIntArray dstCopy = new ResizableIntArray(dst.getLength()); + dstCopy.copy(dst); + + dst.append(src, 0, 0); + assertEquals("length after append zero", dstLen, dst.getLength()); + assertSame("array after append zero", array, dst.getPrimitiveArray()); + assertIntArrayEquals("values after append zero", + dstCopy.getPrimitiveArray(), 0, dst.getPrimitiveArray(), 0, dstLen); + + dst.append(src, 0, srcLen); + assertEquals("length after append", dstLen + srcLen, dst.getLength()); + assertSame("array after append", array, dst.getPrimitiveArray()); + assertTrue("primitive length after append", + dst.getPrimitiveArray().length >= dstLen + srcLen); + assertIntArrayEquals("original values after append", + dstCopy.getPrimitiveArray(), 0, dst.getPrimitiveArray(), 0, dstLen); + assertIntArrayEquals("appended values after append", + src.getPrimitiveArray(), 0, dst.getPrimitiveArray(), dstLen, srcLen); + + dst.append(src, 0, srcLen); + assertEquals("length after 2nd append", dstLen + srcLen * 2, dst.getLength()); + assertNotSame("array after 2nd append", array, dst.getPrimitiveArray()); + assertTrue("primitive length after 2nd append", + dst.getPrimitiveArray().length >= dstLen + srcLen * 2); + assertIntArrayEquals("original values after 2nd append", + dstCopy.getPrimitiveArray(), 0, dst.getPrimitiveArray(), 0, dstLen); + assertIntArrayEquals("appended values after 2nd append", + src.getPrimitiveArray(), 0, dst.getPrimitiveArray(), dstLen, srcLen); + assertIntArrayEquals("appended values after 2nd append", + src.getPrimitiveArray(), 0, dst.getPrimitiveArray(), dstLen + srcLen, srcLen); + } + + public void testFill() { + final int srcLen = DEFAULT_CAPACITY; + final ResizableIntArray src = new ResizableIntArray(srcLen); + for (int i = 0; i < srcLen; i++) { + src.add(i); + } + final int[] array = src.getPrimitiveArray(); + + final int startPos = srcLen / 3; + final int length = srcLen / 3; + final int endPos = startPos + length; + assertTrue(startPos >= 1); + final int value = 123; + try { + src.fill(value, -1, length); + fail("fill from -1 shouldn't succeed"); + } catch (IllegalArgumentException e) { + // success + } + try { + src.fill(value, startPos, -1); + fail("fill negative length shouldn't succeed"); + } catch (IllegalArgumentException e) { + // success + } + + src.fill(value, startPos, length); + assertEquals("length after fill", srcLen, src.getLength()); + assertSame("array after fill", array, src.getPrimitiveArray()); + for (int i = 0; i < srcLen; i++) { + final int v = src.get(i); + if (i >= startPos && i < endPos) { + assertEquals("new values after fill at " + i, value, v); + } else { + assertEquals("unmodified values after fill at " + i, i, v); + } + } + + final int length2 = srcLen * 2 - startPos; + final int largeEnd = startPos + length2; + assertTrue(largeEnd > srcLen); + final int value2 = 456; + src.fill(value2, startPos, length2); + assertEquals("length after large fill", largeEnd, src.getLength()); + assertNotSame("array after large fill", array, src.getPrimitiveArray()); + for (int i = 0; i < largeEnd; i++) { + final int v = src.get(i); + if (i >= startPos && i < largeEnd) { + assertEquals("new values after large fill at " + i, value2, v); + } else { + assertEquals("unmodified values after large fill at " + i, i, v); + } + } + + final int startPos2 = largeEnd + length2; + final int endPos2 = startPos2 + length2; + final int value3 = 789; + src.fill(value3, startPos2, length2); + assertEquals("length after disjoint fill", endPos2, src.getLength()); + for (int i = 0; i < endPos2; i++) { + final int v = src.get(i); + if (i >= startPos2 && i < endPos2) { + assertEquals("new values after disjoint fill at " + i, value3, v); + } else if (i >= startPos && i < largeEnd) { + assertEquals("unmodified values after disjoint fill at " + i, value2, v); + } else if (i < startPos) { + assertEquals("unmodified values after disjoint fill at " + i, i, v); + } else { + assertEquals("gap values after disjoint fill at " + i, 0, v); + } + } + } + + private static void assertIntArrayEquals(final String message, final int[] expecteds, + final int expectedPos, final int[] actuals, final int actualPos, final int length) { + if (expecteds == actuals) { + return; + } + if (expecteds == null || actuals == null) { + assertEquals(message, Arrays.toString(expecteds), Arrays.toString(actuals)); + return; + } + if (expecteds.length < expectedPos + length || actuals.length < actualPos + length) { + fail(message + ": insufficient length: expecteds=" + Arrays.toString(expecteds) + + " actuals=" + Arrays.toString(actuals)); + return; + } + for (int i = 0; i < length; i++) { + assertEquals(message + " [" + i + "]", + expecteds[i + expectedPos], actuals[i + actualPos]); + } + } + + public void testShift() { + final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); + final int limit = DEFAULT_CAPACITY * 10; + final int shiftAmount = 20; + for (int i = 0; i < limit; ++i) { + src.add(i, i); + assertEquals("length after add at " + i, i + 1, src.getLength()); + } + src.shift(shiftAmount); + for (int i = 0; i < limit - shiftAmount; ++i) { + assertEquals("value at " + i, i + shiftAmount, src.get(i)); + } + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/ResourceUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/ResourceUtilsTests.java new file mode 100644 index 000000000..1ae22e307 --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/ResourceUtilsTests.java @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +import com.android.inputmethod.latin.utils.ResourceUtils.DeviceOverridePatternSyntaxError; + +import java.util.HashMap; + +@SmallTest +public class ResourceUtilsTests extends AndroidTestCase { + public void testFindDefaultConstant() { + final String[] nullArray = null; + final String[] emptyArray = {}; + final String[] array = { + "HARDWARE=grouper,0.3", + "HARDWARE=mako,0.4", + ",defaultValue1", + "HARDWARE=manta,0.2", + ",defaultValue2", + }; + + try { + assertNull(ResourceUtils.findDefaultConstant(nullArray)); + assertNull(ResourceUtils.findDefaultConstant(emptyArray)); + assertEquals(ResourceUtils.findDefaultConstant(array), "defaultValue1"); + } catch (final DeviceOverridePatternSyntaxError e) { + fail(e.getMessage()); + } + + final String[] errorArray = { + "HARDWARE=grouper,0.3", + "no_comma" + }; + try { + final String defaultValue = ResourceUtils.findDefaultConstant(errorArray); + fail("exception should be thrown: defaultValue=" + defaultValue); + } catch (final DeviceOverridePatternSyntaxError e) { + assertEquals("Array element has no comma: no_comma", e.getMessage()); + } + } + + public void testFindConstantForKeyValuePairsSimple() { + final HashMap<String,String> anyKeyValue = CollectionUtils.newHashMap(); + anyKeyValue.put("anyKey", "anyValue"); + final HashMap<String,String> nullKeyValue = null; + final HashMap<String,String> emptyKeyValue = CollectionUtils.newHashMap(); + + final String[] nullArray = null; + assertNull(ResourceUtils.findConstantForKeyValuePairs(anyKeyValue, nullArray)); + assertNull(ResourceUtils.findConstantForKeyValuePairs(emptyKeyValue, nullArray)); + assertNull(ResourceUtils.findConstantForKeyValuePairs(nullKeyValue, nullArray)); + + final String[] emptyArray = {}; + assertNull(ResourceUtils.findConstantForKeyValuePairs(anyKeyValue, emptyArray)); + assertNull(ResourceUtils.findConstantForKeyValuePairs(emptyKeyValue, emptyArray)); + assertNull(ResourceUtils.findConstantForKeyValuePairs(nullKeyValue, emptyArray)); + + final String HARDWARE_KEY = "HARDWARE"; + final String[] array = { + ",defaultValue", + "HARDWARE=grouper,0.3", + "HARDWARE=mako,0.4", + "HARDWARE=manta,0.2", + "HARDWARE=mako,0.5", + }; + + final HashMap<String,String> keyValues = CollectionUtils.newHashMap(); + keyValues.put(HARDWARE_KEY, "grouper"); + assertEquals("0.3", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + keyValues.put(HARDWARE_KEY, "mako"); + assertEquals("0.4", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + keyValues.put(HARDWARE_KEY, "manta"); + assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + + keyValues.clear(); + keyValues.put("hardware", "grouper"); + assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + + keyValues.clear(); + keyValues.put(HARDWARE_KEY, "MAKO"); + assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + keyValues.put(HARDWARE_KEY, "mantaray"); + assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + + assertNull(ResourceUtils.findConstantForKeyValuePairs(emptyKeyValue, array)); + } + + public void testFindConstantForKeyValuePairsCombined() { + final String HARDWARE_KEY = "HARDWARE"; + final String MODEL_KEY = "MODEL"; + final String MANUFACTURER_KEY = "MANUFACTURER"; + final String[] array = { + ",defaultValue", + "no_comma", + "error_pattern,0.1", + "HARDWARE=grouper:MANUFACTURER=asus,0.3", + "HARDWARE=mako:MODEL=Nexus 4,0.4", + "HARDWARE=manta:MODEL=Nexus 10:MANUFACTURER=samsung,0.2" + }; + final String[] failArray = { + ",defaultValue", + "HARDWARE=grouper:MANUFACTURER=ASUS,0.3", + "HARDWARE=mako:MODEL=Nexus_4,0.4", + "HARDWARE=mantaray:MODEL=Nexus 10:MANUFACTURER=samsung,0.2" + }; + + final HashMap<String,String> keyValues = CollectionUtils.newHashMap(); + keyValues.put(HARDWARE_KEY, "grouper"); + keyValues.put(MODEL_KEY, "Nexus 7"); + keyValues.put(MANUFACTURER_KEY, "asus"); + assertEquals("0.3", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray)); + + keyValues.clear(); + keyValues.put(HARDWARE_KEY, "mako"); + keyValues.put(MODEL_KEY, "Nexus 4"); + keyValues.put(MANUFACTURER_KEY, "LGE"); + assertEquals("0.4", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray)); + + keyValues.clear(); + keyValues.put(HARDWARE_KEY, "manta"); + keyValues.put(MODEL_KEY, "Nexus 10"); + keyValues.put(MANUFACTURER_KEY, "samsung"); + assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray)); + keyValues.put(HARDWARE_KEY, "mantaray"); + assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray)); + } + + public void testFindConstantForKeyValuePairsRegexp() { + final String HARDWARE_KEY = "HARDWARE"; + final String MODEL_KEY = "MODEL"; + final String MANUFACTURER_KEY = "MANUFACTURER"; + final String[] array = { + ",defaultValue", + "no_comma", + "HARDWARE=error_regexp:MANUFACTURER=error[regexp,0.1", + "HARDWARE=grouper|tilapia:MANUFACTURER=asus,0.3", + "HARDWARE=[mM][aA][kK][oO]:MODEL=Nexus 4,0.4", + "HARDWARE=manta.*:MODEL=Nexus 10:MANUFACTURER=samsung,0.2" + }; + + final HashMap<String,String> keyValues = CollectionUtils.newHashMap(); + keyValues.put(HARDWARE_KEY, "grouper"); + keyValues.put(MODEL_KEY, "Nexus 7"); + keyValues.put(MANUFACTURER_KEY, "asus"); + assertEquals("0.3", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + keyValues.put(HARDWARE_KEY, "tilapia"); + assertEquals("0.3", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + + keyValues.clear(); + keyValues.put(HARDWARE_KEY, "mako"); + keyValues.put(MODEL_KEY, "Nexus 4"); + keyValues.put(MANUFACTURER_KEY, "LGE"); + assertEquals("0.4", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + keyValues.put(HARDWARE_KEY, "MAKO"); + assertEquals("0.4", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + + keyValues.clear(); + keyValues.put(HARDWARE_KEY, "manta"); + keyValues.put(MODEL_KEY, "Nexus 10"); + keyValues.put(MANUFACTURER_KEY, "samsung"); + assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + keyValues.put(HARDWARE_KEY, "mantaray"); + assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java new file mode 100644 index 000000000..fa6ad16c1 --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; +import android.text.style.SuggestionSpan; +import android.text.style.URLSpan; +import android.text.SpannableStringBuilder; +import android.text.Spannable; +import android.text.Spanned; + +@SmallTest +public class SpannableStringUtilsTests extends AndroidTestCase { + public void testConcatWithSuggestionSpansOnly() { + SpannableStringBuilder s = new SpannableStringBuilder("test string\ntest string\n" + + "test string\ntest string\ntest string\ntest string\ntest string\ntest string\n" + + "test string\ntest string\n"); + final int N = 10; + for (int i = 0; i < N; ++i) { + // Put a PARAGRAPH-flagged span that should not be found in the result. + s.setSpan(new SuggestionSpan(getContext(), + new String[] {"" + i}, Spannable.SPAN_PARAGRAPH), + i * 12, i * 12 + 12, Spannable.SPAN_PARAGRAPH); + // Put a normal suggestion span that should be found in the result. + s.setSpan(new SuggestionSpan(getContext(), new String[] {"" + i}, 0), i, i * 2, 0); + // Put a URL span than should not be found in the result. + s.setSpan(new URLSpan("http://a"), i, i * 2, 0); + } + + final CharSequence a = s.subSequence(0, 15); + final CharSequence b = s.subSequence(15, s.length()); + final Spanned result = + (Spanned)SpannableStringUtils.concatWithNonParagraphSuggestionSpansOnly(a, b); + + Object[] spans = result.getSpans(0, result.length(), SuggestionSpan.class); + for (int i = 0; i < spans.length; i++) { + final int flags = result.getSpanFlags(spans[i]); + assertEquals("Should not find a span with PARAGRAPH flag", + flags & Spannable.SPAN_PARAGRAPH, 0); + assertTrue("Should be a SuggestionSpan", spans[i] instanceof SuggestionSpan); + } + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/StringUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/StringUtilsTests.java new file mode 100644 index 000000000..4e396a1cf --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/StringUtilsTests.java @@ -0,0 +1,283 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import com.android.inputmethod.latin.settings.SettingsValues; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +@SmallTest +public class StringUtilsTests extends AndroidTestCase { + public void testContainsInArray() { + assertFalse("empty array", StringUtils.containsInArray("key", new String[0])); + assertFalse("not in 1 element", StringUtils.containsInArray("key", new String[] { + "key1" + })); + assertFalse("not in 2 elements", StringUtils.containsInArray("key", new String[] { + "key1", "key2" + })); + + assertTrue("in 1 element", StringUtils.containsInArray("key", new String[] { + "key" + })); + assertTrue("in 2 elements", StringUtils.containsInArray("key", new String[] { + "key1", "key" + })); + } + + public void testContainsInExtraValues() { + assertFalse("null", StringUtils.containsInCommaSplittableText("key", null)); + assertFalse("empty", StringUtils.containsInCommaSplittableText("key", "")); + assertFalse("not in 1 element", + StringUtils.containsInCommaSplittableText("key", "key1")); + assertFalse("not in 2 elements", + StringUtils.containsInCommaSplittableText("key", "key1,key2")); + + assertTrue("in 1 element", StringUtils.containsInCommaSplittableText("key", "key")); + assertTrue("in 2 elements", StringUtils.containsInCommaSplittableText("key", "key1,key")); + } + + public void testAppendToExtraValuesIfNotExists() { + assertEquals("null", "key", + StringUtils.appendToCommaSplittableTextIfNotExists("key", null)); + assertEquals("empty", "key", + StringUtils.appendToCommaSplittableTextIfNotExists("key", "")); + + assertEquals("not in 1 element", "key1,key", + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key1")); + assertEquals("not in 2 elements", "key1,key2,key", + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key1,key2")); + + assertEquals("in 1 element", "key", + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key")); + assertEquals("in 2 elements at position 1", "key,key2", + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key,key2")); + assertEquals("in 2 elements at position 2", "key1,key", + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key1,key")); + assertEquals("in 3 elements at position 2", "key1,key,key3", + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key1,key,key3")); + } + + public void testRemoveFromExtraValuesIfExists() { + assertEquals("null", "", StringUtils.removeFromCommaSplittableTextIfExists("key", null)); + assertEquals("empty", "", StringUtils.removeFromCommaSplittableTextIfExists("key", "")); + + assertEquals("not in 1 element", "key1", + StringUtils.removeFromCommaSplittableTextIfExists("key", "key1")); + assertEquals("not in 2 elements", "key1,key2", + StringUtils.removeFromCommaSplittableTextIfExists("key", "key1,key2")); + + assertEquals("in 1 element", "", + StringUtils.removeFromCommaSplittableTextIfExists("key", "key")); + assertEquals("in 2 elements at position 1", "key2", + StringUtils.removeFromCommaSplittableTextIfExists("key", "key,key2")); + assertEquals("in 2 elements at position 2", "key1", + StringUtils.removeFromCommaSplittableTextIfExists("key", "key1,key")); + assertEquals("in 3 elements at position 2", "key1,key3", + StringUtils.removeFromCommaSplittableTextIfExists("key", "key1,key,key3")); + + assertEquals("in 3 elements at position 1,2,3", "", + StringUtils.removeFromCommaSplittableTextIfExists("key", "key,key,key")); + assertEquals("in 5 elements at position 2,4", "key1,key3,key5", + StringUtils.removeFromCommaSplittableTextIfExists( + "key", "key1,key,key3,key,key5")); + } + + + public void testCapitalizeFirstCodePoint() { + assertEquals("SSaa", + StringUtils.capitalizeFirstCodePoint("ßaa", Locale.GERMAN)); + assertEquals("Aßa", + StringUtils.capitalizeFirstCodePoint("aßa", Locale.GERMAN)); + assertEquals("Iab", + StringUtils.capitalizeFirstCodePoint("iab", Locale.ENGLISH)); + assertEquals("CAmElCaSe", + StringUtils.capitalizeFirstCodePoint("cAmElCaSe", Locale.ENGLISH)); + assertEquals("İab", + StringUtils.capitalizeFirstCodePoint("iab", new Locale("tr"))); + assertEquals("AİB", + StringUtils.capitalizeFirstCodePoint("AİB", new Locale("tr"))); + assertEquals("A", + StringUtils.capitalizeFirstCodePoint("a", Locale.ENGLISH)); + assertEquals("A", + StringUtils.capitalizeFirstCodePoint("A", Locale.ENGLISH)); + } + + public void testCapitalizeFirstAndDowncaseRest() { + assertEquals("SSaa", + StringUtils.capitalizeFirstAndDowncaseRest("ßaa", Locale.GERMAN)); + assertEquals("Aßa", + StringUtils.capitalizeFirstAndDowncaseRest("aßa", Locale.GERMAN)); + assertEquals("Iab", + StringUtils.capitalizeFirstAndDowncaseRest("iab", Locale.ENGLISH)); + assertEquals("Camelcase", + StringUtils.capitalizeFirstAndDowncaseRest("cAmElCaSe", Locale.ENGLISH)); + assertEquals("İab", + StringUtils.capitalizeFirstAndDowncaseRest("iab", new Locale("tr"))); + assertEquals("Aib", + StringUtils.capitalizeFirstAndDowncaseRest("AİB", new Locale("tr"))); + assertEquals("A", + StringUtils.capitalizeFirstAndDowncaseRest("a", Locale.ENGLISH)); + assertEquals("A", + StringUtils.capitalizeFirstAndDowncaseRest("A", Locale.ENGLISH)); + } + + public void testGetCapitalizationType() { + assertEquals(StringUtils.CAPITALIZE_NONE, + StringUtils.getCapitalizationType("capitalize")); + assertEquals(StringUtils.CAPITALIZE_NONE, + StringUtils.getCapitalizationType("cApITalize")); + assertEquals(StringUtils.CAPITALIZE_NONE, + StringUtils.getCapitalizationType("capitalizE")); + assertEquals(StringUtils.CAPITALIZE_NONE, + StringUtils.getCapitalizationType("__c a piu$@tali56ze")); + assertEquals(StringUtils.CAPITALIZE_FIRST, + StringUtils.getCapitalizationType("A__c a piu$@tali56ze")); + assertEquals(StringUtils.CAPITALIZE_FIRST, + StringUtils.getCapitalizationType("Capitalize")); + assertEquals(StringUtils.CAPITALIZE_FIRST, + StringUtils.getCapitalizationType(" Capitalize")); + assertEquals(StringUtils.CAPITALIZE_ALL, + StringUtils.getCapitalizationType("CAPITALIZE")); + assertEquals(StringUtils.CAPITALIZE_ALL, + StringUtils.getCapitalizationType(" PI26LIE")); + assertEquals(StringUtils.CAPITALIZE_NONE, + StringUtils.getCapitalizationType("")); + } + + public void testIsIdenticalAfterUpcaseIsIdenticalAfterDowncase() { + assertFalse(StringUtils.isIdenticalAfterUpcase("capitalize")); + assertTrue(StringUtils.isIdenticalAfterDowncase("capitalize")); + assertFalse(StringUtils.isIdenticalAfterUpcase("cApITalize")); + assertFalse(StringUtils.isIdenticalAfterDowncase("cApITalize")); + assertFalse(StringUtils.isIdenticalAfterUpcase("capitalizE")); + assertFalse(StringUtils.isIdenticalAfterDowncase("capitalizE")); + assertFalse(StringUtils.isIdenticalAfterUpcase("__c a piu$@tali56ze")); + assertTrue(StringUtils.isIdenticalAfterDowncase("__c a piu$@tali56ze")); + assertFalse(StringUtils.isIdenticalAfterUpcase("A__c a piu$@tali56ze")); + assertFalse(StringUtils.isIdenticalAfterDowncase("A__c a piu$@tali56ze")); + assertFalse(StringUtils.isIdenticalAfterUpcase("Capitalize")); + assertFalse(StringUtils.isIdenticalAfterDowncase("Capitalize")); + assertFalse(StringUtils.isIdenticalAfterUpcase(" Capitalize")); + assertFalse(StringUtils.isIdenticalAfterDowncase(" Capitalize")); + assertTrue(StringUtils.isIdenticalAfterUpcase("CAPITALIZE")); + assertFalse(StringUtils.isIdenticalAfterDowncase("CAPITALIZE")); + assertTrue(StringUtils.isIdenticalAfterUpcase(" PI26LIE")); + assertFalse(StringUtils.isIdenticalAfterDowncase(" PI26LIE")); + assertTrue(StringUtils.isIdenticalAfterUpcase("")); + assertTrue(StringUtils.isIdenticalAfterDowncase("")); + } + + public void testLooksValidForDictionaryInsertion() { + final SettingsValues settings = + SettingsValues.makeDummySettingsValuesForTest(Locale.ENGLISH); + assertTrue(StringUtils.looksValidForDictionaryInsertion("aochaueo", settings)); + assertFalse(StringUtils.looksValidForDictionaryInsertion("", settings)); + assertTrue(StringUtils.looksValidForDictionaryInsertion("ao-ch'aueo", settings)); + assertFalse(StringUtils.looksValidForDictionaryInsertion("2908743256", settings)); + assertTrue(StringUtils.looksValidForDictionaryInsertion("31aochaueo", settings)); + assertFalse(StringUtils.looksValidForDictionaryInsertion("akeo raeoch oerch .", settings)); + assertFalse(StringUtils.looksValidForDictionaryInsertion("!!!", settings)); + } + + private static void checkCapitalize(final String src, final String dst, final String separators, + final Locale locale) { + assertEquals(dst, StringUtils.capitalizeEachWord(src, separators, locale)); + assert(src.equals(dst) + == StringUtils.isIdenticalAfterCapitalizeEachWord(src, separators)); + } + + public void testCapitalizeEachWord() { + checkCapitalize("", "", " ", Locale.ENGLISH); + checkCapitalize("test", "Test", " ", Locale.ENGLISH); + checkCapitalize(" test", " Test", " ", Locale.ENGLISH); + checkCapitalize("Test", "Test", " ", Locale.ENGLISH); + checkCapitalize(" Test", " Test", " ", Locale.ENGLISH); + checkCapitalize(".Test", ".test", " ", Locale.ENGLISH); + checkCapitalize(".Test", ".Test", " .", Locale.ENGLISH); + checkCapitalize(".Test", ".Test", ". ", Locale.ENGLISH); + checkCapitalize("test and retest", "Test And Retest", " .", Locale.ENGLISH); + checkCapitalize("Test and retest", "Test And Retest", " .", Locale.ENGLISH); + checkCapitalize("Test And Retest", "Test And Retest", " .", Locale.ENGLISH); + checkCapitalize("Test And.Retest ", "Test And.Retest ", " .", Locale.ENGLISH); + checkCapitalize("Test And.retest ", "Test And.Retest ", " .", Locale.ENGLISH); + checkCapitalize("Test And.retest ", "Test And.retest ", " ", Locale.ENGLISH); + checkCapitalize("Test And.Retest ", "Test And.retest ", " ", Locale.ENGLISH); + checkCapitalize("test and ietest", "Test And İetest", " .", new Locale("tr")); + checkCapitalize("test and ietest", "Test And Ietest", " .", Locale.ENGLISH); + checkCapitalize("Test&Retest", "Test&Retest", " \n.!?*()&", Locale.ENGLISH); + checkCapitalize("Test&retest", "Test&Retest", " \n.!?*()&", Locale.ENGLISH); + checkCapitalize("test&Retest", "Test&Retest", " \n.!?*()&", Locale.ENGLISH); + checkCapitalize("rest\nrecreation! And in the end...", + "Rest\nRecreation! And In The End...", " \n.!?*,();&", Locale.ENGLISH); + checkCapitalize("lorem ipsum dolor sit amet", "Lorem Ipsum Dolor Sit Amet", + " \n.,!?*()&;", Locale.ENGLISH); + checkCapitalize("Lorem!Ipsum (Dolor) Sit * Amet", "Lorem!Ipsum (Dolor) Sit * Amet", + " \n,.;!?*()&", Locale.ENGLISH); + checkCapitalize("Lorem!Ipsum (dolor) Sit * Amet", "Lorem!Ipsum (Dolor) Sit * Amet", + " \n,.;!?*()&", Locale.ENGLISH); + } + + public void testLooksLikeURL() { + assertTrue(StringUtils.lastPartLooksLikeURL("http://www.google.")); + assertFalse(StringUtils.lastPartLooksLikeURL("word wo")); + assertTrue(StringUtils.lastPartLooksLikeURL("/etc/foo")); + assertFalse(StringUtils.lastPartLooksLikeURL("left/right")); + assertTrue(StringUtils.lastPartLooksLikeURL("www.goo")); + assertTrue(StringUtils.lastPartLooksLikeURL("www.")); + assertFalse(StringUtils.lastPartLooksLikeURL("U.S.A")); + assertFalse(StringUtils.lastPartLooksLikeURL("U.S.A.")); + assertTrue(StringUtils.lastPartLooksLikeURL("rtsp://foo.")); + assertTrue(StringUtils.lastPartLooksLikeURL("://")); + assertFalse(StringUtils.lastPartLooksLikeURL("abc/")); + assertTrue(StringUtils.lastPartLooksLikeURL("abc.def/ghi")); + assertFalse(StringUtils.lastPartLooksLikeURL("abc.def")); + // TODO: ideally this would not look like a URL, but to keep down the complexity of the + // code for now True is acceptable. + assertTrue(StringUtils.lastPartLooksLikeURL("abc./def")); + // TODO: ideally this would not look like a URL, but to keep down the complexity of the + // code for now True is acceptable. + assertTrue(StringUtils.lastPartLooksLikeURL(".abc/def")); + } + + public void testHexStringUtils() { + final byte[] bytes = new byte[] { (byte)0x01, (byte)0x11, (byte)0x22, (byte)0x33, + (byte)0x55, (byte)0x88, (byte)0xEE }; + final String bytesStr = StringUtils.byteArrayToHexString(bytes); + final byte[] bytes2 = StringUtils.hexStringToByteArray(bytesStr); + for (int i = 0; i < bytes.length; ++i) { + assertTrue(bytes[i] == bytes2[i]); + } + final String bytesStr2 = StringUtils.byteArrayToHexString(bytes2); + assertTrue(bytesStr.equals(bytesStr2)); + } + + public void testJsonStringUtils() { + final Object[] objs = new Object[] { 1, "aaa", "bbb", 3 }; + final List<Object> objArray = Arrays.asList(objs); + final String str = StringUtils.listToJsonStr(objArray); + final List<Object> newObjArray = StringUtils.jsonStrToList(str); + for (int i = 0; i < objs.length; ++i) { + assertEquals(objs[i], newObjArray.get(i)); + } + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java new file mode 100644 index 000000000..856b2dbda --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java @@ -0,0 +1,387 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.content.Context; +import android.content.res.Resources; +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; +import android.view.inputmethod.InputMethodSubtype; + +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.RichInputMethodManager; + +import java.util.ArrayList; +import java.util.Locale; + +@SmallTest +public class SubtypeLocaleUtilsTests extends AndroidTestCase { + // Locale to subtypes list. + private final ArrayList<InputMethodSubtype> mSubtypesList = CollectionUtils.newArrayList(); + + private RichInputMethodManager mRichImm; + private Resources mRes; + + InputMethodSubtype EN_US; + InputMethodSubtype EN_GB; + InputMethodSubtype ES_US; + InputMethodSubtype FR; + InputMethodSubtype FR_CA; + InputMethodSubtype DE; + InputMethodSubtype ZZ; + InputMethodSubtype DE_QWERTY; + InputMethodSubtype FR_QWERTZ; + InputMethodSubtype EN_US_AZERTY; + InputMethodSubtype EN_UK_DVORAK; + InputMethodSubtype ES_US_COLEMAK; + InputMethodSubtype ZZ_AZERTY; + InputMethodSubtype ZZ_PC; + + @Override + protected void setUp() throws Exception { + super.setUp(); + final Context context = getContext(); + RichInputMethodManager.init(context); + mRichImm = RichInputMethodManager.getInstance(); + mRes = context.getResources(); + SubtypeLocaleUtils.init(context); + + EN_US = mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet( + Locale.US.toString(), "qwerty"); + EN_GB = mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet( + Locale.UK.toString(), "qwerty"); + ES_US = mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet( + "es_US", "spanish"); + FR = mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet( + Locale.FRENCH.toString(), "azerty"); + FR_CA = mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet( + Locale.CANADA_FRENCH.toString(), "qwerty"); + DE = mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet( + Locale.GERMAN.toString(), "qwertz"); + ZZ = mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet( + SubtypeLocaleUtils.NO_LANGUAGE, "qwerty"); + DE_QWERTY = AdditionalSubtypeUtils.createAdditionalSubtype( + Locale.GERMAN.toString(), "qwerty", null); + FR_QWERTZ = AdditionalSubtypeUtils.createAdditionalSubtype( + Locale.FRENCH.toString(), "qwertz", null); + EN_US_AZERTY = AdditionalSubtypeUtils.createAdditionalSubtype( + Locale.US.toString(), "azerty", null); + EN_UK_DVORAK = AdditionalSubtypeUtils.createAdditionalSubtype( + Locale.UK.toString(), "dvorak", null); + ES_US_COLEMAK = AdditionalSubtypeUtils.createAdditionalSubtype( + "es_US", "colemak", null); + ZZ_AZERTY = AdditionalSubtypeUtils.createAdditionalSubtype( + SubtypeLocaleUtils.NO_LANGUAGE, "azerty", null); + ZZ_PC = AdditionalSubtypeUtils.createAdditionalSubtype( + SubtypeLocaleUtils.NO_LANGUAGE, "pcqwerty", null); + + } + + public void testAllFullDisplayName() { + for (final InputMethodSubtype subtype : mSubtypesList) { + final String subtypeName = + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(subtype); + if (SubtypeLocaleUtils.isNoLanguage(subtype)) { + final String noLanguage = mRes.getString(R.string.subtype_no_language); + assertTrue(subtypeName, subtypeName.contains(noLanguage)); + } else { + final String languageName = + SubtypeLocaleUtils.getSubtypeLocaleDisplayName(subtype.getLocale()); + assertTrue(subtypeName, subtypeName.contains(languageName)); + } + } + } + + public void testKeyboardLayoutSetName() { + assertEquals("en_US", "qwerty", SubtypeLocaleUtils.getKeyboardLayoutSetName(EN_US)); + assertEquals("en_GB", "qwerty", SubtypeLocaleUtils.getKeyboardLayoutSetName(EN_GB)); + assertEquals("es_US", "spanish", SubtypeLocaleUtils.getKeyboardLayoutSetName(ES_US)); + assertEquals("fr ", "azerty", SubtypeLocaleUtils.getKeyboardLayoutSetName(FR)); + assertEquals("fr_CA", "qwerty", SubtypeLocaleUtils.getKeyboardLayoutSetName(FR_CA)); + assertEquals("de ", "qwertz", SubtypeLocaleUtils.getKeyboardLayoutSetName(DE)); + assertEquals("zz ", "qwerty", SubtypeLocaleUtils.getKeyboardLayoutSetName(ZZ)); + } + + // InputMethodSubtype's display name in system locale (en_US). + // isAdditionalSubtype (T=true, F=false) + // locale layout | display name + // ------ ------- - ---------------------- + // en_US qwerty F English (US) exception + // en_GB qwerty F English (UK) exception + // es_US spanish F Spanish (US) exception + // fr azerty F French + // fr_CA qwerty F French (Canada) + // de qwertz F German + // zz qwerty F Alphabet (QWERTY) + // fr qwertz T French (QWERTZ) + // de qwerty T German (QWERTY) + // en_US azerty T English (US) (AZERTY) exception + // en_UK dvorak T English (UK) (Dvorak) exception + // es_US colemak T Spanish (US) (Colemak) exception + // zz pc T Alphabet (PC) + + public void testPredefinedSubtypesInEnglishSystemLocale() { + final RunInLocale<Void> tests = new RunInLocale<Void>() { + @Override + protected Void job(final Resources res) { + assertEquals("en_US", "English (US)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(EN_US)); + assertEquals("en_GB", "English (UK)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(EN_GB)); + assertEquals("es_US", "Spanish (US)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(ES_US)); + assertEquals("fr ", "French", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(FR)); + assertEquals("fr_CA", "French (Canada)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(FR_CA)); + assertEquals("de ", "German", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(DE)); + assertEquals("zz ", "Alphabet (QWERTY)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(ZZ)); + return null; + } + }; + tests.runInLocale(mRes, Locale.ENGLISH); + } + + public void testAdditionalSubtypesInEnglishSystemLocale() { + final RunInLocale<Void> tests = new RunInLocale<Void>() { + @Override + protected Void job(final Resources res) { + assertEquals("fr qwertz", "French (QWERTZ)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(FR_QWERTZ)); + assertEquals("de qwerty", "German (QWERTY)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(DE_QWERTY)); + assertEquals("en_US azerty", "English (US) (AZERTY)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(EN_US_AZERTY)); + assertEquals("en_UK dvorak", "English (UK) (Dvorak)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(EN_UK_DVORAK)); + assertEquals("es_US colemak","Spanish (US) (Colemak)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(ES_US_COLEMAK)); + assertEquals("zz pc", "Alphabet (PC)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(ZZ_PC)); + return null; + } + }; + tests.runInLocale(mRes, Locale.ENGLISH); + } + + // InputMethodSubtype's display name in system locale (fr). + // isAdditionalSubtype (T=true, F=false) + // locale layout | display name + // ------ ------- - ---------------------- + // en_US qwerty F Anglais (États-Unis) exception + // en_GB qwerty F Anglais (Royaume-Uni) exception + // es_US spanish F Espagnol (États-Unis) exception + // fr azerty F Français + // fr_CA qwerty F Français (Canada) + // de qwertz F Allemand + // zz qwerty F Aucune langue (QWERTY) + // fr qwertz T Français (QWERTZ) + // de qwerty T Allemand (QWERTY) + // en_US azerty T Anglais (États-Unis) (AZERTY) exception + // en_UK dvorak T Anglais (Royaume-Uni) (Dvorak) exception + // es_US colemak T Espagnol (États-Unis) (Colemak) exception + // zz pc T Alphabet (PC) + + public void testPredefinedSubtypesInFrenchSystemLocale() { + final RunInLocale<Void> tests = new RunInLocale<Void>() { + @Override + protected Void job(final Resources res) { + assertEquals("en_US", "Anglais (États-Unis)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(EN_US)); + assertEquals("en_GB", "Anglais (Royaume-Uni)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(EN_GB)); + assertEquals("es_US", "Espagnol (États-Unis)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(ES_US)); + assertEquals("fr ", "Français", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(FR)); + assertEquals("fr_CA", "Français (Canada)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(FR_CA)); + assertEquals("de ", "Allemand", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(DE)); + assertEquals("zz ", "Alphabet latin (QWERTY)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(ZZ)); + return null; + } + }; + tests.runInLocale(mRes, Locale.FRENCH); + } + + public void testAdditionalSubtypesInFrenchSystemLocale() { + final RunInLocale<Void> tests = new RunInLocale<Void>() { + @Override + protected Void job(final Resources res) { + assertEquals("fr qwertz", "Français (QWERTZ)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(FR_QWERTZ)); + assertEquals("de qwerty", "Allemand (QWERTY)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(DE_QWERTY)); + assertEquals("en_US azerty", "Anglais (États-Unis) (AZERTY)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(EN_US_AZERTY)); + assertEquals("en_UK dvorak", "Anglais (Royaume-Uni) (Dvorak)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(EN_UK_DVORAK)); + assertEquals("es_US colemak","Espagnol (États-Unis) (Colemak)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(ES_US_COLEMAK)); + assertEquals("zz pc", "Alphabet latin (PC)", + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(ZZ_PC)); + return null; + } + }; + tests.runInLocale(mRes, Locale.FRENCH); + } + + public void testAllFullDisplayNameForSpacebar() { + for (final InputMethodSubtype subtype : mSubtypesList) { + final String subtypeName = + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(subtype); + final String spacebarText = SubtypeLocaleUtils.getFullDisplayName(subtype); + final String languageName = + SubtypeLocaleUtils.getSubtypeLocaleDisplayName(subtype.getLocale()); + if (SubtypeLocaleUtils.isNoLanguage(subtype)) { + assertFalse(subtypeName, spacebarText.contains(languageName)); + } else { + assertTrue(subtypeName, spacebarText.contains(languageName)); + } + } + } + + public void testAllMiddleDisplayNameForSpacebar() { + for (final InputMethodSubtype subtype : mSubtypesList) { + final String subtypeName = + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(subtype); + final String spacebarText = SubtypeLocaleUtils.getMiddleDisplayName(subtype); + if (SubtypeLocaleUtils.isNoLanguage(subtype)) { + assertEquals(subtypeName, + SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype), spacebarText); + } else { + assertEquals(subtypeName, + SubtypeLocaleUtils.getSubtypeLocaleDisplayName(subtype.getLocale()), + spacebarText); + } + } + } + + public void testAllShortDisplayNameForSpacebar() { + for (final InputMethodSubtype subtype : mSubtypesList) { + final String subtypeName = + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(subtype); + final Locale locale = SubtypeLocaleUtils.getSubtypeLocale(subtype); + final String spacebarText = SubtypeLocaleUtils.getShortDisplayName(subtype); + final String languageCode = StringUtils.capitalizeFirstCodePoint( + locale.getLanguage(), locale); + if (SubtypeLocaleUtils.isNoLanguage(subtype)) { + assertEquals(subtypeName, "", spacebarText); + } else { + assertEquals(subtypeName, languageCode, spacebarText); + } + } + } + + // InputMethodSubtype's display name for spacebar text in its locale. + // isAdditionalSubtype (T=true, F=false) + // locale layout | Short Middle Full + // ------ ------- - ---- --------- ---------------------- + // en_US qwerty F En English English (US) exception + // en_GB qwerty F En English English (UK) exception + // es_US spanish F Es Español Español (EE.UU.) exception + // fr azerty F Fr Français Français + // fr_CA qwerty F Fr Français Français (Canada) + // de qwertz F De Deutsch Deutsch + // zz qwerty F QWERTY QWERTY + // fr qwertz T Fr Français Français + // de qwerty T De Deutsch Deutsch + // en_US azerty T En English English (US) + // zz azerty T AZERTY AZERTY + + private final RunInLocale<Void> testsPredefinedSubtypesForSpacebar = new RunInLocale<Void>() { + @Override + protected Void job(final Resources res) { + assertEquals("en_US", "English (US)", SubtypeLocaleUtils.getFullDisplayName(EN_US)); + assertEquals("en_GB", "English (UK)", SubtypeLocaleUtils.getFullDisplayName(EN_GB)); + assertEquals("es_US", "Español (EE.UU.)", + SubtypeLocaleUtils.getFullDisplayName(ES_US)); + assertEquals("fr ", "Français", SubtypeLocaleUtils.getFullDisplayName(FR)); + assertEquals("fr_CA", "Français (Canada)", + SubtypeLocaleUtils.getFullDisplayName(FR_CA)); + assertEquals("de ", "Deutsch", SubtypeLocaleUtils.getFullDisplayName(DE)); + assertEquals("zz ", "QWERTY", SubtypeLocaleUtils.getFullDisplayName(ZZ)); + + assertEquals("en_US", "English", SubtypeLocaleUtils.getMiddleDisplayName(EN_US)); + assertEquals("en_GB", "English", SubtypeLocaleUtils.getMiddleDisplayName(EN_GB)); + assertEquals("es_US", "Español", SubtypeLocaleUtils.getMiddleDisplayName(ES_US)); + assertEquals("fr ", "Français", SubtypeLocaleUtils.getMiddleDisplayName(FR)); + assertEquals("fr_CA", "Français", SubtypeLocaleUtils.getMiddleDisplayName(FR_CA)); + assertEquals("de ", "Deutsch", SubtypeLocaleUtils.getMiddleDisplayName(DE)); + assertEquals("zz ", "QWERTY", SubtypeLocaleUtils.getMiddleDisplayName(ZZ)); + + assertEquals("en_US", "En", SubtypeLocaleUtils.getShortDisplayName(EN_US)); + assertEquals("en_GB", "En", SubtypeLocaleUtils.getShortDisplayName(EN_GB)); + assertEquals("es_US", "Es", SubtypeLocaleUtils.getShortDisplayName(ES_US)); + assertEquals("fr ", "Fr", SubtypeLocaleUtils.getShortDisplayName(FR)); + assertEquals("fr_CA", "Fr", SubtypeLocaleUtils.getShortDisplayName(FR_CA)); + assertEquals("de ", "De", SubtypeLocaleUtils.getShortDisplayName(DE)); + assertEquals("zz ", "", SubtypeLocaleUtils.getShortDisplayName(ZZ)); + return null; + } + }; + + private final RunInLocale<Void> testsAdditionalSubtypesForSpacebar = new RunInLocale<Void>() { + @Override + protected Void job(final Resources res) { + assertEquals("fr qwertz", "Français", + SubtypeLocaleUtils.getFullDisplayName(FR_QWERTZ)); + assertEquals("de qwerty", "Deutsch", + SubtypeLocaleUtils.getFullDisplayName(DE_QWERTY)); + assertEquals("en_US azerty", "English (US)", + SubtypeLocaleUtils.getFullDisplayName(EN_US_AZERTY)); + assertEquals("zz azerty", "AZERTY", + SubtypeLocaleUtils.getFullDisplayName(ZZ_AZERTY)); + + assertEquals("fr qwertz", "Français", + SubtypeLocaleUtils.getMiddleDisplayName(FR_QWERTZ)); + assertEquals("de qwerty", "Deutsch", + SubtypeLocaleUtils.getMiddleDisplayName(DE_QWERTY)); + assertEquals("en_US azerty", "English", + SubtypeLocaleUtils.getMiddleDisplayName(EN_US_AZERTY)); + assertEquals("zz azerty", "AZERTY", + SubtypeLocaleUtils.getMiddleDisplayName(ZZ_AZERTY)); + + assertEquals("fr qwertz", "Fr", SubtypeLocaleUtils.getShortDisplayName(FR_QWERTZ)); + assertEquals("de qwerty", "De", SubtypeLocaleUtils.getShortDisplayName(DE_QWERTY)); + assertEquals("en_US azerty", "En", + SubtypeLocaleUtils.getShortDisplayName(EN_US_AZERTY)); + assertEquals("zz azerty", "", SubtypeLocaleUtils.getShortDisplayName(ZZ_AZERTY)); + return null; + } + }; + + public void testPredefinedSubtypesForSpacebarInEnglish() { + testsPredefinedSubtypesForSpacebar.runInLocale(mRes, Locale.ENGLISH); + } + + public void testAdditionalSubtypeForSpacebarInEnglish() { + testsAdditionalSubtypesForSpacebar.runInLocale(mRes, Locale.ENGLISH); + } + + public void testPredefinedSubtypesForSpacebarInFrench() { + testsPredefinedSubtypesForSpacebar.runInLocale(mRes, Locale.FRENCH); + } + + public void testAdditionalSubtypeForSpacebarInFrench() { + testsAdditionalSubtypesForSpacebar.runInLocale(mRes, Locale.FRENCH); + } +} diff --git a/tests/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtilsTests.java new file mode 100644 index 000000000..3eabe2b3c --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtilsTests.java @@ -0,0 +1,239 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.content.Context; +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.LargeTest; +import android.util.Log; + +import com.android.inputmethod.latin.makedict.DictDecoder; +import com.android.inputmethod.latin.makedict.DictEncoder; +import com.android.inputmethod.latin.makedict.FormatSpec; +import com.android.inputmethod.latin.makedict.FusionDictionary; +import com.android.inputmethod.latin.makedict.FusionDictionary.PtNode; +import com.android.inputmethod.latin.makedict.Ver3DictDecoder; +import com.android.inputmethod.latin.makedict.Ver3DictEncoder; +import com.android.inputmethod.latin.personalization.UserHistoryDictionaryBigramList; +import com.android.inputmethod.latin.utils.UserHistoryDictIOUtils.BigramDictionaryInterface; +import com.android.inputmethod.latin.utils.UserHistoryDictIOUtils.OnAddWordListener; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; + +/** + * Unit tests for UserHistoryDictIOUtils + */ +@LargeTest +public class UserHistoryDictIOUtilsTests extends AndroidTestCase + implements BigramDictionaryInterface { + + private static final String TAG = UserHistoryDictIOUtilsTests.class.getSimpleName(); + private static final int UNIGRAM_FREQUENCY = 50; + private static final int BIGRAM_FREQUENCY = 100; + private static final ArrayList<String> NOT_HAVE_BIGRAM = new ArrayList<String>(); + private static final FormatSpec.FormatOptions FORMAT_OPTIONS = new FormatSpec.FormatOptions(2); + private static final String TEST_DICT_FILE_EXTENSION = ".testDict"; + + /** + * Return same frequency for all words and bigrams + */ + @Override + public int getFrequency(String word1, String word2) { + if (word1 == null) return UNIGRAM_FREQUENCY; + return BIGRAM_FREQUENCY; + } + + // Utilities for Testing + + private void addWord(final String word, + final HashMap<String, ArrayList<String> > addedWords) { + if (!addedWords.containsKey(word)) { + addedWords.put(word, new ArrayList<String>()); + } + } + + private void addBigram(final String word1, final String word2, + final HashMap<String, ArrayList<String> > addedWords) { + addWord(word1, addedWords); + addWord(word2, addedWords); + addedWords.get(word1).add(word2); + } + + private void addBigramToBigramList(final String word1, final String word2, + final HashMap<String, ArrayList<String> > addedWords, + final UserHistoryDictionaryBigramList bigramList) { + bigramList.addBigram(null, word1); + bigramList.addBigram(word1, word2); + + addBigram(word1, word2, addedWords); + } + + private void checkWordInFusionDict(final FusionDictionary dict, final String word, + final ArrayList<String> expectedBigrams) { + final PtNode ptNode = FusionDictionary.findWordInTree(dict.mRootNodeArray, word); + assertNotNull(ptNode); + assertTrue(ptNode.isTerminal()); + + for (final String bigram : expectedBigrams) { + assertNotNull(ptNode.getBigram(bigram)); + } + } + + private void checkWordsInFusionDict(final FusionDictionary dict, + final HashMap<String, ArrayList<String> > bigrams) { + for (final String word : bigrams.keySet()) { + if (bigrams.containsKey(word)) { + checkWordInFusionDict(dict, word, bigrams.get(word)); + } else { + checkWordInFusionDict(dict, word, NOT_HAVE_BIGRAM); + } + } + } + + private void checkWordInBigramList( + final UserHistoryDictionaryBigramList bigramList, final String word, + final ArrayList<String> expectedBigrams) { + // check unigram + final HashMap<String,Byte> unigramMap = bigramList.getBigrams(null); + assertTrue(unigramMap.containsKey(word)); + + // check bigrams + final ArrayList<String> actualBigrams = new ArrayList<String>( + bigramList.getBigrams(word).keySet()); + + Collections.sort(expectedBigrams); + Collections.sort(actualBigrams); + assertEquals(expectedBigrams, actualBigrams); + } + + private void checkWordsInBigramList(final UserHistoryDictionaryBigramList bigramList, + final HashMap<String, ArrayList<String> > addedWords) { + for (final String word : addedWords.keySet()) { + if (addedWords.containsKey(word)) { + checkWordInBigramList(bigramList, word, addedWords.get(word)); + } else { + checkWordInBigramList(bigramList, word, NOT_HAVE_BIGRAM); + } + } + } + + private void writeDictToFile(final File file, + final UserHistoryDictionaryBigramList bigramList) { + final DictEncoder dictEncoder = new Ver3DictEncoder(file); + UserHistoryDictIOUtils.writeDictionary(dictEncoder, this, bigramList, FORMAT_OPTIONS); + } + + private void readDictFromFile(final File file, final OnAddWordListener listener) { + final DictDecoder dictDecoder = FormatSpec.getDictDecoder(file, DictDecoder.USE_BYTEARRAY); + try { + dictDecoder.openDictBuffer(); + } catch (FileNotFoundException e) { + Log.e(TAG, "file not found", e); + } catch (IOException e) { + Log.e(TAG, "IOException", e); + } + UserHistoryDictIOUtils.readDictionaryBinary(dictDecoder, listener); + } + + public void testGenerateFusionDictionary() { + final UserHistoryDictionaryBigramList originalList = new UserHistoryDictionaryBigramList(); + + final HashMap<String, ArrayList<String> > addedWords = + new HashMap<String, ArrayList<String>>(); + addBigramToBigramList("this", "is", addedWords, originalList); + addBigramToBigramList("this", "was", addedWords, originalList); + addBigramToBigramList("hello", "world", addedWords, originalList); + + final FusionDictionary fusionDict = + UserHistoryDictIOUtils.constructFusionDictionary(this, originalList); + + checkWordsInFusionDict(fusionDict, addedWords); + } + + public void testReadAndWrite() { + final Context context = getContext(); + + File file = null; + try { + file = File.createTempFile("testReadAndWrite", TEST_DICT_FILE_EXTENSION, + getContext().getCacheDir()); + } catch (IOException e) { + Log.d(TAG, "IOException while creating a temporary file", e); + } + assertNotNull(file); + + // make original dictionary + final UserHistoryDictionaryBigramList originalList = new UserHistoryDictionaryBigramList(); + final HashMap<String, ArrayList<String>> addedWords = CollectionUtils.newHashMap(); + addBigramToBigramList("this" , "is" , addedWords, originalList); + addBigramToBigramList("this" , "was" , addedWords, originalList); + addBigramToBigramList("is" , "not" , addedWords, originalList); + addBigramToBigramList("hello", "world", addedWords, originalList); + + // write to file + writeDictToFile(file, originalList); + + // make result dict. + final UserHistoryDictionaryBigramList resultList = new UserHistoryDictionaryBigramList(); + final OnAddWordListener listener = new OnAddWordListener() { + @Override + public void setUnigram(final String word, + final String shortcutTarget, final int frequency) { + Log.d(TAG, "in: setUnigram: " + word + "," + frequency); + resultList.addBigram(null, word, (byte)frequency); + } + @Override + public void setBigram(final String word1, final String word2, final int frequency) { + Log.d(TAG, "in: setBigram: " + word1 + "," + word2 + "," + frequency); + resultList.addBigram(word1, word2, (byte)frequency); + } + }; + + // load from file + readDictFromFile(file, listener); + checkWordsInBigramList(resultList, addedWords); + + // add new bigram + addBigramToBigramList("hello", "java", addedWords, resultList); + + // rewrite + writeDictToFile(file, resultList); + final UserHistoryDictionaryBigramList resultList2 = new UserHistoryDictionaryBigramList(); + final OnAddWordListener listener2 = new OnAddWordListener() { + @Override + public void setUnigram(final String word, + final String shortcutTarget, final int frequency) { + Log.d(TAG, "in: setUnigram: " + word + "," + frequency); + resultList2.addBigram(null, word, (byte)frequency); + } + @Override + public void setBigram(final String word1, final String word2, final int frequency) { + Log.d(TAG, "in: setBigram: " + word1 + "," + word2 + "," + frequency); + resultList2.addBigram(word1, word2, (byte)frequency); + } + }; + + // load from file + readDictFromFile(file, listener2); + checkWordsInBigramList(resultList2, addedWords); + } +} |