diff options
Diffstat (limited to 'tests/src')
30 files changed, 1914 insertions, 861 deletions
diff --git a/tests/src/com/android/inputmethod/keyboard/MoreKeysKeyboardBuilderFixedOrderTests.java b/tests/src/com/android/inputmethod/keyboard/MoreKeysKeyboardBuilderFixedOrderTests.java index 01814ae13..6d9c3fdbb 100644 --- a/tests/src/com/android/inputmethod/keyboard/MoreKeysKeyboardBuilderFixedOrderTests.java +++ b/tests/src/com/android/inputmethod/keyboard/MoreKeysKeyboardBuilderFixedOrderTests.java @@ -47,7 +47,7 @@ public class MoreKeysKeyboardBuilderFixedOrderTests extends AndroidTestCase { final int coordXInParent) { final MoreKeysKeyboardParams params = new MoreKeysKeyboardParams(); params.setParameters(numKeys, columnNum, WIDTH, HEIGHT, coordXInParent, KEYBOARD_WIDTH, - /* isFixedOrderColumn */true, /* dividerWidth */0); + true /* isFixedOrderColumn */, 0 /* dividerWidth */); return params; } diff --git a/tests/src/com/android/inputmethod/keyboard/MoreKeysKeyboardBuilderTests.java b/tests/src/com/android/inputmethod/keyboard/MoreKeysKeyboardBuilderTests.java index ce5573da9..b213721bd 100644 --- a/tests/src/com/android/inputmethod/keyboard/MoreKeysKeyboardBuilderTests.java +++ b/tests/src/com/android/inputmethod/keyboard/MoreKeysKeyboardBuilderTests.java @@ -47,7 +47,7 @@ public class MoreKeysKeyboardBuilderTests extends AndroidTestCase { final int coordXInParent) { final MoreKeysKeyboardParams params = new MoreKeysKeyboardParams(); params.setParameters(numKeys, maxColumns, WIDTH, HEIGHT, coordXInParent, KEYBOARD_WIDTH, - /* isFixedOrderColumn */false, /* dividerWidth */0); + false /* isFixedOrderColumn */, 0 /* dividerWidth */); return params; } diff --git a/tests/src/com/android/inputmethod/keyboard/SpacebarTextTests.java b/tests/src/com/android/inputmethod/keyboard/SpacebarTextTests.java deleted file mode 100644 index 850af94f7..000000000 --- a/tests/src/com/android/inputmethod/keyboard/SpacebarTextTests.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * 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.keyboard; - -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.AdditionalSubtype; -import com.android.inputmethod.latin.CollectionUtils; -import com.android.inputmethod.latin.RichInputMethodManager; -import com.android.inputmethod.latin.StringUtils; -import com.android.inputmethod.latin.SubtypeLocale; -import com.android.inputmethod.latin.LocaleUtils.RunInLocale; - -import java.util.ArrayList; -import java.util.Locale; - -@SmallTest -public class SpacebarTextTests 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 US_AZERTY; - InputMethodSubtype ZZ_AZERTY; - - @Override - protected void setUp() throws Exception { - super.setUp(); - final Context context = getContext(); - RichInputMethodManager.init(context); - mRichImm = RichInputMethodManager.getInstance(); - mRes = context.getResources(); - SubtypeLocale.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(SubtypeLocale.NO_LANGUAGE, "qwerty"); - DE_QWERTY = AdditionalSubtype.createAdditionalSubtype( - Locale.GERMAN.toString(), "qwerty", null); - FR_QWERTZ = AdditionalSubtype.createAdditionalSubtype( - Locale.FRENCH.toString(), "qwertz", null); - US_AZERTY = AdditionalSubtype.createAdditionalSubtype( - Locale.US.toString(), "azerty", null); - ZZ_AZERTY = AdditionalSubtype.createAdditionalSubtype( - SubtypeLocale.NO_LANGUAGE, "azerty", null); - } - - public void testAllFullDisplayName() { - for (final InputMethodSubtype subtype : mSubtypesList) { - final String subtypeName = SubtypeLocale.getSubtypeDisplayName(subtype); - final String spacebarText = MainKeyboardView.getFullDisplayName(subtype); - final String languageName = - SubtypeLocale.getSubtypeLocaleDisplayName(subtype.getLocale()); - if (SubtypeLocale.isNoLanguage(subtype)) { - assertFalse(subtypeName, spacebarText.contains(languageName)); - } else { - assertTrue(subtypeName, spacebarText.contains(languageName)); - } - } - } - - public void testAllMiddleDisplayName() { - for (final InputMethodSubtype subtype : mSubtypesList) { - final String subtypeName = SubtypeLocale.getSubtypeDisplayName(subtype); - final String spacebarText = MainKeyboardView.getMiddleDisplayName(subtype); - if (SubtypeLocale.isNoLanguage(subtype)) { - assertEquals(subtypeName, - SubtypeLocale.getKeyboardLayoutSetName(subtype), spacebarText); - } else { - assertEquals(subtypeName, - SubtypeLocale.getSubtypeLocaleDisplayName(subtype.getLocale()), - spacebarText); - } - } - } - - public void testAllShortDisplayName() { - for (final InputMethodSubtype subtype : mSubtypesList) { - final String subtypeName = SubtypeLocale.getSubtypeDisplayName(subtype); - final Locale locale = SubtypeLocale.getSubtypeLocale(subtype); - final String spacebarText = MainKeyboardView.getShortDisplayName(subtype); - final String languageCode = StringUtils.capitalizeFirstCodePoint( - locale.getLanguage(), locale); - if (SubtypeLocale.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> testsPredefinedSubtypes = new RunInLocale<Void>() { - @Override - protected Void job(Resources res) { - assertEquals("en_US", "English (US)", MainKeyboardView.getFullDisplayName(EN_US)); - assertEquals("en_GB", "English (UK)", MainKeyboardView.getFullDisplayName(EN_GB)); - assertEquals("es_US", "Español (EE.UU.)", MainKeyboardView.getFullDisplayName(ES_US)); - assertEquals("fr ", "Français", MainKeyboardView.getFullDisplayName(FR)); - assertEquals("fr_CA", "Français (Canada)", MainKeyboardView.getFullDisplayName(FR_CA)); - assertEquals("de ", "Deutsch", MainKeyboardView.getFullDisplayName(DE)); - assertEquals("zz ", "QWERTY", MainKeyboardView.getFullDisplayName(ZZ)); - - assertEquals("en_US", "English", MainKeyboardView.getMiddleDisplayName(EN_US)); - assertEquals("en_GB", "English", MainKeyboardView.getMiddleDisplayName(EN_GB)); - assertEquals("es_US", "Español", MainKeyboardView.getMiddleDisplayName(ES_US)); - assertEquals("fr ", "Français", MainKeyboardView.getMiddleDisplayName(FR)); - assertEquals("fr_CA", "Français", MainKeyboardView.getMiddleDisplayName(FR_CA)); - assertEquals("de ", "Deutsch", MainKeyboardView.getMiddleDisplayName(DE)); - assertEquals("zz ", "QWERTY", MainKeyboardView.getMiddleDisplayName(ZZ)); - - assertEquals("en_US", "En", MainKeyboardView.getShortDisplayName(EN_US)); - assertEquals("en_GB", "En", MainKeyboardView.getShortDisplayName(EN_GB)); - assertEquals("es_US", "Es", MainKeyboardView.getShortDisplayName(ES_US)); - assertEquals("fr ", "Fr", MainKeyboardView.getShortDisplayName(FR)); - assertEquals("fr_CA", "Fr", MainKeyboardView.getShortDisplayName(FR_CA)); - assertEquals("de ", "De", MainKeyboardView.getShortDisplayName(DE)); - assertEquals("zz ", "", MainKeyboardView.getShortDisplayName(ZZ)); - return null; - } - }; - - private final RunInLocale<Void> testsAdditionalSubtypes = new RunInLocale<Void>() { - @Override - protected Void job(Resources res) { - assertEquals("fr qwertz", "Français", - MainKeyboardView.getFullDisplayName(FR_QWERTZ)); - assertEquals("de qwerty", "Deutsch", - MainKeyboardView.getFullDisplayName(DE_QWERTY)); - assertEquals("en_US azerty", "English (US)", - MainKeyboardView.getFullDisplayName(US_AZERTY)); - assertEquals("zz azerty", "AZERTY", - MainKeyboardView.getFullDisplayName(ZZ_AZERTY)); - - assertEquals("fr qwertz", "Français", - MainKeyboardView.getMiddleDisplayName(FR_QWERTZ)); - assertEquals("de qwerty", "Deutsch", - MainKeyboardView.getMiddleDisplayName(DE_QWERTY)); - assertEquals("en_US azerty", "English", - MainKeyboardView.getMiddleDisplayName(US_AZERTY)); - assertEquals("zz azerty", "AZERTY", - MainKeyboardView.getMiddleDisplayName(ZZ_AZERTY)); - - assertEquals("fr qwertz", "Fr", MainKeyboardView.getShortDisplayName(FR_QWERTZ)); - assertEquals("de qwerty", "De", MainKeyboardView.getShortDisplayName(DE_QWERTY)); - assertEquals("en_US azerty", "En", MainKeyboardView.getShortDisplayName(US_AZERTY)); - assertEquals("zz azerty", "", MainKeyboardView.getShortDisplayName(ZZ_AZERTY)); - return null; - } - }; - - public void testPredefinedSubtypesInEnglish() { - testsPredefinedSubtypes.runInLocale(mRes, Locale.ENGLISH); - } - - public void testAdditionalSubtypeInEnglish() { - testsAdditionalSubtypes.runInLocale(mRes, Locale.ENGLISH); - } - - public void testPredefinedSubtypesInFrench() { - testsPredefinedSubtypes.runInLocale(mRes, Locale.FRENCH); - } - - public void testAdditionalSubtypeInFrench() { - testsAdditionalSubtypes.runInLocale(mRes, Locale.FRENCH); - } -} diff --git a/tests/src/com/android/inputmethod/keyboard/internal/KeySpecParserCsvTests.java b/tests/src/com/android/inputmethod/keyboard/internal/KeySpecParserSplitTests.java index 9014e7cc8..2eb448c82 100644 --- a/tests/src/com/android/inputmethod/keyboard/internal/KeySpecParserCsvTests.java +++ b/tests/src/com/android/inputmethod/keyboard/internal/KeySpecParserSplitTests.java @@ -17,11 +17,13 @@ package com.android.inputmethod.keyboard.internal; import android.app.Instrumentation; +import android.content.Context; +import android.content.res.Resources; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.MediumTest; -import com.android.inputmethod.latin.CollectionUtils; -import com.android.inputmethod.latin.StringUtils; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.RunInLocale; import java.lang.reflect.Field; import java.util.ArrayList; @@ -29,21 +31,30 @@ import java.util.Arrays; import java.util.Locale; @MediumTest -public class KeySpecParserCsvTests extends InstrumentationTestCase { - private final KeyboardTextsSet mTextsSet = new KeyboardTextsSet(); +public class KeySpecParserSplitTests extends InstrumentationTestCase { + private static final Locale TEST_LOCALE = Locale.ENGLISH; + final KeyboardTextsSet mTextsSet = new KeyboardTextsSet(); @Override protected void setUp() throws Exception { super.setUp(); final Instrumentation instrumentation = getInstrumentation(); - mTextsSet.setLanguage(Locale.ENGLISH.getLanguage()); - mTextsSet.loadStringResources(instrumentation.getTargetContext()); + final Context targetContext = instrumentation.getTargetContext(); + mTextsSet.setLanguage(TEST_LOCALE.getLanguage()); + new RunInLocale<Void>() { + @Override + protected Void job(final Resources res) { + mTextsSet.loadStringResources(targetContext); + return null; + } + }.runInLocale(targetContext.getResources(), TEST_LOCALE); final String[] testResourceNames = getAllResourceIdNames( com.android.inputmethod.latin.tests.R.string.class); - mTextsSet.loadStringResourcesInternal(instrumentation.getContext(), - testResourceNames, - com.android.inputmethod.latin.tests.R.string.empty_string); + mTextsSet.loadStringResourcesInternal(instrumentation.getContext(), testResourceNames, + // This dummy raw resource is needed to be able to load string resources from a test + // APK successfully. + com.android.inputmethod.latin.tests.R.raw.dummy_resource_for_testing); } private static String[] getAllResourceIdNames(final Class<?> resourceIdClass) { @@ -56,8 +67,8 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { return names.toArray(new String[names.size()]); } - private static void assertArrayEquals(final String message, final Object[] expected, - final Object[] actual) { + private static <T> void assertArrayEquals(final String message, final T[] expected, + final T[] actual) { if (expected == actual) { return; } @@ -70,15 +81,19 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { return; } for (int i = 0; i < expected.length; i++) { - assertEquals(message + " [" + i + "]", - Arrays.toString(expected), Arrays.toString(actual)); + final T e = expected[i]; + final T a = actual[i]; + if (e == a) { + continue; + } + assertEquals(message + " [" + i + "]", e, a); } } private void assertTextArray(final String message, final String value, final String ... expectedArray) { final String resolvedActual = KeySpecParser.resolveTextReference(value, mTextsSet); - final String[] actual = StringUtils.parseCsvString(resolvedActual); + final String[] actual = KeySpecParser.splitKeySpecs(resolvedActual); final String[] expected = (expectedArray.length == 0) ? null : expectedArray; assertArrayEquals(message, expected, actual); } @@ -101,7 +116,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { private static final String SURROGATE1 = PAIR1 + PAIR2; private static final String SURROGATE2 = PAIR1 + PAIR2 + PAIR3; - public void testParseCsvTextZero() { + public void testSplitZero() { assertTextArray("Empty string", ""); assertTextArray("Empty entry", ","); assertTextArray("Empty entry at beginning", ",a", "a"); @@ -110,7 +125,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { assertTextArray("Empty entries with escape", ",a,b\\,c,,d,", "a", "b\\,c", "d"); } - public void testParseCsvTextSingle() { + public void testSplitSingle() { assertTextArray("Single char", "a", "a"); assertTextArray("Surrogate pair", PAIR1, PAIR1); assertTextArray("Single escape", "\\", "\\"); @@ -139,7 +154,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { assertTextArray("Incomplete resource reference 4", "!" + SURROGATE2, "!" + SURROGATE2); } - public void testParseCsvTextSingleEscaped() { + public void testSplitSingleEscaped() { assertTextArray("Escaped char", "\\a", "\\a"); assertTextArray("Escaped surrogate pair", "\\" + PAIR1, "\\" + PAIR1); assertTextArray("Escaped comma", "\\,", "\\,"); @@ -174,7 +189,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { assertTextArray("Escaped !TEXT/NAME", "\\!TEXT/EMPTY_STRING", "\\!TEXT/EMPTY_STRING"); } - public void testParseCsvTextMulti() { + public void testSplitMulti() { assertTextArray("Multiple chars", "a,b,c", "a", "b", "c"); assertTextArray("Multiple chars", "a,b,\\c", "a", "b", "\\c"); assertTextArray("Multiple chars and escape at beginning and end", @@ -189,7 +204,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { " abc ", " def ", " ghi "); } - public void testParseCsvTextMultiEscaped() { + public void testSplitMultiEscaped() { assertTextArray("Multiple chars with comma", "a,\\,,c", "a", "\\,", "c"); assertTextArray("Multiple chars with comma surrounded by spaces", " a , \\, , c ", " a ", " \\, ", " c "); @@ -208,17 +223,17 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { "\\!", "\\!TEXT/EMPTY_STRING"); } - public void testParseCsvResourceError() { + public void testSplitResourceError() { assertError("Incomplete resource name", "!text/", "!text/"); assertError("Non existing resource", "!text/non_existing"); } - public void testParseCsvResourceZero() { + public void testSplitResourceZero() { assertTextArray("Empty string", "!text/empty_string"); } - public void testParseCsvResourceSingle() { + public void testSplitResourceSingle() { assertTextArray("Single char", "!text/single_char", "a"); assertTextArray("Space", @@ -240,7 +255,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { "\\\\!text/single_char", "\\\\a"); } - public void testParseCsvResourceSingleEscaped() { + public void testSplitResourceSingleEscaped() { assertTextArray("Escaped char", "!text/escaped_char", "\\a"); assertTextArray("Escaped comma", @@ -267,7 +282,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { "!text/escaped_label_with_escape", "a\\\\c"); } - public void testParseCsvResourceMulti() { + public void testSplitResourceMulti() { assertTextArray("Multiple chars", "!text/multiple_chars", "a", "b", "c"); assertTextArray("Multiple chars surrounded by spaces", @@ -279,7 +294,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { "!text/multiple_labels_surrounded_by_spaces", " abc ", " def ", " ghi "); } - public void testParseCsvResourcetMultiEscaped() { + public void testSplitResourcetMultiEscaped() { assertTextArray("Multiple chars with comma", "!text/multiple_chars_with_comma", "a", "\\,", "c"); @@ -300,7 +315,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { " ab\\\\ ", " d\\\\\\, ", " g\\,i "); } - public void testParseMultipleResources() { + public void testSplitMultipleResources() { assertTextArray("Literals and resources", "1,!text/multiple_chars,z", "1", "a", "b", "c", "z"); assertTextArray("Literals and resources and escape at end", @@ -322,7 +337,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { "abcabc", "def", "ghi"); } - public void testParseIndirectReference() { + public void testSplitIndirectReference() { assertTextArray("Indirect", "!text/indirect_string", "a", "b", "c"); assertTextArray("Indirect with literal", @@ -331,7 +346,7 @@ public class KeySpecParserCsvTests extends InstrumentationTestCase { "!text/indirect2_string", "a", "b", "c"); } - public void testParseInfiniteIndirectReference() { + public void testSplitInfiniteIndirectReference() { assertError("Infinite indirection", "1,!text/infinite_indirection,2", "1", "infinite", "<infinite>", "loop", "2"); } diff --git a/tests/src/com/android/inputmethod/keyboard/internal/KeySpecParserTests.java b/tests/src/com/android/inputmethod/keyboard/internal/KeySpecParserTests.java index b1ae6f5b7..afb2b0343 100644 --- a/tests/src/com/android/inputmethod/keyboard/internal/KeySpecParserTests.java +++ b/tests/src/com/android/inputmethod/keyboard/internal/KeySpecParserTests.java @@ -20,23 +20,27 @@ import static com.android.inputmethod.keyboard.internal.KeyboardIconsSet.ICON_UN import static com.android.inputmethod.latin.Constants.CODE_OUTPUT_TEXT; import static com.android.inputmethod.latin.Constants.CODE_UNSPECIFIED; +import android.content.Context; +import android.content.res.Resources; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; import com.android.inputmethod.latin.Constants; +import com.android.inputmethod.latin.utils.RunInLocale; import java.util.Arrays; import java.util.Locale; @SmallTest public class KeySpecParserTests extends AndroidTestCase { - private final KeyboardCodesSet mCodesSet = new KeyboardCodesSet(); - private final KeyboardTextsSet mTextsSet = new KeyboardTextsSet(); + private final static Locale TEST_LOCALE = Locale.ENGLISH; + final KeyboardCodesSet mCodesSet = new KeyboardCodesSet(); + final KeyboardTextsSet mTextsSet = new KeyboardTextsSet(); private static final String CODE_SETTINGS = "!code/key_settings"; private static final String ICON_SETTINGS = "!icon/settings_key"; - private static final String CODE_SETTINGS_UPPERCASE = CODE_SETTINGS.toUpperCase(); - private static final String ICON_SETTINGS_UPPERCASE = ICON_SETTINGS.toUpperCase(); + private static final String CODE_SETTINGS_UPPERCASE = CODE_SETTINGS.toUpperCase(Locale.ROOT); + private static final String ICON_SETTINGS_UPPERCASE = ICON_SETTINGS.toUpperCase(Locale.ROOT); private static final String CODE_NON_EXISTING = "!code/non_existing"; private static final String ICON_NON_EXISTING = "!icon/non_existing"; @@ -48,10 +52,17 @@ public class KeySpecParserTests extends AndroidTestCase { protected void setUp() throws Exception { super.setUp(); - final String language = Locale.ENGLISH.getLanguage(); + final String language = TEST_LOCALE.getLanguage(); mCodesSet.setLanguage(language); mTextsSet.setLanguage(language); - mTextsSet.loadStringResources(getContext()); + final Context context = getContext(); + new RunInLocale<Void>() { + @Override + protected Void job(final Resources res) { + mTextsSet.loadStringResources(context); + return null; + } + }.runInLocale(context.getResources(), TEST_LOCALE); mCodeSettings = KeySpecParser.parseCode( CODE_SETTINGS, mCodesSet, CODE_UNSPECIFIED); @@ -587,7 +598,7 @@ public class KeySpecParserTests extends AndroidTestCase { new String[] { null, "a", "b", "c" }, true); // Upper case specification will not work. assertGetBooleanValue("HAS LABEL", HAS_LABEL, - new String[] { HAS_LABEL.toUpperCase(), "a", "b", "c" }, + new String[] { HAS_LABEL.toUpperCase(Locale.ROOT), "a", "b", "c" }, new String[] { "!HASLABEL!", "a", "b", "c" }, false); assertGetBooleanValue("No has label", HAS_LABEL, @@ -600,13 +611,13 @@ public class KeySpecParserTests extends AndroidTestCase { // Upper case specification will not work. assertGetBooleanValue("Multiple has label", HAS_LABEL, new String[] { - "a", HAS_LABEL.toUpperCase(), "b", "c", HAS_LABEL, "d" }, + "a", HAS_LABEL.toUpperCase(Locale.ROOT), "b", "c", HAS_LABEL, "d" }, new String[] { "a", "!HASLABEL!", "b", "c", null, "d" }, true); // Upper case specification will not work. assertGetBooleanValue("Multiple has label with needs dividers", HAS_LABEL, new String[] { - "a", HAS_LABEL, "b", NEEDS_DIVIDER, HAS_LABEL.toUpperCase(), "d" }, + "a", HAS_LABEL, "b", NEEDS_DIVIDER, HAS_LABEL.toUpperCase(Locale.ROOT), "d" }, new String[] { "a", null, "b", NEEDS_DIVIDER, "!HASLABEL!", "d" }, true); } @@ -625,7 +636,7 @@ public class KeySpecParserTests extends AndroidTestCase { new String[] { null, "a", "b", "c" }, 3); // Upper case specification will not work. assertGetIntValue("FIXED COLUMN ORDER 3", FIXED_COLUMN_ORDER, -1, - new String[] { FIXED_COLUMN_ORDER.toUpperCase() + "3", "a", "b", "c" }, + new String[] { FIXED_COLUMN_ORDER.toUpperCase(Locale.ROOT) + "3", "a", "b", "c" }, new String[] { "!FIXEDCOLUMNORDER!3", "a", "b", "c" }, -1); assertGetIntValue("No fixed column order", FIXED_COLUMN_ORDER, -1, @@ -641,7 +652,7 @@ public class KeySpecParserTests extends AndroidTestCase { // Upper case specification will not work. assertGetIntValue("Multiple fixed column order 5,3 with has label", FIXED_COLUMN_ORDER, -1, new String[] { - FIXED_COLUMN_ORDER.toUpperCase() + "5", HAS_LABEL, "a", + FIXED_COLUMN_ORDER.toUpperCase(Locale.ROOT) + "5", HAS_LABEL, "a", FIXED_COLUMN_ORDER + "3", "b" }, new String[] { "!FIXEDCOLUMNORDER!5", HAS_LABEL, "a", null, "b" }, 3); } diff --git a/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateMultiTouchTests.java b/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateMultiTouchTests.java index b193e66dc..9ad81c01d 100644 --- a/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateMultiTouchTests.java +++ b/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateMultiTouchTests.java @@ -60,7 +60,7 @@ public class KeyboardStateMultiTouchTests extends KeyboardStateTestsBase { // Chording input in shift locked. public void testChordingShiftLocked() { // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press shift key and hold, enter into choring shift state. @@ -119,7 +119,7 @@ public class KeyboardStateMultiTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -137,7 +137,7 @@ public class KeyboardStateMultiTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -196,7 +196,7 @@ public class KeyboardStateMultiTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -216,7 +216,7 @@ public class KeyboardStateMultiTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -397,29 +397,29 @@ public class KeyboardStateMultiTouchTests extends KeyboardStateTestsBase { public void testLongPressShiftAndChording() { // Long press shift key, enter maybe shift locked. - longPressKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); + longPressShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); // Press/release letter key, remain in manual shifted. chordingPressAndReleaseKey('A', ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); // Release shift key, back to alphabet (not shift locked). releaseKey(CODE_SHIFT, ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Long press shift key, enter maybe alphabet. - longPressKey(CODE_SHIFT, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED); + longPressShiftKey(ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED); // Press/release letter key, remain in manual shifted. chordingPressAndReleaseKey('A', ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED); // Release shift key, back to shift locked (not alphabet). releaseKey(CODE_SHIFT, ALPHABET_SHIFT_LOCKED); // Long press shift key, enter alphabet - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_UNSHIFTED); // Press/release shift key, enter alphabet shifted. pressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); // Long press shift key, enter maybe alphabet. - longPressKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); + longPressShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); // Press/release letter key, remain in manual shifted. chordingPressAndReleaseKey('A', ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); // Release shift key, back to alphabet shifted (not alphabet). @@ -430,7 +430,7 @@ public class KeyboardStateMultiTouchTests extends KeyboardStateTestsBase { // Load keyboard, should be in automatic shifted. loadKeyboard(ALPHABET_AUTOMATIC_SHIFTED); // Long press shift key, enter maybe shift locked. - longPressKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); + longPressShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); // Press/release letter key, remain in manual shifted. chordingPressAndReleaseKey('A', ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); // Release shift key, back to alphabet (not shift locked). @@ -449,7 +449,7 @@ public class KeyboardStateMultiTouchTests extends KeyboardStateTestsBase { // releaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED); // // // Long press shift key, enter alphabet shift locked. -// longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, +// longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, // ALPHABET_SHIFT_LOCKED); // // First shift key tap. // pressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_UNSHIFTED); diff --git a/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateSingleTouchTests.java b/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateSingleTouchTests.java index d5b9d1dfd..c7ac76d93 100644 --- a/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateSingleTouchTests.java +++ b/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateSingleTouchTests.java @@ -91,7 +91,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Switching between alphabet shift locked and symbols. public void testAlphabetShiftLockedAndSymbols() { // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. @@ -133,7 +133,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Automatic switch back to alphabet shift locked test by space key. public void testSwitchBackBySpaceShiftLocked() { // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. @@ -196,13 +196,13 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Load keyboard, should be in alphabet. loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release shift key, back to alphabet. pressAndReleaseKey(CODE_SHIFT, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release letter key, remain in shift locked. pressAndReleaseKey('A', ALPHABET_SHIFT_LOCKED, ALPHABET_SHIFT_LOCKED); @@ -212,16 +212,16 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { pressAndReleaseKey(CODE_SHIFT, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Long press shift key, back to alphabet. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_UNSHIFTED); // Press/release shift key, enter alphabet shifted. pressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release shift key, back to alphabet. pressAndReleaseKey(CODE_SHIFT, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_UNSHIFTED); @@ -231,7 +231,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Load keyboard, should be in automatic shifted. loadKeyboard(ALPHABET_AUTOMATIC_SHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release shift key, back to alphabet. pressAndReleaseKey(CODE_SHIFT, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_UNSHIFTED); @@ -293,12 +293,12 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { updateShiftState(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Update shift state, remained in alphabet shift locked. updateShiftState(ALPHABET_SHIFT_LOCKED); // Long press shift key, back to alphabet. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_UNSHIFTED); // Press/release "?123" key, enter into symbols. @@ -326,12 +326,12 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { updateShiftState(ALPHABET_AUTOMATIC_SHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Update shift state, remained in alphabet shift locked (not automatic shifted). updateShiftState(ALPHABET_SHIFT_LOCKED); // Long press shift key, back to alphabet. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_UNSHIFTED); // Load keyboard, should be in automatic shifted. @@ -383,7 +383,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Alphabet shift locked -> shift key + letter -> alphabet shift locked. // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press and slide from "123?" key, enter symbols. pressAndSlideFromKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -441,7 +441,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Alphabet shift locked -> shift key + letter -> cancel -> alphabet shift locked. // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press and slide from "123?" key, enter symbols. pressAndSlideFromKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -500,7 +500,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -517,7 +517,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -574,7 +574,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -592,7 +592,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -651,7 +651,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -670,7 +670,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -733,7 +733,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -753,7 +753,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Load keyboard loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release "?123" key, enter into symbols. pressAndReleaseKey(CODE_SYMBOL, SYMBOLS_UNSHIFTED, SYMBOLS_UNSHIFTED); @@ -777,7 +777,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { loadKeyboard(ALPHABET_UNSHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Change focus to new text field. loadKeyboard(ALPHABET_UNSHIFTED); @@ -808,7 +808,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { loadKeyboard(ALPHABET_AUTOMATIC_SHIFTED); // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Change focus to new text field. loadKeyboard(ALPHABET_AUTOMATIC_SHIFTED); @@ -852,7 +852,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { // Alphabet shift locked -> rotate -> alphabet shift locked. // Long press shift key, enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Rotate device, remain in alphabet shift locked. rotateDevice(ALPHABET_SHIFT_LOCKED); @@ -936,7 +936,7 @@ public class KeyboardStateSingleTouchTests extends KeyboardStateTestsBase { secondPressAndReleaseKey('J', ALPHABET_MANUAL_SHIFTED, ALPHABET_UNSHIFTED); // Long press shift key to enter alphabet shift locked. - longPressAndReleaseKey(CODE_SHIFT, ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, + longPressAndReleaseShiftKey(ALPHABET_MANUAL_SHIFTED, ALPHABET_MANUAL_SHIFTED, ALPHABET_SHIFT_LOCKED); // Press/release shift key pressAndReleaseKey(CODE_SHIFT, ALPHABET_SHIFT_LOCK_SHIFTED, ALPHABET_UNSHIFTED); diff --git a/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateTestsBase.java b/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateTestsBase.java index e06ca064a..3ffd0a96a 100644 --- a/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateTestsBase.java +++ b/tests/src/com/android/inputmethod/keyboard/internal/KeyboardStateTestsBase.java @@ -18,6 +18,8 @@ package com.android.inputmethod.keyboard.internal; import android.test.AndroidTestCase; +import com.android.inputmethod.latin.Constants; + public class KeyboardStateTestsBase extends AndroidTestCase implements MockKeyboardSwitcher.MockConstants { protected MockKeyboardSwitcher mSwitcher; @@ -32,6 +34,11 @@ public class KeyboardStateTestsBase extends AndroidTestCase loadKeyboard(ALPHABET_UNSHIFTED); } + /** + * Set auto caps mode. + * + * @param autoCaps the auto cap mode. + */ public void setAutoCapsMode(final int autoCaps) { mSwitcher.setAutoCapsMode(autoCaps); } @@ -42,17 +49,32 @@ public class KeyboardStateTestsBase extends AndroidTestCase expected == actual); } + /** + * Emulate update keyboard shift state. + * + * @param afterUpdate the keyboard state after updating the keyboard shift state. + */ public void updateShiftState(final int afterUpdate) { mSwitcher.updateShiftState(); assertLayout("afterUpdate", afterUpdate, mSwitcher.getLayoutId()); } + /** + * Emulate load default keyboard. + * + * @param afterLoad the keyboard state after loading default keyboard. + */ public void loadKeyboard(final int afterLoad) { mSwitcher.loadKeyboard(); mSwitcher.updateShiftState(); assertLayout("afterLoad", afterLoad, mSwitcher.getLayoutId()); } + /** + * Emulate rotate device. + * + * @param afterRotate the keyboard state after rotating device. + */ public void rotateDevice(final int afterRotate) { mSwitcher.saveKeyboardState(); mSwitcher.loadKeyboard(); @@ -65,45 +87,97 @@ public class KeyboardStateTestsBase extends AndroidTestCase assertLayout("afterPress", afterPress, mSwitcher.getLayoutId()); } + /** + * Emulate key press. + * + * @param code the key code to press. + * @param afterPress the keyboard state after pressing the key. + */ public void pressKey(final int code, final int afterPress) { mSwitcher.expireDoubleTapTimeout(); pressKeyWithoutTimerExpire(code, true, afterPress); } + /** + * Emulate key release and register. + * + * @param code the key code to release and register + * @param afterRelease the keyboard state after releasing the key. + */ public void releaseKey(final int code, final int afterRelease) { mSwitcher.onCodeInput(code); mSwitcher.onReleaseKey(code, NOT_SLIDING); assertLayout("afterRelease", afterRelease, mSwitcher.getLayoutId()); } + /** + * Emulate key press and release. + * + * @param code the key code to press and release. + * @param afterPress the keyboard state after pressing the key. + * @param afterRelease the keyboard state after releasing the key. + */ public void pressAndReleaseKey(final int code, final int afterPress, final int afterRelease) { pressKey(code, afterPress); releaseKey(code, afterRelease); } + /** + * Emulate chording key press. + * + * @param code the chording key code. + * @param afterPress the keyboard state after pressing chording key. + */ public void chordingPressKey(final int code, final int afterPress) { mSwitcher.expireDoubleTapTimeout(); pressKeyWithoutTimerExpire(code, false, afterPress); } + /** + * Emulate chording key release. + * + * @param code the cording key code. + * @param afterRelease the keyboard state after releasing chording key. + */ public void chordingReleaseKey(final int code, final int afterRelease) { mSwitcher.onCodeInput(code); mSwitcher.onReleaseKey(code, NOT_SLIDING); assertLayout("afterRelease", afterRelease, mSwitcher.getLayoutId()); } + /** + * Emulate chording key press and release. + * + * @param code the chording key code. + * @param afterPress the keyboard state after pressing chording key. + * @param afterRelease the keyboard state after releasing chording key. + */ public void chordingPressAndReleaseKey(final int code, final int afterPress, final int afterRelease) { chordingPressKey(code, afterPress); chordingReleaseKey(code, afterRelease); } + /** + * Emulate start of the sliding key input. + * + * @param code the key code to start sliding. + * @param afterPress the keyboard state after pressing the key. + * @param afterSlide the keyboard state after releasing the key with sliding input. + */ public void pressAndSlideFromKey(final int code, final int afterPress, final int afterSlide) { pressKey(code, afterPress); mSwitcher.onReleaseKey(code, SLIDING); assertLayout("afterSlide", afterSlide, mSwitcher.getLayoutId()); } + /** + * Emulate end of the sliding key input. + * + * @param code the key code to stop sliding. + * @param afterPress the keyboard state after pressing the key. + * @param afterSlide the keyboard state after releasing the key and stop sliding. + */ public void stopSlidingOnKey(final int code, final int afterPress, final int afterSlide) { pressKey(code, afterPress); mSwitcher.onCodeInput(code); @@ -112,28 +186,67 @@ public class KeyboardStateTestsBase extends AndroidTestCase assertLayout("afterSlide", afterSlide, mSwitcher.getLayoutId()); } + /** + * Emulate cancel the sliding key input. + * + * @param afterCancelSliding the keyboard state after canceling sliding input. + */ public void stopSlidingAndCancel(final int afterCancelSliding) { mSwitcher.onFinishSlidingInput(); assertLayout("afterCancelSliding", afterCancelSliding, mSwitcher.getLayoutId()); } - public void longPressKey(final int code, final int afterPress, final int afterLongPress) { - pressKey(code, afterPress); - mSwitcher.onLongPressTimeout(code); + /** + * Emulate long press shift key. + * + * @param afterPress the keyboard state after pressing shift key. + * @param afterLongPress the keyboard state after long press fired. + */ + public void longPressShiftKey(final int afterPress, final int afterLongPress) { + // Long press shift key will register {@link Constants#CODE_CAPS_LOCK}. See + // {@link R.xml#key_styles_common} and its baseForShiftKeyStyle. We thus emulate the + // behavior that is implemented in {@link MainKeyboardView#onLongPress(PointerTracker)}. + pressKey(Constants.CODE_SHIFT, afterPress); + mSwitcher.onPressKey(Constants.CODE_CAPSLOCK, true /* isSinglePointer */); + mSwitcher.onCodeInput(Constants.CODE_CAPSLOCK); assertLayout("afterLongPress", afterLongPress, mSwitcher.getLayoutId()); } - public void longPressAndReleaseKey(final int code, final int afterPress, - final int afterLongPress, final int afterRelease) { - longPressKey(code, afterPress, afterLongPress); - releaseKey(code, afterRelease); - } - - public void secondPressKey(int code, int afterPress) { + /** + * Emulate long press shift key and release. + * + * @param afterPress the keyboard state after pressing shift key. + * @param afterLongPress the keyboard state after long press fired. + * @param afterRelease the keyboard state after shift key is released. + */ + public void longPressAndReleaseShiftKey(final int afterPress, final int afterLongPress, + final int afterRelease) { + // Long press shift key will register {@link Constants#CODE_CAPS_LOCK}. See + // {@link R.xml#key_styles_common} and its baseForShiftKeyStyle. We thus emulate the + // behavior that is implemented in {@link MainKeyboardView#onLongPress(PointerTracker)}. + longPressShiftKey(afterPress, afterLongPress); + releaseKey(Constants.CODE_CAPSLOCK, afterRelease); + } + + /** + * Emulate the second press of the double tap. + * + * @param code the key code to double tap. + * @param afterPress the keyboard state after pressing the second tap. + */ + public void secondPressKey(final int code, final int afterPress) { pressKeyWithoutTimerExpire(code, true, afterPress); } - public void secondPressAndReleaseKey(int code, int afterPress, int afterRelease) { + /** + * Emulate the second tap of the double tap. + * + * @param code the key code to double tap. + * @param afterPress the keyboard state after pressing the second tap. + * @param afterRelease the keyboard state after releasing the second tap. + */ + public void secondPressAndReleaseKey(final int code, final int afterPress, + final int afterRelease) { secondPressKey(code, afterPress); releaseKey(code, afterRelease); } diff --git a/tests/src/com/android/inputmethod/keyboard/internal/MatrixUtilsTests.java b/tests/src/com/android/inputmethod/keyboard/internal/MatrixUtilsTests.java new file mode 100644 index 000000000..e2a11ab99 --- /dev/null +++ b/tests/src/com/android/inputmethod/keyboard/internal/MatrixUtilsTests.java @@ -0,0 +1,84 @@ +/* + * 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.keyboard.internal; + +import com.android.inputmethod.keyboard.internal.MatrixUtils.MatrixOperationFailedException; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +@SmallTest +public class MatrixUtilsTests extends AndroidTestCase { + // "run tests" -c com.android.inputmethod.keyboard.internal.MatrixUtilsTests + private static final boolean DEBUG = false; + private static final float EPSILON = 0.00001f; + + private static void assertEqualsFloat(float f0, float f1) { + assertEqualsFloat(f0, f1, EPSILON); + } + + /* package */ static void assertEqualsFloat(float f0, float f1, float error) { + assertTrue(Math.abs(f0 - f1) < error); + } + + public void testMulti() { + final float[][] matrixA = {{1, 2}, {3, 4}}; + final float[][] matrixB = {{5, 6}, {7, 8}}; + final float[][] retval = new float[2][2]; + try { + MatrixUtils.multiply(matrixA, matrixB, retval); + } catch (MatrixOperationFailedException e) { + assertTrue(false); + } + if (DEBUG) { + MatrixUtils.dump("multi", retval); + } + assertEqualsFloat(retval[0][0], 19); + assertEqualsFloat(retval[0][1], 22); + assertEqualsFloat(retval[1][0], 43); + assertEqualsFloat(retval[1][1], 50); + } + + public void testInverse() { + final int N = 4; + final float[][] matrix = + {{1, 2, 3, 4}, {4, 0, 5, 6}, {6, 4, 2, 0}, {6, 4, 2, 1}}; + final float[][] inverse = new float[N][N]; + final float[][] tempMatrix = new float[N][N]; + for (int i = 0; i < N; ++i) { + for (int j = 0; j < N; ++j) { + tempMatrix[i][j] = matrix[i][j]; + } + } + final float[][] retval = new float[N][N]; + try { + MatrixUtils.inverse(tempMatrix, inverse); + } catch (MatrixOperationFailedException e) { + assertTrue(false); + } + try { + MatrixUtils.multiply(matrix, inverse, retval); + } catch (MatrixOperationFailedException e) { + assertTrue(false); + } + for (int i = 0; i < N; ++i) { + for (int j = 0; j < N; ++j) { + assertEqualsFloat(((i == j) ? 1.0f : 0.0f), retval[i][j]); + } + } + } +} diff --git a/tests/src/com/android/inputmethod/keyboard/internal/MockKeyboardSwitcher.java b/tests/src/com/android/inputmethod/keyboard/internal/MockKeyboardSwitcher.java index 2544b6c52..db3997651 100644 --- a/tests/src/com/android/inputmethod/keyboard/internal/MockKeyboardSwitcher.java +++ b/tests/src/com/android/inputmethod/keyboard/internal/MockKeyboardSwitcher.java @@ -19,7 +19,7 @@ package com.android.inputmethod.keyboard.internal; import android.text.TextUtils; import com.android.inputmethod.latin.Constants; -import com.android.inputmethod.latin.RecapitalizeStatus; +import com.android.inputmethod.latin.utils.RecapitalizeStatus; public class MockKeyboardSwitcher implements KeyboardState.SwitchActions { public interface MockConstants { @@ -53,7 +53,7 @@ public class MockKeyboardSwitcher implements KeyboardState.SwitchActions { // Following InputConnection's behavior. Simulating InputType.TYPE_TEXT_FLAG_CAP_WORDS. private int mAutoCapsState = MockConstants.CAP_MODE_OFF; - private boolean mIsInDoubleTapTimeout; + private boolean mIsInDoubleTapShiftKeyTimeout; private int mLongPressTimeoutCode; private final KeyboardState mState = new KeyboardState(this); @@ -81,7 +81,7 @@ public class MockKeyboardSwitcher implements KeyboardState.SwitchActions { } public void expireDoubleTapTimeout() { - mIsInDoubleTapTimeout = false; + mIsInDoubleTapShiftKeyTimeout = false; } @Override @@ -125,41 +125,18 @@ public class MockKeyboardSwitcher implements KeyboardState.SwitchActions { } @Override - public void startDoubleTapTimer() { - mIsInDoubleTapTimeout = true; + public void startDoubleTapShiftKeyTimer() { + mIsInDoubleTapShiftKeyTimeout = true; } @Override - public void cancelDoubleTapTimer() { - mIsInDoubleTapTimeout = false; + public void cancelDoubleTapShiftKeyTimer() { + mIsInDoubleTapShiftKeyTimeout = false; } @Override - public boolean isInDoubleTapTimeout() { - return mIsInDoubleTapTimeout; - } - - @Override - public void startLongPressTimer(final int code) { - mLongPressTimeoutCode = code; - } - - @Override - public void cancelLongPressTimer() { - mLongPressTimeoutCode = 0; - } - - @Override - public void hapticAndAudioFeedback(final int code) { - // Nothing to do. - } - - public void onLongPressTimeout(final int code) { - // TODO: Handle simultaneous long presses. - if (mLongPressTimeoutCode == code) { - mLongPressTimeoutCode = 0; - mState.onLongPressTimeout(code); - } + public boolean isInDoubleTapShiftKeyTimeout() { + return mIsInDoubleTapShiftKeyTimeout; } public void updateShiftState() { diff --git a/tests/src/com/android/inputmethod/keyboard/internal/SmoothingUtilsTests.java b/tests/src/com/android/inputmethod/keyboard/internal/SmoothingUtilsTests.java new file mode 100644 index 000000000..293741af2 --- /dev/null +++ b/tests/src/com/android/inputmethod/keyboard/internal/SmoothingUtilsTests.java @@ -0,0 +1,45 @@ +/* + * 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.keyboard.internal; + +import com.android.inputmethod.keyboard.internal.MatrixUtils.MatrixOperationFailedException; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +@SmallTest +public class SmoothingUtilsTests extends AndroidTestCase { + // "run tests" -c com.android.inputmethod.keyboard.internal.SmoothingUtilsTests + private static final boolean DEBUG = false; + + public void testGet3DParamaters() { + final float[] xs = new float[] {0, 1, 2, 3, 4}; + final float[] ys = new float[] {1, 4, 15, 40, 85}; // y = x^3 + x^2 + x + 1 + final float[][] retval = new float[4][1]; + try { + SmoothingUtils.get3DParameters(xs, ys, retval); + if (DEBUG) { + MatrixUtils.dump("3d", retval); + } + for (int i = 0; i < 4; ++i) { + MatrixUtilsTests.assertEqualsFloat(retval[i][0], 1.0f, 0.001f); + } + } catch (MatrixOperationFailedException e) { + assertTrue(false); + } + } +} diff --git a/tests/src/com/android/inputmethod/latin/InputPointersTests.java b/tests/src/com/android/inputmethod/latin/InputPointersTests.java index e1149b3fd..f0b6acc75 100644 --- a/tests/src/com/android/inputmethod/latin/InputPointersTests.java +++ b/tests/src/com/android/inputmethod/latin/InputPointersTests.java @@ -19,6 +19,8 @@ package com.android.inputmethod.latin; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; +import com.android.inputmethod.latin.utils.ResizableIntArray; + import java.util.Arrays; @SmallTest @@ -108,13 +110,13 @@ public class InputPointersTests extends AndroidTestCase { assertNotSame("pointerIds after copy", dst.getPointerIds(), src.getPointerIds()); assertNotSame("times after copy", dst.getTimes(), src.getTimes()); final int size = dst.getPointerSize(); - assertArrayEquals("xCoordinates values after copy", + assertIntArrayEquals("xCoordinates values after copy", dst.getXCoordinates(), 0, src.getXCoordinates(), 0, size); - assertArrayEquals("yCoordinates values after copy", + assertIntArrayEquals("yCoordinates values after copy", dst.getYCoordinates(), 0, src.getYCoordinates(), 0, size); - assertArrayEquals("pointerIds values after copy", + assertIntArrayEquals("pointerIds values after copy", dst.getPointerIds(), 0, src.getPointerIds(), 0, size); - assertArrayEquals("times values after copy", + assertIntArrayEquals("times values after copy", dst.getTimes(), 0, src.getTimes(), 0, size); } @@ -135,34 +137,34 @@ public class InputPointersTests extends AndroidTestCase { dst.append(src, 0, 0); assertEquals("size after append zero", dstLen, dst.getPointerSize()); - assertArrayEquals("xCoordinates after append zero", + assertIntArrayEquals("xCoordinates after append zero", dstCopy.getXCoordinates(), 0, dst.getXCoordinates(), 0, dstLen); - assertArrayEquals("yCoordinates after append zero", + assertIntArrayEquals("yCoordinates after append zero", dstCopy.getYCoordinates(), 0, dst.getYCoordinates(), 0, dstLen); - assertArrayEquals("pointerIds after append zero", + assertIntArrayEquals("pointerIds after append zero", dstCopy.getPointerIds(), 0, dst.getPointerIds(), 0, dstLen); - assertArrayEquals("times after append zero", + assertIntArrayEquals("times after append zero", dstCopy.getTimes(), 0, dst.getTimes(), 0, dstLen); dst.append(src, 0, srcLen); assertEquals("size after append", dstLen + srcLen, dst.getPointerSize()); assertTrue("primitive length after append", dst.getPointerIds().length >= dstLen + srcLen); - assertArrayEquals("original xCoordinates values after append", + assertIntArrayEquals("original xCoordinates values after append", dstCopy.getXCoordinates(), 0, dst.getXCoordinates(), 0, dstLen); - assertArrayEquals("original yCoordinates values after append", + assertIntArrayEquals("original yCoordinates values after append", dstCopy.getYCoordinates(), 0, dst.getYCoordinates(), 0, dstLen); - assertArrayEquals("original pointerIds values after append", + assertIntArrayEquals("original pointerIds values after append", dstCopy.getPointerIds(), 0, dst.getPointerIds(), 0, dstLen); - assertArrayEquals("original times values after append", + assertIntArrayEquals("original times values after append", dstCopy.getTimes(), 0, dst.getTimes(), 0, dstLen); - assertArrayEquals("appended xCoordinates values after append", + assertIntArrayEquals("appended xCoordinates values after append", src.getXCoordinates(), 0, dst.getXCoordinates(), dstLen, srcLen); - assertArrayEquals("appended yCoordinates values after append", + assertIntArrayEquals("appended yCoordinates values after append", src.getYCoordinates(), 0, dst.getYCoordinates(), dstLen, srcLen); - assertArrayEquals("appended pointerIds values after append", + assertIntArrayEquals("appended pointerIds values after append", src.getPointerIds(), 0, dst.getPointerIds(), dstLen, srcLen); - assertArrayEquals("appended times values after append", + assertIntArrayEquals("appended times values after append", src.getTimes(), 0, dst.getTimes(), dstLen, srcLen); } @@ -190,47 +192,55 @@ public class InputPointersTests extends AndroidTestCase { dst.append(srcPointerId, srcTimes, srcXCoords, srcYCoords, 0, 0); assertEquals("size after append zero", dstLen, dst.getPointerSize()); - assertArrayEquals("xCoordinates after append zero", + assertIntArrayEquals("xCoordinates after append zero", dstCopy.getXCoordinates(), 0, dst.getXCoordinates(), 0, dstLen); - assertArrayEquals("yCoordinates after append zero", + assertIntArrayEquals("yCoordinates after append zero", dstCopy.getYCoordinates(), 0, dst.getYCoordinates(), 0, dstLen); - assertArrayEquals("pointerIds after append zero", + assertIntArrayEquals("pointerIds after append zero", dstCopy.getPointerIds(), 0, dst.getPointerIds(), 0, dstLen); - assertArrayEquals("times after append zero", + assertIntArrayEquals("times after append zero", dstCopy.getTimes(), 0, dst.getTimes(), 0, dstLen); dst.append(srcPointerId, srcTimes, srcXCoords, srcYCoords, 0, srcLen); assertEquals("size after append", dstLen + srcLen, dst.getPointerSize()); assertTrue("primitive length after append", dst.getPointerIds().length >= dstLen + srcLen); - assertArrayEquals("original xCoordinates values after append", + assertIntArrayEquals("original xCoordinates values after append", dstCopy.getXCoordinates(), 0, dst.getXCoordinates(), 0, dstLen); - assertArrayEquals("original yCoordinates values after append", + assertIntArrayEquals("original yCoordinates values after append", dstCopy.getYCoordinates(), 0, dst.getYCoordinates(), 0, dstLen); - assertArrayEquals("original pointerIds values after append", + assertIntArrayEquals("original pointerIds values after append", dstCopy.getPointerIds(), 0, dst.getPointerIds(), 0, dstLen); - assertArrayEquals("original times values after append", + assertIntArrayEquals("original times values after append", dstCopy.getTimes(), 0, dst.getTimes(), 0, dstLen); - assertArrayEquals("appended xCoordinates values after append", + assertIntArrayEquals("appended xCoordinates values after append", srcXCoords.getPrimitiveArray(), 0, dst.getXCoordinates(), dstLen, srcLen); - assertArrayEquals("appended yCoordinates values after append", + assertIntArrayEquals("appended yCoordinates values after append", srcYCoords.getPrimitiveArray(), 0, dst.getYCoordinates(), dstLen, srcLen); - assertArrayEquals("appended pointerIds values after append", + assertIntArrayEquals("appended pointerIds values after append", srcPointerIds, 0, dst.getPointerIds(), dstLen, srcLen); - assertArrayEquals("appended times values after append", + assertIntArrayEquals("appended times values after append", srcTimes.getPrimitiveArray(), 0, dst.getTimes(), dstLen, srcLen); } - private static void assertArrayEquals(String message, int[] expecteds, int expectedPos, - int[] actuals, int actualPos, int length) { - if (expecteds == null && actuals == null) { + // TODO: Consolidate this method with + // {@link ResizableIntArrayTests#assertIntArrayEquals(String,int[],int,int[],int,int)}. + 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) { - fail(message + ": expecteds=" + expecteds + " actuals=" + actuals); + 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 + ": element at " + i, + assertEquals(message + " [" + i + "]", expecteds[i + expectedPos], actuals[i + actualPos]); } } diff --git a/tests/src/com/android/inputmethod/latin/InputTestsBase.java b/tests/src/com/android/inputmethod/latin/InputTestsBase.java index aec4aaca1..eb4f706cc 100644 --- a/tests/src/com/android/inputmethod/latin/InputTestsBase.java +++ b/tests/src/com/android/inputmethod/latin/InputTestsBase.java @@ -36,6 +36,7 @@ import android.widget.FrameLayout; import com.android.inputmethod.keyboard.Key; import com.android.inputmethod.keyboard.Keyboard; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; +import com.android.inputmethod.latin.utils.LocaleUtils; import java.util.Locale; @@ -224,7 +225,7 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> { protected void waitForDictionaryToBeLoaded() { int remainingAttempts = 300; - while (remainingAttempts > 0 && mLatinIME.mSuggest.isCurrentlyWaitingForMainDictionary()) { + while (remainingAttempts > 0 && mLatinIME.isCurrentlyWaitingForMainDictionary()) { try { Thread.sleep(200); } catch (InterruptedException e) { @@ -233,7 +234,7 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> { --remainingAttempts; } } - if (!mLatinIME.mSuggest.hasMainDictionary()) { + if (!mLatinIME.hasMainDictionary()) { throw new RuntimeException("Can't initialize the main dictionary"); } } @@ -242,6 +243,7 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> { mEditText.mCurrentLocale = LocaleUtils.constructLocaleFromString(locale); SubtypeSwitcher.getInstance().forceLocale(mEditText.mCurrentLocale); mLatinIME.loadKeyboard(); + runMessages(); mKeyboard = mLatinIME.mKeyboardSwitcher.getKeyboard(); waitForDictionaryToBeLoaded(); } diff --git a/tests/src/com/android/inputmethod/latin/RichInputConnectionTests.java b/tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java index aacd60f4d..c0dd9933c 100644 --- a/tests/src/com/android/inputmethod/latin/RichInputConnectionTests.java +++ b/tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java @@ -16,19 +16,26 @@ package com.android.inputmethod.latin; +import com.android.inputmethod.latin.utils.TextRange; + import android.inputmethodservice.InputMethodService; +import android.os.Parcel; import android.test.AndroidTestCase; +import android.test.MoreAsserts; import android.test.suitebuilder.annotation.SmallTest; +import android.text.SpannableString; +import android.text.Spanned; import android.text.TextUtils; +import android.text.style.SuggestionSpan; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputConnectionWrapper; -import com.android.inputmethod.latin.RichInputConnection.Range; +import java.util.Locale; @SmallTest -public class RichInputConnectionTests extends AndroidTestCase { +public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { // The following is meant to be a reasonable default for // the "word_separators" resource. @@ -40,10 +47,30 @@ public class RichInputConnectionTests extends AndroidTestCase { } private class MockConnection extends InputConnectionWrapper { - final String mTextBefore; - final String mTextAfter; + final CharSequence mTextBefore; + final CharSequence mTextAfter; final ExtractedText mExtractedText; + public MockConnection(final CharSequence text, final int cursorPosition) { + super(null, false); + // Interaction of spans with Parcels is completely non-trivial, but in the actual case + // the CharSequences do go through Parcels because they go through IPC. There + // are some significant differences between the behavior of Spanned objects that + // have and that have not gone through parceling, so it's much easier to simulate + // the environment with Parcels than try to emulate things by hand. + final Parcel p = Parcel.obtain(); + TextUtils.writeToParcel(text.subSequence(0, cursorPosition), p, 0 /* flags */); + TextUtils.writeToParcel(text.subSequence(cursorPosition, text.length()), p, + 0 /* flags */); + final byte[] marshalled = p.marshall(); + p.unmarshall(marshalled, 0, marshalled.length); + p.setDataPosition(0); + mTextBefore = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p); + mTextAfter = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p); + mExtractedText = null; + p.recycle(); + } + public MockConnection(String textBefore, String textAfter, ExtractedText extractedText) { super(null, false); mTextBefore = textBefore; @@ -142,7 +169,7 @@ public class RichInputConnectionTests extends AndroidTestCase { mockInputMethodService.setInputConnection(new MockConnection("word wo", "rd", et)); et.startOffset = 0; et.selectionStart = 7; - Range r; + TextRange r; ic.beginBatchEdit(); // basic case @@ -191,4 +218,95 @@ public class RichInputConnectionTests extends AndroidTestCase { ic.endBatchEdit(); assertTrue(TextUtils.equals("word", r.mWord)); } + + /** + * Test logic in getting the word range at the cursor. + */ + public void testGetSuggestionSpansAtWord() { + helpTestGetSuggestionSpansAtWord(10); + helpTestGetSuggestionSpansAtWord(12); + helpTestGetSuggestionSpansAtWord(15); + helpTestGetSuggestionSpansAtWord(16); + } + + private void helpTestGetSuggestionSpansAtWord(final int cursorPos) { + final MockInputMethodService mockInputMethodService = new MockInputMethodService(); + final RichInputConnection ic = new RichInputConnection(mockInputMethodService); + + final String[] SUGGESTIONS1 = { "swing", "strong" }; + final String[] SUGGESTIONS2 = { "storing", "strung" }; + + // Test the usual case. + SpannableString text = new SpannableString("This is a string for test"); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0 /* flags */), + 10 /* start */, 16 /* end */, 0 /* flags */); + mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos)); + TextRange r; + SuggestionSpan[] suggestions; + + r = ic.getWordRangeAtCursor(" ", 0); + suggestions = r.getSuggestionSpansAtWord(); + assertEquals(suggestions.length, 1); + MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); + + // Test the case with 2 suggestion spans in the same place. + text = new SpannableString("This is a string for test"); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0 /* flags */), + 10 /* start */, 16 /* end */, 0 /* flags */); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS2, 0 /* flags */), + 10 /* start */, 16 /* end */, 0 /* flags */); + mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos)); + r = ic.getWordRangeAtCursor(" ", 0); + suggestions = r.getSuggestionSpansAtWord(); + assertEquals(suggestions.length, 2); + MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); + MoreAsserts.assertEquals(suggestions[1].getSuggestions(), SUGGESTIONS2); + + // Test a case with overlapping spans, 2nd extending past the start of the word + text = new SpannableString("This is a string for test"); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0 /* flags */), + 10 /* start */, 16 /* end */, 0 /* flags */); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS2, 0 /* flags */), + 5 /* start */, 16 /* end */, 0 /* flags */); + mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos)); + r = ic.getWordRangeAtCursor(" ", 0); + suggestions = r.getSuggestionSpansAtWord(); + assertEquals(suggestions.length, 1); + MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); + + // Test a case with overlapping spans, 2nd extending past the end of the word + text = new SpannableString("This is a string for test"); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0 /* flags */), + 10 /* start */, 16 /* end */, 0 /* flags */); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS2, 0 /* flags */), + 10 /* start */, 20 /* end */, 0 /* flags */); + mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos)); + r = ic.getWordRangeAtCursor(" ", 0); + suggestions = r.getSuggestionSpansAtWord(); + assertEquals(suggestions.length, 1); + MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); + + // Test a case with overlapping spans, 2nd extending past both ends of the word + text = new SpannableString("This is a string for test"); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0 /* flags */), + 10 /* start */, 16 /* end */, 0 /* flags */); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS2, 0 /* flags */), + 5 /* start */, 20 /* end */, 0 /* flags */); + mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos)); + r = ic.getWordRangeAtCursor(" ", 0); + suggestions = r.getSuggestionSpansAtWord(); + assertEquals(suggestions.length, 1); + MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); + + // Test a case with overlapping spans, none right on the word + text = new SpannableString("This is a string for test"); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS1, 0 /* flags */), + 5 /* start */, 16 /* end */, 0 /* flags */); + text.setSpan(new SuggestionSpan(Locale.ENGLISH, SUGGESTIONS2, 0 /* flags */), + 5 /* start */, 20 /* end */, 0 /* flags */); + mockInputMethodService.setInputConnection(new MockConnection(text, cursorPos)); + r = ic.getWordRangeAtCursor(" ", 0); + suggestions = r.getSuggestionSpansAtWord(); + assertEquals(suggestions.length, 0); + } } diff --git a/tests/src/com/android/inputmethod/latin/SubtypeLocaleTests.java b/tests/src/com/android/inputmethod/latin/SubtypeLocaleTests.java deleted file mode 100644 index abfaf3062..000000000 --- a/tests/src/com/android/inputmethod/latin/SubtypeLocaleTests.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * 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; - -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.LocaleUtils.RunInLocale; - -import java.util.ArrayList; -import java.util.Locale; - -@SmallTest -public class SubtypeLocaleTests 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_PC; - - @Override - protected void setUp() throws Exception { - super.setUp(); - final Context context = getContext(); - RichInputMethodManager.init(context); - mRichImm = RichInputMethodManager.getInstance(); - mRes = context.getResources(); - SubtypeLocale.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( - SubtypeLocale.NO_LANGUAGE, "qwerty"); - DE_QWERTY = AdditionalSubtype.createAdditionalSubtype( - Locale.GERMAN.toString(), "qwerty", null); - FR_QWERTZ = AdditionalSubtype.createAdditionalSubtype( - Locale.FRENCH.toString(), "qwertz", null); - EN_US_AZERTY = AdditionalSubtype.createAdditionalSubtype( - Locale.US.toString(), "azerty", null); - EN_UK_DVORAK = AdditionalSubtype.createAdditionalSubtype( - Locale.UK.toString(), "dvorak", null); - ES_US_COLEMAK = AdditionalSubtype.createAdditionalSubtype( - "es_US", "colemak", null); - ZZ_PC = AdditionalSubtype.createAdditionalSubtype( - SubtypeLocale.NO_LANGUAGE, "pcqwerty", null); - - } - - public void testAllFullDisplayName() { - for (final InputMethodSubtype subtype : mSubtypesList) { - final String subtypeName = SubtypeLocale.getSubtypeDisplayName(subtype); - if (SubtypeLocale.isNoLanguage(subtype)) { - final String noLanguage = mRes.getString(R.string.subtype_no_language); - assertTrue(subtypeName, subtypeName.contains(noLanguage)); - } else { - final String languageName = - SubtypeLocale.getSubtypeLocaleDisplayName(subtype.getLocale()); - assertTrue(subtypeName, subtypeName.contains(languageName)); - } - } - } - - // InputMethodSubtype's display name in its locale. - // 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 Español (EE.UU.) exception - // fr azerty F Français - // fr_CA qwerty F Français (Canada) - // de qwertz F Deutsch - // zz qwerty F No language (QWERTY) in system locale - // fr qwertz T Français (QWERTZ) - // de qwerty T Deutsch (QWERTY) - // en_US azerty T English (US) (AZERTY) exception - // en_UK dvorak T English (UK) (Dvorak) exception - // es_US colemak T Español (EE.UU.) (Colemak) exception - // zz pc T No language (PC) in system locale - - public void testPredefinedSubtypesInEnglish() { - assertEquals("en_US", "qwerty", SubtypeLocale.getKeyboardLayoutSetName(EN_US)); - assertEquals("en_GB", "qwerty", SubtypeLocale.getKeyboardLayoutSetName(EN_GB)); - assertEquals("es_US", "spanish", SubtypeLocale.getKeyboardLayoutSetName(ES_US)); - assertEquals("fr ", "azerty", SubtypeLocale.getKeyboardLayoutSetName(FR)); - assertEquals("fr_CA", "qwerty", SubtypeLocale.getKeyboardLayoutSetName(FR_CA)); - assertEquals("de ", "qwertz", SubtypeLocale.getKeyboardLayoutSetName(DE)); - assertEquals("zz ", "qwerty", SubtypeLocale.getKeyboardLayoutSetName(ZZ)); - - final RunInLocale<Void> tests = new RunInLocale<Void>() { - @Override - protected Void job(Resources res) { - assertEquals("en_US", "English (US)", - SubtypeLocale.getSubtypeDisplayName(EN_US)); - assertEquals("en_GB", "English (UK)", - SubtypeLocale.getSubtypeDisplayName(EN_GB)); - assertEquals("es_US", "Español (EE.UU.)", - SubtypeLocale.getSubtypeDisplayName(ES_US)); - assertEquals("fr ", "Français", - SubtypeLocale.getSubtypeDisplayName(FR)); - assertEquals("fr_CA", "Français (Canada)", - SubtypeLocale.getSubtypeDisplayName(FR_CA)); - assertEquals("de ", "Deutsch", - SubtypeLocale.getSubtypeDisplayName(DE)); - assertEquals("zz ", "No language (QWERTY)", - SubtypeLocale.getSubtypeDisplayName(ZZ)); - return null; - } - }; - tests.runInLocale(mRes, Locale.ENGLISH); - } - - public void testAdditionalSubtypesInEnglish() { - final RunInLocale<Void> tests = new RunInLocale<Void>() { - @Override - protected Void job(Resources res) { - assertEquals("fr qwertz", "Français (QWERTZ)", - SubtypeLocale.getSubtypeDisplayName(FR_QWERTZ)); - assertEquals("de qwerty", "Deutsch (QWERTY)", - SubtypeLocale.getSubtypeDisplayName(DE_QWERTY)); - assertEquals("en_US azerty", "English (US) (AZERTY)", - SubtypeLocale.getSubtypeDisplayName(EN_US_AZERTY)); - assertEquals("en_UK dvorak", "English (UK) (Dvorak)", - SubtypeLocale.getSubtypeDisplayName(EN_UK_DVORAK)); - assertEquals("es_US colemak","Español (EE.UU.) (Colemak)", - SubtypeLocale.getSubtypeDisplayName(ES_US_COLEMAK)); - assertEquals("zz pc", "No language (PC)", - SubtypeLocale.getSubtypeDisplayName(ZZ_PC)); - return null; - } - }; - tests.runInLocale(mRes, Locale.ENGLISH); - } - - public void testPredefinedSubtypesInFrench() { - final RunInLocale<Void> tests = new RunInLocale<Void>() { - @Override - protected Void job(Resources res) { - assertEquals("en_US", "English (US)", - SubtypeLocale.getSubtypeDisplayName(EN_US)); - assertEquals("en_GB", "English (UK)", - SubtypeLocale.getSubtypeDisplayName(EN_GB)); - assertEquals("es_US", "Español (EE.UU.)", - SubtypeLocale.getSubtypeDisplayName(ES_US)); - assertEquals("fr ", "Français", - SubtypeLocale.getSubtypeDisplayName(FR)); - assertEquals("fr_CA", "Français (Canada)", - SubtypeLocale.getSubtypeDisplayName(FR_CA)); - assertEquals("de ", "Deutsch", - SubtypeLocale.getSubtypeDisplayName(DE)); - assertEquals("zz ", "Aucune langue (QWERTY)", - SubtypeLocale.getSubtypeDisplayName(ZZ)); - return null; - } - }; - tests.runInLocale(mRes, Locale.FRENCH); - } - - public void testAdditionalSubtypesInFrench() { - final RunInLocale<Void> tests = new RunInLocale<Void>() { - @Override - protected Void job(Resources res) { - assertEquals("fr qwertz", "Français (QWERTZ)", - SubtypeLocale.getSubtypeDisplayName(FR_QWERTZ)); - assertEquals("de qwerty", "Deutsch (QWERTY)", - SubtypeLocale.getSubtypeDisplayName(DE_QWERTY)); - assertEquals("en_US azerty", "English (US) (AZERTY)", - SubtypeLocale.getSubtypeDisplayName(EN_US_AZERTY)); - assertEquals("en_UK dvorak", "English (UK) (Dvorak)", - SubtypeLocale.getSubtypeDisplayName(EN_UK_DVORAK)); - assertEquals("es_US colemak","Español (EE.UU.) (Colemak)", - SubtypeLocale.getSubtypeDisplayName(ES_US_COLEMAK)); - assertEquals("zz azerty", "Aucune langue (PC)", - SubtypeLocale.getSubtypeDisplayName(ZZ_PC)); - return null; - } - }; - tests.runInLocale(mRes, Locale.FRENCH); - } - - // 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 No language (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 No language (PC) - - public void testPredefinedSubtypesInEnglishSystemLocale() { - assertEquals("en_US", "qwerty", SubtypeLocale.getKeyboardLayoutSetName(EN_US)); - assertEquals("en_GB", "qwerty", SubtypeLocale.getKeyboardLayoutSetName(EN_GB)); - assertEquals("es_US", "spanish", SubtypeLocale.getKeyboardLayoutSetName(ES_US)); - assertEquals("fr ", "azerty", SubtypeLocale.getKeyboardLayoutSetName(FR)); - assertEquals("fr_CA", "qwerty", SubtypeLocale.getKeyboardLayoutSetName(FR_CA)); - assertEquals("de ", "qwertz", SubtypeLocale.getKeyboardLayoutSetName(DE)); - assertEquals("zz ", "qwerty", SubtypeLocale.getKeyboardLayoutSetName(ZZ)); - - final RunInLocale<Void> tests = new RunInLocale<Void>() { - @Override - protected Void job(Resources res) { - assertEquals("en_US", "English (US)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(EN_US)); - assertEquals("en_GB", "English (UK)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(EN_GB)); - assertEquals("es_US", "Spanish (US)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(ES_US)); - assertEquals("fr ", "French", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(FR)); - assertEquals("fr_CA", "French (Canada)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(FR_CA)); - assertEquals("de ", "German", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(DE)); - assertEquals("zz ", "No language (QWERTY)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(ZZ)); - return null; - } - }; - tests.runInLocale(mRes, Locale.ENGLISH); - } - - public void testAdditionalSubtypesInEnglishSystemLocale() { - final RunInLocale<Void> tests = new RunInLocale<Void>() { - @Override - protected Void job(Resources res) { - assertEquals("fr qwertz", "French (QWERTZ)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(FR_QWERTZ)); - assertEquals("de qwerty", "German (QWERTY)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(DE_QWERTY)); - assertEquals("en_US azerty", "English (US) (AZERTY)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(EN_US_AZERTY)); - assertEquals("en_UK dvorak", "English (UK) (Dvorak)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(EN_UK_DVORAK)); - assertEquals("es_US colemak","Spanish (US) (Colemak)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(ES_US_COLEMAK)); - assertEquals("zz azerty", "No language (PC)", - SubtypeLocale.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 Aucune langue (PC) - - public void testPredefinedSubtypesInFrenchSystemLocale() { - final RunInLocale<Void> tests = new RunInLocale<Void>() { - @Override - protected Void job(Resources res) { - assertEquals("en_US", "Anglais (États-Unis)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(EN_US)); - assertEquals("en_GB", "Anglais (Royaume-Uni)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(EN_GB)); - assertEquals("es_US", "Espagnol (États-Unis)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(ES_US)); - assertEquals("fr ", "Français", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(FR)); - assertEquals("fr_CA", "Français (Canada)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(FR_CA)); - assertEquals("de ", "Allemand", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(DE)); - assertEquals("zz ", "Aucune langue (QWERTY)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(ZZ)); - return null; - } - }; - tests.runInLocale(mRes, Locale.FRENCH); - } - - public void testAdditionalSubtypesInFrenchSystemLocale() { - final RunInLocale<Void> tests = new RunInLocale<Void>() { - @Override - protected Void job(Resources res) { - assertEquals("fr qwertz", "Français (QWERTZ)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(FR_QWERTZ)); - assertEquals("de qwerty", "Allemand (QWERTY)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(DE_QWERTY)); - assertEquals("en_US azerty", "Anglais (États-Unis) (AZERTY)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(EN_US_AZERTY)); - assertEquals("en_UK dvorak", "Anglais (Royaume-Uni) (Dvorak)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(EN_UK_DVORAK)); - assertEquals("es_US colemak","Espagnol (États-Unis) (Colemak)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(ES_US_COLEMAK)); - assertEquals("zz azerty", "Aucune langue (PC)", - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(ZZ_PC)); - return null; - } - }; - tests.runInLocale(mRes, Locale.FRENCH); - } -} diff --git a/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java b/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java index 916252292..8d0fe014c 100644 --- a/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java +++ b/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java @@ -21,6 +21,8 @@ import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; +import com.android.inputmethod.latin.utils.CollectionUtils; + import java.util.ArrayList; import java.util.Locale; diff --git a/tests/src/com/android/inputmethod/latin/WordComposerTests.java b/tests/src/com/android/inputmethod/latin/WordComposerTests.java new file mode 100644 index 000000000..1434c6b63 --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/WordComposerTests.java @@ -0,0 +1,93 @@ +/* + * 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; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +/** + * Unit tests for WordComposer. + */ +@SmallTest +public class WordComposerTests extends AndroidTestCase { + public void testMoveCursor() { + final WordComposer wc = new WordComposer(); + final String STR_WITHIN_BMP = "abcdef"; + wc.setComposingWord(STR_WITHIN_BMP, null); + assertEquals(wc.size(), + STR_WITHIN_BMP.codePointCount(0, STR_WITHIN_BMP.length())); + assertFalse(wc.isCursorFrontOrMiddleOfComposingWord()); + wc.setCursorPositionWithinWord(2); + assertTrue(wc.isCursorFrontOrMiddleOfComposingWord()); + // Move the cursor to after the 'd' + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(2)); + assertTrue(wc.isCursorFrontOrMiddleOfComposingWord()); + // Move the cursor to after the 'e' + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(1)); + assertTrue(wc.isCursorFrontOrMiddleOfComposingWord()); + assertEquals(wc.size(), 6); + // Move the cursor to after the 'f' + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(1)); + assertFalse(wc.isCursorFrontOrMiddleOfComposingWord()); + // Move the cursor past the end of the word + assertFalse(wc.moveCursorByAndReturnIfInsideComposingWord(1)); + assertFalse(wc.moveCursorByAndReturnIfInsideComposingWord(15)); + + // \uD861\uDED7 is 𨛗, a character outside the BMP + final String STR_WITH_SUPPLEMENTARY_CHAR = "abcde\uD861\uDED7fgh"; + wc.setComposingWord(STR_WITH_SUPPLEMENTARY_CHAR, null); + assertEquals(wc.size(), STR_WITH_SUPPLEMENTARY_CHAR.codePointCount(0, + STR_WITH_SUPPLEMENTARY_CHAR.length())); + assertFalse(wc.isCursorFrontOrMiddleOfComposingWord()); + wc.setCursorPositionWithinWord(3); + assertTrue(wc.isCursorFrontOrMiddleOfComposingWord()); + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(6)); + assertTrue(wc.isCursorFrontOrMiddleOfComposingWord()); + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(1)); + assertFalse(wc.isCursorFrontOrMiddleOfComposingWord()); + + wc.setComposingWord(STR_WITH_SUPPLEMENTARY_CHAR, null); + wc.setCursorPositionWithinWord(3); + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(7)); + + wc.setComposingWord(STR_WITH_SUPPLEMENTARY_CHAR, null); + wc.setCursorPositionWithinWord(3); + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(7)); + + wc.setComposingWord(STR_WITH_SUPPLEMENTARY_CHAR, null); + wc.setCursorPositionWithinWord(3); + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(-3)); + assertFalse(wc.moveCursorByAndReturnIfInsideComposingWord(-1)); + + wc.setComposingWord(STR_WITH_SUPPLEMENTARY_CHAR, null); + wc.setCursorPositionWithinWord(3); + assertFalse(wc.moveCursorByAndReturnIfInsideComposingWord(-9)); + + wc.setComposingWord(STR_WITH_SUPPLEMENTARY_CHAR, null); + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(-10)); + + wc.setComposingWord(STR_WITH_SUPPLEMENTARY_CHAR, null); + assertFalse(wc.moveCursorByAndReturnIfInsideComposingWord(-11)); + + wc.setComposingWord(STR_WITH_SUPPLEMENTARY_CHAR, null); + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(0)); + + wc.setComposingWord(STR_WITH_SUPPLEMENTARY_CHAR, null); + wc.setCursorPositionWithinWord(2); + assertTrue(wc.moveCursorByAndReturnIfInsideComposingWord(0)); + } +} diff --git a/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOTests.java b/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOTests.java index b704d08b3..ef4ed3396 100644 --- a/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOTests.java +++ b/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOTests.java @@ -22,13 +22,13 @@ import android.test.suitebuilder.annotation.LargeTest; import android.util.Log; import android.util.SparseArray; -import com.android.inputmethod.latin.CollectionUtils; -import com.android.inputmethod.latin.UserHistoryDictIOUtils; import com.android.inputmethod.latin.makedict.BinaryDictInputOutput.FusionDictionaryBufferInterface; import com.android.inputmethod.latin.makedict.FormatSpec.FileHeader; import com.android.inputmethod.latin.makedict.FusionDictionary.CharGroup; import com.android.inputmethod.latin.makedict.FusionDictionary.Node; import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString; +import com.android.inputmethod.latin.utils.ByteArrayWrapper; +import com.android.inputmethod.latin.utils.CollectionUtils; import java.io.File; import java.io.FileInputStream; @@ -51,7 +51,8 @@ import java.util.Set; @LargeTest public class BinaryDictIOTests extends AndroidTestCase { private static final String TAG = BinaryDictIOTests.class.getSimpleName(); - private static final int MAX_UNIGRAMS = 100; + private static final int DEFAULT_MAX_UNIGRAMS = 100; + private static final int DEFAULT_CODE_POINT_SET_SIZE = 50; private static final int UNIGRAM_FREQ = 10; private static final int BIGRAM_FREQ = 50; private static final int TOLERANCE_OF_BIGRAM_FREQ = 5; @@ -73,13 +74,16 @@ public class BinaryDictIOTests extends AndroidTestCase { new FormatSpec.FormatOptions(3, true /* supportsDynamicUpdate */); public BinaryDictIOTests() { - super(); + this(System.currentTimeMillis(), DEFAULT_MAX_UNIGRAMS); + } - final long time = System.currentTimeMillis(); - Log.e(TAG, "Testing dictionary: seed is " + time); - final Random random = new Random(time); + public BinaryDictIOTests(final long seed, final int maxUnigrams) { + super(); + Log.e(TAG, "Testing dictionary: seed is " + seed); + final Random random = new Random(seed); sWords.clear(); - generateWords(MAX_UNIGRAMS, random); + final int[] codePointSet = generateCodePointSet(DEFAULT_CODE_POINT_SET_SIZE, random); + generateWords(maxUnigrams, random, codePointSet); for (int i = 0; i < sWords.size(); ++i) { sChainBigrams.put(i, new ArrayList<Integer>()); @@ -94,6 +98,23 @@ public class BinaryDictIOTests extends AndroidTestCase { } } + private int[] generateCodePointSet(final int codePointSetSize, final Random random) { + final int[] codePointSet = new int[codePointSetSize]; + for (int i = codePointSet.length - 1; i >= 0; ) { + final int r = Math.abs(random.nextInt()); + if (r < 0) continue; + // Don't insert 0~0x20, but insert any other code point. + // Code points are in the range 0~0x10FFFF. + final int candidateCodePoint = (int)(0x20 + r % (Character.MAX_CODE_POINT - 0x20)); + // Code points between MIN_ and MAX_SURROGATE are not valid on their own. + if (candidateCodePoint >= Character.MIN_SURROGATE + && candidateCodePoint <= Character.MAX_SURROGATE) continue; + codePointSet[i] = candidateCodePoint; + --i; + } + return codePointSet; + } + // Utilities for test /** @@ -106,7 +127,7 @@ public class BinaryDictIOTests extends AndroidTestCase { if (bufferType == USE_BYTE_ARRAY) { final byte[] array = new byte[(int)file.length()]; inStream.read(array); - return new UserHistoryDictIOUtils.ByteArrayWrapper(array); + return new ByteArrayWrapper(array); } else if (bufferType == USE_BYTE_BUFFER){ final ByteBuffer buffer = inStream.getChannel().map( FileChannel.MapMode.READ_ONLY, 0, file.length()); @@ -129,28 +150,29 @@ public class BinaryDictIOTests extends AndroidTestCase { /** * Generates a random word. */ - private String generateWord(final Random random) { - StringBuilder builder = new StringBuilder("a"); - int count = random.nextInt() % 30; // Arbitrarily 30 chars max - while (count > 0) { - final long r = Math.abs(random.nextInt()); - if (r < 0) continue; - // Don't insert 0~0x20, but insert any other code point. - // Code points are in the range 0~0x10FFFF. - final int candidateCodePoint = (int)(0x20 + r % (Character.MAX_CODE_POINT - 0x20)); - // Code points between MIN_ and MAX_SURROGATE are not valid on their own. - if (candidateCodePoint >= Character.MIN_SURROGATE - && candidateCodePoint <= Character.MAX_SURROGATE) continue; - builder.appendCodePoint(candidateCodePoint); - --count; + private String generateWord(final Random random, final int[] codePointSet) { + StringBuilder builder = new StringBuilder(); + // 8 * 4 = 32 chars max, but we do it the following way so as to bias the random toward + // longer words. This should be closer to natural language, and more importantly, it will + // exercise the algorithms in dicttool much more. + final int count = 1 + (Math.abs(random.nextInt()) % 5) + + (Math.abs(random.nextInt()) % 5) + + (Math.abs(random.nextInt()) % 5) + + (Math.abs(random.nextInt()) % 5) + + (Math.abs(random.nextInt()) % 5) + + (Math.abs(random.nextInt()) % 5) + + (Math.abs(random.nextInt()) % 5) + + (Math.abs(random.nextInt()) % 5); + while (builder.length() < count) { + builder.appendCodePoint(codePointSet[Math.abs(random.nextInt()) % codePointSet.length]); } return builder.toString(); } - private void generateWords(final int number, final Random random) { + private void generateWords(final int number, final Random random, final int[] codePointSet) { final Set<String> wordSet = CollectionUtils.newHashSet(); while (wordSet.size() < number) { - wordSet.add(generateWord(random)); + wordSet.add(generateWord(random, codePointSet)); } sWords.addAll(wordSet); } @@ -184,6 +206,14 @@ public class BinaryDictIOTests extends AndroidTestCase { } } +// The following is useful to dump the dictionary into a textual file, but it can't compile +// on-device, so it's commented out. +// private void dumpToCombinedFileForDebug(final FusionDictionary dict, final String filename) +// throws IOException { +// com.android.inputmethod.latin.dicttool.CombinedInputOutput.writeDictionaryCombined( +// new java.io.FileWriter(new File(filename)), dict); +// } + private long timeWritingDictToFile(final File file, final FusionDictionary dict, final FormatSpec.FormatOptions formatOptions) { @@ -193,6 +223,9 @@ public class BinaryDictIOTests extends AndroidTestCase { final FileOutputStream out = new FileOutputStream(file); now = System.currentTimeMillis(); + // If you need to dump the dict to a textual file, uncomment the line below and the + // function above + // dumpToCombinedFileForDebug(file, "/tmp/foo"); BinaryDictInputOutput.writeDictionaryBinary(out, dict, formatOptions); diff = System.currentTimeMillis() - now; @@ -558,8 +591,9 @@ public class BinaryDictIOTests extends AndroidTestCase { // Test a word that isn't contained within the dictionary. final Random random = new Random((int)System.currentTimeMillis()); + final int[] codePointSet = generateCodePointSet(DEFAULT_CODE_POINT_SET_SIZE, random); for (int i = 0; i < 1000; ++i) { - final String word = generateWord(random); + final String word = generateWord(random, codePointSet); if (sWords.indexOf(word) != -1) continue; runGetTerminalPosition(buffer, word, i, false); } diff --git a/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtilsTests.java b/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtilsTests.java index 47885f023..9331da44b 100644 --- a/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtilsTests.java @@ -21,12 +21,12 @@ import android.test.MoreAsserts; import android.test.suitebuilder.annotation.LargeTest; import android.util.Log; -import com.android.inputmethod.latin.CollectionUtils; import com.android.inputmethod.latin.makedict.BinaryDictInputOutput.ByteBufferWrapper; import com.android.inputmethod.latin.makedict.BinaryDictInputOutput.FusionDictionaryBufferInterface; import com.android.inputmethod.latin.makedict.FormatSpec.FileHeader; import com.android.inputmethod.latin.makedict.FusionDictionary.Node; import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString; +import com.android.inputmethod.latin.utils.CollectionUtils; import java.io.BufferedOutputStream; import java.io.File; @@ -40,27 +40,35 @@ import java.util.HashMap; import java.util.Random; @LargeTest -public class BinaryDictIOUtilsTests extends AndroidTestCase { +public class BinaryDictIOUtilsTests extends AndroidTestCase { private static final String TAG = BinaryDictIOUtilsTests.class.getSimpleName(); private static final FormatSpec.FormatOptions FORMAT_OPTIONS = new FormatSpec.FormatOptions(3, true); - private static final int MAX_UNIGRAMS = 1500; private static final ArrayList<String> sWords = CollectionUtils.newArrayList(); + public static final int DEFAULT_MAX_UNIGRAMS = 1500; + private final int mMaxUnigrams; private static final String[] CHARACTERS = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "\u00FC" /* ü */, "\u00E2" /* â */, "\u00F1" /* ñ */, // accented characters "\u4E9C" /* 亜 */, "\u4F0A" /* 伊 */, "\u5B87" /* 宇 */, // kanji - "\uD841\uDE28" /* 𠘨 */, "\uD840\uDC0B" /* 𠀋 */, "\uD861\uDeD7" /* 𨛗 */ // surrogate pair + "\uD841\uDE28" /* 𠘨 */, "\uD840\uDC0B" /* 𠀋 */, "\uD861\uDED7" /* 𨛗 */ // surrogate pair }; public BinaryDictIOUtilsTests() { + // 1500 is the default max unigrams + this(System.currentTimeMillis(), DEFAULT_MAX_UNIGRAMS); + } + + public BinaryDictIOUtilsTests(final long seed, final int maxUnigrams) { super(); - final Random random = new Random(123456); + Log.d(TAG, "Seed for test is " + seed + ", maxUnigrams is " + maxUnigrams); + mMaxUnigrams = maxUnigrams; + final Random random = new Random(seed); sWords.clear(); - for (int i = 0; i < MAX_UNIGRAMS; ++i) { + for (int i = 0; i < maxUnigrams; ++i) { sWords.add(generateWord(random.nextInt())); } } @@ -390,6 +398,6 @@ public class BinaryDictIOUtilsTests extends AndroidTestCase { Log.d(TAG, "max = " + ((double)maxTimeToInsert/1000000) + " ms."); Log.d(TAG, "min = " + ((double)minTimeToInsert/1000000) + " ms."); - Log.d(TAG, "avg = " + ((double)sum/MAX_UNIGRAMS/1000000) + " ms."); + Log.d(TAG, "avg = " + ((double)sum/mMaxUnigrams/1000000) + " ms."); } } diff --git a/tests/src/com/android/inputmethod/latin/UserHistoryDictionaryTests.java b/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTests.java index 594ba0e7b..8f9ef1ddd 100644 --- a/tests/src/com/android/inputmethod/latin/UserHistoryDictionaryTests.java +++ b/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.personalization; import android.content.SharedPreferences; import android.preference.PreferenceManager; @@ -22,6 +22,8 @@ import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.LargeTest; import android.util.Log; +import com.android.inputmethod.latin.utils.CollectionUtils; + import java.io.File; import java.util.ArrayList; import java.util.List; @@ -68,7 +70,7 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { return new ArrayList<String>(wordSet); } - private void addToDict(final UserHistoryDictionary dict, final List<String> words) { + private void addToDict(final UserHistoryPredictionDictionary dict, final List<String> words) { String prevWord = null; for (String word : words) { dict.forceAddWordForTest(prevWord, word, true); @@ -80,7 +82,7 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { File dictFile = null; try { Log.d(TAG, "This test can be used for profiling."); - Log.d(TAG, "Usage: please set UserHisotoryDictionary.PROFILE_SAVE_RESTORE to true."); + Log.d(TAG, "Usage: please set UserHistoryDictionary.PROFILE_SAVE_RESTORE to true."); final int numberOfWords = 1000; final Random random = new Random(123456); List<String> words = generateWords(numberOfWords, random); @@ -88,8 +90,9 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { final String locale = "testRandomWords"; final String fileName = "UserHistoryDictionary." + locale + ".dict"; dictFile = new File(getContext().getFilesDir(), fileName); - final UserHistoryDictionary dict = UserHistoryDictionary.getInstance(getContext(), - locale, mPrefs); + final UserHistoryPredictionDictionary dict = + PersonalizationDictionaryHelper.getUserHistoryPredictionDictionary( + getContext(), locale, mPrefs); dict.isTest = true; addToDict(dict, words); @@ -116,4 +119,55 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { } } } + + public void testStressTestForSwitchingLanguagesAndAddingWords() { + final int numberOfLanguages = 2; + final int numberOfLanguageSwitching = 100; + final int numberOfWordsIntertedForEachLanguageSwitch = 100; + + final File dictFiles[] = new File[numberOfLanguages]; + try { + final Random random = new Random(123456); + + // Create locales for this test. + String locales[] = new String[numberOfLanguages]; + for (int i = 0; i < numberOfLanguages; i++) { + locales[i] = "testSwitchingLanguages" + i; + final String fileName = "UserHistoryDictionary." + locales[i] + ".dict"; + dictFiles[i] = new File(getContext().getFilesDir(), fileName); + } + + final long now = System.currentTimeMillis(); + + for (int i = 0; i < numberOfLanguageSwitching; i++) { + final int index = i % numberOfLanguages; + // Switch languages to locales[index]. + final UserHistoryPredictionDictionary dict = + PersonalizationDictionaryHelper.getUserHistoryPredictionDictionary( + getContext(), locales[index], mPrefs); + final List<String> words = generateWords( + numberOfWordsIntertedForEachLanguageSwitch, random); + // Add random words to the user history dictionary. + addToDict(dict, words); + // write to file + dict.close(); + } + + final long end = System.currentTimeMillis(); + Log.d(TAG, "testStressTestForSwitchingLanguageAndAddingWords took " + + (end - now) + " ms"); + try { + Log.d(TAG, "waiting for writing ..."); + Thread.sleep(5000); + } catch (InterruptedException e) { + Log.d(TAG, "InterruptedException: " + e); + } + } finally { + for (final File file : dictFiles) { + if (file != null) { + file.delete(); + } + } + } + } } 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/CapsModeUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/CapsModeUtilsTests.java index 339791d57..cf3bdd680 100644 --- a/tests/src/com/android/inputmethod/latin/CapsModeUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/CapsModeUtilsTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; 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/ForgettingCurveTests.java b/tests/src/com/android/inputmethod/latin/utils/ForgettingCurveTests.java index 3259312df..823bd5d7d 100644 --- a/tests/src/com/android/inputmethod/latin/ForgettingCurveTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/ForgettingCurveTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; diff --git a/tests/src/com/android/inputmethod/latin/RecapitalizeStatusTests.java b/tests/src/com/android/inputmethod/latin/utils/RecapitalizeStatusTests.java index 9d7203e5a..a52041264 100644 --- a/tests/src/com/android/inputmethod/latin/RecapitalizeStatusTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/RecapitalizeStatusTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; diff --git a/tests/src/com/android/inputmethod/latin/ResizableIntArrayTests.java b/tests/src/com/android/inputmethod/latin/utils/ResizableIntArrayTests.java index 2d1b836c2..cfff61ef8 100644 --- a/tests/src/com/android/inputmethod/latin/ResizableIntArrayTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/ResizableIntArrayTests.java @@ -14,11 +14,13 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +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; @@ -186,7 +188,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { assertEquals("length after copy", dst.getLength(), src.getLength()); assertSame("array after copy", array, dst.getPrimitiveArray()); assertNotSame("array after copy", dst.getPrimitiveArray(), src.getPrimitiveArray()); - assertArrayEquals("values after copy", + assertIntArrayEquals("values after copy", dst.getPrimitiveArray(), 0, src.getPrimitiveArray(), 0, dst.getLength()); final int smallerLength = DEFAULT_CAPACITY / 2; @@ -197,7 +199,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { 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()); - assertArrayEquals("values after copy to smaller", + assertIntArrayEquals("values after copy to smaller", dst.getPrimitiveArray(), 0, src.getPrimitiveArray(), 0, dst.getLength()); } @@ -220,7 +222,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { dst.append(src, 0, 0); assertEquals("length after append zero", dstLen, dst.getLength()); assertSame("array after append zero", array, dst.getPrimitiveArray()); - assertArrayEquals("values after append zero", + assertIntArrayEquals("values after append zero", dstCopy.getPrimitiveArray(), 0, dst.getPrimitiveArray(), 0, dstLen); dst.append(src, 0, srcLen); @@ -228,9 +230,9 @@ public class ResizableIntArrayTests extends AndroidTestCase { assertSame("array after append", array, dst.getPrimitiveArray()); assertTrue("primitive length after append", dst.getPrimitiveArray().length >= dstLen + srcLen); - assertArrayEquals("original values after append", + assertIntArrayEquals("original values after append", dstCopy.getPrimitiveArray(), 0, dst.getPrimitiveArray(), 0, dstLen); - assertArrayEquals("appended values after append", + assertIntArrayEquals("appended values after append", src.getPrimitiveArray(), 0, dst.getPrimitiveArray(), dstLen, srcLen); dst.append(src, 0, srcLen); @@ -238,11 +240,11 @@ public class ResizableIntArrayTests extends AndroidTestCase { assertNotSame("array after 2nd append", array, dst.getPrimitiveArray()); assertTrue("primitive length after 2nd append", dst.getPrimitiveArray().length >= dstLen + srcLen * 2); - assertArrayEquals("original values after 2nd append", + assertIntArrayEquals("original values after 2nd append", dstCopy.getPrimitiveArray(), 0, dst.getPrimitiveArray(), 0, dstLen); - assertArrayEquals("appended values after 2nd append", + assertIntArrayEquals("appended values after 2nd append", src.getPrimitiveArray(), 0, dst.getPrimitiveArray(), dstLen, srcLen); - assertArrayEquals("appended values after 2nd append", + assertIntArrayEquals("appended values after 2nd append", src.getPrimitiveArray(), 0, dst.getPrimitiveArray(), dstLen + srcLen, srcLen); } @@ -319,16 +321,22 @@ public class ResizableIntArrayTests extends AndroidTestCase { } } - private static void assertArrayEquals(String message, int[] expecteds, int expectedPos, - int[] actuals, int actualPos, int length) { - if (expecteds == null && actuals == null) { + 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) { - fail(message + ": expecteds=" + expecteds + " actuals=" + actuals); + 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 + ": element at " + i, + assertEquals(message + " [" + i + "]", expecteds[i + expectedPos], actuals[i + actualPos]); } } diff --git a/tests/src/com/android/inputmethod/latin/ResourceUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/ResourceUtilsTests.java index ed16846b9..1ae22e307 100644 --- a/tests/src/com/android/inputmethod/latin/ResourceUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/ResourceUtilsTests.java @@ -14,30 +14,46 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +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; - assertNull(ResourceUtils.findDefaultConstant(nullArray)); - final String[] emptyArray = {}; - assertNull(ResourceUtils.findDefaultConstant(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", - "HARDWARE=mako,0.4", - ",defaultValue1", - "HARDWARE=manta,0.2", - ",defaultValue2", + "no_comma" }; - assertEquals(ResourceUtils.findDefaultConstant(array), "defaultValue1"); + 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() { @@ -67,33 +83,23 @@ public class ResourceUtilsTests extends AndroidTestCase { final HashMap<String,String> keyValues = CollectionUtils.newHashMap(); keyValues.put(HARDWARE_KEY, "grouper"); - assertEquals(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.3"); + assertEquals("0.3", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); keyValues.put(HARDWARE_KEY, "mako"); - assertEquals(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.4"); + assertEquals("0.4", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); keyValues.put(HARDWARE_KEY, "manta"); - assertEquals(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.2"); + assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); + + keyValues.clear(); + keyValues.put("hardware", "grouper"); + assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); - try { - keyValues.clear(); - keyValues.put("hardware", "grouper"); - final String constant = ResourceUtils.findConstantForKeyValuePairs(keyValues, array); - fail("condition without HARDWARE must fail: constant=" + constant); - } catch (final RuntimeException e) { - assertEquals(e.getMessage(), "Found unknown key: HARDWARE=grouper"); - } keyValues.clear(); keyValues.put(HARDWARE_KEY, "MAKO"); assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); keyValues.put(HARDWARE_KEY, "mantaray"); assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); - try { - final String constant = ResourceUtils.findConstantForKeyValuePairs( - emptyKeyValue, array); - fail("emptyCondition shouldn't match: constant=" + constant); - } catch (final RuntimeException e) { - assertEquals(e.getMessage(), "Found unknown key: HARDWARE=grouper"); - } + assertNull(ResourceUtils.findConstantForKeyValuePairs(emptyKeyValue, array)); } public void testFindConstantForKeyValuePairsCombined() { @@ -102,6 +108,8 @@ public class ResourceUtilsTests extends AndroidTestCase { 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" @@ -117,25 +125,25 @@ public class ResourceUtilsTests extends AndroidTestCase { keyValues.put(HARDWARE_KEY, "grouper"); keyValues.put(MODEL_KEY, "Nexus 7"); keyValues.put(MANUFACTURER_KEY, "asus"); - assertEquals(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.3"); + 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(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.4"); + 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(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.2"); + assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray)); keyValues.put(HARDWARE_KEY, "mantaray"); assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); - assertEquals(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray), "0.2"); + assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray)); } public void testFindConstantForKeyValuePairsRegexp() { @@ -144,6 +152,8 @@ public class ResourceUtilsTests extends AndroidTestCase { 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" @@ -153,24 +163,24 @@ public class ResourceUtilsTests extends AndroidTestCase { keyValues.put(HARDWARE_KEY, "grouper"); keyValues.put(MODEL_KEY, "Nexus 7"); keyValues.put(MANUFACTURER_KEY, "asus"); - assertEquals(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.3"); + assertEquals("0.3", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); keyValues.put(HARDWARE_KEY, "tilapia"); - assertEquals(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.3"); + 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(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.4"); + assertEquals("0.4", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); keyValues.put(HARDWARE_KEY, "MAKO"); - assertEquals(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.4"); + 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(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.2"); + assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); keyValues.put(HARDWARE_KEY, "mantaray"); - assertEquals(ResourceUtils.findConstantForKeyValuePairs(keyValues, array), "0.2"); + assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, array)); } } diff --git a/tests/src/com/android/inputmethod/latin/StringUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/StringUtilsTests.java index 29e790a7d..9ee8e387b 100644 --- a/tests/src/com/android/inputmethod/latin/StringUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/StringUtilsTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; @@ -40,57 +40,62 @@ public class StringUtilsTests extends AndroidTestCase { })); } - public void testContainsInCsv() { - assertFalse("null", StringUtils.containsInCsv("key", null)); - assertFalse("empty", StringUtils.containsInCsv("key", "")); - assertFalse("not in 1 element", StringUtils.containsInCsv("key", "key1")); - assertFalse("not in 2 elements", StringUtils.containsInCsv("key", "key1,key2")); + 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.containsInCsv("key", "key")); - assertTrue("in 2 elements", StringUtils.containsInCsv("key", "key1,key")); + assertTrue("in 1 element", StringUtils.containsInCommaSplittableText("key", "key")); + assertTrue("in 2 elements", StringUtils.containsInCommaSplittableText("key", "key1,key")); } - public void testAppendToCsvIfNotExists() { - assertEquals("null", "key", StringUtils.appendToCsvIfNotExists("key", null)); - assertEquals("empty", "key", StringUtils.appendToCsvIfNotExists("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.appendToCsvIfNotExists("key", "key1")); + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key1")); assertEquals("not in 2 elements", "key1,key2,key", - StringUtils.appendToCsvIfNotExists("key", "key1,key2")); + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key1,key2")); assertEquals("in 1 element", "key", - StringUtils.appendToCsvIfNotExists("key", "key")); + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key")); assertEquals("in 2 elements at position 1", "key,key2", - StringUtils.appendToCsvIfNotExists("key", "key,key2")); + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key,key2")); assertEquals("in 2 elements at position 2", "key1,key", - StringUtils.appendToCsvIfNotExists("key", "key1,key")); + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key1,key")); assertEquals("in 3 elements at position 2", "key1,key,key3", - StringUtils.appendToCsvIfNotExists("key", "key1,key,key3")); + StringUtils.appendToCommaSplittableTextIfNotExists("key", "key1,key,key3")); } - public void testRemoveFromCsvIfExists() { - assertEquals("null", "", StringUtils.removeFromCsvIfExists("key", null)); - assertEquals("empty", "", StringUtils.removeFromCsvIfExists("key", "")); + public void testRemoveFromExtraValuesIfExists() { + assertEquals("null", "", StringUtils.removeFromCommaSplittableTextIfExists("key", null)); + assertEquals("empty", "", StringUtils.removeFromCommaSplittableTextIfExists("key", "")); assertEquals("not in 1 element", "key1", - StringUtils.removeFromCsvIfExists("key", "key1")); + StringUtils.removeFromCommaSplittableTextIfExists("key", "key1")); assertEquals("not in 2 elements", "key1,key2", - StringUtils.removeFromCsvIfExists("key", "key1,key2")); + StringUtils.removeFromCommaSplittableTextIfExists("key", "key1,key2")); assertEquals("in 1 element", "", - StringUtils.removeFromCsvIfExists("key", "key")); + StringUtils.removeFromCommaSplittableTextIfExists("key", "key")); assertEquals("in 2 elements at position 1", "key2", - StringUtils.removeFromCsvIfExists("key", "key,key2")); + StringUtils.removeFromCommaSplittableTextIfExists("key", "key,key2")); assertEquals("in 2 elements at position 2", "key1", - StringUtils.removeFromCsvIfExists("key", "key1,key")); + StringUtils.removeFromCommaSplittableTextIfExists("key", "key1,key")); assertEquals("in 3 elements at position 2", "key1,key3", - StringUtils.removeFromCsvIfExists("key", "key1,key,key3")); + StringUtils.removeFromCommaSplittableTextIfExists("key", "key1,key,key3")); assertEquals("in 3 elements at position 1,2,3", "", - StringUtils.removeFromCsvIfExists("key", "key,key,key")); + StringUtils.removeFromCommaSplittableTextIfExists("key", "key,key,key")); assertEquals("in 5 elements at position 2,4", "key1,key3,key5", - StringUtils.removeFromCsvIfExists("key", "key1,key,key3,key,key5")); + StringUtils.removeFromCommaSplittableTextIfExists( + "key", "key1,key,key3,key,key5")); } 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..e165850ac --- /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 No language (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 No language (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 ", "No language (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 azerty", "No language (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 Aucune langue (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 ", "Aucune langue (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 azerty", "Aucune langue (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/UserHistoryDictIOUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtilsTests.java index 211d012d2..b6798392f 100644 --- a/tests/src/com/android/inputmethod/latin/UserHistoryDictIOUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtilsTests.java @@ -14,18 +14,20 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +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.UserHistoryDictIOUtils.BigramDictionaryInterface; -import com.android.inputmethod.latin.UserHistoryDictIOUtils.OnAddWordListener; import com.android.inputmethod.latin.makedict.FormatSpec; import com.android.inputmethod.latin.makedict.FusionDictionary; import com.android.inputmethod.latin.makedict.FusionDictionary.CharGroup; +import com.android.inputmethod.latin.personalization.UserHistoryDictionaryBigramList; +import com.android.inputmethod.latin.utils.ByteArrayWrapper; +import com.android.inputmethod.latin.utils.UserHistoryDictIOUtils.BigramDictionaryInterface; +import com.android.inputmethod.latin.utils.UserHistoryDictIOUtils.OnAddWordListener; import java.io.File; import java.io.FileInputStream; @@ -152,8 +154,7 @@ public class UserHistoryDictIOUtilsTests extends AndroidTestCase final byte[] buffer = new byte[(int)file.length()]; inStream.read(buffer); - UserHistoryDictIOUtils.readDictionaryBinary( - new UserHistoryDictIOUtils.ByteArrayWrapper(buffer), listener); + UserHistoryDictIOUtils.readDictionaryBinary(new ByteArrayWrapper(buffer), listener); } catch (FileNotFoundException e) { Log.e(TAG, "file not found", e); } catch (IOException e) { |