1 /* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.inputmethod.latin.personalization; 18 19 import android.content.SharedPreferences; 20 import android.preference.PreferenceManager; 21 import android.test.AndroidTestCase; 22 import android.test.suitebuilder.annotation.LargeTest; 23 import android.util.Log; 24 25 import com.android.inputmethod.latin.ExpandableBinaryDictionary; 26 import com.android.inputmethod.latin.utils.CollectionUtils; 27 28 import java.io.File; 29 import java.util.ArrayList; 30 import java.util.List; 31 import java.util.Random; 32 import java.util.Set; 33 import java.util.concurrent.TimeUnit; 34 35 /** 36 * Unit tests for UserHistoryDictionary 37 */ 38 @LargeTest 39 public class UserHistoryDictionaryTests extends AndroidTestCase { 40 private static final String TAG = UserHistoryDictionaryTests.class.getSimpleName(); 41 private SharedPreferences mPrefs; 42 43 private static final String[] CHARACTERS = { 44 "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", 45 "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" 46 }; 47 48 private static final int MIN_USER_HISTORY_DICTIONARY_FILE_SIZE = 1000; 49 private static final int WAIT_TERMINATING_IN_MILLISECONDS = 100; 50 51 @Override 52 public void setUp() { 53 mPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); 54 } 55 56 /** 57 * Generates a random word. 58 */ 59 private String generateWord(final int value) { 60 final int lengthOfChars = CHARACTERS.length; 61 StringBuilder builder = new StringBuilder(); 62 long lvalue = Math.abs((long)value); 63 while (lvalue > 0) { 64 builder.append(CHARACTERS[(int)(lvalue % lengthOfChars)]); 65 lvalue /= lengthOfChars; 66 } 67 return builder.toString(); 68 } 69 70 private List<String> generateWords(final int number, final Random random) { 71 final Set<String> wordSet = CollectionUtils.newHashSet(); 72 while (wordSet.size() < number) { 73 wordSet.add(generateWord(random.nextInt())); 74 } 75 return new ArrayList<String>(wordSet); 76 } 77 78 private void addToDict(final UserHistoryDictionary dict, final List<String> words) { 79 String prevWord = null; 80 for (String word : words) { 81 dict.addToDictionary(prevWord, word, true); 82 prevWord = word; 83 } 84 } 85 86 /** 87 * @param checkContents if true, checks whether written words are actually in the dictionary 88 * or not. 89 */ 90 private void addAndWriteRandomWords(final String testFilenameSuffix, final int numberOfWords, 91 final Random random, final boolean checkContents) { 92 final List<String> words = generateWords(numberOfWords, random); 93 final UserHistoryDictionary dict = 94 PersonalizationHelper.getUserHistoryDictionary(getContext(), 95 testFilenameSuffix /* locale */, mPrefs); 96 // Add random words to the user history dictionary. 97 addToDict(dict, words); 98 if (checkContents) { 99 try { 100 Thread.sleep(TimeUnit.MILLISECONDS.convert(5L, TimeUnit.SECONDS)); 101 } catch (InterruptedException e) { 102 } 103 for (int i = 0; i < numberOfWords; ++i) { 104 final String word = words.get(i); 105 assertTrue(dict.isInDictionaryForTests(word)); 106 } 107 } 108 // write to file. 109 dict.close(); 110 } 111 112 /** 113 * Clear all entries in the user history dictionary. 114 * @param testFilenameSuffix file name suffix used for testing. 115 */ 116 private void clearHistory(final String testFilenameSuffix) { 117 final UserHistoryDictionary dict = 118 PersonalizationHelper.getUserHistoryDictionary(getContext(), 119 testFilenameSuffix /* locale */, mPrefs); 120 dict.clearAndFlushDictionary(); 121 dict.close(); 122 } 123 124 /** 125 * Shut down executer and wait until all operations of user history are done. 126 * @param testFilenameSuffix file name suffix used for testing. 127 */ 128 private void waitForWriting(final String testFilenameSuffix) { 129 try { 130 final UserHistoryDictionary dict = 131 PersonalizationHelper.getUserHistoryDictionary(getContext(), 132 testFilenameSuffix, mPrefs); 133 dict.shutdownExecutorForTests(); 134 while (!dict.isTerminatedForTests()) { 135 Thread.sleep(WAIT_TERMINATING_IN_MILLISECONDS); 136 } 137 } catch (InterruptedException e) { 138 Log.d(TAG, "InterruptedException: ", e); 139 } 140 } 141 142 public void testRandomWords() { 143 Log.d(TAG, "This test can be used for profiling."); 144 Log.d(TAG, "Usage: please set UserHistoryDictionary.PROFILE_SAVE_RESTORE to true."); 145 final String testFilenameSuffix = "testRandomWords" + System.currentTimeMillis(); 146 final String fileName = UserHistoryDictionary.NAME + "." + testFilenameSuffix 147 + ExpandableBinaryDictionary.DICT_FILE_EXTENSION; 148 149 final int numberOfWords = 1000; 150 final Random random = new Random(123456); 151 152 try { 153 clearHistory(testFilenameSuffix); 154 addAndWriteRandomWords(testFilenameSuffix, numberOfWords, random, 155 true /* checksContents */); 156 } finally { 157 Log.d(TAG, "waiting for writing ..."); 158 waitForWriting(testFilenameSuffix); 159 final File dictFile = new File(getContext().getFilesDir(), fileName); 160 if (dictFile != null) { 161 assertTrue(dictFile.exists()); 162 assertTrue(dictFile.length() >= MIN_USER_HISTORY_DICTIONARY_FILE_SIZE); 163 dictFile.delete(); 164 } 165 } 166 } 167 168 public void testStressTestForSwitchingLanguagesAndAddingWords() { 169 final int numberOfLanguages = 2; 170 final int numberOfLanguageSwitching = 80; 171 final int numberOfWordsInsertedForEachLanguageSwitch = 100; 172 173 final File dictFiles[] = new File[numberOfLanguages]; 174 final String testFilenameSuffixes[] = new String[numberOfLanguages]; 175 try { 176 final Random random = new Random(123456); 177 178 // Create filename suffixes for this test. 179 for (int i = 0; i < numberOfLanguages; i++) { 180 testFilenameSuffixes[i] = "testSwitchingLanguages" + i; 181 final String fileName = UserHistoryDictionary.NAME + "." + 182 testFilenameSuffixes[i] + ExpandableBinaryDictionary.DICT_FILE_EXTENSION; 183 dictFiles[i] = new File(getContext().getFilesDir(), fileName); 184 clearHistory(testFilenameSuffixes[i]); 185 } 186 187 final long start = System.currentTimeMillis(); 188 189 for (int i = 0; i < numberOfLanguageSwitching; i++) { 190 final int index = i % numberOfLanguages; 191 // Switch languages to testFilenameSuffixes[index]. 192 addAndWriteRandomWords(testFilenameSuffixes[index], 193 numberOfWordsInsertedForEachLanguageSwitch, random, 194 false /* checksContents */); 195 } 196 197 final long end = System.currentTimeMillis(); 198 Log.d(TAG, "testStressTestForSwitchingLanguageAndAddingWords took " 199 + (end - start) + " ms"); 200 } finally { 201 Log.d(TAG, "waiting for writing ..."); 202 for (int i = 0; i < numberOfLanguages; i++) { 203 waitForWriting(testFilenameSuffixes[i]); 204 } 205 for (final File file : dictFiles) { 206 if (file != null) { 207 assertTrue(file.exists()); 208 assertTrue(file.length() >= MIN_USER_HISTORY_DICTIONARY_FILE_SIZE); 209 file.delete(); 210 } 211 } 212 } 213 } 214 215 public void testAddManyWords() { 216 final String testFilenameSuffix = "testRandomWords" + System.currentTimeMillis(); 217 final int numberOfWords = 218 ExpandableBinaryDictionary.ENABLE_BINARY_DICTIONARY_DYNAMIC_UPDATE ? 219 10000 : 1000; 220 final Random random = new Random(123456); 221 clearHistory(testFilenameSuffix); 222 try { 223 addAndWriteRandomWords(testFilenameSuffix, numberOfWords, random, 224 true /* checksContents */); 225 } finally { 226 Log.d(TAG, "waiting for writing ..."); 227 waitForWriting(testFilenameSuffix); 228 final String fileName = UserHistoryDictionary.NAME + "." + testFilenameSuffix 229 + ExpandableBinaryDictionary.DICT_FILE_EXTENSION; 230 final File dictFile = new File(getContext().getFilesDir(), fileName); 231 if (dictFile != null) { 232 assertTrue(dictFile.exists()); 233 assertTrue(dictFile.length() >= MIN_USER_HISTORY_DICTIONARY_FILE_SIZE); 234 dictFile.delete(); 235 } 236 } 237 } 238 239 } 240