diff options
Diffstat (limited to 'core')
17 files changed, 2584 insertions, 0 deletions
diff --git a/core/tests/coretests/Android.mk b/core/tests/coretests/Android.mk new file mode 100644 index 0000000..77c176f --- /dev/null +++ b/core/tests/coretests/Android.mk @@ -0,0 +1,14 @@ +LOCAL_PATH:= $(call my-dir) +include $(CLEAR_VARS) + +# We only want this apk build for tests. +LOCAL_MODULE_TAGS := tests + +# Include all test java files. +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_JAVA_LIBRARIES := android.test.runner +LOCAL_PACKAGE_NAME := FrameworksCoreTests + +include $(BUILD_PACKAGE) + diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml new file mode 100644 index 0000000..674bda7 --- /dev/null +++ b/core/tests/coretests/AndroidManifest.xml @@ -0,0 +1,56 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2008 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. +--> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.frameworks.coretests"> + <uses-permission android:name="android.permission.RECEIVE_SMS"/> + <uses-permission android:name="android.permission.INTERNET" /> + <uses-permission android:name="android.permission.READ_CONTACTS" /> + <uses-permission android:name="android.permission.WRITE_CONTACTS" /> + <uses-permission android:name="android.permission.WAKE_LOCK" /> + <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" /> + <uses-permission android:name="android.permission.WRITE_APN_SETTINGS" /> + <uses-permission android:name="android.permission.BROADCAST_STICKY" /> + + <!-- location test permissions --> + <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> + <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/> + <uses-permission android:name="android.permission.WRITE_SETTINGS"/> + <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/> + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> + + <application> + <uses-library android:name="android.test.runner" /> + <activity android:name="StubTestBrowserActivity" android:label="Stubbed Test Browser"> + <intent-filter> + <action android:name="android.intent.action.MAIN"/> + <category android:name="android.intent.category.FOR_TESTS_ONLY"/> + </intent-filter> + </activity> + + <activity android:name="android.test.TestBrowserTests" android:label="Test Browser Tests"> + <intent-filter> + <action android:name="android.intent.action.MAIN"/> + <category android:name="android.intent.category.UNIT_TEST"/> + </intent-filter> + </activity> + </application> + + <instrumentation + android:name="android.test.InstrumentationTestRunner" + android:targetPackage="com.android.frameworks.coretests" + android:label="Frameworks Core Tests" /> +</manifest> diff --git a/core/tests/coretests/src/android/bluetooth/AtParserTest.java b/core/tests/coretests/src/android/bluetooth/AtParserTest.java new file mode 100644 index 0000000..c5aa52b --- /dev/null +++ b/core/tests/coretests/src/android/bluetooth/AtParserTest.java @@ -0,0 +1,348 @@ +/* + * Copyright (C) 2007 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 android.bluetooth; + +import android.bluetooth.AtCommandHandler; +import android.bluetooth.AtCommandResult; +import android.bluetooth.AtParser; + +import java.util.*; +import junit.framework.*; + +public class AtParserTest extends TestCase { + + /* An AtCommandHandler instrumented for testing purposes + */ + private class HandlerTest extends AtCommandHandler { + boolean mBasicCalled, mActionCalled, mReadCalled, mTestCalled, + mSetCalled; + int mBasicReturn, mActionReturn, mReadReturn, mTestReturn, mSetReturn; + Object[] mSetArgs; + String mBasicArgs; + + HandlerTest() { + this(AtCommandResult.ERROR, AtCommandResult.ERROR, + AtCommandResult.ERROR, AtCommandResult.ERROR, + AtCommandResult.ERROR); + } + + HandlerTest(int a, int b, int c, int d, int e) { + mBasicReturn = a; + mActionReturn = b; + mReadReturn = c; + mSetReturn = d; + mTestReturn = e; + reset(); + } + public void reset() { + mBasicCalled = false; + mActionCalled = false; + mReadCalled = false; + mSetCalled = false; + mTestCalled = false; + mSetArgs = null; + mBasicArgs = null; + } + public boolean wasCalled() { // helper + return mBasicCalled || mActionCalled || mReadCalled || + mTestCalled || mSetCalled; + } + @Override + public AtCommandResult handleBasicCommand(String args) { + mBasicCalled = true; + mBasicArgs = args; + return new AtCommandResult(mBasicReturn); + } + @Override + public AtCommandResult handleActionCommand() { + mActionCalled = true; + return new AtCommandResult(mActionReturn); + } + @Override + public AtCommandResult handleReadCommand() { + mReadCalled = true; + return new AtCommandResult(mReadReturn); + } + @Override + public AtCommandResult handleSetCommand(Object[] args) { + mSetCalled = true; + mSetArgs = args; + return new AtCommandResult(mSetReturn); + } + @Override + public AtCommandResult handleTestCommand() { + mTestCalled = true; + return new AtCommandResult(mTestReturn); + } + } + + private AtParser mParser; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mParser = new AtParser(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + + /* Test that the right method is being called + */ +/* public void testBasic1() throws Exception { + HandlerTest D = new HandlerTest(0, 1, 1, 1, 1); + HandlerTest A = new HandlerTest(0, 1, 1, 1, 1); + mParser.register('D', D); + mParser.register('A', A); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process(" A T D = ? T 1 2 3 4 ").toStrings())); + assertTrue(D.mBasicCalled); + assertFalse(D.mActionCalled); + assertFalse(D.mTestCalled); + assertFalse(D.mSetCalled); + assertFalse(D.mReadCalled); + assertFalse(A.wasCalled()); + assertEquals("=?T1234", D.mBasicArgs); + } +*/ + /* Test some crazy strings + *//* + public void testBasic2() throws Exception { + HandlerTest A = new HandlerTest(0, 1, 1, 1, 1); + mParser.register('A', A); + + assertTrue(Arrays.equals( + new String[]{}, + mParser.process(" ").toStrings())); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process(" a T a t \"\" 1 2 3 a 4 ") + .toStrings())); + assertEquals("T\"\"123A4", A.mBasicArgs); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process(" a T a t \"foo BaR12Z\" 1 2 3 a 4 ") + .toStrings())); + assertEquals("T\"foo BaR12Z\"123A4", A.mBasicArgs); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("ATA\"").toStrings())); + assertEquals("\"\"", A.mBasicArgs); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("ATA\"a").toStrings())); + assertEquals("\"a\"", A.mBasicArgs); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("ATa\" ").toStrings())); + assertEquals("\" \"", A.mBasicArgs); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("ATA \"one \" two \"t hr ee ") + .toStrings())); + assertEquals("\"one \"TWO\"t hr ee \"", A.mBasicArgs); + }*/ + + /* Simple extended commands + *//* + public void testExt1() throws Exception { + HandlerTest A = new HandlerTest(1, 0, 0, 0, 0); + mParser.register("+A", A); + + assertTrue(Arrays.equals( + new String[]{"ERROR"}, + mParser.process("AT+B").toStrings())); + assertFalse(A.wasCalled()); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+A").toStrings())); + assertTrue(A.mActionCalled); + A.mActionCalled = false; + assertFalse(A.wasCalled()); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+A=").toStrings())); + assertTrue(A.mSetCalled); + A.mSetCalled = false; + assertFalse(A.wasCalled()); + assertEquals(1, A.mSetArgs.length); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+A=?").toStrings())); + assertTrue(A.mTestCalled); + A.mTestCalled = false; + assertFalse(A.wasCalled()); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+A?").toStrings())); + assertTrue(A.mReadCalled); + A.mReadCalled = false; + assertFalse(A.wasCalled()); + A.reset(); + } +*/ + + + /* Test chained commands + *//* + public void testChain1() throws Exception { + HandlerTest A = new HandlerTest(0, 1, 1, 1, 1); + HandlerTest B = new HandlerTest(1, 0, 0, 0, 0); + HandlerTest C = new HandlerTest(1, 1, 1, 1, 1); + mParser.register('A', A); + mParser.register("+B", B); + mParser.register("+C", C); + + assertTrue(Arrays.equals( + new String[]{"ERROR"}, + mParser.process("AT+B;+C").toStrings())); + assertTrue(B.mActionCalled); + assertTrue(C.mActionCalled); + B.reset(); + C.reset(); + + assertTrue(Arrays.equals( + new String[]{"ERROR"}, + mParser.process("AT+C;+B").toStrings())); + assertFalse(B.wasCalled()); + assertTrue(C.mActionCalled); + B.reset(); + C.reset(); + }*/ + + /* Test Set command + *//* + public void testSet1() throws Exception { + HandlerTest A = new HandlerTest(1, 1, 1, 0, 1); + mParser.register("+AAAA", A); + Object[] expectedResult; + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+AAAA=1").toStrings())); + expectedResult = new Object[]{(Integer)1}; + assertTrue(Arrays.equals(expectedResult, A.mSetArgs)); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+AAAA=1,2,3").toStrings())); + expectedResult = new Object[]{(Integer)1, (Integer)2, (Integer)3}; + assertTrue(Arrays.equals(expectedResult, A.mSetArgs)); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+AAAA=3,0,0,1").toStrings())); + expectedResult = new Object[]{(Integer)3, (Integer)0, (Integer)0, + (Integer)1}; + assertTrue(Arrays.equals(expectedResult, A.mSetArgs)); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+AAAA=\"foo\",1,\"b,ar").toStrings())); + expectedResult = new Object[]{"\"foo\"", 1, "\"b,ar\""}; + assertTrue(Arrays.equals(expectedResult, A.mSetArgs)); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+AAAA=").toStrings())); + expectedResult = new Object[]{""}; + assertTrue(Arrays.equals(expectedResult, A.mSetArgs)); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+AAAA=,").toStrings())); + expectedResult = new Object[]{"", ""}; + assertTrue(Arrays.equals(expectedResult, A.mSetArgs)); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+AAAA=,,,").toStrings())); + expectedResult = new Object[]{"", "", "", ""}; + assertTrue(Arrays.equals(expectedResult, A.mSetArgs)); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("AT+AAAA=,1,,\"foo\",").toStrings())); + expectedResult = new Object[]{"", 1, "", "\"foo\"", ""}; + assertEquals(5, A.mSetArgs.length); + assertTrue(Arrays.equals(expectedResult, A.mSetArgs)); + A.reset(); + }*/ + + /* Test repeat command "A/" + *//* + public void testRepeat() throws Exception { + HandlerTest A = new HandlerTest(0, 0, 0, 0, 0); + mParser.register('A', A); + + // Try repeated command on fresh parser + assertTrue(Arrays.equals( + new String[]{}, + mParser.process("A/").toStrings())); + assertFalse(A.wasCalled()); + A.reset(); + + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("ATA").toStrings())); + assertTrue(A.mBasicCalled); + assertEquals("", A.mBasicArgs); + A.reset(); + + // Now repeat the command + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("A/").toStrings())); + assertTrue(A.mBasicCalled); + assertEquals("", A.mBasicArgs); + A.reset(); + + // Multiple repeats + assertTrue(Arrays.equals( + new String[]{"OK"}, + mParser.process("A/").toStrings())); + assertTrue(A.mBasicCalled); + assertEquals("", A.mBasicArgs); + A.reset(); + + }*/ +} diff --git a/core/tests/coretests/src/android/content/ObserverNodeTest.java b/core/tests/coretests/src/android/content/ObserverNodeTest.java new file mode 100644 index 0000000..68cc75b --- /dev/null +++ b/core/tests/coretests/src/android/content/ObserverNodeTest.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2007 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 android.content; + +import java.util.ArrayList; + +import android.content.ContentService.ObserverCall; +import android.content.ContentService.ObserverNode; +import android.database.ContentObserver; +import android.net.Uri; +import android.os.Handler; +import android.test.AndroidTestCase; +import android.util.Log; + +public class ObserverNodeTest extends AndroidTestCase { + static class TestObserver extends ContentObserver { + public TestObserver() { + super(new Handler()); + } + } + + public void testUri() { + ObserverNode root = new ObserverNode(""); + Uri[] uris = new Uri[] { + Uri.parse("content://c/a/"), + Uri.parse("content://c/"), + Uri.parse("content://x/"), + Uri.parse("content://c/b/"), + Uri.parse("content://c/a/a1/1/"), + Uri.parse("content://c/a/a1/2/"), + Uri.parse("content://c/b/1/"), + Uri.parse("content://c/b/2/"), + }; + + int[] nums = new int[] {4, 7, 1, 4, 2, 2, 3, 3}; + + // special case + root.addObserver(uris[0], new TestObserver().getContentObserver(), false); + for(int i = 1; i < uris.length; i++) { + root.addObserver(uris[i], new TestObserver().getContentObserver(), true); + } + + ArrayList<ObserverCall> calls = new ArrayList<ObserverCall>(); + + for (int i = nums.length - 1; i >=0; --i) { + root.collectObservers(uris[i], 0, null, false, calls); + assertEquals(nums[i], calls.size()); + calls.clear(); + } + } + + public void testUriNotNotify() { + ObserverNode root = new ObserverNode(""); + Uri[] uris = new Uri[] { + Uri.parse("content://c/"), + Uri.parse("content://x/"), + Uri.parse("content://c/a/"), + Uri.parse("content://c/b/"), + Uri.parse("content://c/a/1/"), + Uri.parse("content://c/a/2/"), + Uri.parse("content://c/b/1/"), + Uri.parse("content://c/b/2/"), + }; + int[] nums = new int[] {7, 1, 3, 3, 1, 1, 1, 1}; + + for(int i = 0; i < uris.length; i++) { + root.addObserver(uris[i], new TestObserver().getContentObserver(), false); + } + + ArrayList<ObserverCall> calls = new ArrayList<ObserverCall>(); + + for (int i = uris.length - 1; i >=0; --i) { + root.collectObservers(uris[i], 0, null, false, calls); + assertEquals(nums[i], calls.size()); + calls.clear(); + } + } +} diff --git a/core/tests/coretests/src/android/content/SyncStorageEngineTest.java b/core/tests/coretests/src/android/content/SyncStorageEngineTest.java new file mode 100644 index 0000000..533338e --- /dev/null +++ b/core/tests/coretests/src/android/content/SyncStorageEngineTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007 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 android.content; + +import android.test.AndroidTestCase; +import android.test.RenamingDelegatingContext; +import android.test.mock.MockContext; +import android.test.mock.MockContentResolver; +import android.accounts.Account; + +public class SyncStorageEngineTest extends AndroidTestCase { + + /** + * Test that we handle the case of a history row being old enough to purge before the + * correcponding sync is finished. This can happen if the clock changes while we are syncing. + */ + public void testPurgeActiveSync() throws Exception { + final Account account = new Account("a@example.com", "example.type"); + final String authority = "testprovider"; + + MockContentResolver mockResolver = new MockContentResolver(); + + SyncStorageEngine engine = SyncStorageEngine.newTestInstance( + new TestContext(mockResolver, getContext())); + + long time0 = 1000; + long historyId = engine.insertStartSyncEvent( + account, authority, time0, SyncStorageEngine.SOURCE_LOCAL); + long time1 = time0 + SyncStorageEngine.MILLIS_IN_4WEEKS * 2; + engine.stopSyncEvent(historyId, time1 - time0, "yay", 0, 0); + } +} + +class TestContext extends ContextWrapper { + + ContentResolver mResolver; + + public TestContext(ContentResolver resolver, Context realContext) { + super(new RenamingDelegatingContext(new MockContext(), realContext, "test.")); + mResolver = resolver; + } + + @Override + public void enforceCallingOrSelfPermission(String permission, String message) { + } + + + @Override + public ContentResolver getContentResolver() { + return mResolver; + } +} diff --git a/core/tests/coretests/src/android/database/MatrixCursorTest.java b/core/tests/coretests/src/android/database/MatrixCursorTest.java new file mode 100644 index 0000000..cddc6c4 --- /dev/null +++ b/core/tests/coretests/src/android/database/MatrixCursorTest.java @@ -0,0 +1,152 @@ +/* + * Copyright (C) 2007 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 android.database; + +import junit.framework.TestCase; + +import java.util.*; + +public class MatrixCursorTest extends TestCase { + + public void testEmptyCursor() { + Cursor cursor = new MatrixCursor(new String[] { "a" }); + assertEquals(0, cursor.getCount()); + } + + public void testNullValue() { + MatrixCursor cursor = new MatrixCursor(new String[] { "a" }); + cursor.newRow().add(null); + cursor.moveToNext(); + assertTrue(cursor.isNull(0)); + assertNull(cursor.getString(0)); + assertEquals(0, cursor.getShort(0)); + assertEquals(0, cursor.getInt(0)); + assertEquals(0L, cursor.getLong(0)); + assertEquals(0.0f, cursor.getFloat(0)); + assertEquals(0.0d, cursor.getDouble(0)); + } + + public void testMatrixCursor() { + MatrixCursor cursor = newMatrixCursor(); + + cursor.newRow() + .add("a") + .add(1) + .add(2) + .add(3) + .add(4) + .add(5); + + cursor.moveToNext(); + + checkValues(cursor); + + cursor.newRow() + .add("a") + .add("1") + .add("2") + .add("3") + .add("4") + .add("5"); + + cursor.moveToNext(); + checkValues(cursor); + + cursor.moveToPrevious(); + checkValues(cursor); + } + + public void testAddArray() { + MatrixCursor cursor = newMatrixCursor(); + + cursor.addRow(new Object[] { "a", 1, 2, 3, 4, 5 }); + cursor.moveToNext(); + checkValues(cursor); + + try { + cursor.addRow(new Object[0]); + fail(); + } catch (IllegalArgumentException e) { /* expected */ } + } + + public void testAddIterable() { + MatrixCursor cursor = newMatrixCursor(); + + cursor.addRow(Arrays.asList("a", 1, 2, 3, 4, 5)); + cursor.moveToNext(); + checkValues(cursor); + + try { + cursor.addRow(Collections.emptyList()); + fail(); + } catch (IllegalArgumentException e) { /* expected */ } + + try { + cursor.addRow(Arrays.asList("a", 1, 2, 3, 4, 5, "Too many!")); + fail(); + } catch (IllegalArgumentException e) { /* expected */ } + } + + public void testAddArrayList() { + MatrixCursor cursor = newMatrixCursor(); + + cursor.addRow(new NonIterableArrayList<Object>( + Arrays.asList("a", 1, 2, 3, 4, 5))); + cursor.moveToNext(); + checkValues(cursor); + + try { + cursor.addRow(new NonIterableArrayList<Object>()); + fail(); + } catch (IllegalArgumentException e) { /* expected */ } + + try { + cursor.addRow(new NonIterableArrayList<Object>( + Arrays.asList("a", 1, 2, 3, 4, 5, "Too many!"))); + fail(); + } catch (IllegalArgumentException e) { /* expected */ } + } + + static class NonIterableArrayList<T> extends ArrayList<T> { + + NonIterableArrayList() {} + + NonIterableArrayList(Collection<? extends T> ts) { + super(ts); + } + + @Override + public Iterator<T> iterator() { + throw new AssertionError(); + } + } + + private MatrixCursor newMatrixCursor() { + return new MatrixCursor(new String[] { + "string", "short", "int", "long", "float", "double" }); + } + + private void checkValues(MatrixCursor cursor) { + assertEquals("a", cursor.getString(0)); + assertEquals(1, cursor.getShort(1)); + assertEquals(2, cursor.getInt(2)); + assertEquals(3, cursor.getLong(3)); + assertEquals(4.0f, cursor.getFloat(4)); + assertEquals(5.0D, cursor.getDouble(5)); + } + +} diff --git a/core/tests/coretests/src/android/database/sqlite/AbstractJDBCDriverTest.java b/core/tests/coretests/src/android/database/sqlite/AbstractJDBCDriverTest.java new file mode 100644 index 0000000..e381a5e --- /dev/null +++ b/core/tests/coretests/src/android/database/sqlite/AbstractJDBCDriverTest.java @@ -0,0 +1,211 @@ +/* + * Copyright (C) 2008 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 android.core; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import junit.framework.TestCase; +import android.test.suitebuilder.annotation.MediumTest; + +/** + * Tests for the most commonly used methods of sql like creating a connection, + * inserting, selecting, updating. + */ +public abstract class AbstractJDBCDriverTest extends TestCase { + + @MediumTest + public void testJDBCDriver() throws Exception { + Connection firstConnection = null; + Connection secondConnection = null; + File dbFile = getDbFile(); + String connectionURL = getConnectionURL(); + Statement firstStmt = null; + Statement secondStmt = null; + try { + Class.forName(getJDBCDriverClassName()); + firstConnection = DriverManager.getConnection(connectionURL); + secondConnection = DriverManager.getConnection(connectionURL); + + String[] ones = {"hello!", "goodbye"}; + short[] twos = {10, 20}; + String[] onesUpdated = new String[ones.length]; + for (int i = 0; i < ones.length; i++) { + onesUpdated[i] = ones[i] + twos[i]; + } + firstStmt = firstConnection.createStatement(); + firstStmt.execute("create table tbl1(one varchar(10), two smallint)"); + secondStmt = secondConnection.createStatement(); + + autoCommitInsertSelectTest(firstStmt, ones, twos); + updateSelectCommitSelectTest(firstStmt, secondStmt, ones, onesUpdated, twos); + updateSelectRollbackSelectTest(firstStmt, secondStmt, onesUpdated, ones, twos); + } finally { + closeConnections(firstConnection, secondConnection, dbFile, firstStmt, secondStmt); + } + } + + protected abstract String getJDBCDriverClassName(); + protected abstract String getConnectionURL(); + protected abstract File getDbFile(); + + private void closeConnections(Connection firstConnection, Connection secondConnection, + File dbFile, Statement firstStmt, Statement secondStmt) { + String failText = null; + try { + if (firstStmt != null) { + firstStmt.execute("drop table tbl1"); + } + } catch (SQLException e) { + failText = e.getLocalizedMessage(); + } + try { + if (firstStmt != null) { + firstStmt.close(); + } + } catch (SQLException e) { + failText = e.getLocalizedMessage(); + } + try { + if (firstConnection != null) { + firstConnection.close(); + } + } catch (SQLException e) { + failText = e.getLocalizedMessage(); + } + try { + if (secondStmt != null) { + secondStmt.close(); + } + } catch (SQLException e) { + failText = e.getLocalizedMessage(); + } + try { + if (secondConnection != null) { + secondConnection.close(); + } + } catch (SQLException e) { + failText = e.getLocalizedMessage(); + } + dbFile.delete(); + assertNull(failText, failText); + } + + /** + * Inserts the values from 'ones' with the values from 'twos' into 'tbl1' + * @param stmt the statement to use for the inserts. + * @param ones the string values to insert into tbl1. + * @param twos the corresponding numerical values to insert into tbl1. + * @throws SQLException in case of a problem during insert. + */ + private void autoCommitInsertSelectTest(Statement stmt, String[] ones, + short[] twos) throws SQLException { + for (int i = 0; i < ones.length; i++) { + stmt.execute("insert into tbl1 values('" + ones[i] + "'," + twos[i] + + ")"); + } + assertAllFromTbl1(stmt, ones, twos); + } + + /** + * Asserts that all values that where added to tbl1 are actually in tbl1. + * @param stmt the statement to use for the select. + * @param ones the string values that where added. + * @param twos the numerical values that where added. + * @throws SQLException in case of a problem during select. + */ + private void assertAllFromTbl1(Statement stmt, String[] ones, short[] twos) + throws SQLException { + ResultSet rs = stmt.executeQuery("select * from tbl1"); + int i = 0; + for (; rs.next(); i++) { + assertTrue(i < ones.length); + assertEquals(ones[i], rs.getString("one")); + assertEquals(twos[i], rs.getShort("two")); + } + assertEquals(i, ones.length); + } + + /** + * Tests the results of an update followed bz a select on a diffrent statement. + * After that the first statement commits its update. and now the second + * statement should also be able to see the changed values in a select. + * @param firstStmt the statement to use for the update and commit. + * @param secondStmt the statement that should be used to check if the commit works + * @param ones the original string values. + * @param onesUpdated the updated string values. + * @param twos the numerical values. + * @throws SQLException in case of a problem during any of the executed commands. + */ + private void updateSelectCommitSelectTest(Statement firstStmt, + Statement secondStmt, String[] ones, String[] onesUpdated, + short[] twos) throws SQLException { + firstStmt.getConnection().setAutoCommit(false); + try { + updateOnes(firstStmt, onesUpdated, twos); + assertAllFromTbl1(secondStmt, ones, twos); + firstStmt.getConnection().commit(); + assertAllFromTbl1(secondStmt, onesUpdated, twos); + } finally { + firstStmt.getConnection().setAutoCommit(true); + } + } + + /** + * Tests if an update followed by a select works. After that a rollback will + * be made and again a select should show that the rollback worked. + * @param firstStmt the statement to use for the update and the rollback + * @param secondStmt the statement to use for checking if the rollback worked as intended. + * @param ones the original string values. + * @param onesUpdated the updated string values. + * @param twos the nomerical values. + * @throws SQLException in case of a problem during any command. + */ + private void updateSelectRollbackSelectTest(Statement firstStmt, + Statement secondStmt, String[] ones, String[] onesUpdated, + short[] twos) throws SQLException { + firstStmt.getConnection().setAutoCommit(false); + try { + updateOnes(firstStmt, onesUpdated, twos); + assertAllFromTbl1(secondStmt, ones, twos); + firstStmt.getConnection().rollback(); + assertAllFromTbl1(secondStmt, ones, twos); + } finally { + firstStmt.getConnection().setAutoCommit(true); + } + } + + /** + * updates the sring values. the original values are stored in 'ones' + * and the updated values in 'ones_updated' + * @param stmt the statement to use for the update. + * @param onesUpdated the new string values. + * @param twos the numerical values. + * @throws SQLException in case of a problem during update. + */ + private void updateOnes(Statement stmt, String[] onesUpdated, short[] twos) + throws SQLException { + for (int i = 0; i < onesUpdated.length; i++) { + stmt.execute("UPDATE tbl1 SET one = '" + onesUpdated[i] + + "' WHERE two = " + twos[i]); + } + } +} diff --git a/core/tests/coretests/src/android/database/sqlite/SQLiteJDBCDriverTest.java b/core/tests/coretests/src/android/database/sqlite/SQLiteJDBCDriverTest.java new file mode 100644 index 0000000..eec82aa --- /dev/null +++ b/core/tests/coretests/src/android/database/sqlite/SQLiteJDBCDriverTest.java @@ -0,0 +1,137 @@ +/* + * Copyright (C) 2008 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 android.core; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import android.test.suitebuilder.annotation.MediumTest; + +/** + * Minimal test for JDBC driver + */ +public class SQLiteJDBCDriverTest extends AbstractJDBCDriverTest { + + private File dbFile; + + @Override + protected void setUp() throws Exception { + super.setUp(); + dbFile = File.createTempFile("sqliteTestDB", null); + } + + @Override + protected void tearDown() throws Exception { + if(dbFile != null) { + dbFile.delete(); + } + super.tearDown(); + } + + @Override + protected String getConnectionURL() { + return "jdbc:sqlite:/" + dbFile; + } + + @Override + protected File getDbFile() { + return dbFile; + } + + @Override + protected String getJDBCDriverClassName() { + return "SQLite.JDBCDriver"; + } + + // Regression test for (Noser) #255: PreparedStatement.executeUpdate results + // in VM crashing with SIGABRT. + @MediumTest + public void test_connection3() throws Exception { + PreparedStatement prst = null; + Statement st = null; + Connection conn = null; + try { + Class.forName("SQLite.JDBCDriver").newInstance(); + if (dbFile.exists()) { + dbFile.delete(); + } + conn = DriverManager.getConnection("jdbc:sqlite:/" + + dbFile.getPath()); + assertNotNull(conn); + + // create table + st = conn.createStatement(); + String sql = "CREATE TABLE zoo (ZID INTEGER NOT NULL, family VARCHAR (20) NOT NULL, name VARCHAR (20) NOT NULL, PRIMARY KEY(ZID) )"; + st.executeUpdate(sql); + + String update = "update zoo set family = ? where name = ?;"; + prst = conn.prepareStatement(update); + prst.setString(1, "cat"); + prst.setString(2, "Yasha"); + // st = conn.createStatement(); + // st.execute("select * from zoo where family = 'cat'"); + // ResultSet rs = st.getResultSet(); + // assertEquals(0, getCount(rs)); + prst.executeUpdate(); + // st.execute("select * from zoo where family = 'cat'"); + // ResultSet rs1 = st.getResultSet(); + // assertEquals(1, getCount(rs1)); + try { + prst = conn.prepareStatement(""); + prst.execute(); + fail("SQLException is not thrown"); + } catch (SQLException e) { + // expected + } + + try { + conn.prepareStatement(null); + fail("NPE is not thrown"); + } catch (Exception e) { + // expected + } + try { + st = conn.createStatement(); + st.execute("drop table if exists zoo"); + + } catch (SQLException e) { + fail("Couldn't drop table: " + e.getMessage()); + } finally { + try { + st.close(); + conn.close(); + } catch (SQLException ee) { + } + } + } finally { + try { + if (prst != null) { + prst.close(); + } + if (st != null) { + st.close(); + } + } catch (SQLException ee) { + } + } + + } + +} diff --git a/core/tests/coretests/src/android/pim/RecurrenceSetTest.java b/core/tests/coretests/src/android/pim/RecurrenceSetTest.java new file mode 100644 index 0000000..64cd6c4 --- /dev/null +++ b/core/tests/coretests/src/android/pim/RecurrenceSetTest.java @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2009 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 android.pim; + +import android.content.ContentValues; +import android.pim.ICalendar; +import android.pim.RecurrenceSet; +import android.test.suitebuilder.annotation.SmallTest; +import android.util.Log; +import android.provider.Calendar; +import junit.framework.TestCase; + +/** + * Test some pim.RecurrenceSet functionality. + */ +public class RecurrenceSetTest extends TestCase { + + // Test a recurrence + @SmallTest + public void testRecurrenceSet0() throws Exception { + String recurrence = "DTSTART;TZID=America/New_York:20080221T070000\n" + + "DTEND;TZID=America/New_York:20080221T190000\n" + + "RRULE:FREQ=DAILY;UNTIL=20080222T000000Z\n" + + "EXDATE:20080222T120000Z"; + verifyPopulateContentValues(recurrence, "FREQ=DAILY;UNTIL=20080222T000000Z", null, + null, "20080222T120000Z", 1203595200000L, "America/New_York", "P43200S", 0); + } + + // Test 1 day all-day event + @SmallTest + public void testRecurrenceSet1() throws Exception { + String recurrence = "DTSTART;VALUE=DATE:20090821\nDTEND;VALUE=DATE:20090822\n" + + "RRULE:FREQ=YEARLY;WKST=SU"; + verifyPopulateContentValues(recurrence, "FREQ=YEARLY;WKST=SU", null, + null, null, 1250812800000L, null, "P1D", 1); + } + + // Test 2 day all-day event + @SmallTest + public void testRecurrenceSet2() throws Exception { + String recurrence = "DTSTART;VALUE=DATE:20090821\nDTEND;VALUE=DATE:20090823\n" + + "RRULE:FREQ=YEARLY;WKST=SU"; + verifyPopulateContentValues(recurrence, "FREQ=YEARLY;WKST=SU", null, + null, null, 1250812800000L, null, "P2D", 1); + } + + // run populateContentValues and verify the results + private void verifyPopulateContentValues(String recurrence, String rrule, String rdate, + String exrule, String exdate, long dtstart, String tzid, String duration, int allDay) + throws ICalendar.FormatException { + ICalendar.Component recurrenceComponent = + new ICalendar.Component("DUMMY", null /* parent */); + ICalendar.parseComponent(recurrenceComponent, recurrence); + ContentValues values = new ContentValues(); + RecurrenceSet.populateContentValues(recurrenceComponent, values); + Log.d("KS", "values " + values); + + assertEquals(rrule, values.get(android.provider.Calendar.Events.RRULE)); + assertEquals(rdate, values.get(android.provider.Calendar.Events.RDATE)); + assertEquals(exrule, values.get(android.provider.Calendar.Events.EXRULE)); + assertEquals(exdate, values.get(android.provider.Calendar.Events.EXDATE)); + assertEquals(dtstart, (long) values.getAsLong(Calendar.Events.DTSTART)); + assertEquals(tzid, values.get(android.provider.Calendar.Events.EVENT_TIMEZONE)); + assertEquals(duration, values.get(android.provider.Calendar.Events.DURATION)); + assertEquals(allDay, + (int) values.getAsInteger(android.provider.Calendar.Events.ALL_DAY)); + } +} diff --git a/core/tests/coretests/src/android/util/DayOfMonthCursorTest.java b/core/tests/coretests/src/android/util/DayOfMonthCursorTest.java new file mode 100644 index 0000000..4c5ad76 --- /dev/null +++ b/core/tests/coretests/src/android/util/DayOfMonthCursorTest.java @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2007 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 android.util; + +import junit.framework.TestCase; + +import java.util.Calendar; +import android.test.suitebuilder.annotation.SmallTest; + +/** + * Unit tests for {@link DayOfMonthCursor}. + */ +public class DayOfMonthCursorTest extends TestCase { + + @SmallTest + public void testMonthRows() { + DayOfMonthCursor mc = new DayOfMonthCursor(2007, + Calendar.SEPTEMBER, 11, Calendar.SUNDAY); + + assertArraysEqual(new int[]{26, 27, 28, 29, 30, 31, 1}, + mc.getDigitsForRow(0)); + assertArraysEqual(new int[]{2, 3, 4, 5, 6, 7, 8}, + mc.getDigitsForRow(1)); + assertArraysEqual(new int[]{30, 1, 2, 3, 4, 5, 6}, + mc.getDigitsForRow(5)); + } + + @SmallTest + public void testMoveLeft() { + DayOfMonthCursor mc = new DayOfMonthCursor(2007, + Calendar.SEPTEMBER, 3, Calendar.SUNDAY); + + assertEquals(Calendar.SEPTEMBER, mc.getMonth()); + assertEquals(3, mc.getSelectedDayOfMonth()); + assertEquals(1, mc.getSelectedRow()); + assertEquals(1, mc.getSelectedColumn()); + + // move left, still same row + assertFalse(mc.left()); + assertEquals(2, mc.getSelectedDayOfMonth()); + assertEquals(1, mc.getSelectedRow()); + assertEquals(0, mc.getSelectedColumn()); + + // wrap over to previous column, same month + assertFalse(mc.left()); + assertEquals(1, mc.getSelectedDayOfMonth()); + assertEquals(0, mc.getSelectedRow()); + assertEquals(6, mc.getSelectedColumn()); + + // wrap to previous month + assertTrue(mc.left()); + assertEquals(Calendar.AUGUST, mc.getMonth()); + assertEquals(31, mc.getSelectedDayOfMonth()); + assertEquals(4, mc.getSelectedRow()); + assertEquals(5, mc.getSelectedColumn()); + } + + @SmallTest + public void testMoveRight() { + DayOfMonthCursor mc = new DayOfMonthCursor(2007, + Calendar.SEPTEMBER, 28, Calendar.SUNDAY); + + assertEquals(Calendar.SEPTEMBER, mc.getMonth()); + assertEquals(28, mc.getSelectedDayOfMonth()); + assertEquals(4, mc.getSelectedRow()); + assertEquals(5, mc.getSelectedColumn()); + + // same row + assertFalse(mc.right()); + assertEquals(29, mc.getSelectedDayOfMonth()); + assertEquals(4, mc.getSelectedRow()); + assertEquals(6, mc.getSelectedColumn()); + + // wrap to next column, same month + assertFalse(mc.right()); + assertEquals(30, mc.getSelectedDayOfMonth()); + assertEquals(5, mc.getSelectedRow()); + assertEquals(0, mc.getSelectedColumn()); + + // next month + assertTrue(mc.right()); + assertEquals(Calendar.OCTOBER, mc.getMonth()); + assertEquals(1, mc.getSelectedDayOfMonth()); + assertEquals(0, mc.getSelectedRow()); + assertEquals(1, mc.getSelectedColumn()); + } + + @SmallTest + public void testMoveUp() { + DayOfMonthCursor mc = new DayOfMonthCursor(2007, + Calendar.SEPTEMBER, 13, Calendar.SUNDAY); + + assertEquals(Calendar.SEPTEMBER, mc.getMonth()); + assertEquals(13, mc.getSelectedDayOfMonth()); + assertEquals(2, mc.getSelectedRow()); + assertEquals(4, mc.getSelectedColumn()); + + // up, same month + assertFalse(mc.up()); + assertEquals(6, mc.getSelectedDayOfMonth()); + assertEquals(1, mc.getSelectedRow()); + assertEquals(4, mc.getSelectedColumn()); + + // up, flips back + assertTrue(mc.up()); + assertEquals(Calendar.AUGUST, mc.getMonth()); + assertEquals(30, mc.getSelectedDayOfMonth()); + assertEquals(4, mc.getSelectedRow()); + assertEquals(4, mc.getSelectedColumn()); + } + + @SmallTest + public void testMoveDown() { + DayOfMonthCursor mc = new DayOfMonthCursor(2007, + Calendar.SEPTEMBER, 23, Calendar.SUNDAY); + + assertEquals(Calendar.SEPTEMBER, mc.getMonth()); + assertEquals(23, mc.getSelectedDayOfMonth()); + assertEquals(4, mc.getSelectedRow()); + assertEquals(0, mc.getSelectedColumn()); + + // down, same month + assertFalse(mc.down()); + assertEquals(30, mc.getSelectedDayOfMonth()); + assertEquals(5, mc.getSelectedRow()); + assertEquals(0, mc.getSelectedColumn()); + + // down, next month + assertTrue(mc.down()); + assertEquals(Calendar.OCTOBER, mc.getMonth()); + assertEquals(7, mc.getSelectedDayOfMonth()); + assertEquals(1, mc.getSelectedRow()); + assertEquals(0, mc.getSelectedColumn()); + } + + private void assertArraysEqual(int[] expected, int[] actual) { + assertEquals("array length", expected.length, actual.length); + for (int i = 0; i < expected.length; i++) { + assertEquals("index " + i, + expected[i], actual[i]); + } + } +} diff --git a/core/tests/coretests/src/android/util/FloatMathTest.java b/core/tests/coretests/src/android/util/FloatMathTest.java new file mode 100644 index 0000000..f479e2b --- /dev/null +++ b/core/tests/coretests/src/android/util/FloatMathTest.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2007 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 android.util; + +import junit.framework.TestCase; +import android.test.suitebuilder.annotation.SmallTest; + +public class FloatMathTest extends TestCase { + + @SmallTest + public void testSqrt() { + assertEquals(7, FloatMath.sqrt(49), 0); + assertEquals(10, FloatMath.sqrt(100), 0); + assertEquals(0, FloatMath.sqrt(0), 0); + assertEquals(1, FloatMath.sqrt(1), 0); + } + + @SmallTest + public void testFloor() { + assertEquals(78, FloatMath.floor(78.89f), 0); + assertEquals(-79, FloatMath.floor(-78.89f), 0); + } + + @SmallTest + public void testCeil() { + assertEquals(79, FloatMath.ceil(78.89f), 0); + assertEquals(-78, FloatMath.ceil(-78.89f), 0); + } + + @SmallTest + public void testSin() { + assertEquals(0.0, FloatMath.sin(0), 0); + assertEquals(0.8414709848078965f, FloatMath.sin(1), 0); + } + + @SmallTest + public void testCos() { + assertEquals(1.0f, FloatMath.cos(0), 0); + assertEquals(0.5403023058681398f, FloatMath.cos(1), 0); + } +} diff --git a/core/tests/coretests/src/android/util/MonthDisplayHelperTest.java b/core/tests/coretests/src/android/util/MonthDisplayHelperTest.java new file mode 100644 index 0000000..5207ad9 --- /dev/null +++ b/core/tests/coretests/src/android/util/MonthDisplayHelperTest.java @@ -0,0 +1,211 @@ +/* + * Copyright (C) 2007 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 android.util; + +import junit.framework.TestCase; +import junit.framework.Test; +import junit.framework.TestSuite; + +import java.util.Calendar; +import android.test.suitebuilder.annotation.SmallTest; +import android.test.suitebuilder.annotation.MediumTest; + +/** + * Unit tests for {@link MonthDisplayHelper}. + */ +public class MonthDisplayHelperTest extends TestCase { + + + @SmallTest + public void testFirstDayOfMonth() { + + assertEquals("august 2007", + Calendar.WEDNESDAY, + new MonthDisplayHelper(2007, Calendar.AUGUST).getFirstDayOfMonth()); + + assertEquals("september, 2007", + Calendar.SATURDAY, + new MonthDisplayHelper(2007, Calendar.SEPTEMBER).getFirstDayOfMonth()); + } + + @MediumTest + public void testNumberOfDaysInCurrentMonth() { + assertEquals(30, + new MonthDisplayHelper(2007, Calendar.SEPTEMBER).getNumberOfDaysInMonth()); + } + + @SmallTest + public void testMonthRows() { + MonthDisplayHelper helper = new MonthDisplayHelper(2007, Calendar.SEPTEMBER); + + assertArraysEqual(new int[]{26, 27, 28, 29, 30, 31, 1}, + helper.getDigitsForRow(0)); + assertArraysEqual(new int[]{2, 3, 4, 5, 6, 7, 8}, + helper.getDigitsForRow(1)); + assertArraysEqual(new int[]{30, 1, 2, 3, 4, 5, 6}, + helper.getDigitsForRow(5)); + + } + + @SmallTest + public void testMonthRowsWeekStartsMonday() { + MonthDisplayHelper helper = new MonthDisplayHelper(2007, + Calendar.SEPTEMBER, Calendar.MONDAY); + + assertArraysEqual(new int[]{27, 28, 29, 30, 31, 1, 2}, + helper.getDigitsForRow(0)); + assertArraysEqual(new int[]{3, 4, 5, 6, 7, 8, 9}, + helper.getDigitsForRow(1)); + assertArraysEqual(new int[]{24, 25, 26, 27, 28, 29, 30}, + helper.getDigitsForRow(4)); + assertArraysEqual(new int[]{1, 2, 3, 4, 5, 6, 7}, + helper.getDigitsForRow(5)); + } + + @SmallTest + public void testMonthRowsWeekStartsSaturday() { + MonthDisplayHelper helper = new MonthDisplayHelper(2007, + Calendar.SEPTEMBER, Calendar.SATURDAY); + + assertArraysEqual(new int[]{1, 2, 3, 4, 5, 6, 7}, + helper.getDigitsForRow(0)); + assertArraysEqual(new int[]{8, 9, 10, 11, 12, 13, 14}, + helper.getDigitsForRow(1)); + assertArraysEqual(new int[]{29, 30, 1, 2, 3, 4, 5}, + helper.getDigitsForRow(4)); + + + helper = new MonthDisplayHelper(2007, + Calendar.AUGUST, Calendar.SATURDAY); + + assertArraysEqual(new int[]{28, 29, 30, 31, 1, 2, 3}, + helper.getDigitsForRow(0)); + assertArraysEqual(new int[]{4, 5, 6, 7, 8, 9, 10}, + helper.getDigitsForRow(1)); + assertArraysEqual(new int[]{25, 26, 27, 28, 29, 30, 31}, + helper.getDigitsForRow(4)); + } + + @SmallTest + public void testGetDayAt() { + MonthDisplayHelper helper = new MonthDisplayHelper(2007, + Calendar.SEPTEMBER, Calendar.SUNDAY); + + assertEquals(26, helper.getDayAt(0, 0)); + assertEquals(1, helper.getDayAt(0, 6)); + assertEquals(17, helper.getDayAt(3, 1)); + assertEquals(2, helper.getDayAt(5, 2)); + } + + @SmallTest + public void testPrevMonth() { + MonthDisplayHelper helper = new MonthDisplayHelper(2007, + Calendar.SEPTEMBER, Calendar.SUNDAY); + + assertArraysEqual(new int[]{26, 27, 28, 29, 30, 31, 1}, + helper.getDigitsForRow(0)); + + helper.previousMonth(); + + assertEquals(Calendar.AUGUST, helper.getMonth()); + assertArraysEqual(new int[]{29, 30, 31, 1, 2, 3, 4}, + helper.getDigitsForRow(0)); + } + + @SmallTest + public void testPrevMonthRollOver() { + MonthDisplayHelper helper = new MonthDisplayHelper(2007, + Calendar.JANUARY); + + helper.previousMonth(); + + assertEquals(2006, helper.getYear()); + assertEquals(Calendar.DECEMBER, helper.getMonth()); + } + + @SmallTest + public void testNextMonth() { + MonthDisplayHelper helper = new MonthDisplayHelper(2007, + Calendar.AUGUST, Calendar.SUNDAY); + + assertArraysEqual(new int[]{29, 30, 31, 1, 2, 3, 4}, + helper.getDigitsForRow(0)); + + helper.nextMonth(); + + assertEquals(Calendar.SEPTEMBER, helper.getMonth()); + assertArraysEqual(new int[]{26, 27, 28, 29, 30, 31, 1}, + helper.getDigitsForRow(0)); + } + + @SmallTest + public void testGetRowOf() { + MonthDisplayHelper helper = new MonthDisplayHelper(2007, + Calendar.AUGUST, Calendar.SUNDAY); + + assertEquals(0, helper.getRowOf(2)); + assertEquals(0, helper.getRowOf(4)); + assertEquals(2, helper.getRowOf(12)); + assertEquals(2, helper.getRowOf(18)); + assertEquals(3, helper.getRowOf(19)); + } + + @SmallTest + public void testGetColumnOf() { + MonthDisplayHelper helper = new MonthDisplayHelper(2007, + Calendar.AUGUST, Calendar.SUNDAY); + + assertEquals(3, helper.getColumnOf(1)); + assertEquals(4, helper.getColumnOf(9)); + assertEquals(5, helper.getColumnOf(17)); + assertEquals(6, helper.getColumnOf(25)); + assertEquals(0, helper.getColumnOf(26)); + } + + @SmallTest + public void testWithinCurrentMonth() { + MonthDisplayHelper helper = new MonthDisplayHelper(2007, + Calendar.SEPTEMBER, Calendar.SUNDAY); + + // out of bounds + assertFalse(helper.isWithinCurrentMonth(-1, 3)); + assertFalse(helper.isWithinCurrentMonth(6, 3)); + assertFalse(helper.isWithinCurrentMonth(2, -1)); + assertFalse(helper.isWithinCurrentMonth(2, 7)); + + // last day of previous month + assertFalse(helper.isWithinCurrentMonth(0, 5)); + + // first day of next month + assertFalse(helper.isWithinCurrentMonth(5, 1)); + + // first day in month + assertTrue(helper.isWithinCurrentMonth(0, 6)); + + // last day in month + assertTrue(helper.isWithinCurrentMonth(5, 0)); + } + + private void assertArraysEqual(int[] expected, int[] actual) { + assertEquals("array length", expected.length, actual.length); + for (int i = 0; i < expected.length; i++) { + assertEquals("index " + i, + expected[i], actual[i]); + } + } + +} diff --git a/core/tests/coretests/src/android/util/StateSetTest.java b/core/tests/coretests/src/android/util/StateSetTest.java new file mode 100644 index 0000000..e481ce04 --- /dev/null +++ b/core/tests/coretests/src/android/util/StateSetTest.java @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2007 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 android.util; + +import junit.framework.TestCase; +import android.test.suitebuilder.annotation.SmallTest; + +/** + * Tests for {@link StateSet} + */ + +public class StateSetTest extends TestCase { + + @SmallTest + public void testStateSetPositiveMatches() throws Exception { + int[] stateSpec = new int[2]; + int[] stateSet = new int[3]; + // Single states in both sets - match + stateSpec[0] = 1; + stateSet[0] = 1; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet)); + // Single states in both sets - non-match + stateSet[0] = 2; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet)); + // Add another state to the spec which the stateSet doesn't match + stateSpec[1] = 2; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet)); + // Add the missing matching element to the stateSet + stateSet[1] = 1; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet)); + // Add an irrelevent state to the stateSpec + stateSet[2] = 12345; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet)); + } + + @SmallTest + public void testStatesSetMatchMixEmUp() throws Exception { + int[] stateSpec = new int[2]; + int[] stateSet = new int[2]; + // One element in stateSpec which we must match and one which we must + // not match. stateSet only contains the match. + stateSpec[0] = 1; + stateSpec[1] = -2; + stateSet[0] = 1; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet)); + // stateSet now contains just the element we must not match + stateSet[0] = 2; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet)); + // Add another matching state to the the stateSet. We still fail + // because stateSet contains a must-not-match element + stateSet[1] = 1; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet)); + // Switch the must-not-match element in stateSet with a don't care + stateSet[0] = 12345; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet)); + } + + @SmallTest + public void testStateSetNegativeMatches() throws Exception { + int[] stateSpec = new int[2]; + int[] stateSet = new int[3]; + // Single states in both sets - match + stateSpec[0] = -1; + stateSet[0] = 2; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet)); + // Add another arrelevent state to the stateSet + stateSet[1] = 12345; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet)); + // Single states in both sets - non-match + stateSet[0] = 1; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet)); + // Add another state to the spec which the stateSet doesn't match + stateSpec[1] = -2; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet)); + // Add an irrelevent state to the stateSet + stateSet[2] = 12345; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet)); + } + + @SmallTest + public void testEmptySetMatchesNegtives() throws Exception { + int[] stateSpec = {-12345, -6789}; + int[] stateSet = new int[0]; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet)); + int[] stateSet2 = {0}; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet2)); + } + + @SmallTest + public void testEmptySetFailsPositives() throws Exception { + int[] stateSpec = {12345}; + int[] stateSet = new int[0]; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet)); + int[] stateSet2 = {0}; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet2)); + } + + @SmallTest + public void testEmptySetMatchesWildcard() throws Exception { + int[] stateSpec = StateSet.WILD_CARD; + int[] stateSet = new int[0]; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet)); + int[] stateSet2 = {0}; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet2)); + } + + @SmallTest + public void testSingleStatePositiveMatches() throws Exception { + int[] stateSpec = new int[2]; + int state; + // match + stateSpec[0] = 1; + state = 1; + assertTrue(StateSet.stateSetMatches(stateSpec, state)); + // non-match + state = 2; + assertFalse(StateSet.stateSetMatches(stateSpec, state)); + // add irrelevant must-not-match + stateSpec[1] = -12345; + assertFalse(StateSet.stateSetMatches(stateSpec, state)); + } + + @SmallTest + public void testSingleStateNegativeMatches() throws Exception { + int[] stateSpec = new int[2]; + int state; + // match + stateSpec[0] = -1; + state = 1; + assertFalse(StateSet.stateSetMatches(stateSpec, state)); + // non-match + state = 2; + assertTrue(StateSet.stateSetMatches(stateSpec, state)); + // add irrelevant must-not-match + stateSpec[1] = -12345; + assertTrue(StateSet.stateSetMatches(stateSpec, state)); + } + + @SmallTest + public void testZeroStateOnlyMatchesDefault() throws Exception { + int[] stateSpec = new int[3]; + int state = 0; + // non-match + stateSpec[0] = 1; + assertFalse(StateSet.stateSetMatches(stateSpec, state)); + // non-match + stateSpec[1] = -1; + assertFalse(StateSet.stateSetMatches(stateSpec, state)); + // match + stateSpec = StateSet.WILD_CARD; + assertTrue(StateSet.stateSetMatches(stateSpec, state)); + } + + @SmallTest + public void testNullStateOnlyMatchesDefault() throws Exception { + int[] stateSpec = new int[3]; + int[] stateSet = null; + // non-match + stateSpec[0] = 1; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet)); + // non-match + stateSpec[1] = -1; + assertFalse(StateSet.stateSetMatches(stateSpec, stateSet)); + // match + stateSpec = StateSet.WILD_CARD; + assertTrue(StateSet.stateSetMatches(stateSpec, stateSet)); + } +} diff --git a/core/tests/coretests/src/android/view/FocusFinderTest.java b/core/tests/coretests/src/android/view/FocusFinderTest.java new file mode 100644 index 0000000..7ac8dfc --- /dev/null +++ b/core/tests/coretests/src/android/view/FocusFinderTest.java @@ -0,0 +1,576 @@ +/* + * Copyright (C) 2008 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 android.view; + +import android.graphics.Rect; +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.SmallTest; + +public class FocusFinderTest extends AndroidTestCase { + + private FocusFinderHelper mFocusFinder; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + mFocusFinder = new FocusFinderHelper(FocusFinder.getInstance()); + } + + @SmallTest + public void testPreconditions() { + assertNotNull("focus finder instance", mFocusFinder); + } + + @SmallTest + public void testBelowNotCandidateForDirectionUp() { + assertIsNotCandidate(View.FOCUS_UP, + new Rect(0, 30, 10, 40), // src (left, top, right, bottom) + new Rect(0, 50, 10, 60)); // dest (left, top, right, bottom) + } + + @SmallTest + public void testAboveShareEdgeEdgeOkForDirectionUp() { + final Rect src = new Rect(0, 30, 10, 40); + + final Rect dest = new Rect(src); + dest.offset(0, -src.height()); + assertEquals(src.top, dest.bottom); + + assertDirectionIsCandidate(View.FOCUS_UP, src, dest); + } + + @SmallTest + public void testCompletelyContainedNotCandidate() { + assertIsNotCandidate( + View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 50, 50), + new Rect(0, 1, 50, 49)); + } + + @SmallTest + public void testContinaedWithCommonBottomNotCandidate() { + assertIsNotCandidate( + View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 50, 50), + new Rect(0, 1, 50, 50)); + } + + @SmallTest + public void testOverlappingIsCandidateWhenBothEdgesAreInDirection() { + assertDirectionIsCandidate( + View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 50, 50), + new Rect(0, 1, 50, 51)); + } + + @SmallTest + public void testTopEdgeOfDestAtOrAboveTopOfSrcNotCandidateForDown() { + assertIsNotCandidate( + View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 50, 50), + new Rect(0, 0, 50, 51)); + assertIsNotCandidate( + View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 50, 50), + new Rect(0, -1, 50, 51)); + } + + @SmallTest + public void testSameRectBeamsOverlap() { + final Rect rect = new Rect(0, 0, 20, 20); + + assertBeamsOverlap(View.FOCUS_LEFT, rect, rect); + assertBeamsOverlap(View.FOCUS_RIGHT, rect, rect); + assertBeamsOverlap(View.FOCUS_UP, rect, rect); + assertBeamsOverlap(View.FOCUS_DOWN, rect, rect); + } + + @SmallTest + public void testOverlapBeamsRightLeftUpToEdge() { + final Rect rect1 = new Rect(0, 0, 20, 20); + final Rect rect2 = new Rect(rect1); + + // just below bottom edge + rect2.offset(0, rect1.height() - 1); + assertBeamsOverlap(View.FOCUS_LEFT, rect1, rect2); + assertBeamsOverlap(View.FOCUS_RIGHT, rect1, rect2); + + // at edge + rect2.offset(0, 1); + assertBeamsOverlap(View.FOCUS_LEFT, rect1, rect2); + assertBeamsOverlap(View.FOCUS_RIGHT, rect1, rect2); + + // just beyond + rect2.offset(0, 1); + assertBeamsDontOverlap(View.FOCUS_LEFT, rect1, rect2); + assertBeamsDontOverlap(View.FOCUS_RIGHT, rect1, rect2); + + // just below top edge + rect2.set(rect1); + rect2.offset(0, -(rect1.height() - 1)); + assertBeamsOverlap(View.FOCUS_LEFT, rect1, rect2); + assertBeamsOverlap(View.FOCUS_RIGHT, rect1, rect2); + + // at top edge + rect2.offset(0, -1); + assertBeamsOverlap(View.FOCUS_LEFT, rect1, rect2); + assertBeamsOverlap(View.FOCUS_RIGHT, rect1, rect2); + + // just beyond top edge + rect2.offset(0, -1); + assertBeamsDontOverlap(View.FOCUS_LEFT, rect1, rect2); + assertBeamsDontOverlap(View.FOCUS_RIGHT, rect1, rect2); + } + + @SmallTest + public void testOverlapBeamsUpDownUpToEdge() { + final Rect rect1 = new Rect(0, 0, 20, 20); + final Rect rect2 = new Rect(rect1); + + // just short of right edge + rect2.offset(rect1.width() - 1, 0); + assertBeamsOverlap(View.FOCUS_UP, rect1, rect2); + assertBeamsOverlap(View.FOCUS_DOWN, rect1, rect2); + + // at edge + rect2.offset(1, 0); + assertBeamsOverlap(View.FOCUS_UP, rect1, rect2); + assertBeamsOverlap(View.FOCUS_DOWN, rect1, rect2); + + // just beyond + rect2.offset(1, 0); + assertBeamsDontOverlap(View.FOCUS_UP, rect1, rect2); + assertBeamsDontOverlap(View.FOCUS_DOWN, rect1, rect2); + + // just short of left edge + rect2.set(rect1); + rect2.offset(-(rect1.width() - 1), 0); + assertBeamsOverlap(View.FOCUS_UP, rect1, rect2); + assertBeamsOverlap(View.FOCUS_DOWN, rect1, rect2); + + // at edge + rect2.offset(-1, 0); + assertBeamsOverlap(View.FOCUS_UP, rect1, rect2); + assertBeamsOverlap(View.FOCUS_DOWN, rect1, rect2); + + // just beyond edge + rect2.offset(-1, 0); + assertBeamsDontOverlap(View.FOCUS_UP, rect1, rect2); + assertBeamsDontOverlap(View.FOCUS_DOWN, rect1, rect2); + } + + @SmallTest + public void testDirectlyAboveTrumpsAboveLeft() { + Rect src = new Rect(0, 50, 20, 70); // src (left, top, right, bottom) + + Rect directlyAbove = new Rect(src); + directlyAbove.offset(0, -(1 + src.height())); + + Rect aboveLeft = new Rect(src); + aboveLeft.offset(-(1 + src.width()), -(1 + src.height())); + + assertBetterCandidate(View.FOCUS_UP, src, directlyAbove, aboveLeft); + } + + @SmallTest + public void testAboveInBeamTrumpsSlightlyCloserOutOfBeam() { + Rect src = new Rect(0, 50, 20, 70); // src (left, top, right, bottom) + + Rect directlyAbove = new Rect(src); + directlyAbove.offset(0, -(1 + src.height())); + + Rect aboveLeft = new Rect(src); + aboveLeft.offset(-(1 + src.width()), -(1 + src.height())); + + // offset directly above a little further up + directlyAbove.offset(0, -5); + assertBetterCandidate(View.FOCUS_UP, src, directlyAbove, aboveLeft); + } + + @SmallTest + public void testOutOfBeamBeatsInBeamUp() { + + Rect src = new Rect(0, 0, 50, 50); // (left, top, right, bottom) + + Rect aboveLeftOfBeam = new Rect(src); + aboveLeftOfBeam.offset(-(src.width() + 1), -src.height()); + assertBeamsDontOverlap(View.FOCUS_UP, src, aboveLeftOfBeam); + + Rect aboveInBeam = new Rect(src); + aboveInBeam.offset(0, -src.height()); + assertBeamsOverlap(View.FOCUS_UP, src, aboveInBeam); + + // in beam wins + assertBetterCandidate(View.FOCUS_UP, src, aboveInBeam, aboveLeftOfBeam); + + // still wins while aboveInBeam's bottom edge is < out of beams' top + aboveInBeam.offset(0, -(aboveLeftOfBeam.height() - 1)); + assertTrue("aboveInBeam.bottom > aboveLeftOfBeam.top", aboveInBeam.bottom > aboveLeftOfBeam.top); + assertBetterCandidate(View.FOCUS_UP, src, aboveInBeam, aboveLeftOfBeam); + + // cross the threshold: the out of beam prevails + aboveInBeam.offset(0, -1); + assertEquals(aboveInBeam.bottom, aboveLeftOfBeam.top); + assertBetterCandidate(View.FOCUS_UP, src, aboveLeftOfBeam, aboveInBeam); + } + + /** + * A non-candidate (even a much closer one) is always a worse choice + * than a real candidate. + */ + @MediumTest + public void testSomeCandidateBetterThanNonCandidate() { + Rect src = new Rect(0, 0, 50, 50); // (left, top, right, bottom) + + Rect nonCandidate = new Rect(src); + nonCandidate.offset(src.width() + 1, 0); + + assertIsNotCandidate(View.FOCUS_LEFT, src, nonCandidate); + + Rect candidate = new Rect(src); + candidate.offset(-(4 * src.width()), 0); + assertDirectionIsCandidate(View.FOCUS_LEFT, src, candidate); + + assertBetterCandidate(View.FOCUS_LEFT, src, candidate, nonCandidate); + } + + /** + * Grabbed from {@link com.android.frameworktest.focus.VerticalFocusSearchTest#testSearchFromMidLeft()} + */ + @SmallTest + public void testVerticalFocusSearchScenario() { + assertBetterCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(0, 109, 153, 169), // src + new Rect(166, 169, 319, 229), // expectedbetter + new Rect(0, 229, 320, 289)); // expectedworse + + // failing test 4/10/2008, the values were tweaked somehow in functional + // test... + assertBetterCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(0, 91, 153, 133), // src + new Rect(166, 133, 319, 175), // expectedbetter + new Rect(0, 175, 320, 217)); // expectedworse + + } + + /** + * Example: going down from a thin button all the way to the left of a + * screen where, just below, is a very wide button, and just below that, + * is an equally skinny button all the way to the left. want to make + * sure any minor axis factor doesn't override the fact that the one below + * in vertical beam should be next focus + */ + @SmallTest + public void testBeamsOverlapMajorAxisCloserMinorAxisFurther() { + assertBetterCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 100, 100), // src + new Rect(0, 100, 480, 200), // expectedbetter + new Rect(0, 200, 100, 300)); // expectedworse + } + + /** + * Real scenario grabbed from song playback screen. + */ + @SmallTest + public void testMusicPlaybackScenario() { + assertBetterCandidate(View.FOCUS_LEFT, + // L T R B + new Rect(227, 185, 312, 231), // src + new Rect(195, 386, 266, 438), // expectedbetter + new Rect(124, 386, 195, 438)); // expectedworse + } + + /** + * more generalized version of {@link #testMusicPlaybackScenario()} + */ + @SmallTest + public void testOutOfBeamOverlapBeatsOutOfBeamFurtherOnMajorAxis() { + assertBetterCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 50, 50), // src + new Rect(60, 40, 110, 90), // expectedbetter + new Rect(60, 70, 110, 120)); // expectedworse + } + + /** + * Make sure that going down prefers views that are actually + * down (and not those next to but still a candidate because + * they are overlapping on the major axis) + */ + @SmallTest + public void testInBeamTrumpsOutOfBeamOverlapping() { + assertBetterCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 50, 50), // src + new Rect(0, 60, 50, 110), // expectedbetter + new Rect(51, 1, 101, 51)); // expectedworse + } + + @SmallTest + public void testOverlappingBeatsNonOverlapping() { + assertBetterCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 50, 50), // src + new Rect(0, 40, 50, 90), // expectedbetter + new Rect(0, 75, 50, 125)); // expectedworse + } + + @SmallTest + public void testEditContactScenarioLeftFromDiscardChangesGoesToSaveContactInLandscape() { + assertBetterCandidate(View.FOCUS_LEFT, + // L T R B + new Rect(357, 258, 478, 318), // src + new Rect(2, 258, 100, 318), // better + new Rect(106, 120, 424, 184)); // worse + } + + /** + * A dial pad with 9 squares arranged in a grid. no padding, so + * the edges are equal. see {@link com.android.frameworktest.focus.LinearLayoutGrid} + */ + @SmallTest + public void testGridWithTouchingEdges() { + assertBetterCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(106, 49, 212, 192), // src + new Rect(106, 192, 212, 335), // better + new Rect(0, 192, 106, 335)); // worse + + assertBetterCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(106, 49, 212, 192), // src + new Rect(106, 192, 212, 335), // better + new Rect(212, 192, 318, 335)); // worse + } + + @SmallTest + public void testSearchFromEmptyRect() { + assertBetterCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 0, 0), // src + new Rect(0, 0, 320, 45), // better + new Rect(0, 45, 320, 545)); // worse + } + + /** + * Reproduce bug 1124559, drilling down to actual bug + * (majorAxisDistance was wrong for direction left) + */ + @SmallTest + public void testGmailReplyButtonsScenario() { + assertBetterCandidate(View.FOCUS_LEFT, + // L T R B + new Rect(223, 380, 312, 417), // src + new Rect(102, 380, 210, 417), // better + new Rect(111, 443, 206, 480)); // worse + + assertBeamBeats(View.FOCUS_LEFT, + // L T R B + new Rect(223, 380, 312, 417), // src + new Rect(102, 380, 210, 417), // better + new Rect(111, 443, 206, 480)); // worse + + assertBeamsOverlap(View.FOCUS_LEFT, + // L T R B + new Rect(223, 380, 312, 417), + new Rect(102, 380, 210, 417)); + + assertBeamsDontOverlap(View.FOCUS_LEFT, + // L T R B + new Rect(223, 380, 312, 417), + new Rect(111, 443, 206, 480)); + + assertTrue( + "major axis distance less than major axis distance to " + + "far edge", + FocusFinderHelper.majorAxisDistance(View.FOCUS_LEFT, + // L T R B + new Rect(223, 380, 312, 417), + new Rect(102, 380, 210, 417)) < + FocusFinderHelper.majorAxisDistanceToFarEdge(View.FOCUS_LEFT, + // L T R B + new Rect(223, 380, 312, 417), + new Rect(111, 443, 206, 480))); + } + + @SmallTest + public void testGmailScenarioBug1203288() { + assertBetterCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(0, 2, 480, 82), // src + new Rect(344, 87, 475, 124), // better + new Rect(0, 130, 480, 203)); // worse + } + + @SmallTest + public void testHomeShortcutScenarioBug1295354() { + assertBetterCandidate(View.FOCUS_RIGHT, + // L T R B + new Rect(3, 338, 77, 413), // src + new Rect(163, 338, 237, 413), // better + new Rect(83, 38, 157, 113)); // worse + } + + @SmallTest + public void testBeamAlwaysBeatsHoriz() { + assertBetterCandidate(View.FOCUS_RIGHT, + // L T R B + new Rect(0, 0, 50, 50), // src + new Rect(150, 0, 200, 50), // better, (way further, but in beam) + new Rect(60, 51, 110, 101)); // worse, even though it is closer + + assertBetterCandidate(View.FOCUS_LEFT, + // L T R B + new Rect(150, 0, 200, 50), // src + new Rect(0, 50, 50, 50), // better, (way further, but in beam) + new Rect(49, 99, 149, 101)); // worse, even though it is closer + } + + @SmallTest + public void testIsCandidateOverlappingEdgeFromEmptyRect() { + assertDirectionIsCandidate(View.FOCUS_DOWN, + // L T R B + new Rect(0, 0, 0, 0), // src + new Rect(0, 0, 20, 1)); // candidate + + assertDirectionIsCandidate(View.FOCUS_UP, + // L T R B + new Rect(0, 0, 0, 0), // src + new Rect(0, -1, 20, 0)); // candidate + + assertDirectionIsCandidate(View.FOCUS_LEFT, + // L T R B + new Rect(0, 0, 0, 0), // src + new Rect(-1, 0, 0, 20)); // candidate + + assertDirectionIsCandidate(View.FOCUS_RIGHT, + // L T R B + new Rect(0, 0, 0, 0), // src + new Rect(0, 0, 1, 20)); // candidate + } + + private void assertBeamsOverlap(int direction, Rect rect1, Rect rect2) { + String directionStr = validateAndGetStringFor(direction); + String assertMsg = String.format("Expected beams to overlap in direction %s " + + "for rectangles %s and %s", directionStr, rect1, rect2); + assertTrue(assertMsg, mFocusFinder.beamsOverlap(direction, rect1, rect2)); + } + + private void assertBeamsDontOverlap(int direction, Rect rect1, Rect rect2) { + String directionStr = validateAndGetStringFor(direction); + String assertMsg = String.format("Expected beams not to overlap in direction %s " + + "for rectangles %s and %s", directionStr, rect1, rect2); + assertFalse(assertMsg, mFocusFinder.beamsOverlap(direction, rect1, rect2)); + } + + /** + * Assert that particular rect is a better focus search candidate from a + * source rect than another. + * @param direction The direction of focus search. + * @param srcRect The src rectangle. + * @param expectedBetter The candidate that should be better. + * @param expectedWorse The candidate that should be worse. + */ + private void assertBetterCandidate(int direction, Rect srcRect, + Rect expectedBetter, Rect expectedWorse) { + + String directionStr = validateAndGetStringFor(direction); + String assertMsg = String.format( + "expected %s to be a better focus search candidate than " + + "%s when searching " + + "from %s in direction %s", + expectedBetter, expectedWorse, srcRect, directionStr); + + assertTrue(assertMsg, + mFocusFinder.isBetterCandidate(direction, srcRect, + expectedBetter, expectedWorse)); + + assertMsg = String.format( + "expected %s to not be a better focus search candidate than " + + "%s when searching " + + "from %s in direction %s", + expectedWorse, expectedBetter, srcRect, directionStr); + + assertFalse(assertMsg, + mFocusFinder.isBetterCandidate(direction, srcRect, + expectedWorse, expectedBetter)); + } + + private void assertIsNotCandidate(int direction, Rect src, Rect dest) { + String directionStr = validateAndGetStringFor(direction); + + final String assertMsg = String.format( + "expected going from %s to %s in direction %s to be an invalid " + + "focus search candidate", + src, dest, directionStr); + assertFalse(assertMsg, mFocusFinder.isCandidate(src, dest, direction)); + } + + private void assertBeamBeats(int direction, Rect srcRect, + Rect rect1, Rect rect2) { + + String directionStr = validateAndGetStringFor(direction); + String assertMsg = String.format( + "expecting %s to beam beat %s w.r.t %s in direction %s", + rect1, rect2, srcRect, directionStr); + assertTrue(assertMsg, mFocusFinder.beamBeats(direction, srcRect, rect1, rect2)); + } + + + private void assertDirectionIsCandidate(int direction, Rect src, Rect dest) { + String directionStr = validateAndGetStringFor(direction); + + final String assertMsg = String.format( + "expected going from %s to %s in direction %s to be a valid " + + "focus search candidate", + src, dest, directionStr); + assertTrue(assertMsg, mFocusFinder.isCandidate(src, dest, direction)); + } + + private String validateAndGetStringFor(int direction) { + String directionStr = "??"; + switch(direction) { + case View.FOCUS_UP: + directionStr = "FOCUS_UP"; + break; + case View.FOCUS_DOWN: + directionStr = "FOCUS_DOWN"; + break; + case View.FOCUS_LEFT: + directionStr = "FOCUS_LEFT"; + break; + case View.FOCUS_RIGHT: + directionStr = "FOCUS_RIGHT"; + break; + default: + fail("passed in unknown direction, ya blewit!"); + } + return directionStr; + } + + +} diff --git a/core/tests/coretests/src/android/view/ViewGroupAttributesTest.java b/core/tests/coretests/src/android/view/ViewGroupAttributesTest.java new file mode 100644 index 0000000..b4ef0e7 --- /dev/null +++ b/core/tests/coretests/src/android/view/ViewGroupAttributesTest.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2008 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 android.view; + +import android.content.Context; +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; + +public class ViewGroupAttributesTest extends AndroidTestCase { + + private MyViewGroup mViewGroup; + + private static final class MyViewGroup extends ViewGroup { + + public MyViewGroup(Context context) { + super(context); + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + } + + @Override + public boolean isChildrenDrawnWithCacheEnabled() { + return super.isChildrenDrawnWithCacheEnabled(); + } + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + mViewGroup = new MyViewGroup(getContext()); + } + + @SmallTest + public void testDescendantFocusabilityEnum() { + assertEquals("expected ViewGroup.FOCUS_BEFORE_DESCENDANTS to be default", + ViewGroup.FOCUS_BEFORE_DESCENDANTS, mViewGroup.getDescendantFocusability()); + + // remember some state before we muck with flags + final boolean isAnimationCachEnabled = mViewGroup.isAnimationCacheEnabled(); + final boolean isAlwaysDrawnWithCacheEnabled = mViewGroup.isAlwaysDrawnWithCacheEnabled(); + final boolean isChildrenDrawnWithCacheEnabled = mViewGroup.isChildrenDrawnWithCacheEnabled(); + + mViewGroup.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); + assertEquals(ViewGroup.FOCUS_AFTER_DESCENDANTS, mViewGroup.getDescendantFocusability()); + + mViewGroup.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); + assertEquals(ViewGroup.FOCUS_BLOCK_DESCENDANTS, mViewGroup.getDescendantFocusability()); + + mViewGroup.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); + assertEquals(ViewGroup.FOCUS_BEFORE_DESCENDANTS, mViewGroup.getDescendantFocusability()); + + // verify we didn't change something unrelated + final String msg = "setDescendantFocusability messed with an unrelated flag"; + assertEquals(msg, isAnimationCachEnabled, mViewGroup.isAnimationCacheEnabled()); + assertEquals(msg, isAlwaysDrawnWithCacheEnabled, mViewGroup.isAlwaysDrawnWithCacheEnabled()); + assertEquals(msg, isChildrenDrawnWithCacheEnabled, mViewGroup.isChildrenDrawnWithCacheEnabled()); + } + + @SmallTest + public void testWrongIntSetForDescendantFocusabilityEnum() { + try { + mViewGroup.setDescendantFocusability(0); + fail("expected setting wrong flag to throw an exception"); + } catch (IllegalArgumentException expected) { + } + } +} diff --git a/core/tests/coretests/src/android/webkit/UrlInterceptRegistryTest.java b/core/tests/coretests/src/android/webkit/UrlInterceptRegistryTest.java new file mode 100644 index 0000000..7504449 --- /dev/null +++ b/core/tests/coretests/src/android/webkit/UrlInterceptRegistryTest.java @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2009 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 android.webkit; + +import android.test.AndroidTestCase; +import android.util.Log; +import android.webkit.CacheManager.CacheResult; +import android.webkit.PluginData; +import android.webkit.UrlInterceptHandler; + +import java.util.LinkedList; +import java.util.Map; + +public class UrlInterceptRegistryTest extends AndroidTestCase { + + /** + * To run these tests: $ mmm + * frameworks/base/tests/CoreTests/android && adb remount && adb + * sync $ adb shell am instrument -w -e class \ + * android.webkit.UrlInterceptRegistryTest \ + * android.core/android.test.InstrumentationTestRunner + */ + + private static class MockUrlInterceptHandler implements UrlInterceptHandler { + private PluginData mData; + private String mUrl; + + public MockUrlInterceptHandler(PluginData data, String url) { + mData = data; + mUrl = url; + } + + public CacheResult service(String url, Map<String, String> headers) { + return null; + } + + public PluginData getPluginData(String url, + Map<String, + String> headers) { + if (mUrl.equals(url)) { + return mData; + } + + return null; + } + } + + public void testGetPluginData() { + PluginData data = new PluginData(null, 0 , null, 200); + String url = new String("url1"); + MockUrlInterceptHandler handler1 = + new MockUrlInterceptHandler(data, url); + + data = new PluginData(null, 0 , null, 404); + url = new String("url2"); + MockUrlInterceptHandler handler2 = + new MockUrlInterceptHandler(data, url); + + assertTrue(UrlInterceptRegistry.registerHandler(handler1)); + assertTrue(UrlInterceptRegistry.registerHandler(handler2)); + + data = UrlInterceptRegistry.getPluginData("url1", null); + assertTrue(data != null); + assertTrue(data.getStatusCode() == 200); + + data = UrlInterceptRegistry.getPluginData("url2", null); + assertTrue(data != null); + assertTrue(data.getStatusCode() == 404); + + assertTrue(UrlInterceptRegistry.unregisterHandler(handler1)); + assertTrue(UrlInterceptRegistry.unregisterHandler(handler2)); + + } +} diff --git a/core/tests/coretests/src/com/android/internal/util/PredicatesTest.java b/core/tests/coretests/src/com/android/internal/util/PredicatesTest.java new file mode 100644 index 0000000..c46ff05 --- /dev/null +++ b/core/tests/coretests/src/com/android/internal/util/PredicatesTest.java @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2008 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.internal.util; + +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.Collections; + +public class PredicatesTest extends TestCase { + + private static final Predicate<Object> TRUE = new Predicate<Object>() { + public boolean apply(Object o) { + return true; + } + }; + + private static final Predicate<Object> FALSE = new Predicate<Object>() { + public boolean apply(Object o) { + return false; + } + }; + + public void testAndPredicate_AllConditionsTrue() throws Exception { + assertTrue(Predicates.and(newArrayList(TRUE)).apply(null)); + assertTrue(Predicates.and(newArrayList(TRUE, TRUE)).apply(null)); + } + + public void testAndPredicate_AtLeastOneConditionIsFalse() throws Exception { + assertFalse(Predicates.and(newArrayList(FALSE, TRUE, TRUE)).apply(null)); + assertFalse(Predicates.and(newArrayList(TRUE, FALSE, TRUE)).apply(null)); + assertFalse(Predicates.and(newArrayList(TRUE, TRUE, FALSE)).apply(null)); + } + + public void testOrPredicate_AllConditionsTrue() throws Exception { + assertTrue(Predicates.or(newArrayList(TRUE, TRUE, TRUE)).apply(null)); + } + + public void testOrPredicate_AllConditionsFalse() throws Exception { + assertFalse(Predicates.or(newArrayList(FALSE, FALSE, FALSE)).apply(null)); + } + + public void testOrPredicate_AtLeastOneConditionIsTrue() throws Exception { + assertTrue(Predicates.or(newArrayList(TRUE, FALSE, FALSE)).apply(null)); + assertTrue(Predicates.or(newArrayList(FALSE, TRUE, FALSE)).apply(null)); + assertTrue(Predicates.or(newArrayList(FALSE, FALSE, TRUE)).apply(null)); + } + + public void testNotPredicate() throws Exception { + assertTrue(Predicates.not(FALSE).apply(null)); + assertFalse(Predicates.not(TRUE).apply(null)); + } + + private static <E> ArrayList<E> newArrayList(E... elements) { + ArrayList<E> list = new ArrayList<E>(); + Collections.addAll(list, elements); + return list; + } + +} |