diff options
Diffstat (limited to 'tests/src')
7 files changed, 257 insertions, 153 deletions
diff --git a/tests/src/com/android/inputmethod/latin/InputLogicTests.java b/tests/src/com/android/inputmethod/latin/InputLogicTests.java index d27a7a903..6cc4befae 100644 --- a/tests/src/com/android/inputmethod/latin/InputLogicTests.java +++ b/tests/src/com/android/inputmethod/latin/InputLogicTests.java @@ -17,6 +17,7 @@ package com.android.inputmethod.latin; import android.test.suitebuilder.annotation.LargeTest; +import android.view.inputmethod.BaseInputConnection; @LargeTest public class InputLogicTests extends InputTestsBase { @@ -290,5 +291,19 @@ public class InputLogicTests extends InputTestsBase { } assertEquals("delete whole composing word", "", mEditText.getText().toString()); } + + public void testResumeSuggestionOnBackspace() { + final String WORD_TO_TYPE = "and this "; + type(WORD_TO_TYPE); + assertEquals("resume suggestion on backspace", -1, + BaseInputConnection.getComposingSpanStart(mEditText.getText())); + assertEquals("resume suggestion on backspace", -1, + BaseInputConnection.getComposingSpanEnd(mEditText.getText())); + type(Constants.CODE_DELETE); + assertEquals("resume suggestion on backspace", 4, + BaseInputConnection.getComposingSpanStart(mEditText.getText())); + assertEquals("resume suggestion on backspace", 8, + BaseInputConnection.getComposingSpanEnd(mEditText.getText())); + } // TODO: Add some tests for non-BMP characters } diff --git a/tests/src/com/android/inputmethod/latin/InputLogicTestsLanguageWithoutSpaces.java b/tests/src/com/android/inputmethod/latin/InputLogicTestsLanguageWithoutSpaces.java new file mode 100644 index 000000000..0f0ebafb9 --- /dev/null +++ b/tests/src/com/android/inputmethod/latin/InputLogicTestsLanguageWithoutSpaces.java @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin; + +import android.test.suitebuilder.annotation.LargeTest; +import android.view.inputmethod.BaseInputConnection; + +import com.android.inputmethod.latin.suggestions.SuggestionStripView; + +@LargeTest +public class InputLogicTestsLanguageWithoutSpaces extends InputTestsBase { + public void testAutoCorrectForLanguageWithoutSpaces() { + final String STRING_TO_TYPE = "tgis is"; + final String EXPECTED_RESULT = "thisis"; + changeKeyboardLocaleAndDictLocale("th", "en_US"); + type(STRING_TO_TYPE); + assertEquals("simple auto-correct for language without spaces", EXPECTED_RESULT, + mEditText.getText().toString()); + } + + public void testRevertAutoCorrectForLanguageWithoutSpaces() { + final String STRING_TO_TYPE = "tgis "; + final String EXPECTED_INTERMEDIATE_RESULT = "this"; + final String EXPECTED_FINAL_RESULT = "tgis"; + changeKeyboardLocaleAndDictLocale("th", "en_US"); + type(STRING_TO_TYPE); + assertEquals("simple auto-correct for language without spaces", + EXPECTED_INTERMEDIATE_RESULT, mEditText.getText().toString()); + type(Constants.CODE_DELETE); + assertEquals("simple auto-correct for language without spaces", + EXPECTED_FINAL_RESULT, mEditText.getText().toString()); + // Check we are back to composing the word + assertEquals("don't resume suggestion on backspace", 0, + BaseInputConnection.getComposingSpanStart(mEditText.getText())); + assertEquals("don't resume suggestion on backspace", 4, + BaseInputConnection.getComposingSpanEnd(mEditText.getText())); + } + + public void testDontResumeSuggestionOnBackspace() { + final String WORD_TO_TYPE = "and this "; + changeKeyboardLocaleAndDictLocale("th", "en_US"); + type(WORD_TO_TYPE); + assertEquals("don't resume suggestion on backspace", -1, + BaseInputConnection.getComposingSpanStart(mEditText.getText())); + assertEquals("don't resume suggestion on backspace", -1, + BaseInputConnection.getComposingSpanEnd(mEditText.getText())); + type(" "); + type(Constants.CODE_DELETE); + assertEquals("don't resume suggestion on backspace", -1, + BaseInputConnection.getComposingSpanStart(mEditText.getText())); + assertEquals("don't resume suggestion on backspace", -1, + BaseInputConnection.getComposingSpanEnd(mEditText.getText())); + } + + public void testStartComposingInsideText() { + final String WORD_TO_TYPE = "abcdefgh "; + final int typedLength = WORD_TO_TYPE.length() - 1; // -1 because space gets eaten + final int CURSOR_POS = 4; + changeKeyboardLocaleAndDictLocale("th", "en_US"); + type(WORD_TO_TYPE); + mLatinIME.onUpdateSelection(0, 0, typedLength, typedLength, -1, -1); + mInputConnection.setSelection(CURSOR_POS, CURSOR_POS); + mLatinIME.onUpdateSelection(typedLength, typedLength, + CURSOR_POS, CURSOR_POS, -1, -1); + sleep(DELAY_TO_WAIT_FOR_PREDICTIONS); + runMessages(); + assertEquals("start composing inside text", -1, + BaseInputConnection.getComposingSpanStart(mEditText.getText())); + assertEquals("start composing inside text", -1, + BaseInputConnection.getComposingSpanEnd(mEditText.getText())); + type("xxxx"); + assertEquals("start composing inside text", 4, + BaseInputConnection.getComposingSpanStart(mEditText.getText())); + assertEquals("start composing inside text", 8, + BaseInputConnection.getComposingSpanEnd(mEditText.getText())); + } + + public void testPredictions() { + final String WORD_TO_TYPE = "Barack "; + changeKeyboardLocaleAndDictLocale("th", "en_US"); + type(WORD_TO_TYPE); + sleep(DELAY_TO_WAIT_FOR_PREDICTIONS); + runMessages(); + // Make sure there is no space + assertEquals("predictions in lang without spaces", "Barack", + mEditText.getText().toString()); + // Test the first prediction is displayed + assertEquals("predictions in lang without spaces", "Obama", + mLatinIME.getFirstSuggestedWord()); + } +} diff --git a/tests/src/com/android/inputmethod/latin/InputTestsBase.java b/tests/src/com/android/inputmethod/latin/InputTestsBase.java index cc3e0d74d..480570e62 100644 --- a/tests/src/com/android/inputmethod/latin/InputTestsBase.java +++ b/tests/src/com/android/inputmethod/latin/InputTestsBase.java @@ -46,6 +46,8 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> { // The message that sets the underline is posted with a 100 ms delay protected static final int DELAY_TO_WAIT_FOR_UNDERLINE = 200; + // The message that sets predictions is posted with a 100 ms delay + protected static final int DELAY_TO_WAIT_FOR_PREDICTIONS = 200; protected LatinIME mLatinIME; protected Keyboard mKeyboard; @@ -233,9 +235,6 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> { --remainingAttempts; } } - if (!mLatinIME.hasMainDictionary()) { - throw new RuntimeException("Can't initialize the main dictionary"); - } } protected void changeLanguage(final String locale) { @@ -247,6 +246,16 @@ public class InputTestsBase extends ServiceTestCase<LatinIMEForTests> { waitForDictionaryToBeLoaded(); } + protected void changeKeyboardLocaleAndDictLocale(final String keyboardLocale, + final String dictLocale) { + changeLanguage(keyboardLocale); + if (!keyboardLocale.equals(dictLocale)) { + mLatinIME.replaceMainDictionaryForTest( + LocaleUtils.constructLocaleFromString(dictLocale)); + } + waitForDictionaryToBeLoaded(); + } + protected void pickSuggestionManually(final int index, final String suggestion) { mLatinIME.pickSuggestionManually(index, new SuggestedWordInfo(suggestion, 1, SuggestedWordInfo.KIND_CORRECTION, "main")); diff --git a/tests/src/com/android/inputmethod/latin/makedict/BinaryDictDecoderEncoderTests.java b/tests/src/com/android/inputmethod/latin/makedict/BinaryDictDecoderEncoderTests.java index 6d37466b7..be468c19b 100644 --- a/tests/src/com/android/inputmethod/latin/makedict/BinaryDictDecoderEncoderTests.java +++ b/tests/src/com/android/inputmethod/latin/makedict/BinaryDictDecoderEncoderTests.java @@ -71,6 +71,8 @@ public class BinaryDictDecoderEncoderTests extends AndroidTestCase { private static final FormatSpec.FormatOptions VERSION3_WITH_DYNAMIC_UPDATE = new FormatSpec.FormatOptions(3, true /* supportsDynamicUpdate */); + private static final String TEST_DICT_FILE_EXTENSION = ".testDict"; + public BinaryDictDecoderEncoderTests() { this(System.currentTimeMillis(), DEFAULT_MAX_UNIGRAMS); } @@ -293,7 +295,8 @@ public class BinaryDictDecoderEncoderTests extends AndroidTestCase { final String message) { File file = null; try { - file = File.createTempFile("runReadAndWrite", ".dict", getContext().getCacheDir()); + file = File.createTempFile("runReadAndWrite", TEST_DICT_FILE_EXTENSION, + getContext().getCacheDir()); } catch (IOException e) { Log.e(TAG, "IOException", e); } @@ -435,7 +438,8 @@ public class BinaryDictDecoderEncoderTests extends AndroidTestCase { final FormatSpec.FormatOptions formatOptions, final String message) { File file = null; try { - file = File.createTempFile("runReadUnigrams", ".dict", getContext().getCacheDir()); + file = File.createTempFile("runReadUnigrams", TEST_DICT_FILE_EXTENSION, + getContext().getCacheDir()); } catch (IOException e) { Log.e(TAG, "IOException", e); } @@ -493,31 +497,31 @@ public class BinaryDictDecoderEncoderTests extends AndroidTestCase { } // Tests for getTerminalPosition - private String getWordFromBinary(final FusionDictionaryBufferInterface buffer, - final int address) { + private String getWordFromBinary(final BinaryDictReader dictReader, final int address) { + final FusionDictionaryBufferInterface buffer = dictReader.getBuffer(); if (buffer.position() != 0) buffer.position(0); - FileHeader header = null; + FileHeader fileHeader = null; try { - header = BinaryDictDecoder.readHeader(buffer); + fileHeader = BinaryDictDecoder.readHeader(dictReader); } catch (IOException e) { return null; } catch (UnsupportedFormatException e) { return null; } - if (header == null) return null; - return BinaryDictDecoder.getWordAtAddress(buffer, header.mHeaderSize, - address - header.mHeaderSize, header.mFormatOptions).mWord; + if (fileHeader == null) return null; + return BinaryDictDecoder.getWordAtAddress(buffer, fileHeader.mHeaderSize, + address - fileHeader.mHeaderSize, fileHeader.mFormatOptions).mWord; } - private long runGetTerminalPosition(final FusionDictionaryBufferInterface buffer, - final String word, int index, boolean contained) { + private long runGetTerminalPosition(final BinaryDictReader reader, final String word, int index, + boolean contained) { final int expectedFrequency = (UNIGRAM_FREQ + index) % 255; long diff = -1; int position = -1; try { final long now = System.nanoTime(); - position = BinaryDictIOUtils.getTerminalPosition(buffer, word); + position = BinaryDictIOUtils.getTerminalPosition(reader, word); diff = System.nanoTime() - now; } catch (IOException e) { Log.e(TAG, "IOException while getTerminalPosition", e); @@ -526,14 +530,14 @@ public class BinaryDictDecoderEncoderTests extends AndroidTestCase { } assertEquals(FormatSpec.NOT_VALID_WORD != position, contained); - if (contained) assertEquals(getWordFromBinary(buffer, position), word); + if (contained) assertEquals(getWordFromBinary(reader, position), word); return diff; } public void testGetTerminalPosition() { File file = null; try { - file = File.createTempFile("testGetTerminalPosition", ".dict", + file = File.createTempFile("testGetTerminalPosition", TEST_DICT_FILE_EXTENSION, getContext().getCacheDir()); } catch (IOException e) { // do nothing @@ -547,29 +551,27 @@ public class BinaryDictDecoderEncoderTests extends AndroidTestCase { timeWritingDictToFile(file, dict, VERSION3_WITH_DYNAMIC_UPDATE); final BinaryDictReader reader = new BinaryDictReader(file); - FusionDictionaryBufferInterface buffer = null; try { - buffer = reader.openAndGetBuffer( - new BinaryDictReader.FusionDictionaryBufferFromByteArrayFactory()); + reader.openBuffer(new BinaryDictReader.FusionDictionaryBufferFromByteArrayFactory()); } catch (IOException e) { // ignore Log.e(TAG, "IOException while opening the buffer", e); } - assertNotNull("Can't get the buffer", buffer); + assertNotNull("Can't get the buffer", reader.getBuffer()); try { // too long word final String longWord = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; assertEquals(FormatSpec.NOT_VALID_WORD, - BinaryDictIOUtils.getTerminalPosition(buffer, longWord)); + BinaryDictIOUtils.getTerminalPosition(reader, longWord)); // null assertEquals(FormatSpec.NOT_VALID_WORD, - BinaryDictIOUtils.getTerminalPosition(buffer, null)); + BinaryDictIOUtils.getTerminalPosition(reader, null)); // empty string assertEquals(FormatSpec.NOT_VALID_WORD, - BinaryDictIOUtils.getTerminalPosition(buffer, "")); + BinaryDictIOUtils.getTerminalPosition(reader, "")); } catch (IOException e) { } catch (UnsupportedFormatException e) { } @@ -577,7 +579,7 @@ public class BinaryDictDecoderEncoderTests extends AndroidTestCase { // Test a word that is contained within the dictionary. long sum = 0; for (int i = 0; i < sWords.size(); ++i) { - final long time = runGetTerminalPosition(buffer, sWords.get(i), i, true); + final long time = runGetTerminalPosition(reader, sWords.get(i), i, true); sum += time == -1 ? 0 : time; } Log.d(TAG, "per a search : " + (((double)sum) / sWords.size() / 1000000)); @@ -588,14 +590,15 @@ public class BinaryDictDecoderEncoderTests extends AndroidTestCase { for (int i = 0; i < 1000; ++i) { final String word = generateWord(random, codePointSet); if (sWords.indexOf(word) != -1) continue; - runGetTerminalPosition(buffer, word, i, false); + runGetTerminalPosition(reader, word, i, false); } } public void testDeleteWord() { File file = null; try { - file = File.createTempFile("testDeleteWord", ".dict", getContext().getCacheDir()); + file = File.createTempFile("testDeleteWord", TEST_DICT_FILE_EXTENSION, + getContext().getCacheDir()); } catch (IOException e) { // do nothing } @@ -608,28 +611,27 @@ public class BinaryDictDecoderEncoderTests extends AndroidTestCase { timeWritingDictToFile(file, dict, VERSION3_WITH_DYNAMIC_UPDATE); final BinaryDictReader reader = new BinaryDictReader(file); - FusionDictionaryBufferInterface buffer = null; try { - buffer = reader.openAndGetBuffer( + reader.openBuffer( new BinaryDictReader.FusionDictionaryBufferFromByteArrayFactory()); } catch (IOException e) { // ignore Log.e(TAG, "IOException while opening the buffer", e); } - assertNotNull("Can't get the buffer", buffer); + assertNotNull("Can't get the buffer", reader.getBuffer()); try { MoreAsserts.assertNotEqual(FormatSpec.NOT_VALID_WORD, - BinaryDictIOUtils.getTerminalPosition(buffer, sWords.get(0))); - DynamicBinaryDictIOUtils.deleteWord(buffer, sWords.get(0)); + BinaryDictIOUtils.getTerminalPosition(reader, sWords.get(0))); + DynamicBinaryDictIOUtils.deleteWord(reader, sWords.get(0)); assertEquals(FormatSpec.NOT_VALID_WORD, - BinaryDictIOUtils.getTerminalPosition(buffer, sWords.get(0))); + BinaryDictIOUtils.getTerminalPosition(reader, sWords.get(0))); MoreAsserts.assertNotEqual(FormatSpec.NOT_VALID_WORD, - BinaryDictIOUtils.getTerminalPosition(buffer, sWords.get(5))); - DynamicBinaryDictIOUtils.deleteWord(buffer, sWords.get(5)); + BinaryDictIOUtils.getTerminalPosition(reader, sWords.get(5))); + DynamicBinaryDictIOUtils.deleteWord(reader, sWords.get(5)); assertEquals(FormatSpec.NOT_VALID_WORD, - BinaryDictIOUtils.getTerminalPosition(buffer, sWords.get(5))); + BinaryDictIOUtils.getTerminalPosition(reader, sWords.get(5))); } catch (IOException e) { } catch (UnsupportedFormatException e) { } diff --git a/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtilsTests.java b/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtilsTests.java index 011d711de..bcf2c3187 100644 --- a/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtilsTests.java @@ -21,8 +21,9 @@ import android.test.MoreAsserts; import android.test.suitebuilder.annotation.LargeTest; import android.util.Log; -import com.android.inputmethod.latin.makedict.BinaryDictDecoder.ByteBufferWrapper; import com.android.inputmethod.latin.makedict.BinaryDictDecoder.FusionDictionaryBufferInterface; +import com.android.inputmethod.latin.makedict.BinaryDictReader. + FusionDictionaryBufferFromWritableByteBufferFactory; import com.android.inputmethod.latin.makedict.FormatSpec.FileHeader; import com.android.inputmethod.latin.makedict.FusionDictionary.PtNodeArray; import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString; @@ -33,8 +34,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; @@ -49,6 +48,8 @@ public class BinaryDictIOUtilsTests extends AndroidTestCase { public static final int DEFAULT_MAX_UNIGRAMS = 1500; private final int mMaxUnigrams; + private static final String TEST_DICT_FILE_EXTENSION = ".testDict"; + private static final String[] CHARACTERS = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", @@ -127,22 +128,24 @@ public class BinaryDictIOUtilsTests extends AndroidTestCase { } } - private static void printBinaryFile(final FusionDictionaryBufferInterface buffer) + private static void printBinaryFile(final BinaryDictReader dictReader) throws IOException, UnsupportedFormatException { - FileHeader header = BinaryDictDecoder.readHeader(buffer); + final FileHeader fileHeader = BinaryDictDecoder.readHeader(dictReader); + final FusionDictionaryBufferInterface buffer = dictReader.getBuffer(); while (buffer.position() < buffer.limit()) { - printNode(buffer, header.mFormatOptions); + printNode(buffer, fileHeader.mFormatOptions); } } private int getWordPosition(final File file, final String word) { int position = FormatSpec.NOT_VALID_WORD; + final BinaryDictReader dictReader = new BinaryDictReader(file); FileInputStream inStream = null; try { inStream = new FileInputStream(file); - final FusionDictionaryBufferInterface buffer = new ByteBufferWrapper( - inStream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length())); - position = BinaryDictIOUtils.getTerminalPosition(buffer, word); + dictReader.openBuffer( + new BinaryDictReader.FusionDictionaryBufferFromByteBufferFactory()); + position = BinaryDictIOUtils.getTerminalPosition(dictReader, word); } catch (IOException e) { } catch (UnsupportedFormatException e) { } finally { @@ -158,23 +161,14 @@ public class BinaryDictIOUtilsTests extends AndroidTestCase { } private CharGroupInfo findWordFromFile(final File file, final String word) { - FileInputStream inStream = null; + final BinaryDictReader dictReader = new BinaryDictReader(file); CharGroupInfo info = null; try { - inStream = new FileInputStream(file); - final FusionDictionaryBufferInterface buffer = new ByteBufferWrapper( - inStream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length())); - info = BinaryDictIOUtils.findWordFromBuffer(buffer, word); + dictReader.openBuffer( + new BinaryDictReader.FusionDictionaryBufferFromByteBufferFactory()); + info = BinaryDictIOUtils.findWordByBinaryDictReader(dictReader, word); } catch (IOException e) { } catch (UnsupportedFormatException e) { - } finally { - if (inStream != null) { - try { - inStream.close(); - } catch (IOException e) { - // do nothing - } - } } return info; } @@ -183,42 +177,33 @@ public class BinaryDictIOUtilsTests extends AndroidTestCase { private long insertAndCheckWord(final File file, final String word, final int frequency, final boolean exist, final ArrayList<WeightedString> bigrams, final ArrayList<WeightedString> shortcuts) { - RandomAccessFile raFile = null; + final BinaryDictReader dictReader = new BinaryDictReader(file); BufferedOutputStream outStream = null; - FusionDictionaryBufferInterface buffer = null; long amountOfTime = -1; try { - raFile = new RandomAccessFile(file, "rw"); - buffer = new ByteBufferWrapper(raFile.getChannel().map( - FileChannel.MapMode.READ_WRITE, 0, file.length())); + dictReader.openBuffer(new FusionDictionaryBufferFromWritableByteBufferFactory()); outStream = new BufferedOutputStream(new FileOutputStream(file, true)); if (!exist) { assertEquals(FormatSpec.NOT_VALID_WORD, getWordPosition(file, word)); } final long now = System.nanoTime(); - DynamicBinaryDictIOUtils.insertWord(buffer, outStream, word, frequency, bigrams, + DynamicBinaryDictIOUtils.insertWord(dictReader, outStream, word, frequency, bigrams, shortcuts, false, false); amountOfTime = System.nanoTime() - now; outStream.flush(); MoreAsserts.assertNotEqual(FormatSpec.NOT_VALID_WORD, getWordPosition(file, word)); outStream.close(); - raFile.close(); } catch (IOException e) { + Log.e(TAG, "Raised an IOException while inserting a word", e); } catch (UnsupportedFormatException e) { + Log.e(TAG, "Raised an UnsupportedFormatException error while inserting a word", e); } finally { if (outStream != null) { try { outStream.close(); } catch (IOException e) { - // do nothing - } - } - if (raFile != null) { - try { - raFile.close(); - } catch (IOException e) { - // do nothing + Log.e(TAG, "Failed to close the output stream", e); } } } @@ -226,52 +211,37 @@ public class BinaryDictIOUtilsTests extends AndroidTestCase { } private void deleteWord(final File file, final String word) { - RandomAccessFile raFile = null; - FusionDictionaryBufferInterface buffer = null; + final BinaryDictReader dictReader = new BinaryDictReader(file); try { - raFile = new RandomAccessFile(file, "rw"); - buffer = new ByteBufferWrapper(raFile.getChannel().map( - FileChannel.MapMode.READ_WRITE, 0, file.length())); - DynamicBinaryDictIOUtils.deleteWord(buffer, word); + dictReader.openBuffer(new FusionDictionaryBufferFromWritableByteBufferFactory()); + DynamicBinaryDictIOUtils.deleteWord(dictReader, word); } catch (IOException e) { } catch (UnsupportedFormatException e) { - } finally { - if (raFile != null) { - try { - raFile.close(); - } catch (IOException e) { - // do nothing - } - } } } private void checkReverseLookup(final File file, final String word, final int position) { - FileInputStream inStream = null; + final BinaryDictReader dictReader = new BinaryDictReader(file); try { - inStream = new FileInputStream(file); - final FusionDictionaryBufferInterface buffer = new ByteBufferWrapper( - inStream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length())); - final FileHeader header = BinaryDictDecoder.readHeader(buffer); - assertEquals(word, BinaryDictDecoder.getWordAtAddress(buffer, header.mHeaderSize, - position - header.mHeaderSize, header.mFormatOptions).mWord); + final FusionDictionaryBufferInterface buffer = dictReader.openAndGetBuffer( + new BinaryDictReader.FusionDictionaryBufferFromByteBufferFactory()); + final FileHeader fileHeader = BinaryDictDecoder.readHeader(dictReader); + assertEquals(word, + BinaryDictDecoder.getWordAtAddress(dictReader.getBuffer(), + fileHeader.mHeaderSize, position - fileHeader.mHeaderSize, + fileHeader.mFormatOptions).mWord); } catch (IOException e) { + Log.e(TAG, "Raised an IOException while looking up a word", e); } catch (UnsupportedFormatException e) { - } finally { - if (inStream != null) { - try { - inStream.close(); - } catch (IOException e) { - // do nothing - } - } + Log.e(TAG, "Raised an UnsupportedFormatException error while looking up a word", e); } } public void testInsertWord() { File file = null; try { - file = File.createTempFile("testInsertWord", ".dict", getContext().getCacheDir()); + file = File.createTempFile("testInsertWord", TEST_DICT_FILE_EXTENSION, + getContext().getCacheDir()); } catch (IOException e) { fail("IOException while creating temporary file: " + e); } @@ -321,7 +291,7 @@ public class BinaryDictIOUtilsTests extends AndroidTestCase { public void testInsertWordWithBigrams() { File file = null; try { - file = File.createTempFile("testInsertWordWithBigrams", ".dict", + file = File.createTempFile("testInsertWordWithBigrams", TEST_DICT_FILE_EXTENSION, getContext().getCacheDir()); } catch (IOException e) { fail("IOException while creating temporary file: " + e); @@ -359,7 +329,8 @@ public class BinaryDictIOUtilsTests extends AndroidTestCase { public void testRandomWords() { File file = null; try { - file = File.createTempFile("testRandomWord", ".dict", getContext().getCacheDir()); + file = File.createTempFile("testRandomWord", TEST_DICT_FILE_EXTENSION, + getContext().getCacheDir()); } catch (IOException e) { } assertNotNull(file); diff --git a/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTests.java b/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTests.java index b3e2ee0ff..99ccb1a75 100644 --- a/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTests.java +++ b/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTests.java @@ -22,6 +22,7 @@ import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.LargeTest; import android.util.Log; +import com.android.inputmethod.latin.ExpandableBinaryDictionary; import com.android.inputmethod.latin.utils.CollectionUtils; import java.io.File; @@ -29,6 +30,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; +import java.util.concurrent.TimeUnit; /** * Unit tests for UserHistoryDictionary @@ -43,6 +45,8 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; + private static final int MIN_USER_HISTORY_DICTIONARY_FILE_SIZE = 1000; + @Override public void setUp() { mPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); @@ -78,43 +82,43 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { } } + private void addAndWriteRandomWords(final String testFilenameSuffix, final int numberOfWords, + final Random random) { + final List<String> words = generateWords(numberOfWords, random); + final UserHistoryPredictionDictionary dict = + PersonalizationDictionaryHelper.getUserHistoryPredictionDictionary(getContext(), + testFilenameSuffix /* locale */, mPrefs); + // Add random words to the user history dictionary. + addToDict(dict, words); + // write to file. + dict.close(); + } + public void testRandomWords() { File dictFile = null; - try { - Log.d(TAG, "This test can be used for profiling."); - Log.d(TAG, "Usage: please set UserHistoryDictionary.PROFILE_SAVE_RESTORE to true."); - final int numberOfWords = 1000; - final Random random = new Random(123456); - List<String> words = generateWords(numberOfWords, random); - - final String locale = "testRandomWords"; - final String fileName = "UserHistoryDictionary." + locale + ".dict"; - dictFile = new File(getContext().getFilesDir(), fileName); - final UserHistoryPredictionDictionary dict = - PersonalizationDictionaryHelper.getUserHistoryPredictionDictionary( - getContext(), locale, mPrefs); - dict.mIsTest = true; - - addToDict(dict, words); + Log.d(TAG, "This test can be used for profiling."); + Log.d(TAG, "Usage: please set UserHistoryDictionary.PROFILE_SAVE_RESTORE to true."); + final String testFilenameSuffix = "testRandomWords" + System.currentTimeMillis(); + final int numberOfWords = 1000; + final Random random = new Random(123456); + try { + addAndWriteRandomWords(testFilenameSuffix, numberOfWords, random); + } finally { try { - Log.d(TAG, "waiting for adding the word ..."); - Thread.sleep(2000); + Log.d(TAG, "waiting for writing ..."); + Thread.sleep(TimeUnit.MILLISECONDS.convert(5L, TimeUnit.SECONDS)); } catch (InterruptedException e) { Log.d(TAG, "InterruptedException: " + e); } - // write to file - dict.close(); + final String fileName = UserHistoryPredictionDictionary.NAME + "." + testFilenameSuffix + + ExpandableBinaryDictionary.DICT_FILE_EXTENSION; + dictFile = new File(getContext().getFilesDir(), fileName); - try { - Log.d(TAG, "waiting for writing ..."); - Thread.sleep(5000); - } catch (InterruptedException e) { - Log.d(TAG, "InterruptedException: " + e); - } - } finally { if (dictFile != null) { + assertTrue(dictFile.exists()); + assertTrue(dictFile.length() >= MIN_USER_HISTORY_DICTIONARY_FILE_SIZE); dictFile.delete(); } } @@ -122,49 +126,45 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { public void testStressTestForSwitchingLanguagesAndAddingWords() { final int numberOfLanguages = 2; - final int numberOfLanguageSwitching = 100; - final int numberOfWordsIntertedForEachLanguageSwitch = 100; + final int numberOfLanguageSwitching = 80; + final int numberOfWordsInsertedForEachLanguageSwitch = 100; final File dictFiles[] = new File[numberOfLanguages]; try { final Random random = new Random(123456); - // Create locales for this test. - String locales[] = new String[numberOfLanguages]; + // Create filename suffixes for this test. + String testFilenameSuffixes[] = new String[numberOfLanguages]; for (int i = 0; i < numberOfLanguages; i++) { - locales[i] = "testSwitchingLanguages" + i; - final String fileName = "UserHistoryDictionary." + locales[i] + ".dict"; + testFilenameSuffixes[i] = "testSwitchingLanguages" + i; + final String fileName = UserHistoryPredictionDictionary.NAME + "." + + testFilenameSuffixes[i] + ExpandableBinaryDictionary.DICT_FILE_EXTENSION; dictFiles[i] = new File(getContext().getFilesDir(), fileName); } - final long now = System.currentTimeMillis(); + final long start = System.currentTimeMillis(); for (int i = 0; i < numberOfLanguageSwitching; i++) { final int index = i % numberOfLanguages; - // Switch languages to locales[index]. - final UserHistoryPredictionDictionary dict = - PersonalizationDictionaryHelper.getUserHistoryPredictionDictionary( - getContext(), locales[index], mPrefs); - final List<String> words = generateWords( - numberOfWordsIntertedForEachLanguageSwitch, random); - // Add random words to the user history dictionary. - addToDict(dict, words); - // write to file - dict.close(); + // Switch languages to testFilenameSuffixes[index]. + addAndWriteRandomWords(testFilenameSuffixes[index], + numberOfWordsInsertedForEachLanguageSwitch, random); } final long end = System.currentTimeMillis(); Log.d(TAG, "testStressTestForSwitchingLanguageAndAddingWords took " - + (end - now) + " ms"); + + (end - start) + " ms"); + } finally { try { Log.d(TAG, "waiting for writing ..."); - Thread.sleep(5000); + Thread.sleep(TimeUnit.MILLISECONDS.convert(5L, TimeUnit.SECONDS)); } catch (InterruptedException e) { Log.d(TAG, "InterruptedException: " + e); } - } finally { for (final File file : dictFiles) { if (file != null) { + assertTrue(file.exists()); + assertTrue(file.length() >= MIN_USER_HISTORY_DICTIONARY_FILE_SIZE); file.delete(); } } diff --git a/tests/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtilsTests.java index fd5517665..8f5bec8a4 100644 --- a/tests/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtilsTests.java @@ -49,6 +49,7 @@ public class UserHistoryDictIOUtilsTests extends AndroidTestCase private static final int BIGRAM_FREQUENCY = 100; private static final ArrayList<String> NOT_HAVE_BIGRAM = new ArrayList<String>(); private static final FormatSpec.FormatOptions FORMAT_OPTIONS = new FormatSpec.FormatOptions(2); + private static final String TEST_DICT_FILE_EXTENSION = ".testDict"; /** * Return same frequency for all words and bigrams @@ -177,7 +178,8 @@ public class UserHistoryDictIOUtilsTests extends AndroidTestCase File file = null; try { - file = File.createTempFile("testReadAndWrite", ".dict", getContext().getCacheDir()); + file = File.createTempFile("testReadAndWrite", TEST_DICT_FILE_EXTENSION, + getContext().getCacheDir()); } catch (IOException e) { Log.d(TAG, "IOException while creating a temporary file", e); } |