aboutsummaryrefslogtreecommitdiffstats
path: root/tests/src
diff options
context:
space:
mode:
Diffstat (limited to 'tests/src')
-rw-r--r--tests/src/com/android/inputmethod/compat/SuggestionSpanUtilsTest.java3
-rw-r--r--tests/src/com/android/inputmethod/keyboard/layout/tests/KeyboardLayoutSetSubtypesCountTests.java2
-rw-r--r--tests/src/com/android/inputmethod/keyboard/layout/tests/TestsTamilLK.java4
-rw-r--r--tests/src/com/android/inputmethod/latin/BinaryDictionaryTests.java261
-rw-r--r--tests/src/com/android/inputmethod/latin/BlueUnderlineTests.java4
-rw-r--r--tests/src/com/android/inputmethod/latin/InputLogicTests.java187
-rw-r--r--tests/src/com/android/inputmethod/latin/InputTestsBase.java25
-rw-r--r--tests/src/com/android/inputmethod/latin/NgramContextTests.java22
-rw-r--r--tests/src/com/android/inputmethod/latin/PunctuationTests.java34
-rw-r--r--tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java8
-rw-r--r--tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java4
-rw-r--r--tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java14
-rw-r--r--tests/src/com/android/inputmethod/latin/makedict/Ver2DictDecoder.java319
-rw-r--r--tests/src/com/android/inputmethod/latin/makedict/Ver2DictDecoderTests.java150
-rw-r--r--tests/src/com/android/inputmethod/latin/makedict/Ver2DictEncoder.java279
-rw-r--r--tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTestsHelper.java4
-rw-r--r--tests/src/com/android/inputmethod/latin/settings/AccountsSettingsFragmentTests.java101
-rw-r--r--tests/src/com/android/inputmethod/latin/touchinputconsumer/NullGestureConsumerTests.java2
-rw-r--r--tests/src/com/android/inputmethod/latin/utils/ExecutorUtilsTests.java3
-rw-r--r--tests/src/com/android/inputmethod/latin/utils/ImportantNoticeUtilsTests.java42
20 files changed, 296 insertions, 1172 deletions
diff --git a/tests/src/com/android/inputmethod/compat/SuggestionSpanUtilsTest.java b/tests/src/com/android/inputmethod/compat/SuggestionSpanUtilsTest.java
index 7bbf965f9..daf412cc3 100644
--- a/tests/src/com/android/inputmethod/compat/SuggestionSpanUtilsTest.java
+++ b/tests/src/com/android/inputmethod/compat/SuggestionSpanUtilsTest.java
@@ -42,7 +42,8 @@ public class SuggestionSpanUtilsTest extends AndroidTestCase {
* @return a new instance of {@link SuggestedWordInfo}.
*/
private static SuggestedWordInfo createWordInfo(final String word, final int kindAndFlags) {
- return new SuggestedWordInfo(word, 1 /* score */, kindAndFlags, null /* sourceDict */,
+ return new SuggestedWordInfo(word, "" /* prevWordsContext */, 1 /* score */, kindAndFlags,
+ null /* sourceDict */,
SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */);
}
diff --git a/tests/src/com/android/inputmethod/keyboard/layout/tests/KeyboardLayoutSetSubtypesCountTests.java b/tests/src/com/android/inputmethod/keyboard/layout/tests/KeyboardLayoutSetSubtypesCountTests.java
index 3e351b643..3a8d19d08 100644
--- a/tests/src/com/android/inputmethod/keyboard/layout/tests/KeyboardLayoutSetSubtypesCountTests.java
+++ b/tests/src/com/android/inputmethod/keyboard/layout/tests/KeyboardLayoutSetSubtypesCountTests.java
@@ -27,7 +27,7 @@ import java.util.ArrayList;
@SmallTest
public class KeyboardLayoutSetSubtypesCountTests extends KeyboardLayoutSetTestsBase {
- private static final int NUMBER_OF_SUBTYPES = 84;
+ private static final int NUMBER_OF_SUBTYPES = 82;
private static final int NUMBER_OF_ASCII_CAPABLE_SUBTYPES = 50;
private static final int NUMBER_OF_PREDEFINED_ADDITIONAL_SUBTYPES = 2;
diff --git a/tests/src/com/android/inputmethod/keyboard/layout/tests/TestsTamilLK.java b/tests/src/com/android/inputmethod/keyboard/layout/tests/TestsTamilLK.java
index 6e49c5953..72872ba66 100644
--- a/tests/src/com/android/inputmethod/keyboard/layout/tests/TestsTamilLK.java
+++ b/tests/src/com/android/inputmethod/keyboard/layout/tests/TestsTamilLK.java
@@ -16,7 +16,7 @@
package com.android.inputmethod.keyboard.layout.tests;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.test.suitebuilder.annotation.Suppress;
import com.android.inputmethod.keyboard.layout.LayoutBase;
import com.android.inputmethod.keyboard.layout.Symbols;
@@ -30,7 +30,7 @@ import java.util.Locale;
/**
* ta_LK: Tamil (Sri Lanka)/tamil
*/
-@SmallTest
+@Suppress
public final class TestsTamilLK extends LayoutTestsBase {
private static final Locale LOCALE = new Locale("ta", "LK");
private static final LayoutBase LAYOUT = new Tamil(new TamilLKCustomizer(LOCALE));
diff --git a/tests/src/com/android/inputmethod/latin/BinaryDictionaryTests.java b/tests/src/com/android/inputmethod/latin/BinaryDictionaryTests.java
index 9da1e9470..e92831c48 100644
--- a/tests/src/com/android/inputmethod/latin/BinaryDictionaryTests.java
+++ b/tests/src/com/android/inputmethod/latin/BinaryDictionaryTests.java
@@ -24,7 +24,6 @@ import android.util.Pair;
import com.android.inputmethod.latin.NgramContext.WordInfo;
import com.android.inputmethod.latin.common.CodePointUtils;
import com.android.inputmethod.latin.common.FileUtils;
-import com.android.inputmethod.latin.define.DecoderSpecificConstants;
import com.android.inputmethod.latin.makedict.DictionaryHeader;
import com.android.inputmethod.latin.makedict.FormatSpec;
import com.android.inputmethod.latin.makedict.WeightedString;
@@ -43,8 +42,6 @@ import java.util.Random;
public class BinaryDictionaryTests extends AndroidTestCase {
private static final String TEST_DICT_FILE_EXTENSION = ".testDict";
private static final String TEST_LOCALE = "test";
- private static final int[] DICT_FORMAT_VERSIONS =
- new int[] { FormatSpec.VERSION402, FormatSpec.VERSION403, FormatSpec.VERSION4_DEV };
private static final String DICTIONARY_ID = "TestBinaryDictionary";
private static boolean supportsNgram(final int formatVersion) {
@@ -114,13 +111,7 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testIsValidDictionary() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testIsValidDictionary(formatVersion);
- }
- }
-
- private void testIsValidDictionary(final int formatVersion) {
- final File dictFile = createEmptyDictionaryAndGetFile(formatVersion);
+ final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403);
BinaryDictionary binaryDictionary = getBinaryDictionary(dictFile);
assertTrue("binaryDictionary must be valid for existing valid dictionary file.",
binaryDictionary.isValidDictionary());
@@ -135,20 +126,14 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testConstructingDictionaryOnMemory() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testConstructingDictionaryOnMemory(formatVersion);
- }
- }
-
- private void testConstructingDictionaryOnMemory(final int formatVersion) {
- final File dictFile = createEmptyDictionaryAndGetFile(formatVersion);
+ final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403);
FileUtils.deleteRecursively(dictFile);
assertFalse(dictFile.exists());
final BinaryDictionary binaryDictionary = new BinaryDictionary(dictFile.getAbsolutePath(),
- true /* useFullEditDistance */, Locale.getDefault(), TEST_LOCALE, formatVersion,
- new HashMap<String, String>());
+ true /* useFullEditDistance */, Locale.getDefault(), TEST_LOCALE,
+ FormatSpec.VERSION403, new HashMap<String, String>());
assertTrue(binaryDictionary.isValidDictionary());
- assertEquals(formatVersion, binaryDictionary.getFormatVersion());
+ assertEquals(FormatSpec.VERSION403, binaryDictionary.getFormatVersion());
final int probability = 100;
addUnigramWord(binaryDictionary, "word", probability);
assertEquals(probability, binaryDictionary.getFrequency("word"));
@@ -156,21 +141,15 @@ public class BinaryDictionaryTests extends AndroidTestCase {
binaryDictionary.flush();
assertTrue(dictFile.exists());
assertTrue(binaryDictionary.isValidDictionary());
- assertEquals(formatVersion, binaryDictionary.getFormatVersion());
+ assertEquals(FormatSpec.VERSION403, binaryDictionary.getFormatVersion());
assertEquals(probability, binaryDictionary.getFrequency("word"));
binaryDictionary.close();
}
public void testAddTooLongWord() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testAddTooLongWord(formatVersion);
- }
- }
-
- private void testAddTooLongWord(final int formatVersion) {
- final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(formatVersion);
+ final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403);
final StringBuffer stringBuilder = new StringBuffer();
- for (int i = 0; i < DecoderSpecificConstants.DICTIONARY_MAX_WORD_LENGTH; i++) {
+ for (int i = 0; i < BinaryDictionary.DICTIONARY_MAX_WORD_LENGTH; i++) {
stringBuilder.append('a');
}
final String validLongWord = stringBuilder.toString();
@@ -235,13 +214,7 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testAddUnigramWord() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testAddUnigramWord(formatVersion);
- }
- }
-
- private void testAddUnigramWord(final int formatVersion) {
- final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(formatVersion);
+ final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403);
final int probability = 100;
addUnigramWord(binaryDictionary, "aaa", probability);
// Reallocate and create.
@@ -268,16 +241,10 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testRandomlyAddUnigramWord() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testRandomlyAddUnigramWord(formatVersion);
- }
- }
-
- private void testRandomlyAddUnigramWord(final int formatVersion) {
final int wordCount = 1000;
final int codePointSetSize = 50;
final long seed = System.currentTimeMillis();
- final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(formatVersion);
+ final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403);
final HashMap<String, Integer> probabilityMap = new HashMap<>();
// Test a word that isn't contained within the dictionary.
@@ -296,13 +263,7 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testAddBigramWords() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testAddBigramWords(formatVersion);
- }
- }
-
- private void testAddBigramWords(final int formatVersion) {
- final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(formatVersion);
+ final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403);
final int unigramProbability = 100;
final int bigramProbability = 150;
@@ -355,18 +316,12 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testRandomlyAddBigramWords() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testRandomlyAddBigramWords(formatVersion);
- }
- }
-
- private void testRandomlyAddBigramWords(final int formatVersion) {
final int wordCount = 100;
final int bigramCount = 1000;
final int codePointSetSize = 50;
final long seed = System.currentTimeMillis();
final Random random = new Random(seed);
- final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(formatVersion);
+ final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403);
final ArrayList<String> words = new ArrayList<>();
final ArrayList<Pair<String, String>> bigramWords = new ArrayList<>();
@@ -407,15 +362,7 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testAddTrigramWords() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- if (supportsNgram(formatVersion)) {
- testAddTrigramWords(formatVersion);
- }
- }
- }
-
- private void testAddTrigramWords(final int formatVersion) {
- final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(formatVersion);
+ final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403);
final int unigramProbability = 100;
final int trigramProbability = 150;
final int updatedTrigramProbability = 200;
@@ -441,13 +388,7 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testFlushDictionary() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testFlushDictionary(formatVersion);
- }
- }
-
- private void testFlushDictionary(final int formatVersion) {
- final File dictFile = createEmptyDictionaryAndGetFile(formatVersion);
+ final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403);
BinaryDictionary binaryDictionary = getBinaryDictionary(dictFile);
final int probability = 100;
@@ -481,13 +422,7 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testFlushWithGCDictionary() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testFlushWithGCDictionary(formatVersion);
- }
- }
-
- private void testFlushWithGCDictionary(final int formatVersion) {
- final File dictFile = createEmptyDictionaryAndGetFile(formatVersion);
+ final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403);
BinaryDictionary binaryDictionary = getBinaryDictionary(dictFile);
final int unigramProbability = 100;
final int bigramProbability = 150;
@@ -517,20 +452,13 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testAddBigramWordsAndFlashWithGC() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testAddBigramWordsAndFlashWithGC(formatVersion);
- }
- }
-
- // TODO: Evaluate performance of GC
- private void testAddBigramWordsAndFlashWithGC(final int formatVersion) {
final int wordCount = 100;
final int bigramCount = 1000;
final int codePointSetSize = 30;
final long seed = System.currentTimeMillis();
final Random random = new Random(seed);
- final File dictFile = createEmptyDictionaryAndGetFile(formatVersion);
+ final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403);
BinaryDictionary binaryDictionary = getBinaryDictionary(dictFile);
final ArrayList<String> words = new ArrayList<>();
@@ -576,12 +504,6 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testRandomOperationsAndFlashWithGC() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testRandomOperationsAndFlashWithGC(formatVersion);
- }
- }
-
- private void testRandomOperationsAndFlashWithGC(final int formatVersion) {
final int maxUnigramCount = 5000;
final int maxBigramCount = 10000;
final HashMap<String, String> attributeMap = new HashMap<>();
@@ -597,7 +519,7 @@ public class BinaryDictionaryTests extends AndroidTestCase {
final long seed = System.currentTimeMillis();
final Random random = new Random(seed);
- final File dictFile = createEmptyDictionaryWithAttributesAndGetFile(formatVersion,
+ final File dictFile = createEmptyDictionaryWithAttributesAndGetFile(FormatSpec.VERSION403,
attributeMap);
BinaryDictionary binaryDictionary = getBinaryDictionary(dictFile);
@@ -676,19 +598,13 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testAddManyUnigramsAndFlushWithGC() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testAddManyUnigramsAndFlushWithGC(formatVersion);
- }
- }
-
- private void testAddManyUnigramsAndFlushWithGC(final int formatVersion) {
final int flashWithGCIterationCount = 3;
final int codePointSetSize = 50;
final long seed = System.currentTimeMillis();
final Random random = new Random(seed);
- final File dictFile = createEmptyDictionaryAndGetFile(formatVersion);
+ final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403);
final ArrayList<String> words = new ArrayList<>();
final HashMap<String, Integer> unigramProbabilities = new HashMap<>();
@@ -717,12 +633,6 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testUnigramAndBigramCount() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testUnigramAndBigramCount(formatVersion);
- }
- }
-
- private void testUnigramAndBigramCount(final int formatVersion) {
final int maxUnigramCount = 5000;
final int maxBigramCount = 10000;
final HashMap<String, String> attributeMap = new HashMap<>();
@@ -735,7 +645,7 @@ public class BinaryDictionaryTests extends AndroidTestCase {
final int bigramCountPerIteration = 2000;
final long seed = System.currentTimeMillis();
final Random random = new Random(seed);
- final File dictFile = createEmptyDictionaryWithAttributesAndGetFile(formatVersion,
+ final File dictFile = createEmptyDictionaryWithAttributesAndGetFile(FormatSpec.VERSION403,
attributeMap);
final ArrayList<String> words = new ArrayList<>();
@@ -779,19 +689,13 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testGetWordProperties() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testGetWordProperties(formatVersion);
- }
- }
-
- private void testGetWordProperties(final int formatVersion) {
final long seed = System.currentTimeMillis();
final Random random = new Random(seed);
final int UNIGRAM_COUNT = 1000;
final int BIGRAM_COUNT = 1000;
final int codePointSetSize = 20;
final int[] codePointSet = CodePointUtils.generateCodePointSet(codePointSetSize, random);
- final File dictFile = createEmptyDictionaryAndGetFile(formatVersion);
+ final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403);
final BinaryDictionary binaryDictionary = getBinaryDictionary(dictFile);
final WordProperty invalidWordProperty = binaryDictionary.getWordProperty("dummyWord",
@@ -870,19 +774,13 @@ public class BinaryDictionaryTests extends AndroidTestCase {
}
public void testIterateAllWords() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testIterateAllWords(formatVersion);
- }
- }
-
- private void testIterateAllWords(final int formatVersion) {
final long seed = System.currentTimeMillis();
final Random random = new Random(seed);
final int UNIGRAM_COUNT = 1000;
final int BIGRAM_COUNT = 1000;
final int codePointSetSize = 20;
final int[] codePointSet = CodePointUtils.generateCodePointSet(codePointSetSize, random);
- final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(formatVersion);
+ final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403);
final WordProperty invalidWordProperty = binaryDictionary.getWordProperty("dummyWord",
false /* isBeginningOfSentence */);
@@ -966,123 +864,8 @@ public class BinaryDictionaryTests extends AndroidTestCase {
assertEquals(true, wordProperty.mIsPossiblyOffensive);
}
- public void testDictMigration() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testDictMigration(FormatSpec.VERSION4_ONLY_FOR_TESTING, formatVersion);
- }
- }
-
- private void testDictMigration(final int fromFormatVersion, final int toFormatVersion) {
- final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(fromFormatVersion);
- final int unigramProbability = 100;
- addUnigramWord(binaryDictionary, "aaa", unigramProbability);
- addUnigramWord(binaryDictionary, "bbb", unigramProbability);
- final int bigramProbability = 150;
- addBigramWords(binaryDictionary, "aaa", "bbb", bigramProbability);
- binaryDictionary.addUnigramEntry("ccc", unigramProbability,
- false /* isBeginningOfSentence */, false /* isNotAWord */,
- false /* isPossiblyOffensive */, 0 /* timestamp */);
- binaryDictionary.addUnigramEntry("ddd", unigramProbability,
- false /* isBeginningOfSentence */,
- true /* isNotAWord */, true /* isPossiblyOffensive */, 0 /* timestamp */);
- binaryDictionary.addNgramEntry(NgramContext.BEGINNING_OF_SENTENCE,
- "aaa", bigramProbability, 0 /* timestamp */);
- assertEquals(unigramProbability, binaryDictionary.getFrequency("aaa"));
- assertEquals(unigramProbability, binaryDictionary.getFrequency("bbb"));
- assertTrue(isValidBigram(binaryDictionary, "aaa", "bbb"));
- assertEquals(fromFormatVersion, binaryDictionary.getFormatVersion());
- assertTrue(binaryDictionary.migrateTo(toFormatVersion));
- assertTrue(binaryDictionary.isValidDictionary());
- assertEquals(toFormatVersion, binaryDictionary.getFormatVersion());
- assertEquals(unigramProbability, binaryDictionary.getFrequency("aaa"));
- assertEquals(unigramProbability, binaryDictionary.getFrequency("bbb"));
- assertEquals(bigramProbability, getBigramProbability(binaryDictionary, "aaa", "bbb"));
- assertEquals(bigramProbability, binaryDictionary.getNgramProbability(
- NgramContext.BEGINNING_OF_SENTENCE, "aaa"));
- assertTrue(isValidBigram(binaryDictionary, "aaa", "bbb"));
- WordProperty wordProperty = binaryDictionary.getWordProperty("ccc",
- false /* isBeginningOfSentence */);
- wordProperty = binaryDictionary.getWordProperty("ddd",
- false /* isBeginningOfSentence */);
- assertTrue(wordProperty.mIsPossiblyOffensive);
- assertTrue(wordProperty.mIsNotAWord);
- }
-
- public void testLargeDictMigration() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testLargeDictMigration(FormatSpec.VERSION4_ONLY_FOR_TESTING, formatVersion);
- }
- }
-
- private void testLargeDictMigration(final int fromFormatVersion, final int toFormatVersion) {
- final int UNIGRAM_COUNT = 3000;
- final int BIGRAM_COUNT = 3000;
- final int codePointSetSize = 50;
- final long seed = System.currentTimeMillis();
- final Random random = new Random(seed);
- final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(fromFormatVersion);
-
- final ArrayList<String> words = new ArrayList<>();
- final ArrayList<Pair<String, String>> bigrams = new ArrayList<>();
- final int[] codePointSet = CodePointUtils.generateCodePointSet(codePointSetSize, random);
- final HashMap<String, Integer> unigramProbabilities = new HashMap<>();
- final HashMap<Pair<String, String>, Integer> bigramProbabilities = new HashMap<>();
-
- for (int i = 0; i < UNIGRAM_COUNT; i++) {
- final String word = CodePointUtils.generateWord(random, codePointSet);
- final int unigramProbability = random.nextInt(0xFF);
- addUnigramWord(binaryDictionary, word, unigramProbability);
- if (binaryDictionary.needsToRunGC(true /* mindsBlockByGC */)) {
- binaryDictionary.flushWithGC();
- }
- words.add(word);
- unigramProbabilities.put(word, unigramProbability);
- }
-
- for (int i = 0; i < BIGRAM_COUNT; i++) {
- final int word0Index = random.nextInt(words.size());
- final int word1Index = random.nextInt(words.size());
- if (word0Index == word1Index) {
- continue;
- }
- final String word0 = words.get(word0Index);
- final String word1 = words.get(word1Index);
- final int unigramProbability = unigramProbabilities.get(word1);
- final int bigramProbability =
- random.nextInt(0xFF - unigramProbability) + unigramProbability;
- addBigramWords(binaryDictionary, word0, word1, bigramProbability);
- if (binaryDictionary.needsToRunGC(true /* mindsBlockByGC */)) {
- binaryDictionary.flushWithGC();
- }
- final Pair<String, String> bigram = new Pair<>(word0, word1);
- bigrams.add(bigram);
- bigramProbabilities.put(bigram, bigramProbability);
- }
- assertTrue(binaryDictionary.migrateTo(toFormatVersion));
-
- for (final String word : words) {
- assertEquals((int)unigramProbabilities.get(word), binaryDictionary.getFrequency(word));
- }
- assertEquals(unigramProbabilities.size(), Integer.parseInt(
- binaryDictionary.getPropertyForGettingStats(BinaryDictionary.UNIGRAM_COUNT_QUERY)));
-
- for (final Pair<String, String> bigram : bigrams) {
- assertEquals((int)bigramProbabilities.get(bigram),
- getBigramProbability(binaryDictionary, bigram.first, bigram.second));
- assertTrue(isValidBigram(binaryDictionary, bigram.first, bigram.second));
- }
- assertEquals(bigramProbabilities.size(), Integer.parseInt(
- binaryDictionary.getPropertyForGettingStats(BinaryDictionary.BIGRAM_COUNT_QUERY)));
- }
-
public void testBeginningOfSentence() {
- for (final int formatVersion : DICT_FORMAT_VERSIONS) {
- testBeginningOfSentence(formatVersion);
- }
- }
-
- private void testBeginningOfSentence(final int formatVersion) {
- final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(formatVersion);
+ final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403);
final int dummyProbability = 0;
final NgramContext beginningOfSentenceContext = NgramContext.BEGINNING_OF_SENTENCE;
final int bigramProbability = 200;
diff --git a/tests/src/com/android/inputmethod/latin/BlueUnderlineTests.java b/tests/src/com/android/inputmethod/latin/BlueUnderlineTests.java
index 1c8a2f242..afb94ef05 100644
--- a/tests/src/com/android/inputmethod/latin/BlueUnderlineTests.java
+++ b/tests/src/com/android/inputmethod/latin/BlueUnderlineTests.java
@@ -39,8 +39,8 @@ public class BlueUnderlineTests extends InputTestsBase {
}
public void testBlueUnderlineDisappears() {
- final String STRING_1_TO_TYPE = "tgis";
- final String STRING_2_TO_TYPE = "q";
+ final String STRING_1_TO_TYPE = "tqis";
+ final String STRING_2_TO_TYPE = "g";
final int EXPECTED_SPAN_START = 0;
final int EXPECTED_SPAN_END = 5;
type(STRING_1_TO_TYPE);
diff --git a/tests/src/com/android/inputmethod/latin/InputLogicTests.java b/tests/src/com/android/inputmethod/latin/InputLogicTests.java
index a6c9bbee0..f2885f5f2 100644
--- a/tests/src/com/android/inputmethod/latin/InputLogicTests.java
+++ b/tests/src/com/android/inputmethod/latin/InputLogicTests.java
@@ -16,17 +16,33 @@
package com.android.inputmethod.latin;
-import android.test.MoreAsserts;
+import static android.test.MoreAsserts.assertNotEqual;
+
import android.test.suitebuilder.annotation.LargeTest;
import android.text.TextUtils;
import android.view.inputmethod.BaseInputConnection;
import com.android.inputmethod.latin.common.Constants;
+import com.android.inputmethod.latin.define.DecoderSpecificConstants;
import com.android.inputmethod.latin.settings.Settings;
@LargeTest
public class InputLogicTests extends InputTestsBase {
+ private boolean mNextWordPrediction;
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ mNextWordPrediction = getBooleanPreference(Settings.PREF_BIGRAM_PREDICTIONS, true);
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ setBooleanPreference(Settings.PREF_BIGRAM_PREDICTIONS, mNextWordPrediction, true);
+ super.tearDown();
+ }
+
public void testTypeWord() {
final String WORD_TO_TYPE = "abcd";
type(WORD_TO_TYPE);
@@ -201,22 +217,45 @@ public class InputLogicTests extends InputTestsBase {
}
public void testDoubleSpace() {
- // Set default pref just in case
- setBooleanPreference(Settings.PREF_KEY_USE_DOUBLE_SPACE_PERIOD, true, true);
// U+1F607 is an emoji
final String[] STRINGS_TO_TYPE =
new String[] { "this ", "a+ ", "\u1F607 ", ".. ", ") ", "( ", "% " };
final String[] EXPECTED_RESULTS =
new String[] { "this. ", "a+. ", "\u1F607. ", ".. ", "). ", "( ", "%. " };
- for (int i = 0; i < STRINGS_TO_TYPE.length; ++i) {
+ verifyDoubleSpace(STRINGS_TO_TYPE, EXPECTED_RESULTS);
+ }
+
+ public void testDoubleSpaceHindi() {
+ changeLanguage("hi");
+ // U+1F607 is an emoji
+ final String[] STRINGS_TO_TYPE =
+ new String[] { "this ", "a+ ", "\u1F607 ", "|| ", ") ", "( ", "% " };
+ final String[] EXPECTED_RESULTS =
+ new String[] { "this| ", "a+| ", "\u1F607| ", "|| ", ")| ", "( ", "%| " };
+ verifyDoubleSpace(STRINGS_TO_TYPE, EXPECTED_RESULTS);
+ }
+
+ private void verifyDoubleSpace(String[] stringsToType, String[] expectedResults) {
+ // Set default pref just in case
+ setBooleanPreference(Settings.PREF_KEY_USE_DOUBLE_SPACE_PERIOD, true, true);
+ for (int i = 0; i < stringsToType.length; ++i) {
mEditText.setText("");
- type(STRINGS_TO_TYPE[i]);
- assertEquals("double space processing", EXPECTED_RESULTS[i],
+ type(stringsToType[i]);
+ assertEquals("double space processing", expectedResults[i],
mEditText.getText().toString());
}
}
- public void testCancelDoubleSpace() {
+ public void testCancelDoubleSpaceEnglish() {
+ final String STRING_TO_TYPE = "this ";
+ final String EXPECTED_RESULT = "this ";
+ type(STRING_TO_TYPE);
+ type(Constants.CODE_DELETE);
+ assertEquals("double space make a period", EXPECTED_RESULT, mEditText.getText().toString());
+ }
+
+ public void testCancelDoubleSpaceHindi() {
+ changeLanguage("hi");
final String STRING_TO_TYPE = "this ";
final String EXPECTED_RESULT = "this ";
type(STRING_TO_TYPE);
@@ -265,9 +304,9 @@ public class InputLogicTests extends InputTestsBase {
public void testDoubleSpacePeriod() {
// Reset settings to default, else these tests will go flaky.
setBooleanPreference(Settings.PREF_SHOW_SUGGESTIONS, true, true);
- setStringPreference(Settings.PREF_AUTO_CORRECTION_THRESHOLD, "1", "1");
+ setBooleanPreference(Settings.PREF_AUTO_CORRECTION, true, true);
setBooleanPreference(Settings.PREF_KEY_USE_DOUBLE_SPACE_PERIOD, true, true);
- testDoubleSpacePeriodWithSettings(true /* expectsPeriod */);
+ testDoubleSpacePeriodWithSettings(true);
// "Suggestion visibility" to off
testDoubleSpacePeriodWithSettings(true, Settings.PREF_SHOW_SUGGESTIONS, false);
// "Suggestion visibility" to on
@@ -277,18 +316,16 @@ public class InputLogicTests extends InputTestsBase {
testDoubleSpacePeriodWithSettings(false, Settings.PREF_KEY_USE_DOUBLE_SPACE_PERIOD, false);
// "Auto-correction" to "off"
- testDoubleSpacePeriodWithSettings(true, Settings.PREF_AUTO_CORRECTION_THRESHOLD, "0");
- // "Auto-correction" to "modest"
- testDoubleSpacePeriodWithSettings(true, Settings.PREF_AUTO_CORRECTION_THRESHOLD, "1");
- // "Auto-correction" to "very aggressive"
- testDoubleSpacePeriodWithSettings(true, Settings.PREF_AUTO_CORRECTION_THRESHOLD, "3");
+ testDoubleSpacePeriodWithSettings(true, Settings.PREF_AUTO_CORRECTION, false);
+ // "Auto-correction" to "on"
+ testDoubleSpacePeriodWithSettings(true, Settings.PREF_AUTO_CORRECTION, true);
// "Suggestion visibility" to "always hide" and "Auto-correction" to "off"
testDoubleSpacePeriodWithSettings(true, Settings.PREF_SHOW_SUGGESTIONS, false,
- Settings.PREF_AUTO_CORRECTION_THRESHOLD, "0");
+ Settings.PREF_AUTO_CORRECTION, false);
// "Suggestion visibility" to "always hide" and "Auto-correction" to "off"
testDoubleSpacePeriodWithSettings(false, Settings.PREF_SHOW_SUGGESTIONS, false,
- Settings.PREF_AUTO_CORRECTION_THRESHOLD, "0",
+ Settings.PREF_AUTO_CORRECTION, false,
Settings.PREF_KEY_USE_DOUBLE_SPACE_PERIOD, false);
}
@@ -449,38 +486,19 @@ public class InputLogicTests extends InputTestsBase {
type(" ");
helperTestComposing("a'", true);
}
+
// TODO: Add some tests for non-BMP characters
public void testAutoCorrectByUserHistory() {
- final String WORD_TO_BE_CORRECTED = "qpmx";
- final String NOT_CORRECTED_RESULT = "qpmx ";
- final String DESIRED_WORD = "qpmz";
- final String CORRECTED_RESULT = "qpmz ";
- final int typeCountNotToAutocorrect = 1;
- final int typeCountToAutoCorrect = 16;
- int startIndex = 0;
- int endIndex = 0;
-
- for (int i = 0; i < typeCountNotToAutocorrect; i++) {
- type(DESIRED_WORD);
- type(Constants.CODE_SPACE);
- }
- startIndex = mEditText.getText().length();
- type(WORD_TO_BE_CORRECTED);
+ type("qpmz");
type(Constants.CODE_SPACE);
- endIndex = mEditText.getText().length();
- assertEquals("not auto-corrected by user history", NOT_CORRECTED_RESULT,
- mEditText.getText().subSequence(startIndex, endIndex).toString());
- for (int i = typeCountNotToAutocorrect; i < typeCountToAutoCorrect; i++) {
- type(DESIRED_WORD);
- type(Constants.CODE_SPACE);
- }
- startIndex = mEditText.getText().length();
- type(WORD_TO_BE_CORRECTED);
+
+ int startIndex = mEditText.getText().length();
+ type("qpmx");
type(Constants.CODE_SPACE);
- endIndex = mEditText.getText().length();
+ int endIndex = mEditText.getText().length();
assertEquals("auto-corrected by user history",
- CORRECTED_RESULT, mEditText.getText().subSequence(startIndex, endIndex).toString());
+ "qpmz ", mEditText.getText().subSequence(startIndex, endIndex).toString());
}
public void testPredictionsAfterSpace() {
@@ -496,26 +514,19 @@ public class InputLogicTests extends InputTestsBase {
public void testPredictionsWithDoubleSpaceToPeriod() {
mLatinIME.clearPersonalizedDictionariesForTest();
- final String WORD_TO_TYPE = "Barack ";
+ final String WORD_TO_TYPE = "Barack ";
type(WORD_TO_TYPE);
sleep(DELAY_TO_WAIT_FOR_PREDICTIONS_MILLIS);
runMessages();
- // No need to test here, testPredictionsAfterSpace is testing it already
- type(" ");
- sleep(DELAY_TO_WAIT_FOR_PREDICTIONS_MILLIS);
- runMessages();
- // Corrections have been replaced with predictions.
- SuggestedWords suggestedWords = mLatinIME.getSuggestedWordsForTest();
- String word = suggestedWords == null ? null : suggestedWords.getWord(0);
- assertTrue("predictions after double-space-to-period is I or The",
- "I".equals(word) || "The".equals(word));
+
type(Constants.CODE_DELETE);
sleep(DELAY_TO_WAIT_FOR_PREDICTIONS_MILLIS);
runMessages();
- // Test the first prediction is displayed
+
+ SuggestedWords suggestedWords = mLatinIME.getSuggestedWordsForTest();
suggestedWords = mLatinIME.getSuggestedWordsForTest();
assertEquals("predictions after cancel double-space-to-period", "Obama",
- suggestedWords.size() > 0 ? suggestedWords.getWord(0) : null);
+ mLatinIME.getSuggestedWordsForTest().getWord(0));
}
public void testPredictionsAfterManualPick() {
@@ -531,6 +542,17 @@ public class InputLogicTests extends InputTestsBase {
suggestedWords.size() > 0 ? suggestedWords.getWord(0) : null);
}
+ public void testPredictionsAfterPeriod() {
+ mLatinIME.clearPersonalizedDictionariesForTest();
+ final String WORD_TO_TYPE = "Barack. ";
+ type(WORD_TO_TYPE);
+ sleep(DELAY_TO_WAIT_FOR_PREDICTIONS_MILLIS);
+ runMessages();
+
+ SuggestedWords suggestedWords = mLatinIME.getSuggestedWordsForTest();
+ assertFalse(mLatinIME.getSuggestedWordsForTest().isEmpty());
+ }
+
public void testPredictionsAfterRecorrection() {
final String PREFIX = "A ";
final String WORD_TO_TYPE = "Barack";
@@ -641,13 +663,13 @@ public class InputLogicTests extends InputTestsBase {
public void testBasicGesture() {
gesture("this");
- assertEquals("gesture \"this\"", "this", mEditText.getText().toString());
+ assertEquals("this", mEditText.getText().toString());
}
public void testGestureGesture() {
- gesture("this");
- gesture("is");
- assertEquals("gesture \"this is\"", "this is", mEditText.getText().toString());
+ gesture("got");
+ gesture("milk");
+ assertEquals("got milk", mEditText.getText().toString());
}
public void testGestureBackspaceGestureAgain() {
@@ -655,8 +677,11 @@ public class InputLogicTests extends InputTestsBase {
type(Constants.CODE_DELETE);
assertEquals("gesture then backspace", "", mEditText.getText().toString());
gesture("this");
- MoreAsserts.assertNotEqual("gesture twice the same thing", "this",
- mEditText.getText().toString());
+ if (DecoderSpecificConstants.SHOULD_REMOVE_PREVIOUSLY_REJECTED_SUGGESTION) {
+ assertNotEqual("this", mEditText.getText().toString());
+ } else {
+ assertEquals("this", mEditText.getText().toString());
+ }
}
private void typeOrGestureWordAndPutCursorInside(final boolean gesture, final String word,
@@ -673,8 +698,6 @@ public class InputLogicTests extends InputTestsBase {
sendUpdateForCursorMoveTo(NEW_CURSOR_POSITION);
sleep(DELAY_TO_WAIT_FOR_UNDERLINE_MILLIS);
runMessages();
- ensureComposingSpanPos("move cursor inside word leaves composing span in the right place",
- startPos, END_OF_WORD);
}
private void typeWordAndPutCursorInside(final String word, final int startPos) {
@@ -704,7 +727,7 @@ public class InputLogicTests extends InputTestsBase {
assertEquals("mbo", "some thing ", mEditText.getText().toString());
typeWordAndPutCursorInside(WORD_TO_TYPE, cursorPos + 1 /* startPos */);
type(Constants.CODE_DELETE);
- ensureComposingSpanPos("space while in the middle of a word cancels composition", -1, -1);
+ ensureComposingSpanPos("delete while in the middle of a word cancels composition", -1, -1);
}
public void testTypeWithinGestureComposing() {
@@ -720,15 +743,15 @@ public class InputLogicTests extends InputTestsBase {
type(" ");
typeWordAndPutCursorInside(WORD_TO_TYPE, cursorPos + 1 /* startPos */);
type(Constants.CODE_DELETE);
- ensureComposingSpanPos("space while in the middle of a word cancels composition", -1, -1);
+ ensureComposingSpanPos("delete while in the middle of a word cancels composition", -1, -1);
}
public void testAutoCorrectForFrench() {
final String STRING_TO_TYPE = "irq ";
- final String EXPECTED_RESULT = "ira ";
- changeLanguage("fr");
+ final String EXPECTED_RESULT = "ir a ";
+ changeLanguage("es");
type(STRING_TO_TYPE);
- assertEquals("simple auto-correct for French", EXPECTED_RESULT,
+ assertEquals("simple auto-correct for Spanish", EXPECTED_RESULT,
mEditText.getText().toString());
}
@@ -758,6 +781,8 @@ public class InputLogicTests extends InputTestsBase {
}
public void testWordThenSpaceThenPunctuationFromStripTwiceForFrench() {
+ setBooleanPreference(Settings.PREF_BIGRAM_PREDICTIONS, false, true);
+
final String WORD_TO_TYPE = "test ";
final String PUNCTUATION_FROM_STRIP = "!";
final String EXPECTED_RESULT = "test !!";
@@ -802,32 +827,4 @@ public class InputLogicTests extends InputTestsBase {
assertEquals("auto-correct with umlaut for German", EXPECTED_RESULT,
mEditText.getText().toString());
}
-
- // Corresponds to InputLogicTests#testDoubleSpace
- public void testDoubleSpaceHindi() {
- changeLanguage("hi");
- // Set default pref just in case
- setBooleanPreference(Settings.PREF_KEY_USE_DOUBLE_SPACE_PERIOD, true, true);
- // U+1F607 is an emoji
- final String[] STRINGS_TO_TYPE =
- new String[] { "this ", "a+ ", "\u1F607 ", "|| ", ") ", "( ", "% " };
- final String[] EXPECTED_RESULTS =
- new String[] { "this| ", "a+| ", "\u1F607| ", "|| ", ")| ", "( ", "%| " };
- for (int i = 0; i < STRINGS_TO_TYPE.length; ++i) {
- mEditText.setText("");
- type(STRINGS_TO_TYPE[i]);
- assertEquals("double space processing", EXPECTED_RESULTS[i],
- mEditText.getText().toString());
- }
- }
-
- // Corresponds to InputLogicTests#testCancelDoubleSpace
- public void testCancelDoubleSpaceHindi() {
- changeLanguage("hi");
- final String STRING_TO_TYPE = "this ";
- final String EXPECTED_RESULT = "this ";
- type(STRING_TO_TYPE);
- type(Constants.CODE_DELETE);
- assertEquals("double space make a period", EXPECTED_RESULT, mEditText.getText().toString());
- }
}
diff --git a/tests/src/com/android/inputmethod/latin/InputTestsBase.java b/tests/src/com/android/inputmethod/latin/InputTestsBase.java
index ea7823c64..0d9b36ac0 100644
--- a/tests/src/com/android/inputmethod/latin/InputTestsBase.java
+++ b/tests/src/com/android/inputmethod/latin/InputTestsBase.java
@@ -58,7 +58,7 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> {
// Default value for auto-correction threshold. This is the string representation of the
// index in the resources array of auto-correction threshold settings.
- private static final String DEFAULT_AUTO_CORRECTION_THRESHOLD = "1";
+ private static final boolean DEFAULT_AUTO_CORRECTION = true;
// The message that sets the underline is posted with a 500 ms delay
protected static final int DELAY_TO_WAIT_FOR_UNDERLINE_MILLIS = 500;
@@ -77,7 +77,8 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> {
protected MyEditText mEditText;
protected View mInputView;
protected InputConnection mInputConnection;
- private String mPreviousAutoCorrectSetting;
+ private boolean mPreviousAutoCorrectSetting;
+ private boolean mPreviousBigramPredictionSettings;
// A helper class to ease span tests
public static class SpanGetter {
@@ -163,6 +164,11 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> {
return previousSetting;
}
+ protected boolean getBooleanPreference(final String key, final boolean defaultValue) {
+ return PreferenceManager.getDefaultSharedPreferences(mLatinIME)
+ .getBoolean(key, defaultValue);
+ }
+
protected String setStringPreference(final String key, final String value,
final String defaultValue) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mLatinIME);
@@ -200,8 +206,10 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> {
setupService();
mLatinIME = getService();
setDebugMode(true);
- mPreviousAutoCorrectSetting = setStringPreference(Settings.PREF_AUTO_CORRECTION_THRESHOLD,
- DEFAULT_AUTO_CORRECTION_THRESHOLD, DEFAULT_AUTO_CORRECTION_THRESHOLD);
+ mPreviousBigramPredictionSettings = setBooleanPreference(Settings.PREF_BIGRAM_PREDICTIONS,
+ true, true /* defaultValue */);
+ mPreviousAutoCorrectSetting = setBooleanPreference(Settings.PREF_AUTO_CORRECTION,
+ DEFAULT_AUTO_CORRECTION, DEFAULT_AUTO_CORRECTION);
mLatinIME.onCreate();
EditorInfo ei = new EditorInfo();
final InputConnection ic = mEditText.onCreateInputConnection(ei);
@@ -230,8 +238,10 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> {
mLatinIME.onFinishInput();
runMessages();
mLatinIME.mHandler.removeAllMessages();
- setStringPreference(Settings.PREF_AUTO_CORRECTION_THRESHOLD, mPreviousAutoCorrectSetting,
- DEFAULT_AUTO_CORRECTION_THRESHOLD);
+ setBooleanPreference(Settings.PREF_BIGRAM_PREDICTIONS, mPreviousBigramPredictionSettings,
+ true /* defaultValue */);
+ setBooleanPreference(Settings.PREF_AUTO_CORRECTION, mPreviousAutoCorrectSetting,
+ DEFAULT_AUTO_CORRECTION);
setDebugMode(false);
mLatinIME.recycle();
super.tearDown();
@@ -399,7 +409,8 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> {
}
protected void pickSuggestionManually(final String suggestion) {
- mLatinIME.pickSuggestionManually(new SuggestedWordInfo(suggestion, 1,
+ mLatinIME.pickSuggestionManually(new SuggestedWordInfo(suggestion,
+ "" /* prevWordsContext */, 1 /* score */,
SuggestedWordInfo.KIND_CORRECTION, DICTIONARY_TEST,
SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */));
diff --git a/tests/src/com/android/inputmethod/latin/NgramContextTests.java b/tests/src/com/android/inputmethod/latin/NgramContextTests.java
index 7749bff63..0a662db82 100644
--- a/tests/src/com/android/inputmethod/latin/NgramContextTests.java
+++ b/tests/src/com/android/inputmethod/latin/NgramContextTests.java
@@ -17,6 +17,8 @@
package com.android.inputmethod.latin;
import com.android.inputmethod.latin.NgramContext.WordInfo;
+import com.android.inputmethod.latin.settings.SpacingAndPunctuations;
+import com.android.inputmethod.latin.utils.NgramContextUtils;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
@@ -120,4 +122,24 @@ public class NgramContextTests extends AndroidTestCase {
assertEquals(1, ngramContext_a_empty.extractPrevWordsContextArray().length);
assertEquals("a", ngramContext_a_empty.extractPrevWordsContextArray()[0]);
}
+
+ public void testGetNgramContextFromNthPreviousWord() {
+ SpacingAndPunctuations spacingAndPunctuations = new SpacingAndPunctuations(
+ mContext.getResources());
+ assertEquals("<S>", NgramContextUtils.getNgramContextFromNthPreviousWord("",
+ spacingAndPunctuations, 1).extractPrevWordsContext());
+ assertEquals("<S> b", NgramContextUtils.getNgramContextFromNthPreviousWord("a. b ",
+ spacingAndPunctuations, 1).extractPrevWordsContext());
+ assertEquals("<S> b", NgramContextUtils.getNgramContextFromNthPreviousWord("a? b ",
+ spacingAndPunctuations, 1).extractPrevWordsContext());
+ assertEquals("<S> b", NgramContextUtils.getNgramContextFromNthPreviousWord("a! b ",
+ spacingAndPunctuations, 1).extractPrevWordsContext());
+ assertEquals("<S> b", NgramContextUtils.getNgramContextFromNthPreviousWord("a\nb ",
+ spacingAndPunctuations, 1).extractPrevWordsContext());
+ assertEquals("<S> a b", NgramContextUtils.getNgramContextFromNthPreviousWord("a b ",
+ spacingAndPunctuations, 1).extractPrevWordsContext());
+ assertFalse(NgramContextUtils
+ .getNgramContextFromNthPreviousWord("a b c d e", spacingAndPunctuations, 1)
+ .extractPrevWordsContext().startsWith("<S>"));
+ }
}
diff --git a/tests/src/com/android/inputmethod/latin/PunctuationTests.java b/tests/src/com/android/inputmethod/latin/PunctuationTests.java
index 9ac220407..3537918de 100644
--- a/tests/src/com/android/inputmethod/latin/PunctuationTests.java
+++ b/tests/src/com/android/inputmethod/latin/PunctuationTests.java
@@ -19,23 +19,37 @@ package com.android.inputmethod.latin;
import android.provider.Settings.Secure;
import android.test.suitebuilder.annotation.LargeTest;
+import com.android.inputmethod.latin.R;
+
@LargeTest
public class PunctuationTests extends InputTestsBase {
+ final String NEXT_WORD_PREDICTION_OPTION = "next_word_prediction";
+
public void testWordThenSpaceThenPunctuationFromStripTwice() {
final String WORD_TO_TYPE = "this ";
final String PUNCTUATION_FROM_STRIP = "!";
final String EXPECTED_RESULT = "this!! ";
- mLatinIME.loadSettings();
- type(WORD_TO_TYPE);
- sleep(DELAY_TO_WAIT_FOR_UNDERLINE_MILLIS);
- runMessages();
- assertTrue("type word then type space should display punctuation strip",
- mLatinIME.getSuggestedWordsForTest().isPunctuationSuggestions());
- pickSuggestionManually(PUNCTUATION_FROM_STRIP);
- pickSuggestionManually(PUNCTUATION_FROM_STRIP);
- assertEquals("type word then type space then punctuation from strip twice",
- EXPECTED_RESULT, mEditText.getText().toString());
+ final boolean defaultNextWordPredictionOption =
+ mLatinIME.getResources().getBoolean(R.bool.config_default_next_word_prediction);
+ final boolean previousNextWordPredictionOption =
+ setBooleanPreference(NEXT_WORD_PREDICTION_OPTION, false,
+ defaultNextWordPredictionOption);
+ try {
+ mLatinIME.loadSettings();
+ type(WORD_TO_TYPE);
+ sleep(DELAY_TO_WAIT_FOR_UNDERLINE_MILLIS);
+ runMessages();
+ assertTrue("type word then type space should display punctuation strip",
+ mLatinIME.getSuggestedWordsForTest().isPunctuationSuggestions());
+ pickSuggestionManually(PUNCTUATION_FROM_STRIP);
+ pickSuggestionManually(PUNCTUATION_FROM_STRIP);
+ assertEquals("type word then type space then punctuation from strip twice",
+ EXPECTED_RESULT, mEditText.getText().toString());
+ } finally {
+ setBooleanPreference(NEXT_WORD_PREDICTION_OPTION, previousNextWordPredictionOption,
+ defaultNextWordPredictionOption);
+ }
}
public void testWordThenSpaceThenPunctuationFromKeyboardTwice() {
diff --git a/tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java b/tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java
index 8614ccc0e..08779b9d3 100644
--- a/tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java
+++ b/tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java
@@ -206,10 +206,14 @@ public class RichInputConnectionAndTextRangeTests extends AndroidTestCase {
"abc def .", mSpacingAndPunctuations, 1), NgramContext.BEGINNING_OF_SENTENCE);
assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord(
"abc, def", mSpacingAndPunctuations, 2), NgramContext.EMPTY_PREV_WORDS_INFO);
+ // question mark is treated as the end of the sentence. Hence, beginning of the
+ // sentence is expected.
assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord(
- "abc? def", mSpacingAndPunctuations, 2), NgramContext.EMPTY_PREV_WORDS_INFO);
+ "abc? def", mSpacingAndPunctuations, 2), NgramContext.BEGINNING_OF_SENTENCE);
+ // Exclamation mark is treated as the end of the sentence. Hence, beginning of the
+ // sentence is expected.
assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord(
- "abc! def", mSpacingAndPunctuations, 2), NgramContext.EMPTY_PREV_WORDS_INFO);
+ "abc! def", mSpacingAndPunctuations, 2), NgramContext.BEGINNING_OF_SENTENCE);
assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord(
"abc 'def", mSpacingAndPunctuations, 2), NgramContext.EMPTY_PREV_WORDS_INFO);
}
diff --git a/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java b/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java
index 657cec8d7..d465ce674 100644
--- a/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java
+++ b/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java
@@ -37,7 +37,7 @@ public class SuggestedWordsTests extends AndroidTestCase {
private static SuggestedWordInfo createTypedWordInfo(final String word) {
// Use 100 as the frequency because the numerical value does not matter as
// long as it's > 1 and < INT_MAX.
- return new SuggestedWordInfo(word, 100 /* score */,
+ return new SuggestedWordInfo(word, "" /* prevWordsContext */, 100 /* score */,
SuggestedWordInfo.KIND_TYPED,
null /* sourceDict */,
SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
@@ -52,7 +52,7 @@ public class SuggestedWordsTests extends AndroidTestCase {
* @return a new instance of {@link SuggestedWordInfo}.
*/
private static SuggestedWordInfo createCorrectionWordInfo(final String word) {
- return new SuggestedWordInfo(word, 1 /* score */,
+ return new SuggestedWordInfo(word, "" /* prevWordsContext */, 1 /* score */,
SuggestedWordInfo.KIND_CORRECTION,
null /* sourceDict */,
SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */,
diff --git a/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java b/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java
index a432ca740..da1b32a8b 100644
--- a/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java
+++ b/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java
@@ -43,22 +43,12 @@ public final class BinaryDictIOUtils {
*/
public static DictDecoder getDictDecoder(final File dictFile, final long offset,
final long length, final int bufferType) {
- if (dictFile.isDirectory()) {
- return new Ver4DictDecoder(dictFile);
- } else if (dictFile.isFile()) {
- return new Ver2DictDecoder(dictFile, offset, length, bufferType);
- }
- return null;
+ return new Ver4DictDecoder(dictFile);
}
public static DictDecoder getDictDecoder(final File dictFile, final long offset,
final long length, final DictionaryBufferFactory factory) {
- if (dictFile.isDirectory()) {
- return new Ver4DictDecoder(dictFile);
- } else if (dictFile.isFile()) {
- return new Ver2DictDecoder(dictFile, offset, length, factory);
- }
- return null;
+ return new Ver4DictDecoder(dictFile);
}
public static DictDecoder getDictDecoder(final File dictFile, final long offset,
diff --git a/tests/src/com/android/inputmethod/latin/makedict/Ver2DictDecoder.java b/tests/src/com/android/inputmethod/latin/makedict/Ver2DictDecoder.java
deleted file mode 100644
index 7ee1df92b..000000000
--- a/tests/src/com/android/inputmethod/latin/makedict/Ver2DictDecoder.java
+++ /dev/null
@@ -1,319 +0,0 @@
-/*
- * 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.makedict;
-
-import com.android.inputmethod.annotations.UsedForTesting;
-import com.android.inputmethod.latin.BinaryDictionary;
-import com.android.inputmethod.latin.makedict.BinaryDictDecoderUtils.CharEncoding;
-import com.android.inputmethod.latin.makedict.BinaryDictDecoderUtils.DictBuffer;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-/**
- * An implementation of DictDecoder for version 2 binary dictionary.
- */
-// TODO: Separate logics that are used only for testing.
-@UsedForTesting
-public class Ver2DictDecoder extends AbstractDictDecoder {
- /**
- * A utility class for reading a PtNode.
- */
- static class PtNodeReader {
- static ProbabilityInfo readProbabilityInfo(final DictBuffer dictBuffer) {
- // Ver2 dicts don't contain historical information.
- return new ProbabilityInfo(dictBuffer.readUnsignedByte());
- }
-
- static int readPtNodeOptionFlags(final DictBuffer dictBuffer) {
- return dictBuffer.readUnsignedByte();
- }
-
- static int readChildrenAddress(final DictBuffer dictBuffer,
- final int ptNodeFlags) {
- switch (ptNodeFlags & FormatSpec.MASK_CHILDREN_ADDRESS_TYPE) {
- case FormatSpec.FLAG_CHILDREN_ADDRESS_TYPE_ONEBYTE:
- return dictBuffer.readUnsignedByte();
- case FormatSpec.FLAG_CHILDREN_ADDRESS_TYPE_TWOBYTES:
- return dictBuffer.readUnsignedShort();
- case FormatSpec.FLAG_CHILDREN_ADDRESS_TYPE_THREEBYTES:
- return dictBuffer.readUnsignedInt24();
- case FormatSpec.FLAG_CHILDREN_ADDRESS_TYPE_NOADDRESS:
- default:
- return FormatSpec.NO_CHILDREN_ADDRESS;
- }
- }
-
- // Reads shortcuts and returns the read length.
- static int readShortcut(final DictBuffer dictBuffer,
- final ArrayList<WeightedString> shortcutTargets) {
- final int pointerBefore = dictBuffer.position();
- dictBuffer.readUnsignedShort(); // skip the size
- while (true) {
- final int targetFlags = dictBuffer.readUnsignedByte();
- final String word = CharEncoding.readString(dictBuffer);
- shortcutTargets.add(new WeightedString(word,
- targetFlags & FormatSpec.FLAG_BIGRAM_SHORTCUT_ATTR_FREQUENCY));
- if (0 == (targetFlags & FormatSpec.FLAG_BIGRAM_SHORTCUT_ATTR_HAS_NEXT)) break;
- }
- return dictBuffer.position() - pointerBefore;
- }
-
- static int readBigramAddresses(final DictBuffer dictBuffer,
- final ArrayList<PendingAttribute> bigrams, final int baseAddress) {
- int readLength = 0;
- int bigramCount = 0;
- while (bigramCount++ < FormatSpec.MAX_BIGRAMS_IN_A_PTNODE) {
- final int bigramFlags = dictBuffer.readUnsignedByte();
- ++readLength;
- final int sign = 0 == (bigramFlags & FormatSpec.FLAG_BIGRAM_ATTR_OFFSET_NEGATIVE)
- ? 1 : -1;
- int bigramAddress = baseAddress + readLength;
- switch (bigramFlags & FormatSpec.MASK_BIGRAM_ATTR_ADDRESS_TYPE) {
- case FormatSpec.FLAG_BIGRAM_ATTR_ADDRESS_TYPE_ONEBYTE:
- bigramAddress += sign * dictBuffer.readUnsignedByte();
- readLength += 1;
- break;
- case FormatSpec.FLAG_BIGRAM_ATTR_ADDRESS_TYPE_TWOBYTES:
- bigramAddress += sign * dictBuffer.readUnsignedShort();
- readLength += 2;
- break;
- case FormatSpec.FLAG_BIGRAM_ATTR_ADDRESS_TYPE_THREEBYTES:
- bigramAddress += sign * dictBuffer.readUnsignedInt24();
- readLength += 3;
- break;
- default:
- throw new RuntimeException("Has bigrams with no address");
- }
- bigrams.add(new PendingAttribute(
- bigramFlags & FormatSpec.FLAG_BIGRAM_SHORTCUT_ATTR_FREQUENCY,
- bigramAddress));
- if (0 == (bigramFlags & FormatSpec.FLAG_BIGRAM_SHORTCUT_ATTR_HAS_NEXT)) break;
- }
- return readLength;
- }
- }
-
- protected final File mDictionaryBinaryFile;
- protected final long mOffset;
- protected final long mLength;
- // TODO: Remove mBufferFactory and mDictBuffer from this class members because they are now
- // used only for testing.
- private final DictionaryBufferFactory mBufferFactory;
- protected DictBuffer mDictBuffer;
-
- @UsedForTesting
- /* package */ Ver2DictDecoder(final File file, final long offset, final long length,
- final int factoryFlag) {
- mDictionaryBinaryFile = file;
- mOffset = offset;
- mLength = length;
- mDictBuffer = null;
- if ((factoryFlag & MASK_DICTBUFFER) == USE_READONLY_BYTEBUFFER) {
- mBufferFactory = new DictionaryBufferFromReadOnlyByteBufferFactory();
- } else if ((factoryFlag & MASK_DICTBUFFER) == USE_BYTEARRAY) {
- mBufferFactory = new DictionaryBufferFromByteArrayFactory();
- } else if ((factoryFlag & MASK_DICTBUFFER) == USE_WRITABLE_BYTEBUFFER) {
- mBufferFactory = new DictionaryBufferFromWritableByteBufferFactory();
- } else {
- mBufferFactory = new DictionaryBufferFromReadOnlyByteBufferFactory();
- }
- }
-
- /* package */ Ver2DictDecoder(final File file, final long offset, final long length,
- final DictionaryBufferFactory factory) {
- mDictionaryBinaryFile = file;
- mOffset = offset;
- mLength = length;
- mBufferFactory = factory;
- }
-
- @Override
- public void openDictBuffer() throws FileNotFoundException, IOException {
- mDictBuffer = mBufferFactory.getDictionaryBuffer(mDictionaryBinaryFile);
- }
-
- @Override
- public boolean isDictBufferOpen() {
- return mDictBuffer != null;
- }
-
- /* package */ DictBuffer getDictBuffer() {
- return mDictBuffer;
- }
-
- @UsedForTesting
- /* package */ DictBuffer openAndGetDictBuffer() throws FileNotFoundException, IOException {
- openDictBuffer();
- return getDictBuffer();
- }
-
- @Override
- public DictionaryHeader readHeader() throws IOException, UnsupportedFormatException {
- // dictType is not being used in dicttool. Passing an empty string.
- final BinaryDictionary binaryDictionary = new BinaryDictionary(
- mDictionaryBinaryFile.getAbsolutePath(), mOffset, mLength,
- true /* useFullEditDistance */, null /* locale */, "" /* dictType */,
- false /* isUpdatable */);
- final DictionaryHeader header = binaryDictionary.getHeader();
- binaryDictionary.close();
- if (header == null) {
- throw new IOException("Cannot read the dictionary header.");
- }
- if (header.mFormatOptions.mVersion != FormatSpec.VERSION2 &&
- header.mFormatOptions.mVersion != FormatSpec.VERSION201 &&
- header.mFormatOptions.mVersion != FormatSpec.VERSION202) {
- throw new UnsupportedFormatException("File header has a wrong version : "
- + header.mFormatOptions.mVersion);
- }
- if (!isDictBufferOpen()) {
- openDictBuffer();
- }
- // Advance buffer reading position to the head of dictionary body.
- setPosition(header.mBodyOffset);
- return header;
- }
-
- // TODO: Make this buffer multi thread safe.
- private final int[] mCharacterBuffer = new int[FormatSpec.MAX_WORD_LENGTH];
- @Override
- public PtNodeInfo readPtNode(final int ptNodePos) {
- int addressPointer = ptNodePos;
- final int flags = PtNodeReader.readPtNodeOptionFlags(mDictBuffer);
- addressPointer += FormatSpec.PTNODE_FLAGS_SIZE;
- final int characters[];
- if (0 != (flags & FormatSpec.FLAG_HAS_MULTIPLE_CHARS)) {
- int index = 0;
- int character = CharEncoding.readChar(mDictBuffer);
- addressPointer += CharEncoding.getCharSize(character, null);
- while (FormatSpec.INVALID_CHARACTER != character) {
- // FusionDictionary is making sure that the length of the word is smaller than
- // MAX_WORD_LENGTH.
- // So we'll never write past the end of mCharacterBuffer.
- mCharacterBuffer[index++] = character;
- character = CharEncoding.readChar(mDictBuffer);
- addressPointer += CharEncoding.getCharSize(character, null);
- }
- characters = Arrays.copyOfRange(mCharacterBuffer, 0, index);
- } else {
- final int character = CharEncoding.readChar(mDictBuffer);
- addressPointer += CharEncoding.getCharSize(character, null);
- characters = new int[] { character };
- }
- final ProbabilityInfo probabilityInfo;
- if (0 != (FormatSpec.FLAG_IS_TERMINAL & flags)) {
- probabilityInfo = PtNodeReader.readProbabilityInfo(mDictBuffer);
- addressPointer += FormatSpec.PTNODE_FREQUENCY_SIZE;
- } else {
- probabilityInfo = null;
- }
- int childrenAddress = PtNodeReader.readChildrenAddress(mDictBuffer, flags);
- if (childrenAddress != FormatSpec.NO_CHILDREN_ADDRESS) {
- childrenAddress += addressPointer;
- }
- addressPointer += BinaryDictIOUtils.getChildrenAddressSize(flags);
- final ArrayList<WeightedString> shortcutTargets;
- if (0 != (flags & FormatSpec.FLAG_HAS_SHORTCUT_TARGETS)) {
- // readShortcut will add shortcuts to shortcutTargets.
- shortcutTargets = new ArrayList<>();
- addressPointer += PtNodeReader.readShortcut(mDictBuffer, shortcutTargets);
- } else {
- shortcutTargets = null;
- }
-
- final ArrayList<PendingAttribute> bigrams;
- if (0 != (flags & FormatSpec.FLAG_HAS_BIGRAMS)) {
- bigrams = new ArrayList<>();
- addressPointer += PtNodeReader.readBigramAddresses(mDictBuffer, bigrams,
- addressPointer);
- if (bigrams.size() >= FormatSpec.MAX_BIGRAMS_IN_A_PTNODE) {
- throw new RuntimeException("Too many bigrams in a PtNode (" + bigrams.size()
- + " but max is " + FormatSpec.MAX_BIGRAMS_IN_A_PTNODE + ")");
- }
- } else {
- bigrams = null;
- }
- return new PtNodeInfo(ptNodePos, addressPointer, flags, characters, probabilityInfo,
- childrenAddress, shortcutTargets, bigrams);
- }
-
- @Override
- public FusionDictionary readDictionaryBinary(final boolean deleteDictIfBroken)
- throws FileNotFoundException, IOException, UnsupportedFormatException {
- // dictType is not being used in dicttool. Passing an empty string.
- final BinaryDictionary binaryDictionary = new BinaryDictionary(
- mDictionaryBinaryFile.getAbsolutePath(), 0 /* offset */,
- mDictionaryBinaryFile.length() /* length */, true /* useFullEditDistance */,
- null /* locale */, "" /* dictType */, false /* isUpdatable */);
- final DictionaryHeader header = readHeader();
- final FusionDictionary fusionDict =
- new FusionDictionary(new FusionDictionary.PtNodeArray(), header.mDictionaryOptions);
- int token = 0;
- final ArrayList<WordProperty> wordProperties = new ArrayList<>();
- do {
- final BinaryDictionary.GetNextWordPropertyResult result =
- binaryDictionary.getNextWordProperty(token);
- final WordProperty wordProperty = result.mWordProperty;
- if (wordProperty == null) {
- binaryDictionary.close();
- if (deleteDictIfBroken) {
- mDictionaryBinaryFile.delete();
- }
- return null;
- }
- wordProperties.add(wordProperty);
- token = result.mNextToken;
- } while (token != 0);
-
- // Insert unigrams into the fusion dictionary.
- for (final WordProperty wordProperty : wordProperties) {
- fusionDict.add(wordProperty.mWord, wordProperty.mProbabilityInfo,
- wordProperty.mIsNotAWord,
- wordProperty.mIsPossiblyOffensive);
- }
- // Insert bigrams into the fusion dictionary.
- for (final WordProperty wordProperty : wordProperties) {
- if (!wordProperty.mHasNgrams) {
- continue;
- }
- final String word0 = wordProperty.mWord;
- for (final WeightedString bigram : wordProperty.getBigrams()) {
- fusionDict.setBigram(word0, bigram.mWord, bigram.mProbabilityInfo);
- }
- }
- binaryDictionary.close();
- return fusionDict;
- }
-
- @Override
- public void setPosition(int newPos) {
- mDictBuffer.position(newPos);
- }
-
- @Override
- public int getPosition() {
- return mDictBuffer.position();
- }
-
- @Override
- public int readPtNodeCount() {
- return BinaryDictDecoderUtils.readPtNodeCount(mDictBuffer);
- }
-}
diff --git a/tests/src/com/android/inputmethod/latin/makedict/Ver2DictDecoderTests.java b/tests/src/com/android/inputmethod/latin/makedict/Ver2DictDecoderTests.java
deleted file mode 100644
index 3882c2c55..000000000
--- a/tests/src/com/android/inputmethod/latin/makedict/Ver2DictDecoderTests.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * 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.makedict;
-
-import com.android.inputmethod.latin.makedict.BinaryDictDecoderUtils.DictBuffer;
-import com.android.inputmethod.latin.makedict.DictDecoder.DictionaryBufferFactory;
-import com.android.inputmethod.latin.makedict.DictDecoder.DictionaryBufferFromByteArrayFactory;
-import com.android.inputmethod.latin.makedict.DictDecoder.
- DictionaryBufferFromReadOnlyByteBufferFactory;
-import com.android.inputmethod.latin.makedict.DictDecoder.
- DictionaryBufferFromWritableByteBufferFactory;
-
-import android.test.AndroidTestCase;
-import android.util.Log;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-/**
- * Unit tests for Ver2DictDecoder
- */
-public class Ver2DictDecoderTests extends AndroidTestCase {
- private static final String TAG = Ver2DictDecoderTests.class.getSimpleName();
-
- private final byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
-
- // Utilities for testing
- public void writeDataToFile(final File file) {
- FileOutputStream outStream = null;
- try {
- outStream = new FileOutputStream(file);
- outStream.write(data);
- } catch (IOException e) {
- fail ("Can't write data to the test file");
- } finally {
- if (outStream != null) {
- try {
- outStream.close();
- } catch (IOException e) {
- Log.e(TAG, "Failed to close the output stream", e);
- }
- }
- }
- }
-
- public void runTestOpenBuffer(final String testName, final DictionaryBufferFactory factory) {
- File testFile = null;
- try {
- testFile = File.createTempFile(testName, ".tmp", getContext().getCacheDir());
- } catch (IOException e) {
- Log.e(TAG, "IOException while the creating temporary file", e);
- }
-
- assertNotNull(testFile);
- final Ver2DictDecoder dictDecoder = new Ver2DictDecoder(testFile, 0, testFile.length(),
- factory);
- try {
- dictDecoder.openDictBuffer();
- } catch (Exception e) {
- Log.e(TAG, "Failed to open the buffer", e);
- }
-
- writeDataToFile(testFile);
-
- try {
- dictDecoder.openDictBuffer();
- } catch (Exception e) {
- Log.e(TAG, "Raised the exception while opening buffer", e);
- }
-
- assertEquals(testFile.length(), dictDecoder.getDictBuffer().capacity());
- }
-
- public void testOpenBufferWithByteBuffer() {
- runTestOpenBuffer("testOpenBufferWithByteBuffer",
- new DictionaryBufferFromReadOnlyByteBufferFactory());
- }
-
- public void testOpenBufferWithByteArray() {
- runTestOpenBuffer("testOpenBufferWithByteArray",
- new DictionaryBufferFromByteArrayFactory());
- }
-
- public void testOpenBufferWithWritableByteBuffer() {
- runTestOpenBuffer("testOpenBufferWithWritableByteBuffer",
- new DictionaryBufferFromWritableByteBufferFactory());
- }
-
- public void runTestGetBuffer(final String testName, final DictionaryBufferFactory factory) {
- File testFile = null;
- try {
- testFile = File.createTempFile(testName, ".tmp", getContext().getCacheDir());
- } catch (IOException e) {
- Log.e(TAG, "IOException while the creating temporary file", e);
- }
-
- final Ver2DictDecoder dictDecoder = new Ver2DictDecoder(testFile, 0, testFile.length(),
- factory);
-
- // the default return value of getBuffer() must be null.
- assertNull("the default return value of getBuffer() is not null",
- dictDecoder.getDictBuffer());
-
- writeDataToFile(testFile);
- assertTrue(testFile.exists());
- Log.d(TAG, "file length = " + testFile.length());
-
- DictBuffer dictBuffer = null;
- try {
- dictBuffer = dictDecoder.openAndGetDictBuffer();
- } catch (IOException e) {
- Log.e(TAG, "Failed to open and get the buffer", e);
- }
- assertNotNull("the buffer must not be null", dictBuffer);
-
- for (int i = 0; i < data.length; ++i) {
- assertEquals(data[i], dictBuffer.readUnsignedByte());
- }
- }
-
- public void testGetBufferWithByteBuffer() {
- runTestGetBuffer("testGetBufferWithByteBuffer",
- new DictionaryBufferFromReadOnlyByteBufferFactory());
- }
-
- public void testGetBufferWithByteArray() {
- runTestGetBuffer("testGetBufferWithByteArray",
- new DictionaryBufferFromByteArrayFactory());
- }
-
- public void testGetBufferWithWritableByteBuffer() {
- runTestGetBuffer("testGetBufferWithWritableByteBuffer",
- new DictionaryBufferFromWritableByteBufferFactory());
- }
-}
diff --git a/tests/src/com/android/inputmethod/latin/makedict/Ver2DictEncoder.java b/tests/src/com/android/inputmethod/latin/makedict/Ver2DictEncoder.java
deleted file mode 100644
index c63b972eb..000000000
--- a/tests/src/com/android/inputmethod/latin/makedict/Ver2DictEncoder.java
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * 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.makedict;
-
-import com.android.inputmethod.annotations.UsedForTesting;
-import com.android.inputmethod.latin.makedict.BinaryDictDecoderUtils.CharEncoding;
-import com.android.inputmethod.latin.makedict.BinaryDictEncoderUtils.CodePointTable;
-import com.android.inputmethod.latin.makedict.FormatSpec.FormatOptions;
-import com.android.inputmethod.latin.makedict.FusionDictionary.PtNode;
-import com.android.inputmethod.latin.makedict.FusionDictionary.PtNodeArray;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map.Entry;
-
-/**
- * An implementation of DictEncoder for version 2 binary dictionary.
- */
-@UsedForTesting
-public class Ver2DictEncoder implements DictEncoder {
-
- private final File mDictFile;
- private OutputStream mOutStream;
- private byte[] mBuffer;
- private int mPosition;
- private final int mCodePointTableMode;
- public static final int CODE_POINT_TABLE_OFF = 0;
- public static final int CODE_POINT_TABLE_ON = 1;
-
- @UsedForTesting
- public Ver2DictEncoder(final File dictFile, final int codePointTableMode) {
- mDictFile = dictFile;
- mOutStream = null;
- mBuffer = null;
- mCodePointTableMode = codePointTableMode;
- }
-
- // This constructor is used only by BinaryDictOffdeviceUtilsTests.
- // If you want to use this in the production code, you should consider keeping consistency of
- // the interface of Ver3DictDecoder by using factory.
- @UsedForTesting
- public Ver2DictEncoder(final OutputStream outStream) {
- mDictFile = null;
- mOutStream = outStream;
- mCodePointTableMode = CODE_POINT_TABLE_OFF;
- }
-
- private void openStream() throws FileNotFoundException {
- mOutStream = new FileOutputStream(mDictFile);
- }
-
- private void close() throws IOException {
- if (mOutStream != null) {
- mOutStream.close();
- mOutStream = null;
- }
- }
-
- // Package for testing
- static CodePointTable makeCodePointTable(final FusionDictionary dict) {
- final HashMap<Integer, Integer> codePointOccurrenceCounts = new HashMap<>();
- for (final WordProperty word : dict) {
- // Store per code point occurrence
- final String wordString = word.mWord;
- for (int i = 0; i < wordString.length(); ++i) {
- final int codePoint = Character.codePointAt(wordString, i);
- if (codePointOccurrenceCounts.containsKey(codePoint)) {
- codePointOccurrenceCounts.put(codePoint,
- codePointOccurrenceCounts.get(codePoint) + 1);
- } else {
- codePointOccurrenceCounts.put(codePoint, 1);
- }
- }
- }
- final ArrayList<Entry<Integer, Integer>> codePointOccurrenceArray =
- new ArrayList<>(codePointOccurrenceCounts.entrySet());
- // Descending order sort by occurrence (value side)
- Collections.sort(codePointOccurrenceArray, new Comparator<Entry<Integer, Integer>>() {
- @Override
- public int compare(final Entry<Integer, Integer> a, final Entry<Integer, Integer> b) {
- if (a.getValue() != b.getValue()) {
- return b.getValue().compareTo(a.getValue());
- }
- return b.getKey().compareTo(a.getKey());
- }
- });
- int currentCodePointTableIndex = FormatSpec.MINIMAL_ONE_BYTE_CHARACTER_VALUE;
- // Temporary map for writing of nodes
- final HashMap<Integer, Integer> codePointToOneByteCodeMap = new HashMap<>();
- for (final Entry<Integer, Integer> entry : codePointOccurrenceArray) {
- // Put a relation from the original code point to the one byte code.
- codePointToOneByteCodeMap.put(entry.getKey(), currentCodePointTableIndex);
- if (FormatSpec.MAXIMAL_ONE_BYTE_CHARACTER_VALUE < ++currentCodePointTableIndex) {
- break;
- }
- }
- // codePointToOneByteCodeMap for writing the trie
- // codePointOccurrenceArray for writing the header
- return new CodePointTable(codePointToOneByteCodeMap, codePointOccurrenceArray);
- }
-
- @Override
- public void writeDictionary(final FusionDictionary dict, final FormatOptions formatOptions)
- throws IOException, UnsupportedFormatException {
- // We no longer support anything but the latest version of v2.
- if (formatOptions.mVersion != FormatSpec.VERSION202) {
- throw new UnsupportedFormatException(
- "The given format options has wrong version number : "
- + formatOptions.mVersion);
- }
-
- if (mOutStream == null) {
- openStream();
- }
-
- // Make code point conversion table ordered by occurrence of code points
- // Version 201 or later have codePointTable
- final CodePointTable codePointTable;
- if (mCodePointTableMode == CODE_POINT_TABLE_OFF || formatOptions.mVersion
- < FormatSpec.MINIMUM_SUPPORTED_VERSION_OF_CODE_POINT_TABLE) {
- codePointTable = new CodePointTable();
- } else {
- codePointTable = makeCodePointTable(dict);
- }
-
- BinaryDictEncoderUtils.writeDictionaryHeader(mOutStream, dict, formatOptions,
- codePointTable.mCodePointOccurrenceArray);
-
- // Addresses are limited to 3 bytes, but since addresses can be relative to each node
- // array, the structure itself is not limited to 16MB. However, if it is over 16MB deciding
- // the order of the PtNode arrays becomes a quite complicated problem, because though the
- // dictionary itself does not have a size limit, each node array must still be within 16MB
- // of all its children and parents. As long as this is ensured, the dictionary file may
- // grow to any size.
-
- // Leave the choice of the optimal node order to the flattenTree function.
- MakedictLog.i("Flattening the tree...");
- ArrayList<PtNodeArray> flatNodes = BinaryDictEncoderUtils.flattenTree(dict.mRootNodeArray);
-
- MakedictLog.i("Computing addresses...");
- BinaryDictEncoderUtils.computeAddresses(dict, flatNodes,
- codePointTable.mCodePointToOneByteCodeMap);
- MakedictLog.i("Checking PtNode array...");
- if (MakedictLog.DBG) BinaryDictEncoderUtils.checkFlatPtNodeArrayList(flatNodes);
-
- // Create a buffer that matches the final dictionary size.
- final PtNodeArray lastNodeArray = flatNodes.get(flatNodes.size() - 1);
- final int bufferSize = lastNodeArray.mCachedAddressAfterUpdate + lastNodeArray.mCachedSize;
- mBuffer = new byte[bufferSize];
-
- MakedictLog.i("Writing file...");
-
- for (PtNodeArray nodeArray : flatNodes) {
- BinaryDictEncoderUtils.writePlacedPtNodeArray(dict, this, nodeArray,
- codePointTable.mCodePointToOneByteCodeMap);
- }
- if (MakedictLog.DBG) BinaryDictEncoderUtils.showStatistics(flatNodes);
- mOutStream.write(mBuffer, 0, mPosition);
-
- MakedictLog.i("Done");
- close();
- }
-
- @Override
- public void setPosition(final int position) {
- if (mBuffer == null || position < 0 || position >= mBuffer.length) return;
- mPosition = position;
- }
-
- @Override
- public int getPosition() {
- return mPosition;
- }
-
- @Override
- public void writePtNodeCount(final int ptNodeCount) {
- final int countSize = BinaryDictIOUtils.getPtNodeCountSize(ptNodeCount);
- if (countSize != 1 && countSize != 2) {
- throw new RuntimeException("Strange size from getGroupCountSize : " + countSize);
- }
- final int encodedPtNodeCount = (countSize == 2) ?
- (ptNodeCount | FormatSpec.LARGE_PTNODE_ARRAY_SIZE_FIELD_SIZE_FLAG) : ptNodeCount;
- mPosition = BinaryDictEncoderUtils.writeUIntToBuffer(mBuffer, mPosition, encodedPtNodeCount,
- countSize);
- }
-
- private void writePtNodeFlags(final PtNode ptNode,
- final HashMap<Integer, Integer> codePointToOneByteCodeMap) {
- final int childrenPos = BinaryDictEncoderUtils.getChildrenPosition(ptNode,
- codePointToOneByteCodeMap);
- mPosition = BinaryDictEncoderUtils.writeUIntToBuffer(mBuffer, mPosition,
- BinaryDictEncoderUtils.makePtNodeFlags(ptNode, childrenPos),
- FormatSpec.PTNODE_FLAGS_SIZE);
- }
-
- private void writeCharacters(final int[] codePoints, final boolean hasSeveralChars,
- final HashMap<Integer, Integer> codePointToOneByteCodeMap) {
- mPosition = CharEncoding.writeCharArray(codePoints, mBuffer, mPosition,
- codePointToOneByteCodeMap);
- if (hasSeveralChars) {
- mBuffer[mPosition++] = FormatSpec.PTNODE_CHARACTERS_TERMINATOR;
- }
- }
-
- private void writeFrequency(final int frequency) {
- if (frequency >= 0) {
- mPosition = BinaryDictEncoderUtils.writeUIntToBuffer(mBuffer, mPosition, frequency,
- FormatSpec.PTNODE_FREQUENCY_SIZE);
- }
- }
-
- private void writeChildrenPosition(final PtNode ptNode,
- final HashMap<Integer, Integer> codePointToOneByteCodeMap) {
- final int childrenPos = BinaryDictEncoderUtils.getChildrenPosition(ptNode,
- codePointToOneByteCodeMap);
- mPosition += BinaryDictEncoderUtils.writeChildrenPosition(mBuffer, mPosition,
- childrenPos);
- }
-
- /**
- * Write a bigram attributes list to mBuffer.
- *
- * @param bigrams the bigram attributes list.
- * @param dict the dictionary the node array is a part of (for relative offsets).
- */
- private void writeBigrams(final ArrayList<WeightedString> bigrams,
- final FusionDictionary dict) {
- if (bigrams == null) return;
-
- final Iterator<WeightedString> bigramIterator = bigrams.iterator();
- while (bigramIterator.hasNext()) {
- final WeightedString bigram = bigramIterator.next();
- final PtNode target =
- FusionDictionary.findWordInTree(dict.mRootNodeArray, bigram.mWord);
- final int addressOfBigram = target.mCachedAddressAfterUpdate;
- final int unigramFrequencyForThisWord = target.getProbability();
- final int offset = addressOfBigram
- - (mPosition + FormatSpec.PTNODE_ATTRIBUTE_FLAGS_SIZE);
- final int bigramFlags = BinaryDictEncoderUtils.makeBigramFlags(bigramIterator.hasNext(),
- offset, bigram.getProbability(), unigramFrequencyForThisWord, bigram.mWord);
- mPosition = BinaryDictEncoderUtils.writeUIntToBuffer(mBuffer, mPosition, bigramFlags,
- FormatSpec.PTNODE_ATTRIBUTE_FLAGS_SIZE);
- mPosition += BinaryDictEncoderUtils.writeChildrenPosition(mBuffer, mPosition,
- Math.abs(offset));
- }
- }
-
- @Override
- public void writePtNode(final PtNode ptNode, final FusionDictionary dict,
- final HashMap<Integer, Integer> codePointToOneByteCodeMap) {
- writePtNodeFlags(ptNode, codePointToOneByteCodeMap);
- writeCharacters(ptNode.mChars, ptNode.hasSeveralChars(), codePointToOneByteCodeMap);
- writeFrequency(ptNode.getProbability());
- writeChildrenPosition(ptNode, codePointToOneByteCodeMap);
- writeBigrams(ptNode.mBigrams, dict);
- }
-}
diff --git a/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTestsHelper.java b/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTestsHelper.java
index 94105aa12..4b7b9bc36 100644
--- a/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTestsHelper.java
+++ b/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTestsHelper.java
@@ -18,6 +18,7 @@ package com.android.inputmethod.latin.personalization;
import android.content.Context;
+import com.android.inputmethod.latin.BinaryDictionary;
import com.android.inputmethod.latin.NgramContext;
import com.android.inputmethod.latin.NgramContext.WordInfo;
import com.android.inputmethod.latin.common.FileUtils;
@@ -98,7 +99,8 @@ public class UserHistoryDictionaryTestsHelper {
private static void addWordsToDictionary(final UserHistoryDictionary dict,
final List<String> words, final int timestamp) {
- NgramContext ngramContext = NgramContext.EMPTY_PREV_WORDS_INFO;
+ NgramContext ngramContext = NgramContext.getEmptyPrevWordsContext(
+ BinaryDictionary.MAX_PREV_WORD_COUNT_FOR_N_GRAM);
for (final String word : words) {
UserHistoryDictionary.addToDictionary(dict, ngramContext, word, true, timestamp);
ngramContext = ngramContext.getNextNgramContext(new WordInfo(word));
diff --git a/tests/src/com/android/inputmethod/latin/settings/AccountsSettingsFragmentTests.java b/tests/src/com/android/inputmethod/latin/settings/AccountsSettingsFragmentTests.java
index 81a0f6934..0878e74cb 100644
--- a/tests/src/com/android/inputmethod/latin/settings/AccountsSettingsFragmentTests.java
+++ b/tests/src/com/android/inputmethod/latin/settings/AccountsSettingsFragmentTests.java
@@ -16,7 +16,12 @@
package com.android.inputmethod.latin.settings;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import android.app.AlertDialog;
+import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
@@ -24,6 +29,11 @@ import android.test.suitebuilder.annotation.MediumTest;
import android.view.View;
import android.widget.ListView;
+import com.android.inputmethod.latin.utils.ManagedProfileUtils;
+
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -33,6 +43,8 @@ public class AccountsSettingsFragmentTests
private static final String FRAG_NAME = AccountsSettingsFragment.class.getName();
private static final long TEST_TIMEOUT_MILLIS = 5000;
+ @Mock private ManagedProfileUtils mManagedProfileUtils;
+
public AccountsSettingsFragmentTests() {
super(TestFragmentActivity.class);
}
@@ -40,11 +52,22 @@ public class AccountsSettingsFragmentTests
@Override
protected void setUp() throws Exception {
super.setUp();
+
+ // Initialize the mocks.
+ MockitoAnnotations.initMocks(this);
+ ManagedProfileUtils.setTestInstance(mManagedProfileUtils);
+
Intent intent = new Intent();
intent.putExtra(TestFragmentActivity.EXTRA_SHOW_FRAGMENT, FRAG_NAME);
setActivityIntent(intent);
}
+ @Override
+ public void tearDown() throws Exception {
+ ManagedProfileUtils.setTestInstance(null);
+ super.tearDown();
+ }
+
public void testEmptyAccounts() {
final AccountsSettingsFragment fragment =
(AccountsSettingsFragment) getActivity().mFragment;
@@ -61,36 +84,26 @@ public class AccountsSettingsFragmentTests
DialogHolder() {}
}
- public void testMultipleAccounts_noCurrentAccount() {
+ public void testMultipleAccounts_noSettingsForManagedProfile() {
+ when(mManagedProfileUtils.hasManagedWorkProfile(any(Context.class))).thenReturn(true);
+
final AccountsSettingsFragment fragment =
(AccountsSettingsFragment) getActivity().mFragment;
- final DialogHolder dialogHolder = new DialogHolder();
- final CountDownLatch latch = new CountDownLatch(1);
+ final AlertDialog dialog = initDialog(fragment, null).mDialog;
+ final ListView lv = dialog.getListView();
- getActivity().runOnUiThread(new Runnable() {
- @Override
- public void run() {
- final AlertDialog dialog = fragment.createAccountPicker(
- new String[] {
- "1@example.com",
- "2@example.com",
- "3@example.com",
- "4@example.com"},
- null, null /* positiveButtonListner */);
- dialog.show();
- dialogHolder.mDialog = dialog;
- latch.countDown();
- }
- });
+ // Nothing to check/uncheck.
+ assertNull(fragment.findPreference(AccountsSettingsFragment.PREF_ACCCOUNT_SWITCHER));
+ }
- try {
- latch.await(TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
- } catch (InterruptedException ex) {
- fail();
- }
- getInstrumentation().waitForIdleSync();
- final AlertDialog dialog = dialogHolder.mDialog;
+ public void testMultipleAccounts_noCurrentAccount() {
+ when(mManagedProfileUtils.hasManagedWorkProfile(any(Context.class))).thenReturn(false);
+
+ final AccountsSettingsFragment fragment =
+ (AccountsSettingsFragment) getActivity().mFragment;
+ final AlertDialog dialog = initDialog(fragment, null).mDialog;
final ListView lv = dialog.getListView();
+
// The 1st account should be checked by default.
assertEquals("checked-item", 0, lv.getCheckedItemPosition());
// There should be 4 accounts in the list.
@@ -105,10 +118,32 @@ public class AccountsSettingsFragmentTests
}
public void testMultipleAccounts_currentAccount() {
+ when(mManagedProfileUtils.hasManagedWorkProfile(any(Context.class))).thenReturn(false);
+
final AccountsSettingsFragment fragment =
(AccountsSettingsFragment) getActivity().mFragment;
+ final AlertDialog dialog = initDialog(fragment, "3@example.com").mDialog;
+ final ListView lv = dialog.getListView();
+
+ // The 3rd account should be checked by default.
+ assertEquals("checked-item", 2, lv.getCheckedItemPosition());
+ // There should be 4 accounts in the list.
+ assertEquals("count", 4, lv.getCount());
+ // The sign-out button should be shown
+ assertEquals(View.VISIBLE,
+ dialog.getButton(DialogInterface.BUTTON_NEUTRAL).getVisibility());
+ assertEquals(View.VISIBLE,
+ dialog.getButton(DialogInterface.BUTTON_NEGATIVE).getVisibility());
+ assertEquals(View.VISIBLE,
+ dialog.getButton(DialogInterface.BUTTON_POSITIVE).getVisibility());
+ }
+
+ private DialogHolder initDialog(
+ final AccountsSettingsFragment fragment,
+ final String selectedAccount) {
final DialogHolder dialogHolder = new DialogHolder();
final CountDownLatch latch = new CountDownLatch(1);
+
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
@@ -118,7 +153,7 @@ public class AccountsSettingsFragmentTests
"2@example.com",
"3@example.com",
"4@example.com"},
- "3@example.com", null /* positiveButtonListner */);
+ selectedAccount, null /* positiveButtonListner */);
dialog.show();
dialogHolder.mDialog = dialog;
latch.countDown();
@@ -131,18 +166,6 @@ public class AccountsSettingsFragmentTests
fail();
}
getInstrumentation().waitForIdleSync();
- final AlertDialog dialog = dialogHolder.mDialog;
- final ListView lv = dialog.getListView();
- // The 3rd account should be checked by default.
- assertEquals("checked-item", 2, lv.getCheckedItemPosition());
- // There should be 4 accounts in the list.
- assertEquals("count", 4, lv.getCount());
- // The sign-out button should be shown
- assertEquals(View.VISIBLE,
- dialog.getButton(DialogInterface.BUTTON_NEUTRAL).getVisibility());
- assertEquals(View.VISIBLE,
- dialog.getButton(DialogInterface.BUTTON_NEGATIVE).getVisibility());
- assertEquals(View.VISIBLE,
- dialog.getButton(DialogInterface.BUTTON_POSITIVE).getVisibility());
+ return dialogHolder;
}
}
diff --git a/tests/src/com/android/inputmethod/latin/touchinputconsumer/NullGestureConsumerTests.java b/tests/src/com/android/inputmethod/latin/touchinputconsumer/NullGestureConsumerTests.java
index ca1039bd9..ad6bcc3c4 100644
--- a/tests/src/com/android/inputmethod/latin/touchinputconsumer/NullGestureConsumerTests.java
+++ b/tests/src/com/android/inputmethod/latin/touchinputconsumer/NullGestureConsumerTests.java
@@ -34,7 +34,7 @@ public class NullGestureConsumerTests extends AndroidTestCase {
GestureConsumer.NULL_GESTURE_CONSUMER.onGestureStarted(null, null);
GestureConsumer.NULL_GESTURE_CONSUMER.onGestureCanceled();
GestureConsumer.NULL_GESTURE_CONSUMER.onGestureCompleted(null);
- GestureConsumer.NULL_GESTURE_CONSUMER.onImeSuggestionsProcessed(null, -1, -1);
+ GestureConsumer.NULL_GESTURE_CONSUMER.onImeSuggestionsProcessed(null, -1, -1, null);
}
/**
diff --git a/tests/src/com/android/inputmethod/latin/utils/ExecutorUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/ExecutorUtilsTests.java
index d722151cf..86923059b 100644
--- a/tests/src/com/android/inputmethod/latin/utils/ExecutorUtilsTests.java
+++ b/tests/src/com/android/inputmethod/latin/utils/ExecutorUtilsTests.java
@@ -35,7 +35,8 @@ public class ExecutorUtilsTests extends AndroidTestCase {
private static final int DELAY_FOR_WAITING_TASKS_MILLISECONDS = 500;
public void testExecute() {
- final ExecutorService executor = ExecutorUtils.getBackgroundExecutor();
+ final ExecutorService executor =
+ ExecutorUtils.getBackgroundExecutor(ExecutorUtils.KEYBOARD);
final AtomicInteger v = new AtomicInteger(0);
for (int i = 0; i < NUM_OF_TASKS; ++i) {
executor.execute(new Runnable() {
diff --git a/tests/src/com/android/inputmethod/latin/utils/ImportantNoticeUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/ImportantNoticeUtilsTests.java
index cbabf7e8d..e361c7704 100644
--- a/tests/src/com/android/inputmethod/latin/utils/ImportantNoticeUtilsTests.java
+++ b/tests/src/com/android/inputmethod/latin/utils/ImportantNoticeUtilsTests.java
@@ -18,6 +18,7 @@ package com.android.inputmethod.latin.utils;
import static com.android.inputmethod.latin.utils.ImportantNoticeUtils.KEY_IMPORTANT_NOTICE_VERSION;
import static com.android.inputmethod.latin.utils.ImportantNoticeUtils.KEY_TIMESTAMP_OF_FIRST_IMPORTANT_NOTICE;
+import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.SharedPreferences;
@@ -25,6 +26,11 @@ import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.text.TextUtils;
+import com.android.inputmethod.latin.settings.SettingsValues;
+
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
import java.util.concurrent.TimeUnit;
@MediumTest
@@ -34,6 +40,8 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase {
private ImportantNoticePreferences mImportantNoticePreferences;
+ @Mock private SettingsValues mMockSettingsValues;
+
private static class ImportantNoticePreferences {
private final SharedPreferences mPref;
@@ -97,8 +105,10 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
+ MockitoAnnotations.initMocks(this);
mImportantNoticePreferences = new ImportantNoticePreferences(getContext());
mImportantNoticePreferences.save();
+ when(mMockSettingsValues.isPersonalizationEnabled()).thenReturn(true);
}
@Override
@@ -117,9 +127,9 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase {
// Check internal state of {@link ImportantNoticeUtils.shouldShowImportantNotice(Context)}
// after fresh install.
- assertEquals("Has new imortant notice after fresh install", true,
+ assertEquals("Has new important notice after fresh install", true,
ImportantNoticeUtils.hasNewImportantNotice(getContext()));
- assertEquals("Next important norice title after fresh install", false, TextUtils.isEmpty(
+ assertEquals("Next important notice title after fresh install", false, TextUtils.isEmpty(
ImportantNoticeUtils.getNextImportantNoticeTitle(getContext())));
assertEquals("Is in system setup wizard after fresh install", false,
ImportantNoticeUtils.isInSystemSetupWizard(getContext()));
@@ -131,14 +141,14 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase {
mImportantNoticePreferences.getLong(KEY_TIMESTAMP_OF_FIRST_IMPORTANT_NOTICE));
assertEquals("Current boolean before update", true,
- ImportantNoticeUtils.shouldShowImportantNotice(getContext()));
+ ImportantNoticeUtils.shouldShowImportantNotice(getContext(), mMockSettingsValues));
}
public void testUpdateVersion() {
mImportantNoticePreferences.clear();
assertEquals("Current boolean before update", true,
- ImportantNoticeUtils.shouldShowImportantNotice(getContext()));
+ ImportantNoticeUtils.shouldShowImportantNotice(getContext(), mMockSettingsValues));
assertEquals("Last version before update", 0,
ImportantNoticeUtils.getLastImportantNoticeVersion(getContext()));
assertEquals("Next version before update ", 1,
@@ -151,7 +161,7 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase {
ImportantNoticeUtils.updateLastImportantNoticeVersion(getContext());
assertEquals("Current boolean after update", false,
- ImportantNoticeUtils.shouldShowImportantNotice(getContext()));
+ ImportantNoticeUtils.shouldShowImportantNotice(getContext(), mMockSettingsValues));
assertEquals("Last version after update", 1,
ImportantNoticeUtils.getLastImportantNoticeVersion(getContext()));
assertEquals("Next version after update", 2,
@@ -180,7 +190,7 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase {
// Call {@link ImportantNoticeUtils#shouldShowImportantNotice(Context)} before timeout.
assertEquals("Current boolean before timeout 1", true,
- ImportantNoticeUtils.shouldShowImportantNotice(getContext()));
+ ImportantNoticeUtils.shouldShowImportantNotice(getContext(), mMockSettingsValues));
assertEquals("Last version before timeout 1", 0,
ImportantNoticeUtils.getLastImportantNoticeVersion(getContext()));
assertEquals("Next version before timeout 1", 1,
@@ -197,7 +207,7 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase {
// Call {@link ImportantNoticeUtils#shouldShowImportantNotice(Context)} before timeout
// again.
assertEquals("Current boolean before timeout 2", true,
- ImportantNoticeUtils.shouldShowImportantNotice(getContext()));
+ ImportantNoticeUtils.shouldShowImportantNotice(getContext(), mMockSettingsValues));
assertEquals("Last version before timeout 2", 0,
ImportantNoticeUtils.getLastImportantNoticeVersion(getContext()));
assertEquals("Next version before timeout 2", 1,
@@ -213,7 +223,7 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase {
// Call {@link ImportantNoticeUtils#shouldShowImportantNotice(Context)} after timeout.
assertEquals("Current boolean after timeout 1", false,
- ImportantNoticeUtils.shouldShowImportantNotice(getContext()));
+ ImportantNoticeUtils.shouldShowImportantNotice(getContext(), mMockSettingsValues));
assertEquals("Last version after timeout 1", 1,
ImportantNoticeUtils.getLastImportantNoticeVersion(getContext()));
assertEquals("Next version after timeout 1", 2,
@@ -229,7 +239,7 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase {
// Call {@link ImportantNoticeUtils#shouldShowImportantNotice(Context)} after timeout again.
assertEquals("Current boolean after timeout 2", false,
- ImportantNoticeUtils.shouldShowImportantNotice(getContext()));
+ ImportantNoticeUtils.shouldShowImportantNotice(getContext(), mMockSettingsValues));
assertEquals("Last version after timeout 2", 1,
ImportantNoticeUtils.getLastImportantNoticeVersion(getContext()));
assertEquals("Next version after timeout 2", 2,
@@ -241,4 +251,18 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase {
assertEquals("Current contents after timeout 2", true, TextUtils.isEmpty(
ImportantNoticeUtils.getNextImportantNoticeContents(getContext())));
}
+
+ public void testPersonalizationSetting() {
+ mImportantNoticePreferences.clear();
+
+ // Personalization enabled.
+ when(mMockSettingsValues.isPersonalizationEnabled()).thenReturn(true);
+ assertEquals("Current boolean with personalization enabled", true,
+ ImportantNoticeUtils.shouldShowImportantNotice(getContext(), mMockSettingsValues));
+
+ // Personalization disabled.
+ when(mMockSettingsValues.isPersonalizationEnabled()).thenReturn(false);
+ assertEquals("Current boolean with personalization disabled", false,
+ ImportantNoticeUtils.shouldShowImportantNotice(getContext(), mMockSettingsValues));
+ }
}