UserHistoryDictionaryTests.java revision 71ffcc63326305fcd315a139cc0093019a641091
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
17package com.android.inputmethod.latin.personalization;
18
19import android.content.SharedPreferences;
20import android.preference.PreferenceManager;
21import android.test.AndroidTestCase;
22import android.test.suitebuilder.annotation.LargeTest;
23import android.util.Log;
24
25import com.android.inputmethod.latin.utils.CollectionUtils;
26
27import java.io.File;
28import java.util.ArrayList;
29import java.util.List;
30import java.util.Random;
31import java.util.Set;
32
33/**
34 * Unit tests for UserHistoryDictionary
35 */
36@LargeTest
37public class UserHistoryDictionaryTests extends AndroidTestCase {
38    private static final String TAG = UserHistoryDictionaryTests.class.getSimpleName();
39    private SharedPreferences mPrefs;
40
41    private static final String[] CHARACTERS = {
42        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
43        "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
44    };
45
46    @Override
47    public void setUp() {
48        mPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
49    }
50
51    /**
52     * Generates a random word.
53     */
54    private String generateWord(final int value) {
55        final int lengthOfChars = CHARACTERS.length;
56        StringBuilder builder = new StringBuilder();
57        long lvalue = Math.abs((long)value);
58        while (lvalue > 0) {
59            builder.append(CHARACTERS[(int)(lvalue % lengthOfChars)]);
60            lvalue /= lengthOfChars;
61        }
62        return builder.toString();
63    }
64
65    private List<String> generateWords(final int number, final Random random) {
66        final Set<String> wordSet = CollectionUtils.newHashSet();
67        while (wordSet.size() < number) {
68            wordSet.add(generateWord(random.nextInt()));
69        }
70        return new ArrayList<String>(wordSet);
71    }
72
73    private void addToDict(final UserHistoryPredictionDictionary dict, final List<String> words) {
74        String prevWord = null;
75        for (String word : words) {
76            dict.forceAddWordForTest(prevWord, word, true);
77            prevWord = word;
78        }
79    }
80
81    public void testRandomWords() {
82        File dictFile = null;
83        try {
84            Log.d(TAG, "This test can be used for profiling.");
85            Log.d(TAG, "Usage: please set UserHistoryDictionary.PROFILE_SAVE_RESTORE to true.");
86            final int numberOfWords = 1000;
87            final Random random = new Random(123456);
88            List<String> words = generateWords(numberOfWords, random);
89
90            final String locale = "testRandomWords";
91            final String fileName = "UserHistoryDictionary." + locale + ".dict";
92            dictFile = new File(getContext().getFilesDir(), fileName);
93            final UserHistoryPredictionDictionary dict =
94                    PersonalizationDictionaryHelper.getUserHistoryPredictionDictionary(
95                            getContext(), locale, mPrefs);
96            dict.mIsTest = true;
97
98            addToDict(dict, words);
99
100            try {
101                Log.d(TAG, "waiting for adding the word ...");
102                Thread.sleep(2000);
103            } catch (InterruptedException e) {
104                Log.d(TAG, "InterruptedException: " + e);
105            }
106
107            // write to file
108            dict.close();
109
110            try {
111                Log.d(TAG, "waiting for writing ...");
112                Thread.sleep(5000);
113            } catch (InterruptedException e) {
114                Log.d(TAG, "InterruptedException: " + e);
115            }
116        } finally {
117            if (dictFile != null) {
118                dictFile.delete();
119            }
120        }
121    }
122
123    public void testStressTestForSwitchingLanguagesAndAddingWords() {
124        final int numberOfLanguages = 2;
125        final int numberOfLanguageSwitching = 100;
126        final int numberOfWordsIntertedForEachLanguageSwitch = 100;
127
128        final File dictFiles[] = new File[numberOfLanguages];
129        try {
130            final Random random = new Random(123456);
131
132            // Create locales for this test.
133            String locales[] = new String[numberOfLanguages];
134            for (int i = 0; i < numberOfLanguages; i++) {
135                locales[i] = "testSwitchingLanguages" + i;
136                final String fileName = "UserHistoryDictionary." + locales[i] + ".dict";
137                dictFiles[i] = new File(getContext().getFilesDir(), fileName);
138            }
139
140            final long now = System.currentTimeMillis();
141
142            for (int i = 0; i < numberOfLanguageSwitching; i++) {
143                final int index = i % numberOfLanguages;
144                // Switch languages to locales[index].
145                final UserHistoryPredictionDictionary dict =
146                        PersonalizationDictionaryHelper.getUserHistoryPredictionDictionary(
147                                getContext(), locales[index], mPrefs);
148                final List<String> words = generateWords(
149                        numberOfWordsIntertedForEachLanguageSwitch, random);
150                // Add random words to the user history dictionary.
151                addToDict(dict, words);
152                // write to file
153                dict.close();
154            }
155
156            final long end = System.currentTimeMillis();
157            Log.d(TAG, "testStressTestForSwitchingLanguageAndAddingWords took "
158                    + (end - now) + " ms");
159            try {
160                Log.d(TAG, "waiting for writing ...");
161                Thread.sleep(5000);
162            } catch (InterruptedException e) {
163                Log.d(TAG, "InterruptedException: " + e);
164            }
165        } finally {
166            for (final File file : dictFiles) {
167                if (file != null) {
168                    file.delete();
169                }
170            }
171        }
172    }
173}
174