diff options
Diffstat (limited to 'tests/src/com/android/inputmethod/latin')
36 files changed, 693 insertions, 704 deletions
diff --git a/tests/src/com/android/inputmethod/latin/BinaryDictionaryTests.java b/tests/src/com/android/inputmethod/latin/BinaryDictionaryTests.java index e96c934cb..db8b80949 100644 --- a/tests/src/com/android/inputmethod/latin/BinaryDictionaryTests.java +++ b/tests/src/com/android/inputmethod/latin/BinaryDictionaryTests.java @@ -16,11 +16,18 @@ package com.android.inputmethod.latin; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.LargeTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import android.text.TextUtils; import android.util.Pair; +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.LargeTest; +import androidx.test.runner.AndroidJUnit4; + import com.android.inputmethod.latin.NgramContext.WordInfo; import com.android.inputmethod.latin.common.CodePointUtils; import com.android.inputmethod.latin.common.FileUtils; @@ -30,6 +37,11 @@ import com.android.inputmethod.latin.makedict.WeightedString; import com.android.inputmethod.latin.makedict.WordProperty; import com.android.inputmethod.latin.utils.BinaryDictionaryUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -39,26 +51,25 @@ import java.util.Locale; import java.util.Random; @LargeTest -public class BinaryDictionaryTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class BinaryDictionaryTests { private static final String TEST_DICT_FILE_EXTENSION = ".testDict"; private static final String TEST_LOCALE = "test"; private static final String DICTIONARY_ID = "TestBinaryDictionary"; private HashSet<File> mDictFilesToBeDeleted = new HashSet<>(); - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { mDictFilesToBeDeleted.clear(); } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { for (final File dictFile : mDictFilesToBeDeleted) { dictFile.delete(); } mDictFilesToBeDeleted.clear(); - super.tearDown(); } private File createEmptyDictionaryAndGetFile(final int formatVersion) { @@ -82,7 +93,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { private File createEmptyVer4DictionaryAndGetFile(final int formatVersion, final HashMap<String, String> attributeMap) throws IOException { final File file = File.createTempFile(DICTIONARY_ID, TEST_DICT_FILE_EXTENSION, - getContext().getCacheDir()); + InstrumentationRegistry.getTargetContext().getCacheDir()); file.delete(); file.mkdir(); if (BinaryDictionaryUtils.createEmptyDictFile(file.getAbsolutePath(), formatVersion, @@ -106,6 +117,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { Locale.getDefault(), TEST_LOCALE, true /* isUpdatable */); } + @Test public void testIsValidDictionary() { final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403); BinaryDictionary binaryDictionary = getBinaryDictionary(dictFile); @@ -121,6 +133,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { binaryDictionary.close(); } + @Test public void testConstructingDictionaryOnMemory() { final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403); FileUtils.deleteRecursively(dictFile); @@ -142,6 +155,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { binaryDictionary.close(); } + @Test public void testAddTooLongWord() { final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403); final StringBuffer stringBuilder = new StringBuffer(); @@ -209,6 +223,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { new NgramContext(new WordInfo(word1), new WordInfo(word0)), word2); } + @Test public void testAddUnigramWord() { final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403); final int probability = 100; @@ -236,6 +251,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { assertEquals(updatedProbability, binaryDictionary.getFrequency("aaa")); } + @Test public void testRandomlyAddUnigramWord() { final int wordCount = 1000; final int codePointSetSize = 50; @@ -258,6 +274,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { } } + @Test public void testAddBigramWords() { final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403); @@ -311,6 +328,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { getBigramProbability(binaryDictionary, "abcde", "fghij")); } + @Test public void testRandomlyAddBigramWords() { final int wordCount = 100; final int bigramCount = 1000; @@ -357,6 +375,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { } } + @Test public void testAddTrigramWords() { final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403); final int unigramProbability = 100; @@ -383,6 +402,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { getTrigramProbability(binaryDictionary, "bcc", "abb", "aaa")); } + @Test public void testFlushDictionary() { final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403); BinaryDictionary binaryDictionary = getBinaryDictionary(dictFile); @@ -417,6 +437,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { binaryDictionary.close(); } + @Test public void testFlushWithGCDictionary() { final File dictFile = createEmptyDictionaryAndGetFile(FormatSpec.VERSION403); BinaryDictionary binaryDictionary = getBinaryDictionary(dictFile); @@ -447,6 +468,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { binaryDictionary.close(); } + @Test public void testAddBigramWordsAndFlashWithGC() { final int wordCount = 100; final int bigramCount = 1000; @@ -499,6 +521,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { } } + @Test public void testRandomOperationsAndFlashWithGC() { final int maxUnigramCount = 5000; final int maxBigramCount = 10000; @@ -593,6 +616,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { } } + @Test public void testAddManyUnigramsAndFlushWithGC() { final int flashWithGCIterationCount = 3; final int codePointSetSize = 50; @@ -628,6 +652,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { } } + @Test public void testUnigramAndBigramCount() { final int maxUnigramCount = 5000; final int maxBigramCount = 10000; @@ -684,6 +709,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { } } + @Test public void testGetWordProperties() { final long seed = System.currentTimeMillis(); final Random random = new Random(seed); @@ -769,6 +795,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { } } + @Test public void testIterateAllWords() { final long seed = System.currentTimeMillis(); final Random random = new Random(seed); @@ -852,6 +879,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { assertTrue(bigramSet.isEmpty()); } + @Test public void testPossiblyOffensiveAttributeMaintained() { final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403); @@ -860,6 +888,7 @@ public class BinaryDictionaryTests extends AndroidTestCase { assertEquals(true, wordProperty.mIsPossiblyOffensive); } + @Test public void testBeginningOfSentence() { final BinaryDictionary binaryDictionary = getEmptyBinaryDictionary(FormatSpec.VERSION403); final int dummyProbability = 0; diff --git a/tests/src/com/android/inputmethod/latin/ContactsContentObserverTest.java b/tests/src/com/android/inputmethod/latin/ContactsContentObserverTest.java index f90a18bf1..029e1b506 100644 --- a/tests/src/com/android/inputmethod/latin/ContactsContentObserverTest.java +++ b/tests/src/com/android/inputmethod/latin/ContactsContentObserverTest.java @@ -24,11 +24,14 @@ import static org.mockito.Mockito.when; import android.content.Context; import android.provider.ContactsContract.Contacts; -import android.test.suitebuilder.annotation.SmallTest; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -38,6 +41,7 @@ import java.util.ArrayList; * Tests for {@link ContactsContentObserver}. */ @SmallTest +@RunWith(AndroidJUnit4.class) public class ContactsContentObserverTest { private static final int UPDATED_CONTACT_COUNT = 10; private static final int STALE_CONTACT_COUNT = 8; diff --git a/tests/src/com/android/inputmethod/latin/ContactsDictionaryUtilsTest.java b/tests/src/com/android/inputmethod/latin/ContactsDictionaryUtilsTest.java index 9b49f1abb..a00c9dfdd 100644 --- a/tests/src/com/android/inputmethod/latin/ContactsDictionaryUtilsTest.java +++ b/tests/src/com/android/inputmethod/latin/ContactsDictionaryUtilsTest.java @@ -20,9 +20,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import android.test.suitebuilder.annotation.SmallTest; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import org.junit.Test; +import org.junit.runner.RunWith; import java.util.Locale; @@ -30,6 +32,7 @@ import java.util.Locale; * Tests for {@link ContactsDictionaryUtils} */ @SmallTest +@RunWith(AndroidJUnit4.class) public class ContactsDictionaryUtilsTest { @Test diff --git a/tests/src/com/android/inputmethod/latin/ContactsManagerTest.java b/tests/src/com/android/inputmethod/latin/ContactsManagerTest.java index f987e0c05..d3d746df5 100644 --- a/tests/src/com/android/inputmethod/latin/ContactsManagerTest.java +++ b/tests/src/com/android/inputmethod/latin/ContactsManagerTest.java @@ -16,6 +16,10 @@ package com.android.inputmethod.latin; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; @@ -23,17 +27,20 @@ import android.database.MatrixCursor; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.Contacts; -import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import android.test.mock.MockContentProvider; import android.test.mock.MockContentResolver; -import android.test.suitebuilder.annotation.SmallTest; + +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.ContactsDictionaryConstants; import com.android.inputmethod.latin.ContactsManager; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.HashMap; @@ -43,14 +50,16 @@ import java.util.concurrent.TimeUnit; * Tests for {@link ContactsManager} */ @SmallTest -public class ContactsManagerTest extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class ContactsManagerTest { private ContactsManager mManager; private FakeContactsContentProvider mFakeContactsContentProvider; private MatrixCursor mMatrixCursor; + private final static float EPSILON = 0.00001f; + @Before - @Override public void setUp() throws Exception { // Fake content provider mFakeContactsContentProvider = new FakeContactsContentProvider(); @@ -59,7 +68,8 @@ public class ContactsManagerTest extends AndroidTestCase { final MockContentResolver contentResolver = new MockContentResolver(); contentResolver.addProvider(ContactsContract.AUTHORITY, mFakeContactsContentProvider); // Add the fake content resolver to a fake context. - final ContextWithMockContentResolver context = new ContextWithMockContentResolver(mContext); + final ContextWithMockContentResolver context = + new ContextWithMockContentResolver(InstrumentationRegistry.getTargetContext()); context.setContentResolver(contentResolver); mManager = new ContactsManager(context); @@ -113,9 +123,10 @@ public class ContactsManagerTest extends AndroidTestCase { cursor.moveToFirst(); ContactsManager.RankedContact contact = new ContactsManager.RankedContact(cursor); contact.computeAffinity(1, month_ago); - assertEquals(contact.getAffinity(), 1.0f); + assertEquals(contact.getAffinity(), 1.0f, EPSILON); contact.computeAffinity(2, now); - assertEquals(contact.getAffinity(), (2.0f/3.0f + (float)Math.pow(0.5, 3) + 1.0f) / 3); + assertEquals(contact.getAffinity(), (2.0f/3.0f + (float)Math.pow(0.5, 3) + 1.0f) / 3, + EPSILON); } @Test diff --git a/tests/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCacheTests.java b/tests/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCacheTests.java index 6b0bbc279..f8130f33c 100644 --- a/tests/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCacheTests.java +++ b/tests/src/com/android/inputmethod/latin/DictionaryFacilitatorLruCacheTests.java @@ -16,16 +16,26 @@ package com.android.inputmethod.latin; -import java.util.Locale; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.LargeTest; +import androidx.test.runner.AndroidJUnit4; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.LargeTest; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.Locale; @LargeTest -public class DictionaryFacilitatorLruCacheTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class DictionaryFacilitatorLruCacheTests { + + @Test public void testGetFacilitator() { final DictionaryFacilitatorLruCache cache = - new DictionaryFacilitatorLruCache(getContext(), ""); + new DictionaryFacilitatorLruCache(InstrumentationRegistry.getTargetContext(), ""); final DictionaryFacilitator dictionaryFacilitatorEnUs = cache.get(Locale.US); assertNotNull(dictionaryFacilitatorEnUs); diff --git a/tests/src/com/android/inputmethod/latin/NgramContextTests.java b/tests/src/com/android/inputmethod/latin/NgramContextTests.java index 0a662db82..505818439 100644 --- a/tests/src/com/android/inputmethod/latin/NgramContextTests.java +++ b/tests/src/com/android/inputmethod/latin/NgramContextTests.java @@ -16,15 +16,26 @@ package com.android.inputmethod.latin; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + 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; +import org.junit.Test; +import org.junit.runner.RunWith; @SmallTest -public class NgramContextTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class NgramContextTests { + + @Test public void testConstruct() { assertEquals(new NgramContext(new WordInfo("a")), new NgramContext(new WordInfo("a"))); assertEquals(new NgramContext(WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO), @@ -35,6 +46,7 @@ public class NgramContextTests extends AndroidTestCase { new NgramContext(WordInfo.EMPTY_WORD_INFO)); } + @Test public void testIsBeginningOfSentenceContext() { assertFalse(new NgramContext().isBeginningOfSentenceContext()); assertTrue(new NgramContext(WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO) @@ -52,6 +64,7 @@ public class NgramContextTests extends AndroidTestCase { .isBeginningOfSentenceContext()); } + @Test public void testGetNextNgramContext() { final NgramContext ngramContext_a = new NgramContext(new WordInfo("a")); final NgramContext ngramContext_b_a = @@ -67,6 +80,7 @@ public class NgramContextTests extends AndroidTestCase { assertEquals("c", ngramContext_c_bos.getNthPrevWord(1)); } + @Test public void testExtractPrevWordsContextTest() { final NgramContext ngramContext_bos = new NgramContext(WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO); @@ -92,6 +106,7 @@ public class NgramContextTests extends AndroidTestCase { assertEquals("a", ngramContext_a_empty.extractPrevWordsContext()); } + @Test public void testExtractPrevWordsContextArray() { final NgramContext ngramContext_bos = new NgramContext(WordInfo.BEGINNING_OF_SENTENCE_WORD_INFO); @@ -123,9 +138,10 @@ public class NgramContextTests extends AndroidTestCase { assertEquals("a", ngramContext_a_empty.extractPrevWordsContextArray()[0]); } + @Test public void testGetNgramContextFromNthPreviousWord() { SpacingAndPunctuations spacingAndPunctuations = new SpacingAndPunctuations( - mContext.getResources()); + InstrumentationRegistry.getTargetContext().getResources()); assertEquals("<S>", NgramContextUtils.getNgramContextFromNthPreviousWord("", spacingAndPunctuations, 1).extractPrevWordsContext()); assertEquals("<S> b", NgramContextUtils.getNgramContextFromNthPreviousWord("a. b ", diff --git a/tests/src/com/android/inputmethod/latin/PersonalDictionaryLookupTest.java b/tests/src/com/android/inputmethod/latin/PersonalDictionaryLookupTest.java deleted file mode 100644 index c06adedfd..000000000 --- a/tests/src/com/android/inputmethod/latin/PersonalDictionaryLookupTest.java +++ /dev/null @@ -1,492 +0,0 @@ -/* - * Copyright (C) 2015 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 static com.android.inputmethod.latin.PersonalDictionaryLookup.ANY_LOCALE; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import android.annotation.SuppressLint; -import android.content.ContentResolver; -import android.database.Cursor; -import android.net.Uri; -import android.provider.UserDictionary; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; -import android.util.Log; - -import com.android.inputmethod.latin.PersonalDictionaryLookup.PersonalDictionaryListener; -import com.android.inputmethod.latin.utils.ExecutorUtils; - -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; - -/** - * Unit tests for {@link PersonalDictionaryLookup}. - * - * Note, this test doesn't mock out the ContentResolver, in order to make sure - * {@link PersonalDictionaryLookup} works in a real setting. - */ -@SmallTest -public class PersonalDictionaryLookupTest extends AndroidTestCase { - private static final String TAG = PersonalDictionaryLookupTest.class.getSimpleName(); - - private ContentResolver mContentResolver; - private HashSet<Uri> mAddedBackup; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mContentResolver = mContext.getContentResolver(); - mAddedBackup = new HashSet<Uri>(); - } - - @Override - protected void tearDown() throws Exception { - // Remove all entries added during this test. - for (Uri row : mAddedBackup) { - mContentResolver.delete(row, null, null); - } - mAddedBackup.clear(); - - super.tearDown(); - } - - /** - * Adds the given word to the personal dictionary. - * - * @param word the word to add - * @param locale the locale of the word to add - * @param frequency the frequency of the word to add - * @return the Uri for the given word - */ - @SuppressLint("NewApi") - private Uri addWord(final String word, final Locale locale, int frequency, String shortcut) { - // Add the given word for the given locale. - UserDictionary.Words.addWord(mContext, word, frequency, shortcut, locale); - // Obtain an Uri for the given word. - Cursor cursor = mContentResolver.query(UserDictionary.Words.CONTENT_URI, null, - UserDictionary.Words.WORD + "='" + word + "'", null, null); - assertTrue(cursor.moveToFirst()); - Uri uri = Uri.withAppendedPath(UserDictionary.Words.CONTENT_URI, - cursor.getString(cursor.getColumnIndex(UserDictionary.Words._ID))); - // Add the row to the backup for later clearing. - mAddedBackup.add(uri); - return uri; - } - - /** - * Deletes the entry for the given word from UserDictionary. - * - * @param uri the Uri for the word as returned by addWord - */ - private void deleteWord(Uri uri) { - // Remove the word from the backup so that it's not cleared again later. - mAddedBackup.remove(uri); - // Remove the word from the personal dictionary. - mContentResolver.delete(uri, null, null); - } - - private PersonalDictionaryLookup setUpWord(final Locale locale) { - // Insert "foo" in the personal dictionary for the given locale. - addWord("foo", locale, 17, null); - - // Create the PersonalDictionaryLookup and wait until it's loaded. - PersonalDictionaryLookup lookup = - new PersonalDictionaryLookup(mContext, ExecutorUtils.SPELLING); - lookup.open(); - return lookup; - } - - private PersonalDictionaryLookup setUpShortcut(final Locale locale) { - // Insert "shortcut" => "Expansion" in the personal dictionary for the given locale. - addWord("Expansion", locale, 17, "shortcut"); - - // Create the PersonalDictionaryLookup and wait until it's loaded. - PersonalDictionaryLookup lookup = - new PersonalDictionaryLookup(mContext, ExecutorUtils.SPELLING); - lookup.open(); - return lookup; - } - - private void verifyWordExists(final Set<String> set, final String word) { - assertTrue(set.contains(word)); - } - - private void verifyWordDoesNotExist(final Set<String> set, final String word) { - assertFalse(set.contains(word)); - } - - public void testShortcutKeyMatching() { - Log.d(TAG, "testShortcutKeyMatching"); - PersonalDictionaryLookup lookup = setUpShortcut(Locale.US); - - assertEquals("Expansion", lookup.expandShortcut("shortcut", Locale.US)); - assertNull(lookup.expandShortcut("Shortcut", Locale.US)); - assertNull(lookup.expandShortcut("SHORTCUT", Locale.US)); - assertNull(lookup.expandShortcut("shortcu", Locale.US)); - assertNull(lookup.expandShortcut("shortcutt", Locale.US)); - - lookup.close(); - } - - public void testShortcutMatchesInputCountry() { - Log.d(TAG, "testShortcutMatchesInputCountry"); - PersonalDictionaryLookup lookup = setUpShortcut(Locale.US); - - verifyWordExists(lookup.getShortcutsForLocale(Locale.US), "shortcut"); - assertTrue(lookup.getShortcutsForLocale(Locale.UK).isEmpty()); - assertTrue(lookup.getShortcutsForLocale(Locale.ENGLISH).isEmpty()); - assertTrue(lookup.getShortcutsForLocale(Locale.FRENCH).isEmpty()); - assertTrue(lookup.getShortcutsForLocale(ANY_LOCALE).isEmpty()); - - assertEquals("Expansion", lookup.expandShortcut("shortcut", Locale.US)); - assertNull(lookup.expandShortcut("shortcut", Locale.UK)); - assertNull(lookup.expandShortcut("shortcut", Locale.ENGLISH)); - assertNull(lookup.expandShortcut("shortcut", Locale.FRENCH)); - assertNull(lookup.expandShortcut("shortcut", ANY_LOCALE)); - - lookup.close(); - } - - public void testShortcutMatchesInputLanguage() { - Log.d(TAG, "testShortcutMatchesInputLanguage"); - PersonalDictionaryLookup lookup = setUpShortcut(Locale.ENGLISH); - - verifyWordExists(lookup.getShortcutsForLocale(Locale.US), "shortcut"); - verifyWordExists(lookup.getShortcutsForLocale(Locale.UK), "shortcut"); - verifyWordExists(lookup.getShortcutsForLocale(Locale.ENGLISH), "shortcut"); - assertTrue(lookup.getShortcutsForLocale(Locale.FRENCH).isEmpty()); - assertTrue(lookup.getShortcutsForLocale(ANY_LOCALE).isEmpty()); - - assertEquals("Expansion", lookup.expandShortcut("shortcut", Locale.US)); - assertEquals("Expansion", lookup.expandShortcut("shortcut", Locale.UK)); - assertEquals("Expansion", lookup.expandShortcut("shortcut", Locale.ENGLISH)); - assertNull(lookup.expandShortcut("shortcut", Locale.FRENCH)); - assertNull(lookup.expandShortcut("shortcut", ANY_LOCALE)); - - lookup.close(); - } - - public void testShortcutMatchesAnyLocale() { - PersonalDictionaryLookup lookup = setUpShortcut(PersonalDictionaryLookup.ANY_LOCALE); - - verifyWordExists(lookup.getShortcutsForLocale(Locale.US), "shortcut"); - verifyWordExists(lookup.getShortcutsForLocale(Locale.UK), "shortcut"); - verifyWordExists(lookup.getShortcutsForLocale(Locale.ENGLISH), "shortcut"); - verifyWordExists(lookup.getShortcutsForLocale(Locale.FRENCH), "shortcut"); - verifyWordExists(lookup.getShortcutsForLocale(ANY_LOCALE), "shortcut"); - - assertEquals("Expansion", lookup.expandShortcut("shortcut", Locale.US)); - assertEquals("Expansion", lookup.expandShortcut("shortcut", Locale.UK)); - assertEquals("Expansion", lookup.expandShortcut("shortcut", Locale.ENGLISH)); - assertEquals("Expansion", lookup.expandShortcut("shortcut", Locale.FRENCH)); - assertEquals("Expansion", lookup.expandShortcut("shortcut", ANY_LOCALE)); - - lookup.close(); - } - - public void testExactLocaleMatch() { - Log.d(TAG, "testExactLocaleMatch"); - PersonalDictionaryLookup lookup = setUpWord(Locale.US); - - verifyWordExists(lookup.getWordsForLocale(Locale.US), "foo"); - verifyWordDoesNotExist(lookup.getWordsForLocale(Locale.UK), "foo"); - verifyWordDoesNotExist(lookup.getWordsForLocale(Locale.ENGLISH), "foo"); - verifyWordDoesNotExist(lookup.getWordsForLocale(Locale.FRENCH), "foo"); - verifyWordDoesNotExist(lookup.getWordsForLocale(ANY_LOCALE), "foo"); - - // Any capitalization variation should match. - assertTrue(lookup.isValidWord("foo", Locale.US)); - assertTrue(lookup.isValidWord("Foo", Locale.US)); - assertTrue(lookup.isValidWord("FOO", Locale.US)); - // But similar looking words don't match. - assertFalse(lookup.isValidWord("fo", Locale.US)); - assertFalse(lookup.isValidWord("fop", Locale.US)); - assertFalse(lookup.isValidWord("fooo", Locale.US)); - // Other locales, including more general locales won't match. - assertFalse(lookup.isValidWord("foo", Locale.ENGLISH)); - assertFalse(lookup.isValidWord("foo", Locale.UK)); - assertFalse(lookup.isValidWord("foo", Locale.FRENCH)); - assertFalse(lookup.isValidWord("foo", ANY_LOCALE)); - - lookup.close(); - } - - public void testSubLocaleMatch() { - Log.d(TAG, "testSubLocaleMatch"); - PersonalDictionaryLookup lookup = setUpWord(Locale.ENGLISH); - - verifyWordExists(lookup.getWordsForLocale(Locale.US), "foo"); - verifyWordExists(lookup.getWordsForLocale(Locale.UK), "foo"); - verifyWordExists(lookup.getWordsForLocale(Locale.ENGLISH), "foo"); - verifyWordDoesNotExist(lookup.getWordsForLocale(Locale.FRENCH), "foo"); - verifyWordDoesNotExist(lookup.getWordsForLocale(ANY_LOCALE), "foo"); - - // Any capitalization variation should match for both en and en_US. - assertTrue(lookup.isValidWord("foo", Locale.ENGLISH)); - assertTrue(lookup.isValidWord("foo", Locale.US)); - assertTrue(lookup.isValidWord("Foo", Locale.US)); - assertTrue(lookup.isValidWord("FOO", Locale.US)); - // But similar looking words don't match. - assertFalse(lookup.isValidWord("fo", Locale.US)); - assertFalse(lookup.isValidWord("fop", Locale.US)); - assertFalse(lookup.isValidWord("fooo", Locale.US)); - - lookup.close(); - } - - public void testAllLocalesMatch() { - Log.d(TAG, "testAllLocalesMatch"); - PersonalDictionaryLookup lookup = setUpWord(null); - - verifyWordExists(lookup.getWordsForLocale(Locale.US), "foo"); - verifyWordExists(lookup.getWordsForLocale(Locale.UK), "foo"); - verifyWordExists(lookup.getWordsForLocale(Locale.ENGLISH), "foo"); - verifyWordExists(lookup.getWordsForLocale(Locale.FRENCH), "foo"); - verifyWordExists(lookup.getWordsForLocale(ANY_LOCALE), "foo"); - - // Any capitalization variation should match for fr, en and en_US. - assertTrue(lookup.isValidWord("foo", ANY_LOCALE)); - assertTrue(lookup.isValidWord("foo", Locale.FRENCH)); - assertTrue(lookup.isValidWord("foo", Locale.ENGLISH)); - assertTrue(lookup.isValidWord("foo", Locale.US)); - assertTrue(lookup.isValidWord("Foo", Locale.US)); - assertTrue(lookup.isValidWord("FOO", Locale.US)); - // But similar looking words don't match. - assertFalse(lookup.isValidWord("fo", Locale.US)); - assertFalse(lookup.isValidWord("fop", Locale.US)); - assertFalse(lookup.isValidWord("fooo", Locale.US)); - - lookup.close(); - } - - public void testMultipleLocalesMatch() { - Log.d(TAG, "testMultipleLocalesMatch"); - - // Insert "Foo" as capitalized in the personal dictionary under the en_US and en_CA and fr - // locales. - addWord("Foo", Locale.US, 17, null); - addWord("foO", Locale.CANADA, 17, null); - addWord("fOo", Locale.FRENCH, 17, null); - - // Create the PersonalDictionaryLookup and wait until it's loaded. - PersonalDictionaryLookup lookup = new PersonalDictionaryLookup(mContext, - ExecutorUtils.SPELLING); - lookup.open(); - - // Both en_CA and en_US match. - assertTrue(lookup.isValidWord("foo", Locale.CANADA)); - assertTrue(lookup.isValidWord("foo", Locale.US)); - assertTrue(lookup.isValidWord("foo", Locale.FRENCH)); - // Other locales, including more general locales won't match. - assertFalse(lookup.isValidWord("foo", Locale.ENGLISH)); - assertFalse(lookup.isValidWord("foo", Locale.UK)); - assertFalse(lookup.isValidWord("foo", ANY_LOCALE)); - - lookup.close(); - } - - - public void testCaseMatchingForWordsAndShortcuts() { - Log.d(TAG, "testCaseMatchingForWordsAndShortcuts"); - addWord("Foo", Locale.US, 17, "f"); - addWord("bokabu", Locale.US, 17, "Bu"); - - // Create the PersonalDictionaryLookup and wait until it's loaded. - PersonalDictionaryLookup lookup = new PersonalDictionaryLookup(mContext, - ExecutorUtils.SPELLING); - lookup.open(); - - // Valid, inspite of capitalization in US but not in other - // locales. - assertTrue(lookup.isValidWord("Foo", Locale.US)); - assertTrue(lookup.isValidWord("foo", Locale.US)); - assertFalse(lookup.isValidWord("Foo", Locale.UK)); - assertFalse(lookup.isValidWord("foo", Locale.UK)); - - // Valid in all forms in US. - assertTrue(lookup.isValidWord("bokabu", Locale.US)); - assertTrue(lookup.isValidWord("BOKABU", Locale.US)); - assertTrue(lookup.isValidWord("BokaBU", Locale.US)); - - // Correct capitalization; sensitive to shortcut casing & locale. - assertEquals("Foo", lookup.expandShortcut("f", Locale.US)); - assertNull(lookup.expandShortcut("f", Locale.UK)); - - // Correct capitalization; sensitive to shortcut casing & locale. - assertEquals("bokabu", lookup.expandShortcut("Bu", Locale.US)); - assertNull(lookup.expandShortcut("Bu", Locale.UK)); - assertNull(lookup.expandShortcut("bu", Locale.US)); - - // Verify that raw strings are retained for #getWordsForLocale. - verifyWordExists(lookup.getWordsForLocale(Locale.US), "Foo"); - verifyWordDoesNotExist(lookup.getWordsForLocale(Locale.US), "foo"); - } - - public void testManageListeners() { - Log.d(TAG, "testManageListeners"); - - PersonalDictionaryLookup lookup = - new PersonalDictionaryLookup(mContext, ExecutorUtils.SPELLING); - - PersonalDictionaryListener listener = mock(PersonalDictionaryListener.class); - // Add the same listener a bunch of times. It doesn't make a difference. - lookup.addListener(listener); - lookup.addListener(listener); - lookup.addListener(listener); - lookup.notifyListeners(); - - verify(listener, times(1)).onUpdate(); - - // Remove the same listener a bunch of times. It doesn't make a difference. - lookup.removeListener(listener); - lookup.removeListener(listener); - lookup.removeListener(listener); - lookup.notifyListeners(); - - verifyNoMoreInteractions(listener); - } - - public void testReload() { - Log.d(TAG, "testReload"); - - // Insert "foo". - Uri uri = addWord("foo", Locale.US, 17, null); - - // Create the PersonalDictionaryLookup and wait until it's loaded. - PersonalDictionaryLookup lookup = - new PersonalDictionaryLookup(mContext, ExecutorUtils.SPELLING); - lookup.open(); - - // "foo" should match. - assertTrue(lookup.isValidWord("foo", Locale.US)); - - // "bar" shouldn't match. - assertFalse(lookup.isValidWord("bar", Locale.US)); - - // Now delete "foo" and add "bar". - deleteWord(uri); - addWord("bar", Locale.US, 18, null); - - // Wait a little bit before expecting a change. The time we wait should be greater than - // PersonalDictionaryLookup.RELOAD_DELAY_MS. - try { - Thread.sleep(PersonalDictionaryLookup.RELOAD_DELAY_MS + 1000); - } catch (InterruptedException e) { - } - - // Perform lookups again. Reload should have occured. - // - // "foo" should not match. - assertFalse(lookup.isValidWord("foo", Locale.US)); - - // "bar" should match. - assertTrue(lookup.isValidWord("bar", Locale.US)); - - lookup.close(); - } - - public void testDictionaryStats() { - Log.d(TAG, "testDictionaryStats"); - - // Insert "foo" and "bar". Only "foo" has a shortcut. - Uri uri = addWord("foo", Locale.GERMANY, 17, "f"); - addWord("bar", Locale.GERMANY, 17, null); - - // Create the PersonalDictionaryLookup and wait until it's loaded. - PersonalDictionaryLookup lookup = - new PersonalDictionaryLookup(mContext, ExecutorUtils.SPELLING); - lookup.open(); - - // "foo" should match. - assertTrue(lookup.isValidWord("foo", Locale.GERMANY)); - - // "bar" should match. - assertTrue(lookup.isValidWord("bar", Locale.GERMANY)); - - // "foo" should have a shortcut. - assertEquals("foo", lookup.expandShortcut("f", Locale.GERMANY)); - - // Now delete "foo". - deleteWord(uri); - - // Wait a little bit before expecting a change. The time we wait should be greater than - // PersonalDictionaryLookup.RELOAD_DELAY_MS. - try { - Thread.sleep(PersonalDictionaryLookup.RELOAD_DELAY_MS + 1000); - } catch (InterruptedException e) { - } - - // Perform lookups again. Reload should have occured. - // - // "foo" should not match. - assertFalse(lookup.isValidWord("foo", Locale.GERMANY)); - - // "foo" should not have a shortcut. - assertNull(lookup.expandShortcut("f", Locale.GERMANY)); - - // "bar" should still match. - assertTrue(lookup.isValidWord("bar", Locale.GERMANY)); - - lookup.close(); - } - - public void testClose() { - Log.d(TAG, "testClose"); - - // Insert "foo". - Uri uri = addWord("foo", Locale.US, 17, null); - - // Create the PersonalDictionaryLookup and wait until it's loaded. - PersonalDictionaryLookup lookup = - new PersonalDictionaryLookup(mContext, ExecutorUtils.SPELLING); - lookup.open(); - - // "foo" should match. - assertTrue(lookup.isValidWord("foo", Locale.US)); - - // "bar" shouldn't match. - assertFalse(lookup.isValidWord("bar", Locale.US)); - - // Now close (prevents further reloads). - lookup.close(); - - // Now delete "foo" and add "bar". - deleteWord(uri); - addWord("bar", Locale.US, 18, null); - - // Wait a little bit before expecting a change. The time we wait should be greater than - // PersonalDictionaryLookup.RELOAD_DELAY_MS. - try { - Thread.sleep(PersonalDictionaryLookup.RELOAD_DELAY_MS + 1000); - } catch (InterruptedException e) { - } - - // Perform lookups again. Reload should not have occurred. - // - // "foo" should stil match. - assertTrue(lookup.isValidWord("foo", Locale.US)); - - // "bar" should still not match. - assertFalse(lookup.isValidWord("bar", Locale.US)); - } -} diff --git a/tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java b/tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java index 128f9f7db..ac38468f9 100644 --- a/tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java +++ b/tests/src/com/android/inputmethod/latin/RichInputConnectionAndTextRangeTests.java @@ -16,12 +16,13 @@ package com.android.inputmethod.latin; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import android.content.res.Resources; import android.inputmethodservice.InputMethodService; import android.os.Parcel; -import android.test.AndroidTestCase; -import android.test.MoreAsserts; -import android.test.suitebuilder.annotation.SmallTest; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.SuggestionSpan; @@ -30,6 +31,10 @@ import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputConnectionWrapper; +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + import com.android.inputmethod.latin.common.Constants; import com.android.inputmethod.latin.common.StringUtils; import com.android.inputmethod.latin.settings.SpacingAndPunctuations; @@ -38,25 +43,29 @@ import com.android.inputmethod.latin.utils.RunInLocale; import com.android.inputmethod.latin.utils.ScriptUtils; import com.android.inputmethod.latin.utils.TextRange; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.Locale; @SmallTest -public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class RichInputConnectionAndTextRangeTests { // The following is meant to be a reasonable default for // the "word_separators" resource. private SpacingAndPunctuations mSpacingAndPunctuations; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { final RunInLocale<SpacingAndPunctuations> job = new RunInLocale<SpacingAndPunctuations>() { @Override protected SpacingAndPunctuations job(final Resources res) { return new SpacingAndPunctuations(res); } }; - final Resources res = getContext().getResources(); + final Resources res = InstrumentationRegistry.getTargetContext().getResources(); mSpacingAndPunctuations = job.runInLocale(res, Locale.ENGLISH); } @@ -156,6 +165,7 @@ public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { /** * Test for getting previous word (for bigram suggestions) */ + @Test public void testGetPreviousWord() { // If one of the following cases breaks, the bigram suggestions won't work. assertEquals(NgramContextUtils.getNgramContextFromNthPreviousWord( @@ -218,6 +228,7 @@ public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { "abc 'def", mSpacingAndPunctuations, 2), NgramContext.EMPTY_PREV_WORDS_INFO); } + @Test public void testGetWordRangeAtCursor() { /** * Test logic in getting the word range at the cursor. @@ -282,6 +293,7 @@ public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { /** * Test logic in getting the word range at the cursor. */ + @Test public void testGetSuggestionSpansAtWord() { helpTestGetSuggestionSpansAtWord(10); helpTestGetSuggestionSpansAtWord(12); @@ -309,7 +321,7 @@ public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN); suggestions = r.getSuggestionSpansAtWord(); assertEquals(suggestions.length, 1); - MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); + assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); // Test the case with 2 suggestion spans in the same place. text = new SpannableString("This is a string for test"); @@ -321,8 +333,8 @@ public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN); suggestions = r.getSuggestionSpansAtWord(); assertEquals(suggestions.length, 2); - MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); - MoreAsserts.assertEquals(suggestions[1].getSuggestions(), SUGGESTIONS2); + assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); + assertEquals(suggestions[1].getSuggestions(), SUGGESTIONS2); // Test a case with overlapping spans, 2nd extending past the start of the word text = new SpannableString("This is a string for test"); @@ -334,7 +346,7 @@ public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN); suggestions = r.getSuggestionSpansAtWord(); assertEquals(suggestions.length, 1); - MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); + assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); // Test a case with overlapping spans, 2nd extending past the end of the word text = new SpannableString("This is a string for test"); @@ -346,7 +358,7 @@ public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN); suggestions = r.getSuggestionSpansAtWord(); assertEquals(suggestions.length, 1); - MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); + assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); // Test a case with overlapping spans, 2nd extending past both ends of the word text = new SpannableString("This is a string for test"); @@ -358,7 +370,7 @@ public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { r = ic.getWordRangeAtCursor(SPACE, ScriptUtils.SCRIPT_LATIN); suggestions = r.getSuggestionSpansAtWord(); assertEquals(suggestions.length, 1); - MoreAsserts.assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); + assertEquals(suggestions[0].getSuggestions(), SUGGESTIONS1); // Test a case with overlapping spans, none right on the word text = new SpannableString("This is a string for test"); @@ -372,6 +384,7 @@ public class RichInputConnectionAndTextRangeTests extends AndroidTestCase { assertEquals(suggestions.length, 0); } + @Test public void testCursorTouchingWord() { final MockInputMethodService ims = new MockInputMethodService(); final RichInputConnection ic = new RichInputConnection(ims); diff --git a/tests/src/com/android/inputmethod/latin/RichInputMethodSubtypeTests.java b/tests/src/com/android/inputmethod/latin/RichInputMethodSubtypeTests.java index af94be664..578e6bea0 100644 --- a/tests/src/com/android/inputmethod/latin/RichInputMethodSubtypeTests.java +++ b/tests/src/com/android/inputmethod/latin/RichInputMethodSubtypeTests.java @@ -16,13 +16,20 @@ package com.android.inputmethod.latin; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import android.content.Context; import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodSubtype; +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.RichInputMethodManager; import com.android.inputmethod.latin.RichInputMethodSubtype; @@ -30,11 +37,17 @@ import com.android.inputmethod.latin.utils.AdditionalSubtypeUtils; import com.android.inputmethod.latin.utils.RunInLocale; import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.ArrayList; import java.util.Locale; @SmallTest -public class RichInputMethodSubtypeTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class RichInputMethodSubtypeTests { // All input method subtypes of LatinIME. private final ArrayList<RichInputMethodSubtype> mSubtypesList = new ArrayList<>(); @@ -67,10 +80,9 @@ public class RichInputMethodSubtypeTests extends AndroidTestCase { RichInputMethodSubtype HI_LATN_DVORAK; RichInputMethodSubtype SR_LATN_QWERTY; - @Override - protected void setUp() throws Exception { - super.setUp(); - final Context context = getContext(); + @Before + public void setUp() throws Exception { + final Context context = InstrumentationRegistry.getTargetContext(); mRes = context.getResources(); RichInputMethodManager.init(context); mRichImm = RichInputMethodManager.getInstance(); @@ -152,13 +164,13 @@ public class RichInputMethodSubtypeTests extends AndroidTestCase { } } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { // Restore additional subtypes. mRichImm.setAdditionalInputMethodSubtypes(mSavedAddtionalSubtypes); - super.tearDown(); } + @Test public void testAllFullDisplayNameForSpacebar() { for (final RichInputMethodSubtype subtype : mSubtypesList) { final String subtypeName = SubtypeLocaleUtils @@ -174,7 +186,8 @@ public class RichInputMethodSubtypeTests extends AndroidTestCase { } } - public void testAllMiddleDisplayNameForSpacebar() { + @Test + public void testAllMiddleDisplayNameForSpacebar() { for (final RichInputMethodSubtype subtype : mSubtypesList) { final String subtypeName = SubtypeLocaleUtils .getSubtypeDisplayNameInSystemLocale(subtype.getRawSubtype()); @@ -293,22 +306,27 @@ public class RichInputMethodSubtypeTests extends AndroidTestCase { } }; + @Test public void testPredefinedSubtypesForSpacebarInEnglish() { testsPredefinedSubtypesForSpacebar.runInLocale(mRes, Locale.ENGLISH); } + @Test public void testAdditionalSubtypeForSpacebarInEnglish() { testsAdditionalSubtypesForSpacebar.runInLocale(mRes, Locale.ENGLISH); } + @Test public void testPredefinedSubtypesForSpacebarInFrench() { testsPredefinedSubtypesForSpacebar.runInLocale(mRes, Locale.FRENCH); } + @Test public void testAdditionalSubtypeForSpacebarInFrench() { testsAdditionalSubtypesForSpacebar.runInLocale(mRes, Locale.FRENCH); } + @Test public void testRichInputMethodSubtypeForNullInputMethodSubtype() { RichInputMethodSubtype subtype = RichInputMethodSubtype.getRichInputMethodSubtype(null); assertNotNull(subtype); diff --git a/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java b/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java index d465ce674..92bff0e2e 100644 --- a/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java +++ b/tests/src/com/android/inputmethod/latin/SuggestedWordsTests.java @@ -16,16 +16,24 @@ package com.android.inputmethod.latin; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.ArrayList; import java.util.Locale; @SmallTest -public class SuggestedWordsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class SuggestedWordsTests { /** * Helper method to create a dummy {@link SuggestedWordInfo} with specifying @@ -80,30 +88,35 @@ public class SuggestedWordsTests extends AndroidTestCase { return returnedWordInfo; } + @Test public void testRemoveDupesNoDupes() { final ArrayList<SuggestedWordInfo> infos = createCorrectionWordInfos("a", "c"); assertEquals(-1, SuggestedWordInfo.removeDups("b", infos)); assertEquals(2, infos.size()); } + @Test public void testRemoveDupesTypedWordNotDupe() { final ArrayList<SuggestedWordInfo> infos = createCorrectionWordInfos("a", "a", "c"); assertEquals(-1, SuggestedWordInfo.removeDups("b", infos)); assertEquals(2, infos.size()); } + @Test public void testRemoveDupesTypedWordOnlyDupe() { final ArrayList<SuggestedWordInfo> infos = createCorrectionWordInfos("a", "b", "c"); assertEquals(1, SuggestedWordInfo.removeDups("b", infos)); assertEquals(2, infos.size()); } + @Test public void testRemoveDupesTypedWordNotOnlyDupe() { final ArrayList<SuggestedWordInfo> infos = createCorrectionWordInfos("a", "b", "b", "c"); assertEquals(1, SuggestedWordInfo.removeDups("b", infos)); assertEquals(2, infos.size()); } + @Test public void testGetTransformedSuggestedWordInfo() { SuggestedWordInfo result = transformWordInfo("word", 0); assertEquals(result.mWord, "word"); @@ -119,6 +132,7 @@ public class SuggestedWordsTests extends AndroidTestCase { assertEquals(result.mWord, "didn't''"); } + @Test public void testGetTypedWordInfoOrNull() { final String TYPED_WORD = "typed"; final SuggestedWordInfo TYPED_WORD_INFO = createTypedWordInfo(TYPED_WORD); diff --git a/tests/src/com/android/inputmethod/latin/WordComposerTests.java b/tests/src/com/android/inputmethod/latin/WordComposerTests.java index 8ae475f7e..4ac094b25 100644 --- a/tests/src/com/android/inputmethod/latin/WordComposerTests.java +++ b/tests/src/com/android/inputmethod/latin/WordComposerTests.java @@ -16,18 +16,28 @@ package com.android.inputmethod.latin; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.common.Constants; import com.android.inputmethod.latin.common.CoordinateUtils; import com.android.inputmethod.latin.common.StringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; + /** * Unit tests for WordComposer. */ @SmallTest -public class WordComposerTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class WordComposerTests { + + @Test public void testMoveCursor() { final WordComposer wc = new WordComposer(); // BMP is the Basic Multilingual Plane, as defined by Unicode. This includes diff --git a/tests/src/com/android/inputmethod/latin/accounts/AccountsChangedReceiverTests.java b/tests/src/com/android/inputmethod/latin/accounts/AccountsChangedReceiverTests.java index 832817967..86f453b08 100644 --- a/tests/src/com/android/inputmethod/latin/accounts/AccountsChangedReceiverTests.java +++ b/tests/src/com/android/inputmethod/latin/accounts/AccountsChangedReceiverTests.java @@ -16,40 +16,55 @@ package com.android.inputmethod.latin.accounts; +import static org.junit.Assert.assertEquals; + import android.accounts.AccountManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; -import android.test.AndroidTestCase; + +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.settings.LocalSettingsConstants; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + /** * Tests for {@link AccountsChangedReceiver}. */ -public class AccountsChangedReceiverTests extends AndroidTestCase { +@SmallTest +@RunWith(AndroidJUnit4.class) +public class AccountsChangedReceiverTests { private static final String ACCOUNT_1 = "account1@example.com"; private static final String ACCOUNT_2 = "account2@example.com"; private SharedPreferences mPrefs; private String mLastKnownAccount = null; - @Override - protected void setUp() throws Exception { - super.setUp(); + private Context getContext() { + return InstrumentationRegistry.getTargetContext(); + } + + @Before + public void setUp() throws Exception { mPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); // Keep track of the current account so that we restore it when the test finishes. mLastKnownAccount = mPrefs.getString(LocalSettingsConstants.PREF_ACCOUNT_NAME, null); } - @Override - protected void tearDown() throws Exception { - super.tearDown(); + @After + public void tearDown() throws Exception { // Restore the account that was present before running the test. updateAccountName(mLastKnownAccount); } + @Test public void testUnknownIntent() { updateAccountName(ACCOUNT_1); AccountsChangedReceiver reciever = new AccountsChangedReceiver(); @@ -58,6 +73,7 @@ public class AccountsChangedReceiverTests extends AndroidTestCase { assertAccountName(ACCOUNT_1); } + @Test public void testAccountRemoved() { updateAccountName(ACCOUNT_1); AccountsChangedReceiver reciever = new AccountsChangedReceiver() { @@ -71,6 +87,7 @@ public class AccountsChangedReceiverTests extends AndroidTestCase { assertAccountName(null); } + @Test public void testAccountRemoved_noAccounts() { updateAccountName(ACCOUNT_2); AccountsChangedReceiver reciever = new AccountsChangedReceiver() { @@ -84,6 +101,7 @@ public class AccountsChangedReceiverTests extends AndroidTestCase { assertAccountName(null); } + @Test public void testAccountNotRemoved() { updateAccountName(ACCOUNT_2); AccountsChangedReceiver reciever = new AccountsChangedReceiver() { diff --git a/tests/src/com/android/inputmethod/latin/common/InputPointersTests.java b/tests/src/com/android/inputmethod/latin/common/InputPointersTests.java index 6b3490de8..29abec365 100644 --- a/tests/src/com/android/inputmethod/latin/common/InputPointersTests.java +++ b/tests/src/com/android/inputmethod/latin/common/InputPointersTests.java @@ -16,15 +16,27 @@ package com.android.inputmethod.latin.common; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; import java.util.Arrays; @SmallTest -public class InputPointersTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class InputPointersTests { private static final int DEFAULT_CAPACITY = 48; + @Test public void testNewInstance() { final InputPointers src = new InputPointers(DEFAULT_CAPACITY); assertEquals("new instance size", 0, src.getPointerSize()); @@ -34,6 +46,7 @@ public class InputPointersTests extends AndroidTestCase { assertNotNull("new instance times", src.getTimes()); } + @Test public void testReset() { final InputPointers src = new InputPointers(DEFAULT_CAPACITY); final int[] xCoordinates = src.getXCoordinates(); @@ -49,6 +62,7 @@ public class InputPointersTests extends AndroidTestCase { assertNotSame("times after reset", times, src.getTimes()); } + @Test public void testAdd() { final InputPointers src = new InputPointers(DEFAULT_CAPACITY); final int limit = src.getXCoordinates().length * 2 + 10; @@ -72,6 +86,7 @@ public class InputPointersTests extends AndroidTestCase { } } + @Test public void testAddAt() { final InputPointers src = new InputPointers(DEFAULT_CAPACITY); final int limit = 1000, step = 100; @@ -95,6 +110,7 @@ public class InputPointersTests extends AndroidTestCase { } } + @Test public void testSet() { final InputPointers src = new InputPointers(DEFAULT_CAPACITY); final int limit = src.getXCoordinates().length * 2 + 10; @@ -114,6 +130,7 @@ public class InputPointersTests extends AndroidTestCase { assertSame("times after set", dst.getTimes(), src.getTimes()); } + @Test public void testCopy() { final InputPointers src = new InputPointers(DEFAULT_CAPACITY); final int limit = 100; @@ -142,6 +159,7 @@ public class InputPointersTests extends AndroidTestCase { dst.getTimes(), 0, src.getTimes(), 0, size); } + @Test public void testAppend() { final int dstLength = 50; final InputPointers dst = new InputPointers(DEFAULT_CAPACITY); @@ -211,6 +229,7 @@ public class InputPointersTests extends AndroidTestCase { srcTimes.getPrimitiveArray(), startPos, dst.getTimes(), dstLength, srcLength); } + @Test public void testAppendResizableIntArray() { final int dstLength = 50; final InputPointers dst = new InputPointers(DEFAULT_CAPACITY); @@ -296,6 +315,7 @@ public class InputPointersTests extends AndroidTestCase { } } + @Test public void testShift() { final InputPointers src = new InputPointers(DEFAULT_CAPACITY); final int limit = 100; diff --git a/tests/src/com/android/inputmethod/latin/common/ResizableIntArrayTests.java b/tests/src/com/android/inputmethod/latin/common/ResizableIntArrayTests.java index bd1629faf..5151b6b2b 100644 --- a/tests/src/com/android/inputmethod/latin/common/ResizableIntArrayTests.java +++ b/tests/src/com/android/inputmethod/latin/common/ResizableIntArrayTests.java @@ -16,15 +16,27 @@ package com.android.inputmethod.latin.common; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; import java.util.Arrays; @SmallTest -public class ResizableIntArrayTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class ResizableIntArrayTests { private static final int DEFAULT_CAPACITY = 48; + @Test public void testNewInstance() { final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); final int[] array = src.getPrimitiveArray(); @@ -33,6 +45,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { assertEquals("new instance array length", DEFAULT_CAPACITY, array.length); } + @Test public void testAdd() { final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); final int[] array = src.getPrimitiveArray(); @@ -62,6 +75,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { } } + @Test public void testAddAt() { final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); final int limit = DEFAULT_CAPACITY * 10, step = DEFAULT_CAPACITY * 2; @@ -76,6 +90,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { } } + @Test public void testGet() { final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); try { @@ -105,6 +120,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { } } + @Test public void testReset() { final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); final int[] array = src.getPrimitiveArray(); @@ -136,6 +152,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { } } + @Test public void testSetLength() { final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); final int[] array = src.getPrimitiveArray(); @@ -172,6 +189,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { } } + @Test public void testSet() { final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); final int limit = DEFAULT_CAPACITY * 2 + 10; @@ -186,6 +204,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { assertSame("array after set", dst.getPrimitiveArray(), src.getPrimitiveArray()); } + @Test public void testCopy() { final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); for (int i = 0; i < DEFAULT_CAPACITY; i++) { @@ -214,6 +233,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { dst.getPrimitiveArray(), 0, src.getPrimitiveArray(), 0, dst.getLength()); } + @Test public void testAppend() { final int srcLength = DEFAULT_CAPACITY; final ResizableIntArray src = new ResizableIntArray(srcLength); @@ -264,6 +284,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { srcLength); } + @Test public void testFill() { final int srcLength = DEFAULT_CAPACITY; final ResizableIntArray src = new ResizableIntArray(srcLength); @@ -359,6 +380,7 @@ public class ResizableIntArrayTests extends AndroidTestCase { } } + @Test public void testShift() { final ResizableIntArray src = new ResizableIntArray(DEFAULT_CAPACITY); final int limit = DEFAULT_CAPACITY * 10; diff --git a/tests/src/com/android/inputmethod/latin/common/StringUtilsTests.java b/tests/src/com/android/inputmethod/latin/common/StringUtilsTests.java index ec9d4be92..36a4b912d 100644 --- a/tests/src/com/android/inputmethod/latin/common/StringUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/common/StringUtilsTests.java @@ -16,13 +16,21 @@ package com.android.inputmethod.latin.common; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; import java.util.Locale; @SmallTest -public class StringUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class StringUtilsTests { private static final Locale US = Locale.US; private static final Locale GERMAN = Locale.GERMAN; private static final Locale TURKEY = new Locale("tr", "TR"); @@ -34,6 +42,7 @@ public class StringUtilsTests extends AndroidTestCase { StringUtils.toTitleCaseOfKeyLabel(lowerCase, locale)); } + @Test public void test_toTitleCaseOfKeyLabel() { assert_toTitleCaseOfKeyLabel(US, null, null); assert_toTitleCaseOfKeyLabel(US, "", ""); @@ -116,6 +125,7 @@ public class StringUtilsTests extends AndroidTestCase { StringUtils.toTitleCaseOfKeyCode(lowerCase, locale)); } + @Test public void test_toTitleCaseOfKeyCode() { assert_toTitleCaseOfKeyCode(US, Constants.CODE_ENTER, Constants.CODE_ENTER); assert_toTitleCaseOfKeyCode(US, Constants.CODE_SPACE, Constants.CODE_SPACE); @@ -148,6 +158,7 @@ public class StringUtilsTests extends AndroidTestCase { StringUtils.capitalizeFirstCodePoint(text, locale)); } + @Test public void test_capitalizeFirstCodePoint() { assert_capitalizeFirstCodePoint(US, "", ""); assert_capitalizeFirstCodePoint(US, "a", "A"); @@ -167,6 +178,7 @@ public class StringUtilsTests extends AndroidTestCase { StringUtils.capitalizeFirstAndDowncaseRest(text, locale)); } + @Test public void test_capitalizeFirstAndDowncaseRest() { assert_capitalizeFirstAndDowncaseRest(US, "", ""); assert_capitalizeFirstAndDowncaseRest(US, "a", "A"); @@ -185,6 +197,7 @@ public class StringUtilsTests extends AndroidTestCase { assert_capitalizeFirstAndDowncaseRest(GREECE, "ΆΝΕΣΗ", "Άνεση"); } + @Test public void testContainsInArray() { assertFalse("empty array", StringUtils.containsInArray("key", new String[0])); assertFalse("not in 1 element", StringUtils.containsInArray("key", new String[] { @@ -202,6 +215,7 @@ public class StringUtilsTests extends AndroidTestCase { })); } + @Test public void testContainsInCommaSplittableText() { assertFalse("null", StringUtils.containsInCommaSplittableText("key", null)); assertFalse("empty", StringUtils.containsInCommaSplittableText("key", "")); @@ -214,6 +228,7 @@ public class StringUtilsTests extends AndroidTestCase { assertTrue("in 2 elements", StringUtils.containsInCommaSplittableText("key", "key1,key")); } + @Test public void testRemoveFromCommaSplittableTextIfExists() { assertEquals("null", "", StringUtils.removeFromCommaSplittableTextIfExists("key", null)); assertEquals("empty", "", StringUtils.removeFromCommaSplittableTextIfExists("key", "")); @@ -239,7 +254,7 @@ public class StringUtilsTests extends AndroidTestCase { "key", "key1,key,key3,key,key5")); } - + @Test public void testCapitalizeFirstCodePoint() { assertEquals("SSaa", StringUtils.capitalizeFirstCodePoint("ßaa", Locale.GERMAN)); @@ -259,6 +274,7 @@ public class StringUtilsTests extends AndroidTestCase { StringUtils.capitalizeFirstCodePoint("A", Locale.ENGLISH)); } + @Test public void testCapitalizeFirstAndDowncaseRest() { assertEquals("SSaa", StringUtils.capitalizeFirstAndDowncaseRest("ßaa", Locale.GERMAN)); @@ -278,6 +294,7 @@ public class StringUtilsTests extends AndroidTestCase { StringUtils.capitalizeFirstAndDowncaseRest("A", Locale.ENGLISH)); } + @Test public void testGetCapitalizationType() { assertEquals(StringUtils.CAPITALIZE_NONE, StringUtils.getCapitalizationType("capitalize")); @@ -301,6 +318,7 @@ public class StringUtilsTests extends AndroidTestCase { StringUtils.getCapitalizationType("")); } + @Test public void testIsIdenticalAfterUpcaseIsIdenticalAfterDowncase() { assertFalse(StringUtils.isIdenticalAfterUpcase("capitalize")); assertTrue(StringUtils.isIdenticalAfterDowncase("capitalize")); @@ -337,6 +355,7 @@ public class StringUtilsTests extends AndroidTestCase { StringUtils.toSortedCodePointArray(" \n.!?*()&"); private static final int[] WORD_SEPARATORS = StringUtils.toSortedCodePointArray(" \n.!?*,();&"); + @Test public void testCapitalizeEachWord() { checkCapitalize("", "", SPACE, Locale.ENGLISH); checkCapitalize("test", "Test", SPACE, Locale.ENGLISH); @@ -367,6 +386,7 @@ public class StringUtilsTests extends AndroidTestCase { WORD_SEPARATORS, Locale.ENGLISH); } + @Test public void testLooksLikeURL() { assertTrue(StringUtils.lastPartLooksLikeURL("http://www.google.")); assertFalse(StringUtils.lastPartLooksLikeURL("word wo")); @@ -389,6 +409,7 @@ public class StringUtilsTests extends AndroidTestCase { assertTrue(StringUtils.lastPartLooksLikeURL(".abc/def")); } + @Test public void testHexStringUtils() { final byte[] bytes = new byte[] { (byte)0x01, (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x55, (byte)0x88, (byte)0xEE }; @@ -401,6 +422,7 @@ public class StringUtilsTests extends AndroidTestCase { assertTrue(bytesStr.equals(bytesStr2)); } + @Test public void testToCodePointArray() { final String STR_WITH_SUPPLEMENTARY_CHAR = "abcde\uD861\uDED7fgh\u0000\u2002\u2003\u3000xx"; final int[] EXPECTED_RESULT = new int[] { 'a', 'b', 'c', 'd', 'e', 0x286D7, 'f', 'g', 'h', @@ -414,6 +436,7 @@ public class StringUtilsTests extends AndroidTestCase { } } + @Test public void testCopyCodePointsAndReturnCodePointCount() { final String STR_WITH_SUPPLEMENTARY_CHAR = "AbcDE\uD861\uDED7fGh\u0000\u2002\u3000あx"; final int[] EXPECTED_RESULT = new int[] { 'A', 'b', 'c', 'D', 'E', 0x286D7, @@ -465,6 +488,7 @@ public class StringUtilsTests extends AndroidTestCase { exceptionHappened); } + @Test public void testGetTrailingSingleQuotesCount() { assertEquals(0, StringUtils.getTrailingSingleQuotesCount("")); assertEquals(1, StringUtils.getTrailingSingleQuotesCount("'")); diff --git a/tests/src/com/android/inputmethod/latin/common/UnicodeSurrogateTests.java b/tests/src/com/android/inputmethod/latin/common/UnicodeSurrogateTests.java index 59bb08292..adfbbf418 100644 --- a/tests/src/com/android/inputmethod/latin/common/UnicodeSurrogateTests.java +++ b/tests/src/com/android/inputmethod/latin/common/UnicodeSurrogateTests.java @@ -16,18 +16,27 @@ package com.android.inputmethod.latin.common; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; @SmallTest -public class UnicodeSurrogateTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class UnicodeSurrogateTests { + @Test public void testIsLowSurrogate() { assertFalse(UnicodeSurrogate.isLowSurrogate('\uD7FF')); assertTrue(UnicodeSurrogate.isLowSurrogate('\uD83D')); assertFalse(UnicodeSurrogate.isLowSurrogate('\uDC00')); } + @Test public void testIsHighSurrogate() { assertFalse(UnicodeSurrogate.isHighSurrogate('\uDBFF')); assertTrue(UnicodeSurrogate.isHighSurrogate('\uDE25')); diff --git a/tests/src/com/android/inputmethod/latin/network/BlockingHttpClientTests.java b/tests/src/com/android/inputmethod/latin/network/BlockingHttpClientTests.java index 8f24cdb44..f6f54eb77 100644 --- a/tests/src/com/android/inputmethod/latin/network/BlockingHttpClientTests.java +++ b/tests/src/com/android/inputmethod/latin/network/BlockingHttpClientTests.java @@ -16,16 +16,22 @@ package com.android.inputmethod.latin.network; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.network.BlockingHttpClient.ResponseProcessor; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -44,15 +50,16 @@ import java.util.Random; * Tests for {@link BlockingHttpClient}. */ @SmallTest -public class BlockingHttpClientTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class BlockingHttpClientTests { @Mock HttpURLConnection mMockHttpConnection; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } + @Test public void testError_badGateway() throws IOException, AuthException { when(mMockHttpConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_GATEWAY); final BlockingHttpClient client = new BlockingHttpClient(mMockHttpConnection); @@ -67,6 +74,7 @@ public class BlockingHttpClientTests extends AndroidTestCase { } } + @Test public void testError_clientTimeout() throws Exception { when(mMockHttpConnection.getResponseCode()).thenReturn( HttpURLConnection.HTTP_CLIENT_TIMEOUT); @@ -82,6 +90,7 @@ public class BlockingHttpClientTests extends AndroidTestCase { } } + @Test public void testError_forbiddenWithRequest() throws Exception { final OutputStream mockOutputStream = Mockito.mock(OutputStream.class); when(mMockHttpConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN); @@ -98,6 +107,7 @@ public class BlockingHttpClientTests extends AndroidTestCase { verify(mockOutputStream).write(any(byte[].class), eq(0), eq(100)); } + @Test public void testSuccess_emptyRequest() throws Exception { final Random rand = new Random(); byte[] response = new byte[100]; @@ -112,6 +122,7 @@ public class BlockingHttpClientTests extends AndroidTestCase { assertTrue("ResponseProcessor was not invoked", processor.mInvoked); } + @Test public void testSuccess() throws Exception { final OutputStream mockOutputStream = Mockito.mock(OutputStream.class); final Random rand = new Random(); diff --git a/tests/src/com/android/inputmethod/latin/network/HttpUrlConnectionBuilderTests.java b/tests/src/com/android/inputmethod/latin/network/HttpUrlConnectionBuilderTests.java index 5b3e78eaf..1aa4040b8 100644 --- a/tests/src/com/android/inputmethod/latin/network/HttpUrlConnectionBuilderTests.java +++ b/tests/src/com/android/inputmethod/latin/network/HttpUrlConnectionBuilderTests.java @@ -20,25 +20,28 @@ import static com.android.inputmethod.latin.network.HttpUrlConnectionBuilder.MOD import static com.android.inputmethod.latin.network.HttpUrlConnectionBuilder.MODE_DOWNLOAD_ONLY; import static com.android.inputmethod.latin.network.HttpUrlConnectionBuilder.MODE_UPLOAD_ONLY; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; - /** * Tests for {@link HttpUrlConnectionBuilder}. */ @SmallTest -public class HttpUrlConnectionBuilderTests extends AndroidTestCase { - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - +@RunWith(AndroidJUnit4.class) +public class HttpUrlConnectionBuilderTests { + @Test public void testSetUrl_malformed() { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); try { @@ -49,6 +52,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { } } + @Test public void testSetConnectTimeout_invalid() { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); try { @@ -59,6 +63,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { } } + @Test public void testSetConnectTimeout() throws IOException { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); builder.setUrl("https://www.example.com"); @@ -67,6 +72,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { assertEquals(8765, connection.getConnectTimeout()); } + @Test public void testSetReadTimeout_invalid() { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); try { @@ -77,6 +83,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { } } + @Test public void testSetReadTimeout() throws IOException { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); builder.setUrl("https://www.example.com"); @@ -85,6 +92,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { assertEquals(8765, connection.getReadTimeout()); } + @Test public void testAddHeader() throws IOException { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); builder.setUrl("http://www.example.com"); @@ -93,6 +101,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { assertEquals("some-random-value", connection.getRequestProperty("some-random-key")); } + @Test public void testSetUseCache_notSet() throws IOException { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); builder.setUrl("http://www.example.com"); @@ -100,6 +109,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { assertFalse(connection.getUseCaches()); } + @Test public void testSetUseCache_false() throws IOException { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); builder.setUrl("http://www.example.com"); @@ -108,6 +118,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { assertFalse(connection.getUseCaches()); } + @Test public void testSetUseCache_true() throws IOException { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); builder.setUrl("http://www.example.com"); @@ -116,6 +127,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { assertTrue(connection.getUseCaches()); } + @Test public void testSetMode_uploadOnly() throws IOException { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); builder.setUrl("http://www.example.com"); @@ -125,6 +137,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { assertFalse(connection.getDoOutput()); } + @Test public void testSetMode_downloadOnly() throws IOException { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); builder.setUrl("https://www.example.com"); @@ -134,6 +147,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { assertTrue(connection.getDoOutput()); } + @Test public void testSetMode_bidirectional() throws IOException { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); builder.setUrl("https://www.example.com"); @@ -143,6 +157,7 @@ public class HttpUrlConnectionBuilderTests extends AndroidTestCase { assertTrue(connection.getDoOutput()); } + @Test public void testSetAuthToken() throws IOException { HttpUrlConnectionBuilder builder = new HttpUrlConnectionBuilder(); builder.setUrl("https://www.example.com"); diff --git a/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTests.java b/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTests.java index 559f28642..68f041589 100644 --- a/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTests.java +++ b/tests/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryTests.java @@ -16,13 +16,23 @@ package com.android.inputmethod.latin.personalization; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.LargeTest; +import static org.junit.Assert.assertTrue; + +import android.content.Context; import android.util.Log; +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.LargeTest; +import androidx.test.runner.AndroidJUnit4; + import com.android.inputmethod.latin.ExpandableBinaryDictionary; import com.android.inputmethod.latin.utils.BinaryDictionaryUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.io.File; import java.util.Locale; import java.util.Random; @@ -31,13 +41,18 @@ import java.util.Random; * Unit tests for UserHistoryDictionary */ @LargeTest -public class UserHistoryDictionaryTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class UserHistoryDictionaryTests { private static final String TAG = UserHistoryDictionaryTests.class.getSimpleName(); private static final int WAIT_FOR_WRITING_FILE_IN_MILLISECONDS = 3000; private static final String TEST_ACCOUNT = "account@example.com"; private int mCurrentTime = 0; + private Context getContext() { + return InstrumentationRegistry.getTargetContext(); + } + private static void printAllFiles(final File dir) { Log.d(TAG, dir.getAbsolutePath()); for (final File file : dir.listFiles()) { @@ -62,20 +77,18 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { assertTrue("Following dictionary file doesn't exist: " + dictFile, dictFile.exists()); } - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { resetCurrentTimeForTestMode(); UserHistoryDictionaryTestsHelper.removeAllTestDictFiles( - UserHistoryDictionaryTestsHelper.TEST_LOCALE_PREFIX, mContext); + UserHistoryDictionaryTestsHelper.TEST_LOCALE_PREFIX, getContext()); } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { UserHistoryDictionaryTestsHelper.removeAllTestDictFiles( - UserHistoryDictionaryTestsHelper.TEST_LOCALE_PREFIX, mContext); + UserHistoryDictionaryTestsHelper.TEST_LOCALE_PREFIX, getContext()); stopTestModeInNativeCode(); - super.tearDown(); } private void resetCurrentTimeForTestMode() { @@ -111,7 +124,7 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { null /* dictFile */, testAccount /* account */); final File dictFile = ExpandableBinaryDictionary.getDictFile( - mContext, dictName, null /* dictFile */); + getContext(), dictName, null /* dictFile */); final UserHistoryDictionary dict = PersonalizationHelper.getUserHistoryDictionary( getContext(), dummyLocale, testAccount); clearHistory(dict); @@ -123,18 +136,22 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { assertDictionaryExists(dict, dictFile); } + @Test public void testRandomWords_NullAccount() { doTestRandomWords(null /* testAccount */); } + @Test public void testRandomWords() { doTestRandomWords(TEST_ACCOUNT); } + @Test public void testStressTestForSwitchingLanguagesAndAddingWords() { doTestStressTestForSwitchingLanguagesAndAddingWords(TEST_ACCOUNT); } + @Test public void testStressTestForSwitchingLanguagesAndAddingWords_NullAccount() { doTestStressTestForSwitchingLanguagesAndAddingWords(null /* testAccount */); } @@ -158,7 +175,7 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { UserHistoryDictionary.NAME, dummyLocale, null /* dictFile */, testAccount /* account */); dictFiles[i] = ExpandableBinaryDictionary.getDictFile( - mContext, dictName, null /* dictFile */); + getContext(), dictName, null /* dictFile */); dicts[i] = PersonalizationHelper.getUserHistoryDictionary(getContext(), dummyLocale, testAccount); clearHistory(dicts[i]); @@ -186,10 +203,12 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { } } + @Test public void testAddManyWords() { doTestAddManyWords(TEST_ACCOUNT); } + @Test public void testAddManyWords_NullAccount() { doTestAddManyWords(null /* testAccount */); } @@ -200,7 +219,7 @@ public class UserHistoryDictionaryTests extends AndroidTestCase { final String dictName = UserHistoryDictionary.getUserHistoryDictName( UserHistoryDictionary.NAME, dummyLocale, null /* dictFile */, testAccount); final File dictFile = ExpandableBinaryDictionary.getDictFile( - mContext, dictName, null /* dictFile */); + getContext(), dictName, null /* dictFile */); final int numberOfWords = 10000; final Random random = new Random(123456); final UserHistoryDictionary dict = PersonalizationHelper.getUserHistoryDictionary( diff --git a/tests/src/com/android/inputmethod/latin/settings/AccountsSettingsFragmentTests.java b/tests/src/com/android/inputmethod/latin/settings/AccountsSettingsFragmentTests.java index f2d8973f7..667ffd1ae 100644 --- a/tests/src/com/android/inputmethod/latin/settings/AccountsSettingsFragmentTests.java +++ b/tests/src/com/android/inputmethod/latin/settings/AccountsSettingsFragmentTests.java @@ -16,6 +16,9 @@ package com.android.inputmethod.latin.settings; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; @@ -23,13 +26,19 @@ import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; -import android.test.ActivityInstrumentationTestCase2; -import android.test.suitebuilder.annotation.MediumTest; import android.view.View; import android.widget.ListView; +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.MediumTest; +import androidx.test.runner.AndroidJUnit4; + import com.android.inputmethod.latin.utils.ManagedProfileUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -37,36 +46,41 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @MediumTest -public class AccountsSettingsFragmentTests - extends ActivityInstrumentationTestCase2<TestFragmentActivity> { +@RunWith(AndroidJUnit4.class) +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); + private TestFragmentActivity mActivity; + private TestFragmentActivity getActivity() { + return mActivity; } - @Override - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() throws Exception { // Initialize the mocks. MockitoAnnotations.initMocks(this); ManagedProfileUtils.setTestInstance(mManagedProfileUtils); - Intent intent = new Intent(); - intent.putExtra(TestFragmentActivity.EXTRA_SHOW_FRAGMENT, FRAG_NAME); - setActivityIntent(intent); + final Intent intent = new Intent() + .setAction(Intent.ACTION_MAIN) + .setClass(InstrumentationRegistry.getTargetContext(), TestFragmentActivity.class) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + .addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) + .putExtra(TestFragmentActivity.EXTRA_SHOW_FRAGMENT, FRAG_NAME); + mActivity = (TestFragmentActivity) InstrumentationRegistry.getInstrumentation() + .startActivitySync(intent); } - @Override + @After public void tearDown() throws Exception { ManagedProfileUtils.setTestInstance(null); - super.tearDown(); + mActivity = null; } + @Test public void testEmptyAccounts() { final AccountsSettingsFragment fragment = (AccountsSettingsFragment) getActivity().mFragment; @@ -83,6 +97,7 @@ public class AccountsSettingsFragmentTests DialogHolder() {} } + @Test public void testMultipleAccounts_noSettingsForManagedProfile() { when(mManagedProfileUtils.hasWorkProfile(any(Context.class))).thenReturn(true); @@ -95,6 +110,7 @@ public class AccountsSettingsFragmentTests assertNull(fragment.findPreference(AccountsSettingsFragment.PREF_ACCCOUNT_SWITCHER)); } + @Test public void testMultipleAccounts_noCurrentAccount() { when(mManagedProfileUtils.hasWorkProfile(any(Context.class))).thenReturn(false); @@ -116,6 +132,7 @@ public class AccountsSettingsFragmentTests dialog.getButton(DialogInterface.BUTTON_POSITIVE).getVisibility()); } + @Test public void testMultipleAccounts_currentAccount() { when(mManagedProfileUtils.hasWorkProfile(any(Context.class))).thenReturn(false); @@ -164,7 +181,7 @@ public class AccountsSettingsFragmentTests } catch (InterruptedException ex) { fail(); } - getInstrumentation().waitForIdleSync(); + InstrumentationRegistry.getInstrumentation().waitForIdleSync(); return dialogHolder; } } diff --git a/tests/src/com/android/inputmethod/latin/settings/SpacingAndPunctuationsTests.java b/tests/src/com/android/inputmethod/latin/settings/SpacingAndPunctuationsTests.java index ed632db68..df44fba67 100644 --- a/tests/src/com/android/inputmethod/latin/settings/SpacingAndPunctuationsTests.java +++ b/tests/src/com/android/inputmethod/latin/settings/SpacingAndPunctuationsTests.java @@ -16,9 +16,17 @@ package com.android.inputmethod.latin.settings; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import android.content.Context; import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; + +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.SuggestedWords; import com.android.inputmethod.latin.common.Constants; @@ -26,15 +34,24 @@ import com.android.inputmethod.latin.utils.RunInLocale; import junit.framework.AssertionFailedError; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.Locale; @SmallTest -public class SpacingAndPunctuationsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class SpacingAndPunctuationsTests { private static final int ARMENIAN_FULL_STOP = '\u0589'; private static final int ARMENIAN_COMMA = '\u055D'; private int mScreenMetrics; + private Context getContext() { + return InstrumentationRegistry.getTargetContext(); + } + private boolean isPhone() { return Constants.isPhone(mScreenMetrics); } @@ -63,10 +80,8 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { private SpacingAndPunctuations CAMBODIA_KHMER; private SpacingAndPunctuations LAOS_LAO; - @Override - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() throws Exception { mScreenMetrics = Settings.readScreenMetrics(getContext().getResources()); // Language only @@ -140,6 +155,7 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { assertFalse("Tilde", sp.isWordSeparator('~')); } + @Test public void testWordSeparator() { testingStandardWordSeparator(ENGLISH); testingStandardWordSeparator(FRENCH); @@ -192,6 +208,7 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { } + @Test public void testWordConnector() { testingStandardWordConnector(ENGLISH); testingStandardWordConnector(FRENCH); @@ -245,6 +262,7 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { assertFalse("Question", sp.isUsuallyPrecededBySpace('?')); } + @Test public void testIsUsuallyPrecededBySpace() { testingStandardPrecededBySpace(ENGLISH); testingCommonPrecededBySpace(FRENCH); @@ -298,6 +316,7 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { assertFalse("Tilde", sp.isUsuallyFollowedBySpace('~')); } + @Test public void testIsUsuallyFollowedBySpace() { testingStandardFollowedBySpace(ENGLISH); testingStandardFollowedBySpace(FRENCH); @@ -345,7 +364,8 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { assertFalse("Tilde", sp.isUsuallyFollowedBySpace('~')); } - public void isSentenceSeparator() { + @Test + public void testIsSentenceSeparator() { testingStandardSentenceSeparator(ENGLISH); try { testingStandardSentenceSeparator(ARMENIA_ARMENIAN); @@ -357,6 +377,7 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { assertFalse(ARMENIA_ARMENIAN.isSentenceSeparator(ARMENIAN_COMMA)); } + @Test public void testLanguageHasSpace() { assertTrue(ENGLISH.mCurrentLanguageHasSpaces); assertTrue(FRENCH.mCurrentLanguageHasSpaces); @@ -369,6 +390,7 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { assertTrue(LAO.mCurrentLanguageHasSpaces); } + @Test public void testUsesAmericanTypography() { assertTrue(ENGLISH.mUsesAmericanTypography); assertTrue(UNITED_STATES.mUsesAmericanTypography); @@ -379,6 +401,7 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { assertFalse(SWISS_GERMAN.mUsesAmericanTypography); } + @Test public void testUsesGermanRules() { assertFalse(ENGLISH.mUsesGermanRules); assertFalse(FRENCH.mUsesGermanRules); @@ -436,6 +459,7 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { } } + @Test public void testPhonePunctuationSuggestions() { if (!isPhone()) { return; @@ -454,6 +478,7 @@ public class SpacingAndPunctuationsTests extends AndroidTestCase { PUNCTUATION_LABELS_PHONE, PUNCTUATION_WORDS_PHONE_HEBREW); } + @Test public void testTabletPunctuationSuggestions() { if (!isTablet()) { return; diff --git a/tests/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelperTests.java b/tests/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelperTests.java index f3273a2d1..3706574ef 100644 --- a/tests/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelperTests.java +++ b/tests/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelperTests.java @@ -16,13 +16,22 @@ package com.android.inputmethod.latin.suggestions; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static junit.framework.TestCase.assertEquals; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.SuggestedWords; +import org.junit.Test; +import org.junit.runner.RunWith; + @SmallTest -public class SuggestionStripLayoutHelperTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class SuggestionStripLayoutHelperTests { private static void confirmShowTypedWord(final String message, final int inputType) { assertFalse(message, SuggestionStripLayoutHelper.shouldOmitTypedWord( inputType, @@ -42,6 +51,7 @@ public class SuggestionStripLayoutHelperTests extends AndroidTestCase { true /* shouldShowUiToAcceptTypedWord */)); } + @Test public void testShouldShowTypedWord() { confirmShowTypedWord("no input style", SuggestedWords.INPUT_STYLE_NONE); @@ -51,7 +61,8 @@ public class SuggestionStripLayoutHelperTests extends AndroidTestCase { SuggestedWords.INPUT_STYLE_RECORRECTION); } - public void testshouldOmitTypedWordWhileTyping() { + @Test + public void testShouldOmitTypedWordWhileTyping() { assertFalse("typing", SuggestionStripLayoutHelper.shouldOmitTypedWord( SuggestedWords.INPUT_STYLE_TYPING, false /* gestureFloatingPreviewTextEnabled */, @@ -70,7 +81,8 @@ public class SuggestionStripLayoutHelperTests extends AndroidTestCase { true /* shouldShowUiToAcceptTypedWord */)); } - public void testshouldOmitTypedWordWhileGesturing() { + @Test + public void testShouldOmitTypedWordWhileGesturing() { assertFalse("gesturing", SuggestionStripLayoutHelper.shouldOmitTypedWord( SuggestedWords.INPUT_STYLE_UPDATE_BATCH, false /* gestureFloatingPreviewTextEnabled */, @@ -89,7 +101,8 @@ public class SuggestionStripLayoutHelperTests extends AndroidTestCase { true /* shouldShowUiToAcceptTypedWord */)); } - public void testshouldOmitTypedWordWhenGestured() { + @Test + public void testShouldOmitTypedWordWhenGestured() { assertFalse("gestured", SuggestionStripLayoutHelper.shouldOmitTypedWord( SuggestedWords.INPUT_STYLE_TAIL_BATCH, false /* gestureFloatingPreviewTextEnabled */, @@ -115,6 +128,7 @@ public class SuggestionStripLayoutHelperTests extends AndroidTestCase { private static final int POSITION_CENTER = 1; private static final int POSITION_RIGHT = 2; + @Test public void testGetPositionInSuggestionStrip() { assertEquals("1st word without auto correction", POSITION_CENTER, SuggestionStripLayoutHelper.getPositionInSuggestionStrip( diff --git a/tests/src/com/android/inputmethod/latin/touchinputconsumer/NullGestureConsumerTests.java b/tests/src/com/android/inputmethod/latin/touchinputconsumer/NullGestureConsumerTests.java index ad6bcc3c4..986c8e3dd 100644 --- a/tests/src/com/android/inputmethod/latin/touchinputconsumer/NullGestureConsumerTests.java +++ b/tests/src/com/android/inputmethod/latin/touchinputconsumer/NullGestureConsumerTests.java @@ -16,18 +16,26 @@ package com.android.inputmethod.latin.touchinputconsumer; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; /** * Tests for GestureConsumer.NULL_GESTURE_CONSUMER. */ @SmallTest -public class NullGestureConsumerTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class NullGestureConsumerTests { /** * Tests that GestureConsumer.NULL_GESTURE_CONSUMER indicates that it won't consume gesture data * and that its methods don't raise exceptions even for invalid data. */ + @Test public void testNullGestureConsumer() { assertFalse(GestureConsumer.NULL_GESTURE_CONSUMER.willConsume()); GestureConsumer.NULL_GESTURE_CONSUMER.onInit(null, null); @@ -40,6 +48,7 @@ public class NullGestureConsumerTests extends AndroidTestCase { /** * Tests that newInstance returns NULL_GESTURE_CONSUMER for invalid input. */ + @Test public void testNewInstanceGivesNullGestureConsumerForInvalidInputs() { assertSame(GestureConsumer.NULL_GESTURE_CONSUMER, GestureConsumer.newInstance(null, null, null, null)); diff --git a/tests/src/com/android/inputmethod/latin/utils/AdditionalSubtypeUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/AdditionalSubtypeUtilsTests.java index 1db839506..08c404e12 100644 --- a/tests/src/com/android/inputmethod/latin/utils/AdditionalSubtypeUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/AdditionalSubtypeUtilsTests.java @@ -16,25 +16,36 @@ package com.android.inputmethod.latin.utils; -import static com.android.inputmethod.latin.common.Constants.Subtype.KEYBOARD_MODE; import static com.android.inputmethod.latin.common.Constants.Subtype.ExtraValue.ASCII_CAPABLE; import static com.android.inputmethod.latin.common.Constants.Subtype.ExtraValue.EMOJI_CAPABLE; import static com.android.inputmethod.latin.common.Constants.Subtype.ExtraValue.IS_ADDITIONAL_SUBTYPE; import static com.android.inputmethod.latin.common.Constants.Subtype.ExtraValue.KEYBOARD_LAYOUT_SET; import static com.android.inputmethod.latin.common.Constants.Subtype.ExtraValue.UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME; +import static com.android.inputmethod.latin.common.Constants.Subtype.KEYBOARD_MODE; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import android.content.Context; import android.os.Build; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; import android.view.inputmethod.InputMethodSubtype; +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + import com.android.inputmethod.compat.InputMethodSubtypeCompatUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.Locale; @SmallTest -public class AdditionalSubtypeUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class AdditionalSubtypeUtilsTests { /** * Predictable subtype ID for en_US dvorak layout. This is actually a hash code calculated as @@ -98,10 +109,9 @@ public class AdditionalSubtypeUtilsTests extends AndroidTestCase { ",EmojiCapable" + ",isAdditionalSubtype"; - @Override - protected void setUp() throws Exception { - super.setUp(); - final Context context = getContext(); + @Before + public void setUp() throws Exception { + final Context context = InstrumentationRegistry.getTargetContext(); SubtypeLocaleUtils.init(context); } @@ -149,6 +159,7 @@ public class AdditionalSubtypeUtilsTests extends AndroidTestCase { assertEquals(SUBTYPE_ID_ZZ_AZERTY, subtype.hashCode()); } + @Test public void testRestorable() { final InputMethodSubtype EN_US_DVORAK = AdditionalSubtypeUtils.createAsciiEmojiCapableAdditionalSubtype( diff --git a/tests/src/com/android/inputmethod/latin/utils/AsyncResultHolderTests.java b/tests/src/com/android/inputmethod/latin/utils/AsyncResultHolderTests.java index c214b5fd0..f53780543 100644 --- a/tests/src/com/android/inputmethod/latin/utils/AsyncResultHolderTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/AsyncResultHolderTests.java @@ -16,12 +16,19 @@ package com.android.inputmethod.latin.utils; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; +import static org.junit.Assert.assertEquals; + import android.util.Log; +import androidx.test.filters.MediumTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + @MediumTest -public class AsyncResultHolderTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class AsyncResultHolderTests { static final String TAG = AsyncResultHolderTests.class.getSimpleName(); private static final int TIMEOUT_IN_MILLISECONDS = 500; @@ -44,12 +51,14 @@ public class AsyncResultHolderTests extends AndroidTestCase { }).start(); } + @Test public void testGetWithoutSet() { final AsyncResultHolder<Integer> holder = new AsyncResultHolder<>("Test"); final int resultValue = holder.get(DEFAULT_VALUE, TIMEOUT_IN_MILLISECONDS); assertEquals(DEFAULT_VALUE, resultValue); } + @Test public void testGetBeforeSet() { final AsyncResultHolder<Integer> holder = new AsyncResultHolder<>("Test"); setAfterGivenTime(holder, SET_VALUE, TIMEOUT_IN_MILLISECONDS + MARGIN_IN_MILLISECONDS); @@ -57,6 +66,7 @@ public class AsyncResultHolderTests extends AndroidTestCase { assertEquals(DEFAULT_VALUE, resultValue); } + @Test public void testGetAfterSet() { final AsyncResultHolder<Integer> holder = new AsyncResultHolder<>("Test"); holder.set(SET_VALUE); @@ -64,6 +74,7 @@ public class AsyncResultHolderTests extends AndroidTestCase { assertEquals(SET_VALUE, resultValue); } + @Test public void testGetBeforeTimeout() { final AsyncResultHolder<Integer> holder = new AsyncResultHolder<>("Test"); setAfterGivenTime(holder, SET_VALUE, TIMEOUT_IN_MILLISECONDS - MARGIN_IN_MILLISECONDS); diff --git a/tests/src/com/android/inputmethod/latin/utils/CapsModeUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/CapsModeUtilsTests.java index 9680d85b3..4aac7fc41 100644 --- a/tests/src/com/android/inputmethod/latin/utils/CapsModeUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/CapsModeUtilsTests.java @@ -16,18 +16,27 @@ package com.android.inputmethod.latin.utils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; import android.text.TextUtils; +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + import com.android.inputmethod.latin.common.LocaleUtils; import com.android.inputmethod.latin.settings.SpacingAndPunctuations; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.Locale; @SmallTest -public class CapsModeUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class CapsModeUtilsTests { private static void onePathForCaps(final CharSequence cs, final int expectedResult, final int mask, final SpacingAndPunctuations sp, final boolean hasSpaceBefore) { final int oneTimeResult = expectedResult & mask; @@ -49,6 +58,7 @@ public class CapsModeUtilsTests extends AndroidTestCase { onePathForCaps(cs, expectedResult, s, sp, hasSpaceBefore); } + @Test public void testGetCapsMode() { final int c = TextUtils.CAP_MODE_CHARACTERS; final int w = TextUtils.CAP_MODE_WORDS; @@ -59,7 +69,7 @@ public class CapsModeUtilsTests extends AndroidTestCase { return new SpacingAndPunctuations(res); } }; - final Resources res = getContext().getResources(); + final Resources res = InstrumentationRegistry.getTargetContext().getResources(); SpacingAndPunctuations sp = job.runInLocale(res, Locale.ENGLISH); allPathsForCaps("", c | w | s, sp, false); allPathsForCaps("Word", c, sp, false); diff --git a/tests/src/com/android/inputmethod/latin/utils/CollectionUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/CollectionUtilsTests.java index 0cbb02c4f..da23c9cb8 100644 --- a/tests/src/com/android/inputmethod/latin/utils/CollectionUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/CollectionUtilsTests.java @@ -16,11 +16,19 @@ package com.android.inputmethod.latin.utils; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.common.CollectionUtils; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -32,11 +40,13 @@ import java.util.Map; * Tests for {@link CollectionUtils}. */ @SmallTest -public class CollectionUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class CollectionUtilsTests { /** * Tests that {@link CollectionUtils#arrayAsList(Object[],int,int)} fails as expected * with some invalid inputs. */ + @Test public void testArrayAsListFailure() { final String[] array = { "0", "1" }; // Negative start @@ -66,6 +76,7 @@ public class CollectionUtilsTests extends AndroidTestCase { * Tests that {@link CollectionUtils#arrayAsList(Object[],int,int)} gives the expected * results for a few valid inputs. */ + @Test public void testArrayAsList() { final ArrayList<String> empty = new ArrayList<>(); assertEquals(empty, CollectionUtils.arrayAsList(new String[] {}, 0, 0)); @@ -81,6 +92,7 @@ public class CollectionUtilsTests extends AndroidTestCase { * Tests that {@link CollectionUtils#isNullOrEmpty(java.util.Collection)} gives the expected * results for a few cases. */ + @Test public void testIsNullOrEmpty() { assertTrue(CollectionUtils.isNullOrEmpty((List<String>) null)); assertTrue(CollectionUtils.isNullOrEmpty((Map<String, String>) null)); diff --git a/tests/src/com/android/inputmethod/latin/utils/DictionaryInfoUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/DictionaryInfoUtilsTests.java index 812353cc4..2112f985a 100644 --- a/tests/src/com/android/inputmethod/latin/utils/DictionaryInfoUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/DictionaryInfoUtilsTests.java @@ -16,17 +16,28 @@ package com.android.inputmethod.latin.utils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; + +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.common.LocaleUtils; import com.android.inputmethod.latin.settings.SpacingAndPunctuations; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.Locale; @SmallTest -public class DictionaryInfoUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class DictionaryInfoUtilsTests { + @Test public void testLooksValidForDictionaryInsertion() { final RunInLocale<SpacingAndPunctuations> job = new RunInLocale<SpacingAndPunctuations>() { @Override @@ -34,7 +45,7 @@ public class DictionaryInfoUtilsTests extends AndroidTestCase { return new SpacingAndPunctuations(res); } }; - final Resources res = getContext().getResources(); + final Resources res = InstrumentationRegistry.getTargetContext().getResources(); final SpacingAndPunctuations sp = job.runInLocale(res, Locale.ENGLISH); assertTrue(DictionaryInfoUtils.looksValidForDictionaryInsertion("aochaueo", sp)); assertFalse(DictionaryInfoUtils.looksValidForDictionaryInsertion("", sp)); @@ -46,6 +57,7 @@ public class DictionaryInfoUtilsTests extends AndroidTestCase { assertFalse(DictionaryInfoUtils.looksValidForDictionaryInsertion("!!!", sp)); } + @Test public void testGetMainDictId() { assertEquals("main:en", DictionaryInfoUtils.getMainDictId(LocaleUtils.constructLocaleFromString("en"))); diff --git a/tests/src/com/android/inputmethod/latin/utils/ExecutorUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/ExecutorUtilsTests.java index 86923059b..7c9b3e6ca 100644 --- a/tests/src/com/android/inputmethod/latin/utils/ExecutorUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/ExecutorUtilsTests.java @@ -16,10 +16,16 @@ package com.android.inputmethod.latin.utils; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; +import static org.junit.Assert.assertEquals; + import android.util.Log; +import androidx.test.filters.MediumTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -28,12 +34,14 @@ import java.util.concurrent.atomic.AtomicInteger; * Unit tests for {@link ExecutorUtils}. */ @MediumTest -public class ExecutorUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class ExecutorUtilsTests { private static final String TAG = ExecutorUtilsTests.class.getSimpleName(); private static final int NUM_OF_TASKS = 10; private static final int DELAY_FOR_WAITING_TASKS_MILLISECONDS = 500; + @Test public void testExecute() { final ExecutorService executor = ExecutorUtils.getBackgroundExecutor(ExecutorUtils.KEYBOARD); diff --git a/tests/src/com/android/inputmethod/latin/utils/ImportantNoticeUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/ImportantNoticeUtilsTests.java index df0180729..9d9a541b7 100644 --- a/tests/src/com/android/inputmethod/latin/utils/ImportantNoticeUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/ImportantNoticeUtilsTests.java @@ -17,32 +17,41 @@ package com.android.inputmethod.latin.utils; import static com.android.inputmethod.latin.utils.ImportantNoticeUtils.KEY_TIMESTAMP_OF_CONTACTS_NOTICE; + +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import android.content.Context; import android.content.SharedPreferences; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; -import android.text.TextUtils; + +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.MediumTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.settings.SettingsValues; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.concurrent.TimeUnit; - @MediumTest -public class ImportantNoticeUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class ImportantNoticeUtilsTests { private ImportantNoticePreferences mImportantNoticePreferences; @Mock private SettingsValues mMockSettingsValues; + private Context getContext() { + return InstrumentationRegistry.getTargetContext(); + } + private static class ImportantNoticePreferences { private final SharedPreferences mPref; - private Integer mVersion; private Long mLastTime; public ImportantNoticePreferences(final Context context) { @@ -96,21 +105,20 @@ public class ImportantNoticeUtilsTests extends AndroidTestCase { } } - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mImportantNoticePreferences = new ImportantNoticePreferences(getContext()); mImportantNoticePreferences.save(); when(mMockSettingsValues.isPersonalizationEnabled()).thenReturn(true); } - @Override - protected void tearDown() throws Exception { - super.tearDown(); + @After + public void tearDown() throws Exception { mImportantNoticePreferences.restore(); } + @Test public void testPersonalizationSetting() { mImportantNoticePreferences.clear(); diff --git a/tests/src/com/android/inputmethod/latin/utils/JsonUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/JsonUtilsTests.java index 194112070..fd5e0a4d7 100644 --- a/tests/src/com/android/inputmethod/latin/utils/JsonUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/JsonUtilsTests.java @@ -16,14 +16,21 @@ package com.android.inputmethod.latin.utils; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; import java.util.Arrays; import java.util.List; @SmallTest -public class JsonUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class JsonUtilsTests { + @Test public void testJsonUtils() { final Object[] objs = new Object[] { 1, "aaa", "bbb", 3 }; final List<Object> objArray = Arrays.asList(objs); diff --git a/tests/src/com/android/inputmethod/latin/utils/LanguageOnSpacebarUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/LanguageOnSpacebarUtilsTests.java index e4b6a668c..58e26e8d6 100644 --- a/tests/src/com/android/inputmethod/latin/utils/LanguageOnSpacebarUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/LanguageOnSpacebarUtilsTests.java @@ -20,24 +20,33 @@ import static com.android.inputmethod.latin.utils.LanguageOnSpacebarUtils.FORMAT import static com.android.inputmethod.latin.utils.LanguageOnSpacebarUtils.FORMAT_TYPE_LANGUAGE_ONLY; import static com.android.inputmethod.latin.utils.LanguageOnSpacebarUtils.FORMAT_TYPE_NONE; +import static org.junit.Assert.assertEquals; + import android.content.Context; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; import android.view.inputmethod.InputMethodSubtype; +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + import com.android.inputmethod.latin.RichInputMethodManager; import com.android.inputmethod.latin.RichInputMethodSubtype; import com.android.inputmethod.latin.utils.AdditionalSubtypeUtils; import com.android.inputmethod.latin.utils.LanguageOnSpacebarUtils; import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.ArrayList; import java.util.Locale; import javax.annotation.Nonnull; @SmallTest -public class LanguageOnSpacebarUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class LanguageOnSpacebarUtilsTests { private RichInputMethodManager mRichImm; RichInputMethodSubtype EN_US_QWERTY; @@ -50,10 +59,9 @@ public class LanguageOnSpacebarUtilsTests extends AndroidTestCase { RichInputMethodSubtype IW_HEBREW; RichInputMethodSubtype ZZ_QWERTY; - @Override - protected void setUp() throws Exception { - super.setUp(); - final Context context = getContext(); + @Before + public void setUp() throws Exception { + final Context context = InstrumentationRegistry.getTargetContext(); RichInputMethodManager.init(context); mRichImm = RichInputMethodManager.getInstance(); @@ -99,6 +107,7 @@ public class LanguageOnSpacebarUtilsTests extends AndroidTestCase { LanguageOnSpacebarUtils.getLanguageOnSpacebarFormatType(subtype)); } + @Test public void testOneSubtypeImplicitlyEnabled() { enableSubtypes(EN_US_QWERTY); assertFormatType(EN_US_QWERTY, true, Locale.US, FORMAT_TYPE_NONE); @@ -113,6 +122,7 @@ public class LanguageOnSpacebarUtilsTests extends AndroidTestCase { assertFormatType(FR_CA_QWERTY, true, Locale.CANADA_FRENCH, FORMAT_TYPE_NONE); } + @Test public void testOneSubtypeExplicitlyEnabled() { enableSubtypes(EN_US_QWERTY); assertFormatType(EN_US_QWERTY, false, Locale.UK, FORMAT_TYPE_LANGUAGE_ONLY); @@ -131,6 +141,7 @@ public class LanguageOnSpacebarUtilsTests extends AndroidTestCase { assertFormatType(FR_CA_QWERTY, false, Locale.FRANCE, FORMAT_TYPE_LANGUAGE_ONLY); } + @Test public void testOneSubtypeImplicitlyEnabledWithNoLanguageSubtype() { final Locale Locale_IW = new Locale("iw"); enableSubtypes(IW_HEBREW, ZZ_QWERTY); @@ -140,6 +151,7 @@ public class LanguageOnSpacebarUtilsTests extends AndroidTestCase { assertFormatType(ZZ_QWERTY, true, Locale_IW, FORMAT_TYPE_FULL_LOCALE); } + @Test public void testTwoSubtypesExplicitlyEnabled() { enableSubtypes(EN_US_QWERTY, FR_AZERTY); assertFormatType(EN_US_QWERTY, false, Locale.US, FORMAT_TYPE_LANGUAGE_ONLY); @@ -157,6 +169,7 @@ public class LanguageOnSpacebarUtilsTests extends AndroidTestCase { } + @Test public void testMultiSubtypeWithSameLanuageAndSameLayout() { // Explicitly enable en_US, en_GB, fr_FR, and no language keyboards. enableSubtypes(EN_US_QWERTY, EN_GB_QWERTY, FR_CA_QWERTY, ZZ_QWERTY); @@ -172,6 +185,7 @@ public class LanguageOnSpacebarUtilsTests extends AndroidTestCase { assertFormatType(ZZ_QWERTY, false, Locale.JAPAN, FORMAT_TYPE_FULL_LOCALE); } + @Test public void testMultiSubtypesWithSameLanguageButHaveDifferentLayout() { enableSubtypes(FR_AZERTY, FR_CA_QWERTY, FR_CH_SWISS, FR_CH_QWERTZ); @@ -191,6 +205,7 @@ public class LanguageOnSpacebarUtilsTests extends AndroidTestCase { assertFormatType(FR_CH_QWERTZ, false, Locale.JAPAN, FORMAT_TYPE_LANGUAGE_ONLY); } + @Test public void testMultiSubtypesWithSameLanguageAndMayHaveSameLayout() { enableSubtypes(FR_AZERTY, FR_CA_QWERTY, FR_CH_SWISS, FR_CH_QWERTY, FR_CH_QWERTZ); diff --git a/tests/src/com/android/inputmethod/latin/utils/RecapitalizeStatusTests.java b/tests/src/com/android/inputmethod/latin/utils/RecapitalizeStatusTests.java index 9b826839f..0908f2b54 100644 --- a/tests/src/com/android/inputmethod/latin/utils/RecapitalizeStatusTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/RecapitalizeStatusTests.java @@ -16,17 +16,24 @@ package com.android.inputmethod.latin.utils; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.inputmethod.latin.common.Constants; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.Locale; @SmallTest -public class RecapitalizeStatusTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class RecapitalizeStatusTests { private static final int[] SPACE = { Constants.CODE_SPACE }; + @Test public void testTrim() { final RecapitalizeStatus status = new RecapitalizeStatus(); status.start(30, 40, "abcdefghij", Locale.ENGLISH, SPACE); @@ -54,6 +61,7 @@ public class RecapitalizeStatusTests extends AndroidTestCase { assertEquals(43, status.getNewCursorEnd()); } + @Test public void testRotate() { final RecapitalizeStatus status = new RecapitalizeStatus(); status.start(29, 40, "abcd efghij", Locale.ENGLISH, SPACE); diff --git a/tests/src/com/android/inputmethod/latin/utils/ResourceUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/ResourceUtilsTests.java index 8e764e40f..4aab96a55 100644 --- a/tests/src/com/android/inputmethod/latin/utils/ResourceUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/ResourceUtilsTests.java @@ -16,13 +16,21 @@ package com.android.inputmethod.latin.utils; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; import java.util.HashMap; @SmallTest -public class ResourceUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class ResourceUtilsTests { + @Test public void testFindConstantForKeyValuePairsSimple() { final HashMap<String,String> anyKeyValue = new HashMap<>(); anyKeyValue.put("anyKey", "anyValue"); @@ -69,6 +77,7 @@ public class ResourceUtilsTests extends AndroidTestCase { assertNull(ResourceUtils.findConstantForKeyValuePairs(emptyKeyValue, array)); } + @Test public void testFindConstantForKeyValuePairsCombined() { final String HARDWARE_KEY = "HARDWARE"; final String MODEL_KEY = "MODEL"; @@ -113,6 +122,7 @@ public class ResourceUtilsTests extends AndroidTestCase { assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray)); } + @Test public void testFindConstantForKeyValuePairsRegexp() { final String HARDWARE_KEY = "HARDWARE"; final String MODEL_KEY = "MODEL"; diff --git a/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java index 665d81ccd..a5987cf13 100644 --- a/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/SpannableStringUtilsTests.java @@ -16,17 +16,33 @@ package com.android.inputmethod.latin.utils; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; -import android.text.style.SuggestionSpan; -import android.text.style.URLSpan; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import android.content.Context; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.SpannedString; +import android.text.style.SuggestionSpan; +import android.text.style.URLSpan; + +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; @SmallTest -public class SpannableStringUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class SpannableStringUtilsTests { + + private Context getContext() { + return InstrumentationRegistry.getTargetContext(); + } + + @Test public void testConcatWithSuggestionSpansOnly() { SpannableStringBuilder s = new SpannableStringBuilder("test string\ntest string\n" + "test string\ntest string\ntest string\ntest string\ntest string\ntest string\n" @@ -87,6 +103,7 @@ public class SpannableStringUtilsTests extends AndroidTestCase { assertTrue(false); } + @Test public void testSplitCharSequenceWithSpan() { // text: " a bcd efg hij " // span1: ^^^^^^^ @@ -182,6 +199,7 @@ public class SpannableStringUtilsTests extends AndroidTestCase { assertSpanCount(0, charSequencesFromSpanned[6]); } + @Test public void testSplitCharSequencePreserveTrailingEmptySegmengs() { assertEquals(1, SpannableStringUtils.split("", " ", false /* preserveTrailingEmptySegmengs */).length); diff --git a/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java b/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java index 2297cacf8..6764fd880 100644 --- a/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java +++ b/tests/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtilsTests.java @@ -16,22 +16,35 @@ package com.android.inputmethod.latin.utils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import android.content.Context; import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodSubtype; +import androidx.test.InstrumentationRegistry; +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.RichInputMethodManager; import com.android.inputmethod.latin.RichInputMethodSubtype; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.ArrayList; import java.util.Locale; @SmallTest -public class SubtypeLocaleUtilsTests extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class SubtypeLocaleUtilsTests { // All input method subtypes of LatinIME. private final ArrayList<RichInputMethodSubtype> mSubtypesList = new ArrayList<>(); @@ -64,10 +77,9 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase { InputMethodSubtype HI_LATN_DVORAK; // Hinglis Dvorak InputMethodSubtype SR_LATN_QWERTY; // Serbian Latin Qwerty - @Override - protected void setUp() throws Exception { - super.setUp(); - final Context context = getContext(); + @Before + public void setUp() throws Exception { + final Context context = InstrumentationRegistry.getTargetContext(); mRes = context.getResources(); RichInputMethodManager.init(context); mRichImm = RichInputMethodManager.getInstance(); @@ -136,13 +148,13 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase { } } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { // Restore additional subtypes. mRichImm.setAdditionalInputMethodSubtypes(mSavedAddtionalSubtypes); - super.tearDown(); } + @Test public void testAllFullDisplayName() { for (final RichInputMethodSubtype subtype : mSubtypesList) { final String subtypeName = SubtypeLocaleUtils @@ -159,6 +171,7 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase { } } + @Test public void testKeyboardLayoutSetName() { assertEquals("en_US", "qwerty", SubtypeLocaleUtils.getKeyboardLayoutSetName(EN_US)); assertEquals("en_GB", "qwerty", SubtypeLocaleUtils.getKeyboardLayoutSetName(EN_GB)); @@ -223,6 +236,7 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase { // sr_ZZ qwerty T Serbian (QWERTY) exception // zz pc T Alphabet (PC) + @Test public void testPredefinedSubtypesInEnglishSystemLocale() { final RunInLocale<Void> tests = new RunInLocale<Void>() { @Override @@ -264,6 +278,7 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase { tests.runInLocale(mRes, Locale.ENGLISH); } + @Test public void testAdditionalSubtypesInEnglishSystemLocale() { final RunInLocale<Void> tests = new RunInLocale<Void>() { @Override @@ -323,6 +338,7 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase { // sr_ZZ qwerty T Serbe (QWERTY) exception // zz pc T Alphabet latin (PC) + @Test public void testPredefinedSubtypesInFrenchSystemLocale() { final RunInLocale<Void> tests = new RunInLocale<Void>() { @Override @@ -364,6 +380,7 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase { tests.runInLocale(mRes, Locale.FRENCH); } + @Test public void testAdditionalSubtypesInFrenchSystemLocale() { final RunInLocale<Void> tests = new RunInLocale<Void>() { @Override @@ -405,6 +422,7 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase { // hi_ZZ qwerty F हिंग्लिश // hi_ZZ dvorak T हिंग्लिश (Dvorak) + @Test public void testHinglishSubtypesInHindiSystemLocale() { final RunInLocale<Void> tests = new RunInLocale<Void>() { @Override @@ -432,6 +450,7 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase { // sr_ZZ serbian_qwertz F Српски (латиница) // sr_ZZ qwerty T Српски (QWERTY) + @Test public void testSerbianLatinSubtypesInSerbianSystemLocale() { final RunInLocale<Void> tests = new RunInLocale<Void>() { @Override @@ -451,6 +470,7 @@ public class SubtypeLocaleUtilsTests extends AndroidTestCase { tests.runInLocale(mRes, new Locale("sr")); } + @Test public void testIsRtlLanguage() { // Known Right-to-Left language subtypes. final InputMethodSubtype ARABIC = mRichImm |