diff options
Diffstat (limited to 'tests/unit')
56 files changed, 1778 insertions, 863 deletions
diff --git a/tests/unit/Android.mk b/tests/unit/Android.mk index f53220de..3632fe94 100644 --- a/tests/unit/Android.mk +++ b/tests/unit/Android.mk @@ -12,7 +12,8 @@ LOCAL_STATIC_JAVA_LIBRARIES := \ mockito-target \ tv-test-common \ -LOCAL_JAVA_LIBRARIES := android.test.mock.sdk legacy-android-test + +LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/../common/res LOCAL_PACKAGE_NAME := TVUnitTests @@ -22,3 +23,4 @@ LOCAL_SDK_VERSION := system_current LOCAL_MIN_SDK_VERSION := 23 # M include $(BUILD_PACKAGE) + diff --git a/tests/unit/AndroidManifest.xml b/tests/unit/AndroidManifest.xml index aebb3772..d073f8ac 100644 --- a/tests/unit/AndroidManifest.xml +++ b/tests/unit/AndroidManifest.xml @@ -18,7 +18,7 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.tv.tests" > - <uses-sdk android:targetSdkVersion="23" android:minSdkVersion="21" /> + <uses-sdk android:targetSdkVersion="23" android:minSdkVersion="23" /> <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" diff --git a/tests/unit/OWNERS b/tests/unit/OWNERS new file mode 100644 index 00000000..4aa5fe52 --- /dev/null +++ b/tests/unit/OWNERS @@ -0,0 +1,2 @@ +nchalko@google.com +shubang@google.com diff --git a/tests/unit/src/com/android/tv/BaseMainActivityTestCase.java b/tests/unit/src/com/android/tv/BaseMainActivityTestCase.java index e2f620ed..e6f1af7e 100644 --- a/tests/unit/src/com/android/tv/BaseMainActivityTestCase.java +++ b/tests/unit/src/com/android/tv/BaseMainActivityTestCase.java @@ -15,9 +15,11 @@ */ package com.android.tv; +import static android.support.test.InstrumentationRegistry.getInstrumentation; + import android.content.Context; import android.os.SystemClock; -import android.test.ActivityInstrumentationTestCase2; +import android.support.test.rule.ActivityTestRule; import android.text.TextUtils; import com.android.tv.data.Channel; @@ -28,41 +30,40 @@ import com.android.tv.testing.testinput.TestInputControlConnection; import com.android.tv.testing.testinput.TestInputControlUtils; import com.android.tv.testing.testinput.TvTestInputConstants; +import org.junit.Before; +import org.junit.Rule; + import java.util.List; /** * Base TestCase for tests that need a {@link MainActivity}. */ -public abstract class BaseMainActivityTestCase - extends ActivityInstrumentationTestCase2<MainActivity> { +public abstract class BaseMainActivityTestCase { private static final String TAG = "BaseMainActivityTest"; private static final int CHANNEL_LOADING_CHECK_INTERVAL_MS = 10; + @Rule + public ActivityTestRule<MainActivity> mActivityTestRule = + new ActivityTestRule<>(MainActivity.class); + protected final TestInputControlConnection mConnection = new TestInputControlConnection(); protected MainActivity mActivity; - public BaseMainActivityTestCase(Class<MainActivity> activityClass) { - super(activityClass); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { + mActivity = mActivityTestRule.getActivity(); // TODO: ensure the SampleInputs are setup. - setActivityInitialTouchMode(false); - mActivity = getActivity(); - getInstrumentation().getContext() + getInstrumentation().getTargetContext() .bindService(TestInputControlUtils.createIntent(), mConnection, Context.BIND_AUTO_CREATE); } - @Override - protected void tearDown() throws Exception { + @Before + public void tearDown() { if (mConnection.isBound()) { - getInstrumentation().getContext().unbindService(mConnection); + getInstrumentation().getTargetContext().unbindService(mConnection); } - super.tearDown(); } /** @@ -72,16 +73,12 @@ public abstract class BaseMainActivityTestCase */ protected void tuneToChannel(final Channel channel) { // Run on UI thread so views can be modified - try { - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mActivity.tuneToChannel(channel); - } - }); - } catch (Throwable throwable) { - throw new RuntimeException(throwable); - } + getInstrumentation().runOnMainSync(new Runnable() { + @Override + public void run() { + mActivity.tuneToChannel(channel); + } + }); } /** @@ -130,13 +127,17 @@ public abstract class BaseMainActivityTestCase private Channel findChannelWithName(String displayName) { waitUntilChannelLoadingFinish(); - List<Channel> channelList = mActivity.getChannelDataManager().getChannelList(); + Channel channel = null; + List <Channel> channelList = mActivity.getChannelDataManager().getChannelList(); for (Channel c : channelList) { if (TextUtils.equals(c.getDisplayName(), displayName)) { - return c; + channel = c; + break; } } - throw new AssertionError("'" + displayName + "' channel not found"); + if (channel == null) { + throw new AssertionError("'" + displayName + "' channel not found"); + } + return channel; } - } diff --git a/tests/unit/src/com/android/tv/CurrentPositionMediatorTest.java b/tests/unit/src/com/android/tv/CurrentPositionMediatorTest.java index 899083f3..f2917181 100644 --- a/tests/unit/src/com/android/tv/CurrentPositionMediatorTest.java +++ b/tests/unit/src/com/android/tv/CurrentPositionMediatorTest.java @@ -18,33 +18,37 @@ package com.android.tv; import static com.android.tv.TimeShiftManager.INVALID_TIME; import static com.android.tv.TimeShiftManager.REQUEST_TIMEOUT_MS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import android.support.test.annotation.UiThreadTest; import android.support.test.filters.MediumTest; -import android.test.UiThreadTest; + +import org.junit.Before; +import org.junit.Test; @MediumTest public class CurrentPositionMediatorTest extends BaseMainActivityTestCase { private TimeShiftManager.CurrentPositionMediator mMediator; - public CurrentPositionMediatorTest() { - super(MainActivity.class); - } - @Override - protected void setUp() throws Exception { + @Before + public void setUp() { super.setUp(); mMediator = mActivity.getTimeShiftManager().mCurrentPositionMediator; } @UiThreadTest - public void testInitialize() throws Throwable { + @Test + public void testInitialize() { long currentTimeMs = System.currentTimeMillis(); mMediator.initialize(currentTimeMs); assertCurrentPositionMediator(INVALID_TIME, currentTimeMs); } @UiThreadTest - public void testOnSeekRequested() throws Throwable { + @Test + public void testOnSeekRequested() { long seekToTimeMs = System.currentTimeMillis() - REQUEST_TIMEOUT_MS * 3; mMediator.onSeekRequested(seekToTimeMs); assertNotSame("Seek request time", INVALID_TIME, mMediator.mSeekRequestTimeMs); @@ -52,7 +56,8 @@ public class CurrentPositionMediatorTest extends BaseMainActivityTestCase { } @UiThreadTest - public void testOnCurrentPositionChangedInvalidInput() throws Throwable { + @Test + public void testOnCurrentPositionChangedInvalidInput() { long seekToTimeMs = System.currentTimeMillis() - REQUEST_TIMEOUT_MS * 3; long newCurrentTimeMs = seekToTimeMs + REQUEST_TIMEOUT_MS; mMediator.onSeekRequested(seekToTimeMs); @@ -63,7 +68,8 @@ public class CurrentPositionMediatorTest extends BaseMainActivityTestCase { } @UiThreadTest - public void testOnCurrentPositionChangedValidInput() throws Throwable { + @Test + public void testOnCurrentPositionChangedValidInput() { long seekToTimeMs = System.currentTimeMillis() - REQUEST_TIMEOUT_MS * 3; long newCurrentTimeMs = seekToTimeMs + REQUEST_TIMEOUT_MS - 1; mMediator.onSeekRequested(seekToTimeMs); diff --git a/tests/unit/src/com/android/tv/FeaturesTest.java b/tests/unit/src/com/android/tv/FeaturesTest.java index 644c4248..9d61e757 100644 --- a/tests/unit/src/com/android/tv/FeaturesTest.java +++ b/tests/unit/src/com/android/tv/FeaturesTest.java @@ -16,19 +16,21 @@ package com.android.tv; +import static org.junit.Assert.assertFalse; + import android.support.test.filters.SmallTest; -import junit.framework.TestCase; +import org.junit.Test; /** * Test for features. */ @SmallTest -public class FeaturesTest extends TestCase { - +public class FeaturesTest { + @Test public void testPropertyFeatureKeyLength() { // This forces the class to be loaded and verifies all PropertyFeature key lengths. // If any keys are too long the test will fail to load. - assertEquals(false, Features.TEST_FEATURE.isEnabled(null)); + assertFalse(Features.TEST_FEATURE.isEnabled(null)); } } diff --git a/tests/unit/src/com/android/tv/MainActivityTest.java b/tests/unit/src/com/android/tv/MainActivityTest.java index b2fe6745..15805032 100644 --- a/tests/unit/src/com/android/tv/MainActivityTest.java +++ b/tests/unit/src/com/android/tv/MainActivityTest.java @@ -15,6 +15,10 @@ */ package com.android.tv; +import static android.support.test.InstrumentationRegistry.getInstrumentation; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import android.support.test.filters.MediumTest; import android.view.View; import android.widget.TextView; @@ -23,6 +27,8 @@ import com.android.tv.data.Channel; import com.android.tv.testing.testinput.TvTestInputConstants; import com.android.tv.ui.ChannelBannerView; +import org.junit.Test; + import java.util.List; /** @@ -30,25 +36,22 @@ import java.util.List; */ @MediumTest public class MainActivityTest extends BaseMainActivityTestCase { - - public MainActivityTest() { - super(MainActivity.class); - } - + @Test public void testInitialConditions() { waitUntilChannelLoadingFinish(); List<Channel> channelList = mActivity.getChannelDataManager().getChannelList(); assertTrue("Expected at least one channel", channelList.size() > 0); - assertFalse("PIP disabled", mActivity.isPipEnabled()); } - public void testTuneToChannel() throws Throwable { + @Test + public void testTuneToChannel() { tuneToChannel(TvTestInputConstants.CH_2); assertChannelBannerShown(true); assertChannelName(TvTestInputConstants.CH_2.name); } - public void testShowProgramGuide() throws Throwable { + @Test + public void testShowProgramGuide() { tuneToChannel(TvTestInputConstants.CH_2); showProgramGuide(); getInstrumentation().waitForIdleSync(); @@ -56,7 +59,7 @@ public class MainActivityTest extends BaseMainActivityTestCase { assertProgramGuide(true); } - private void showProgramGuide() throws Throwable { + private void showProgramGuide() { // Run on UI thread so views can be modified getInstrumentation().runOnMainSync(new Runnable() { @Override @@ -81,7 +84,7 @@ public class MainActivityTest extends BaseMainActivityTestCase { } private View assertExpectedBannerSceneClassShown(Class<ChannelBannerView> expectedClass, - boolean expectedShown) throws AssertionError { + boolean expectedShown) { View v = assertViewIsShown(expectedClass.getSimpleName(), R.id.scene_transition_common, expectedShown); if (v != null) { @@ -90,8 +93,7 @@ public class MainActivityTest extends BaseMainActivityTestCase { return v; } - private View assertViewIsShown(String viewName, int viewId, boolean expected) - throws AssertionError { + private View assertViewIsShown(String viewName, int viewId, boolean expected) { View view = mActivity.findViewById(viewId); if (view == null) { if (expected) { @@ -103,5 +105,4 @@ public class MainActivityTest extends BaseMainActivityTestCase { assertEquals(viewName + " shown", expected, view.isShown()); return view; } - } diff --git a/tests/unit/src/com/android/tv/TimeShiftManagerTest.java b/tests/unit/src/com/android/tv/TimeShiftManagerTest.java index f7c6f622..052b5d19 100644 --- a/tests/unit/src/com/android/tv/TimeShiftManagerTest.java +++ b/tests/unit/src/com/android/tv/TimeShiftManagerTest.java @@ -22,23 +22,25 @@ import static com.android.tv.TimeShiftManager.TIME_SHIFT_ACTION_ID_JUMP_TO_PREVI import static com.android.tv.TimeShiftManager.TIME_SHIFT_ACTION_ID_PAUSE; import static com.android.tv.TimeShiftManager.TIME_SHIFT_ACTION_ID_PLAY; import static com.android.tv.TimeShiftManager.TIME_SHIFT_ACTION_ID_REWIND; +import static org.junit.Assert.assertEquals; import android.support.test.filters.MediumTest; +import org.junit.Before; +import org.junit.Test; + @MediumTest public class TimeShiftManagerTest extends BaseMainActivityTestCase { private TimeShiftManager mTimeShiftManager; - public TimeShiftManagerTest() { - super(MainActivity.class); - } - @Override - protected void setUp() throws Exception { + @Before + public void setUp() { super.setUp(); mTimeShiftManager = mActivity.getTimeShiftManager(); } + @Test public void testDisableActions() { enableAllActions(true); assertActionState(true, true, true, true, true, true); @@ -56,6 +58,7 @@ public class TimeShiftManagerTest extends BaseMainActivityTestCase { assertActionState(false, false, false, false, false, false); } + @Test public void testEnableActions() { enableAllActions(false); assertActionState(false, false, false, false, false, false); diff --git a/tests/unit/src/com/android/tv/common/TvContentRatingCacheTest.java b/tests/unit/src/com/android/tv/common/TvContentRatingCacheTest.java deleted file mode 100644 index eadc50d5..00000000 --- a/tests/unit/src/com/android/tv/common/TvContentRatingCacheTest.java +++ /dev/null @@ -1,172 +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.tv.common; - -import android.content.ComponentCallbacks2; -import android.media.tv.TvContentRating; -import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; -import android.test.MoreAsserts; - -import com.android.tv.testing.TvContentRatingConstants; -import com.android.tv.util.Utils; - -/** - * Test for {@link android.media.tv.TvContentRating} tests in {@link Utils}. - */ -@SmallTest -public class TvContentRatingCacheTest extends AndroidTestCase { - - /** - * US_TV_MA and US_TV_Y7 in order - */ - public static final String MA_AND_Y7 = TvContentRatingConstants.STRING_US_TV_MA + "," - + TvContentRatingConstants.STRING_US_TV_Y7_US_TV_FV; - - /** - * US_TV_MA and US_TV_Y7 not in order - */ - public static final String Y7_AND_MA = TvContentRatingConstants.STRING_US_TV_Y7_US_TV_FV + "," - + TvContentRatingConstants.STRING_US_TV_MA; - final TvContentRatingCache mCache = TvContentRatingCache.getInstance(); - - @Override - protected void setUp() throws Exception { - super.setUp(); - mCache.performTrimMemory(ComponentCallbacks2.TRIM_MEMORY_COMPLETE); - } - - @Override - protected void tearDown() throws Exception { - mCache.performTrimMemory(ComponentCallbacks2.TRIM_MEMORY_COMPLETE); - super.tearDown(); - } - - public void testGetRatings_US_TV_MA() { - TvContentRating[] result = mCache.getRatings(TvContentRatingConstants.STRING_US_TV_MA); - MoreAsserts.assertEquals(asArray(TvContentRatingConstants.CONTENT_RATING_US_TV_MA), result); - } - - public void testGetRatings_US_TV_MA_same() { - TvContentRating[] first = mCache.getRatings(TvContentRatingConstants.STRING_US_TV_MA); - TvContentRating[] second = mCache.getRatings(TvContentRatingConstants.STRING_US_TV_MA); - assertSame(first, second); - } - - public void testGetRatings_US_TV_MA_diffAfterClear() { - TvContentRating[] first = mCache.getRatings(TvContentRatingConstants.STRING_US_TV_MA); - mCache.performTrimMemory(ComponentCallbacks2.TRIM_MEMORY_COMPLETE); - TvContentRating[] second = mCache.getRatings(TvContentRatingConstants.STRING_US_TV_MA); - assertNotSame(first, second); - } - - public void testGetRatings_TWO_orderDoesNotMatter() { - TvContentRating[] first = mCache.getRatings(MA_AND_Y7); - TvContentRating[] second = mCache.getRatings(Y7_AND_MA); - assertSame(first, second); - } - - public void testContentRatingsToString_null() { - String result = TvContentRatingCache.contentRatingsToString(null); - assertEquals("ratings string", null, result); - } - - public void testContentRatingsToString_none() { - String result = TvContentRatingCache.contentRatingsToString(asArray()); - assertEquals("ratings string", null, result); - } - - public void testContentRatingsToString_one() { - String result = TvContentRatingCache - .contentRatingsToString(asArray(TvContentRatingConstants.CONTENT_RATING_US_TV_MA)); - assertEquals("ratings string", TvContentRatingConstants.STRING_US_TV_MA, result); - } - - public void testContentRatingsToString_twoInOrder() { - String result = TvContentRatingCache.contentRatingsToString( - asArray(TvContentRatingConstants.CONTENT_RATING_US_TV_MA, - TvContentRatingConstants.CONTENT_RATING_US_TV_Y7_US_TV_FV)); - assertEquals("ratings string", MA_AND_Y7, result); - } - - public void testContentRatingsToString_twoNotInOrder() { - String result = TvContentRatingCache.contentRatingsToString(asArray( - TvContentRatingConstants.CONTENT_RATING_US_TV_Y7_US_TV_FV, - TvContentRatingConstants.CONTENT_RATING_US_TV_MA)); - assertEquals("ratings string", MA_AND_Y7, result); - } - - public void testContentRatingsToString_double() { - String result = TvContentRatingCache.contentRatingsToString(asArray( - TvContentRatingConstants.CONTENT_RATING_US_TV_MA, - TvContentRatingConstants.CONTENT_RATING_US_TV_MA)); - assertEquals("ratings string", TvContentRatingConstants.STRING_US_TV_MA, result); - } - - public void testStringToContentRatings_null() { - assertNull(TvContentRatingCache.stringToContentRatings(null)); - } - - public void testStringToContentRatings_none() { - assertNull(TvContentRatingCache.stringToContentRatings("")); - } - - public void testStringToContentRatings_bad() { - assertNull(TvContentRatingCache.stringToContentRatings("bad")); - } - - public void testStringToContentRatings_oneGoodOneBad() { - TvContentRating[] results = TvContentRatingCache - .stringToContentRatings(TvContentRatingConstants.STRING_US_TV_Y7_US_TV_FV + ",bad"); - MoreAsserts.assertEquals("ratings", - asArray(TvContentRatingConstants.CONTENT_RATING_US_TV_Y7_US_TV_FV), results); - } - - public void testStringToContentRatings_one() { - TvContentRating[] results = TvContentRatingCache - .stringToContentRatings(TvContentRatingConstants.STRING_US_TV_Y7_US_TV_FV); - MoreAsserts.assertEquals("ratings", - asArray(TvContentRatingConstants.CONTENT_RATING_US_TV_Y7_US_TV_FV), results); - } - - public void testStringToContentRatings_twoNotInOrder() { - TvContentRating[] results = TvContentRatingCache.stringToContentRatings(Y7_AND_MA); - MoreAsserts.assertEquals("ratings", - asArray(TvContentRatingConstants.CONTENT_RATING_US_TV_MA, - TvContentRatingConstants.CONTENT_RATING_US_TV_Y7_US_TV_FV), results); - } - - public void testStringToContentRatings_twoInOrder() { - TvContentRating[] results = TvContentRatingCache.stringToContentRatings(MA_AND_Y7); - MoreAsserts.assertEquals("ratings", - asArray(TvContentRatingConstants.CONTENT_RATING_US_TV_MA, - TvContentRatingConstants.CONTENT_RATING_US_TV_Y7_US_TV_FV), results); - } - - public void testStringToContentRatings_double() { - TvContentRating[] results = TvContentRatingCache.stringToContentRatings( - TvContentRatingConstants.STRING_US_TV_MA + "," - + TvContentRatingConstants.STRING_US_TV_MA); - MoreAsserts - .assertEquals("ratings", asArray(TvContentRatingConstants.CONTENT_RATING_US_TV_MA), - results); - } - - private static TvContentRating[] asArray(TvContentRating... ratings) { - return ratings; - } -} diff --git a/tests/unit/src/com/android/tv/data/ChannelDataManagerTest.java b/tests/unit/src/com/android/tv/data/ChannelDataManagerTest.java index 9f9ada1f..7a4a4982 100644 --- a/tests/unit/src/com/android/tv/data/ChannelDataManagerTest.java +++ b/tests/unit/src/com/android/tv/data/ChannelDataManagerTest.java @@ -16,6 +16,12 @@ package com.android.tv.data; +import static android.support.test.InstrumentationRegistry.getInstrumentation; +import static android.support.test.InstrumentationRegistry.getTargetContext; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; @@ -26,9 +32,7 @@ import android.media.tv.TvContract; import android.media.tv.TvContract.Channels; import android.net.Uri; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import android.test.MoreAsserts; -import android.test.UiThreadTest; import android.test.mock.MockContentProvider; import android.test.mock.MockContentResolver; import android.test.mock.MockCursor; @@ -38,9 +42,11 @@ import android.util.SparseArray; import com.android.tv.testing.ChannelInfo; import com.android.tv.testing.Constants; -import com.android.tv.testing.Utils; import com.android.tv.util.TvInputManagerHelper; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; @@ -57,14 +63,13 @@ import java.util.concurrent.TimeUnit; * Note that all the methods of {@link ChannelDataManager} should be called from the UI thread. */ @SmallTest -public class ChannelDataManagerTest extends AndroidTestCase { +public class ChannelDataManagerTest { private static final boolean DEBUG = false; private static final String TAG = "ChannelDataManagerTest"; // Wait time for expected success. private static final long WAIT_TIME_OUT_MS = 1000L; private static final String DUMMY_INPUT_ID = "dummy"; - // TODO: Use Channels.COLUMN_BROWSABLE and Channels.COLUMN_LOCKED instead. private static final String COLUMN_BROWSABLE = "browsable"; private static final String COLUMN_LOCKED = "locked"; @@ -73,51 +78,59 @@ public class ChannelDataManagerTest extends AndroidTestCase { private FakeContentResolver mContentResolver; private FakeContentProvider mContentProvider; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { assertTrue("More than 2 channels to test", Constants.UNIT_TEST_CHANNEL_COUNT > 2); - mContentProvider = new FakeContentProvider(getContext()); + mContentProvider = new FakeContentProvider(getTargetContext()); mContentResolver = new FakeContentResolver(); mContentResolver.addProvider(TvContract.AUTHORITY, mContentProvider); mListener = new TestChannelDataManagerListener(); - Utils.runOnMainSync(new Runnable() { + getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { TvInputManagerHelper mockHelper = Mockito.mock(TvInputManagerHelper.class); Mockito.when(mockHelper.hasTvInputInfo(Matchers.anyString())).thenReturn(true); - mChannelDataManager = new ChannelDataManager(getContext(), mockHelper, + mChannelDataManager = new ChannelDataManager(getTargetContext(), mockHelper, mContentResolver); mChannelDataManager.addListener(mListener); } }); } - @Override - protected void tearDown() throws Exception { - Utils.runOnMainSync(new Runnable() { + @After + public void tearDown() { + getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mChannelDataManager.stop(); } }); - super.tearDown(); } - private void startAndWaitForComplete() throws Exception { - mChannelDataManager.start(); + private void startAndWaitForComplete() throws InterruptedException { + getInstrumentation().runOnMainSync(new Runnable() { + @Override + public void run() { + mChannelDataManager.start(); + } + }); assertTrue(mListener.loadFinishedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); } - private void restart() throws Exception { - mChannelDataManager.stop(); - mListener.reset(); + private void restart() throws InterruptedException { + getInstrumentation().runOnMainSync(new Runnable() { + @Override + public void run() { + mChannelDataManager.stop(); + mListener.reset(); + } + }); startAndWaitForComplete(); } - @UiThreadTest - public void testIsDbLoadFinished() throws Exception { + @Test + public void testIsDbLoadFinished() throws InterruptedException { startAndWaitForComplete(); assertTrue(mChannelDataManager.isDbLoadFinished()); } @@ -128,8 +141,8 @@ public class ChannelDataManagerTest extends AndroidTestCase { * - {@link ChannelDataManager#getChannelList} * - {@link ChannelDataManager#getChannel} */ - @UiThreadTest - public void testGetChannels() throws Exception { + @Test + public void testGetChannels() throws InterruptedException { startAndWaitForComplete(); // Test {@link ChannelDataManager#getChannelCount} @@ -138,7 +151,7 @@ public class ChannelDataManagerTest extends AndroidTestCase { // Test {@link ChannelDataManager#getChannelList} List<ChannelInfo> channelInfoList = new ArrayList<>(); for (int i = 1; i <= Constants.UNIT_TEST_CHANNEL_COUNT; i++) { - channelInfoList.add(ChannelInfo.create(getContext(), i)); + channelInfoList.add(ChannelInfo.create(getTargetContext(), i)); } List<Channel> channelList = mChannelDataManager.getChannelList(); for (Channel channel : channelList) { @@ -163,8 +176,8 @@ public class ChannelDataManagerTest extends AndroidTestCase { /** * Test for {@link ChannelDataManager#getChannelCount} when no channel is available. */ - @UiThreadTest - public void testGetChannels_noChannels() throws Exception { + @Test + public void testGetChannels_noChannels() throws InterruptedException { mContentProvider.clear(); startAndWaitForComplete(); assertEquals(0, mChannelDataManager.getChannelCount()); @@ -175,12 +188,12 @@ public class ChannelDataManagerTest extends AndroidTestCase { * - {@link ChannelDataManager#updateBrowsable} * - {@link ChannelDataManager#applyUpdatedValuesToDb} */ - @UiThreadTest - public void testBrowsable() throws Exception { + @Test + public void testBrowsable() throws InterruptedException { startAndWaitForComplete(); // Test if all channels are browsable - List<Channel> channelList = new ArrayList<>(mChannelDataManager.getChannelList()); + List<Channel> channelList = mChannelDataManager.getChannelList(); List<Channel> browsableChannelList = mChannelDataManager.getBrowsableChannelList(); for (Channel browsableChannel : browsableChannelList) { boolean found = channelList.remove(browsableChannel); @@ -189,9 +202,10 @@ public class ChannelDataManagerTest extends AndroidTestCase { assertEquals(0, channelList.size()); // Prepare for next tests. + channelList = mChannelDataManager.getChannelList(); TestChannelDataManagerChannelListener channelListener = new TestChannelDataManagerChannelListener(); - Channel channel1 = mChannelDataManager.getChannelList().get(0); + Channel channel1 = channelList.get(0); mChannelDataManager.addChannelListener(channel1.getId(), channelListener); // Test {@link ChannelDataManager#updateBrowsable} & notification. @@ -216,15 +230,16 @@ public class ChannelDataManagerTest extends AndroidTestCase { * - {@link ChannelDataManager#updateBrowsable} * - {@link ChannelDataManager#applyUpdatedValuesToDb} */ - @UiThreadTest - public void testBrowsable_skipNotification() throws Exception { + @Test + public void testBrowsable_skipNotification() throws InterruptedException { startAndWaitForComplete(); + List<Channel> channels = mChannelDataManager.getChannelList(); // Prepare for next tests. TestChannelDataManagerChannelListener channelListener = new TestChannelDataManagerChannelListener(); - Channel channel1 = mChannelDataManager.getChannelList().get(0); - Channel channel2 = mChannelDataManager.getChannelList().get(1); + Channel channel1 = channels.get(0); + Channel channel2 = channels.get(1); mChannelDataManager.addChannelListener(channel1.getId(), channelListener); mChannelDataManager.addChannelListener(channel2.getId(), channelListener); @@ -252,8 +267,8 @@ public class ChannelDataManagerTest extends AndroidTestCase { * - {@link ChannelDataManager#updateLocked} * - {@link ChannelDataManager#applyUpdatedValuesToDb} */ - @UiThreadTest - public void testLocked() throws Exception { + @Test + public void testLocked() throws InterruptedException { startAndWaitForComplete(); // Test if all channels aren't locked at the first time. @@ -283,14 +298,14 @@ public class ChannelDataManagerTest extends AndroidTestCase { /** * Test ChannelDataManager when channels in TvContract are updated, removed, or added. */ - @UiThreadTest - public void testChannelListChanged() throws Exception { + @Test + public void testChannelListChanged() throws InterruptedException { startAndWaitForComplete(); // Test channel add. mListener.reset(); long testChannelId = Constants.UNIT_TEST_CHANNEL_COUNT + 1; - ChannelInfo testChannelInfo = ChannelInfo.create(getContext(), (int) testChannelId); + ChannelInfo testChannelInfo = ChannelInfo.create(getTargetContext(), (int) testChannelId); testChannelId = Constants.UNIT_TEST_CHANNEL_COUNT + 1; mContentProvider.simulateInsert(testChannelInfo); assertTrue( @@ -376,7 +391,7 @@ public class ChannelDataManagerTest extends AndroidTestCase { super(context); for (int i = 1; i <= Constants.UNIT_TEST_CHANNEL_COUNT; i++) { mChannelInfoList.put(i, - new ChannelInfoWrapper(ChannelInfo.create(getContext(), i))); + new ChannelInfoWrapper(ChannelInfo.create(getTargetContext(), i))); } } @@ -466,8 +481,8 @@ public class ChannelDataManagerTest extends AndroidTestCase { */ public void simulateInsert(ChannelInfo testChannelInfo) { long channelId = testChannelInfo.originalNetworkId; - mChannelInfoList.put((int) channelId, - new ChannelInfoWrapper(ChannelInfo.create(getContext(), (int) channelId))); + mChannelInfoList.put((int) channelId, new ChannelInfoWrapper( + ChannelInfo.create(getTargetContext(), (int) channelId))); mContentResolver.notifyChange(TvContract.buildChannelUri(channelId), null); } diff --git a/tests/unit/src/com/android/tv/data/ChannelNumberTest.java b/tests/unit/src/com/android/tv/data/ChannelNumberTest.java index 4e6e9f3c..827dcdbd 100644 --- a/tests/unit/src/com/android/tv/data/ChannelNumberTest.java +++ b/tests/unit/src/com/android/tv/data/ChannelNumberTest.java @@ -16,22 +16,24 @@ package com.android.tv.data; import static com.android.tv.data.ChannelNumber.parseChannelNumber; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import android.support.test.filters.SmallTest; import com.android.tv.testing.ComparableTester; -import junit.framework.TestCase; +import org.junit.Test; /** * Tests for {@link ChannelNumber}. */ @SmallTest -public class ChannelNumberTest extends TestCase { - +public class ChannelNumberTest { /** * Test method for {@link ChannelNumber#ChannelNumber()}. */ + @Test public void testChannelNumber() { assertChannelEquals(new ChannelNumber(), "", false, ""); } @@ -40,32 +42,32 @@ public class ChannelNumberTest extends TestCase { * Test method for * {@link com.android.tv.data.ChannelNumber#parseChannelNumber(java.lang.String)}. */ + @Test public void testParseChannelNumber() { assertNull(parseChannelNumber("")); - assertNull(parseChannelNumber(" ")); + assertNull(parseChannelNumber("-")); assertNull(parseChannelNumber("abcd12")); assertNull(parseChannelNumber("12abcd")); assertNull(parseChannelNumber("-12")); assertChannelEquals(parseChannelNumber("1"), "1", false, ""); - assertChannelEquals(parseChannelNumber("1234 4321"), "1234", true, "4321"); + assertChannelEquals(parseChannelNumber("1234-4321"), "1234", true, "4321"); assertChannelEquals(parseChannelNumber("3-4"), "3", true, "4"); - assertChannelEquals(parseChannelNumber("5.6"), "5", true, "6"); + assertChannelEquals(parseChannelNumber("5-6"), "5", true, "6"); } /** * Test method for {@link ChannelNumber#compareTo(com.android.tv.data.ChannelNumber)}. */ + @Test public void testCompareTo() { new ComparableTester<ChannelNumber>() .addEquivalentGroup(parseChannelNumber("1"), parseChannelNumber("1")) .addEquivalentGroup(parseChannelNumber("2")) - .addEquivalentGroup(parseChannelNumber("2 1"), parseChannelNumber("2.1"), - parseChannelNumber("2-1")) + .addEquivalentGroup(parseChannelNumber("2-1")) .addEquivalentGroup(parseChannelNumber("2-2")) .addEquivalentGroup(parseChannelNumber("2-10")) .addEquivalentGroup(parseChannelNumber("3")) - .addEquivalentGroup(parseChannelNumber("4"), parseChannelNumber("4 0"), - parseChannelNumber("4.0"), parseChannelNumber("4-0")) + .addEquivalentGroup(parseChannelNumber("4"), parseChannelNumber("4-0")) .addEquivalentGroup(parseChannelNumber("10")) .addEquivalentGroup(parseChannelNumber("100")) .test(); @@ -74,6 +76,7 @@ public class ChannelNumberTest extends TestCase { /** * Test method for {@link ChannelNumber#compare(java.lang.String, java.lang.String)}. */ + @Test public void testCompare() { // Only need to test nulls, the reset is tested by testCompareTo assertEquals("compareTo(null,null)", 0, ChannelNumber.compare(null, null)); diff --git a/tests/unit/src/com/android/tv/data/ChannelTest.java b/tests/unit/src/com/android/tv/data/ChannelTest.java index 95e3ee90..d270e277 100644 --- a/tests/unit/src/com/android/tv/data/ChannelTest.java +++ b/tests/unit/src/com/android/tv/data/ChannelTest.java @@ -16,17 +16,21 @@ package com.android.tv.data; +import static org.junit.Assert.assertEquals; + import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import com.android.tv.testing.ComparatorTester; import com.android.tv.util.TvInputManagerHelper; +import org.junit.Before; +import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; @@ -38,7 +42,7 @@ import java.util.Comparator; * Tests for {@link Channel}. */ @SmallTest -public class ChannelTest extends AndroidTestCase { +public class ChannelTest { // Used for testing TV inputs with invalid input package. This could happen when a TV input is // uninstalled while drawing an app link card. private static final String INVALID_TV_INPUT_PACKAGE_NAME = @@ -59,9 +63,8 @@ public class ChannelTest extends AndroidTestCase { private Intent mInvalidIntent; private Intent mValidIntent; - @Override - public void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws NameNotFoundException { mInvalidIntent = new Intent(Intent.ACTION_VIEW); mInvalidIntent.setComponent(new ComponentName(INVALID_TV_INPUT_PACKAGE_NAME, ".test")); mValidIntent = new Intent(Intent.ACTION_VIEW); @@ -103,6 +106,7 @@ public class ChannelTest extends AndroidTestCase { Mockito.when(mMockContext.getPackageManager()).thenReturn(mockPackageManager); } + @Test public void testGetAppLinkType_NoText_NoIntent() { assertAppLinkType(Channel.APP_LINK_TYPE_NONE, INVALID_TV_INPUT_PACKAGE_NAME, null, null); assertAppLinkType(Channel.APP_LINK_TYPE_NONE, LIVE_CHANNELS_PACKAGE_NAME, null, null); @@ -226,7 +230,6 @@ public class ChannelTest extends AndroidTestCase { * See <a href="http://b/23031603">b/23031603</a>. */ public void testComparatorLabel() { - TvInputManagerHelper manager = Mockito.mock(TvInputManagerHelper.class); Mockito.when(manager.isPartnerInput(Matchers.anyString())).thenAnswer( new Answer<Boolean>() { @@ -254,6 +257,29 @@ public class ChannelTest extends AndroidTestCase { comparatorTester.test(); } + public void testNormalizeChannelNumber() { + assertNormalizedDisplayNumber(null, null); + assertNormalizedDisplayNumber("", ""); + assertNormalizedDisplayNumber("1", "1"); + assertNormalizedDisplayNumber("abcde", "abcde"); + assertNormalizedDisplayNumber("1-1", "1-1"); + assertNormalizedDisplayNumber("1.1", "1-1"); + assertNormalizedDisplayNumber("1 1", "1-1"); + assertNormalizedDisplayNumber("1\u058a1", "1-1"); + assertNormalizedDisplayNumber("1\u05be1", "1-1"); + assertNormalizedDisplayNumber("1\u14001", "1-1"); + assertNormalizedDisplayNumber("1\u18061", "1-1"); + assertNormalizedDisplayNumber("1\u20101", "1-1"); + assertNormalizedDisplayNumber("1\u20111", "1-1"); + assertNormalizedDisplayNumber("1\u20121", "1-1"); + assertNormalizedDisplayNumber("1\u20131", "1-1"); + assertNormalizedDisplayNumber("1\u20141", "1-1"); + } + + private void assertNormalizedDisplayNumber(String displayNumber, String normalized) { + assertEquals(normalized, Channel.normalizeDisplayNumber(displayNumber)); + } + private class TestChannelComparator extends Channel.DefaultComparator { public TestChannelComparator(TvInputManagerHelper manager) { super(null, manager); diff --git a/tests/unit/src/com/android/tv/data/GenreItemTest.java b/tests/unit/src/com/android/tv/data/GenreItemTest.java index fb48fd41..fdbcb599 100644 --- a/tests/unit/src/com/android/tv/data/GenreItemTest.java +++ b/tests/unit/src/com/android/tv/data/GenreItemTest.java @@ -16,23 +16,32 @@ package com.android.tv.data; +import static android.support.test.InstrumentationRegistry.getTargetContext; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import android.media.tv.TvContract.Programs.Genres; import android.os.Build; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; + +import org.junit.Test; /** * Tests for {@link Channel}. */ @SmallTest -public class GenreItemTest extends AndroidTestCase { +public class GenreItemTest { private static final String INVALID_GENRE = "INVALID GENRE"; + @Test public void testGetLabels() { // Checks if no exception is thrown. - GenreItems.getLabels(getContext()); + GenreItems.getLabels(getTargetContext()); } + @Test public void testGetCanonicalGenre() { int count = GenreItems.getGenreCount(); assertNull(GenreItems.getCanonicalGenre(GenreItems.ID_ALL_CHANNELS)); @@ -41,6 +50,7 @@ public class GenreItemTest extends AndroidTestCase { } } + @Test public void testGetId_base() { int count = GenreItems.getGenreCount(); assertEquals(GenreItems.ID_ALL_CHANNELS, GenreItems.getId(null)); @@ -58,6 +68,7 @@ public class GenreItemTest extends AndroidTestCase { assertInRange(GenreItems.getId(Genres.GAMING), 1, count - 1); } + @Test public void testGetId_lmp_mr1() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) { assertEquals(GenreItems.ID_ALL_CHANNELS, GenreItems.getId(Genres.ARTS)); diff --git a/tests/unit/src/com/android/tv/data/ProgramDataManagerTest.java b/tests/unit/src/com/android/tv/data/ProgramDataManagerTest.java index 430eef91..5457051f 100644 --- a/tests/unit/src/com/android/tv/data/ProgramDataManagerTest.java +++ b/tests/unit/src/com/android/tv/data/ProgramDataManagerTest.java @@ -16,14 +16,20 @@ package com.android.tv.data; +import static android.support.test.InstrumentationRegistry.getTargetContext; +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.database.ContentObserver; import android.database.Cursor; import android.media.tv.TvContract; import android.net.Uri; import android.os.HandlerThread; +import android.support.test.InstrumentationRegistry; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import android.test.mock.MockContentProvider; import android.test.mock.MockContentResolver; import android.test.mock.MockCursor; @@ -35,6 +41,10 @@ import com.android.tv.testing.FakeClock; import com.android.tv.testing.ProgramInfo; import com.android.tv.util.Utils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -45,7 +55,7 @@ import java.util.concurrent.TimeUnit; * Test for {@link com.android.tv.data.ProgramDataManager} */ @SmallTest -public class ProgramDataManagerTest extends AndroidTestCase { +public class ProgramDataManagerTest { private static final boolean DEBUG = false; private static final String TAG = "ProgramDataManagerTest"; @@ -66,31 +76,28 @@ public class ProgramDataManagerTest extends AndroidTestCase { private FakeContentResolver mContentResolver; private FakeContentProvider mContentProvider; - @Override - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() { mClock = FakeClock.createWithCurrentTime(); mListener = new TestProgramDataManagerListener(); - mContentProvider = new FakeContentProvider(getContext()); + mContentProvider = new FakeContentProvider(getTargetContext()); mContentResolver = new FakeContentResolver(); mContentResolver.addProvider(TvContract.AUTHORITY, mContentProvider); mHandlerThread = new HandlerThread(TAG); mHandlerThread.start(); mProgramDataManager = new ProgramDataManager( - mContentResolver, mClock, mHandlerThread.getLooper(), null); + mContentResolver, mClock, mHandlerThread.getLooper()); mProgramDataManager.setPrefetchEnabled(true); mProgramDataManager.addListener(mListener); } - @Override - protected void tearDown() throws Exception { - super.tearDown(); + @After + public void tearDown() { mHandlerThread.quitSafely(); mProgramDataManager.stop(); } - private void startAndWaitForComplete() throws Exception { + private void startAndWaitForComplete() throws InterruptedException { mProgramDataManager.start(); assertTrue(mListener.programUpdatedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); } @@ -98,12 +105,13 @@ public class ProgramDataManagerTest extends AndroidTestCase { /** * Test for {@link ProgramInfo#getIndex} and {@link ProgramInfo#getStartTimeMs}. */ + @Test public void testProgramUtils() { ProgramInfo stub = ProgramInfo.create(); for (long channelId = 1; channelId < Constants.UNIT_TEST_CHANNEL_COUNT; channelId++) { int index = stub.getIndex(mClock.currentTimeMillis(), channelId); long startTimeMs = stub.getStartTimeMs(index, channelId); - ProgramInfo programAt = stub.build(getContext(), index); + ProgramInfo programAt = stub.build(InstrumentationRegistry.getContext(), index); assertTrue(startTimeMs <= mClock.currentTimeMillis()); assertTrue(mClock.currentTimeMillis() < startTimeMs + programAt.durationMs); } @@ -118,7 +126,8 @@ public class ProgramDataManagerTest extends AndroidTestCase { * {@link ProgramDataManager#setPrefetchTimeRange(long)}. * </p> */ - public void testGetPrograms() throws Exception { + @Test + public void testGetPrograms() throws InterruptedException { // Initial setup to test {@link ProgramDataManager#setPrefetchTimeRange(long)}. long preventSnapDelayMs = ProgramDataManager.PROGRAM_GUIDE_SNAP_TIME_MS * 2; long prefetchTimeRangeStartMs = System.currentTimeMillis() + preventSnapDelayMs; @@ -140,7 +149,7 @@ public class ProgramDataManagerTest extends AndroidTestCase { ProgramInfo stub = ProgramInfo.create(); int index = stub.getIndex(mClock.currentTimeMillis(), channelId); for (Program program : programs) { - ProgramInfo programInfoAt = stub.build(getContext(), index); + ProgramInfo programInfoAt = stub.build(InstrumentationRegistry.getContext(), index); long startTimeMs = stub.getStartTimeMs(index, channelId); assertProgramEquals(startTimeMs, programInfoAt, program); index++; @@ -167,14 +176,15 @@ public class ProgramDataManagerTest extends AndroidTestCase { * {@link ProgramDataManager#removeOnCurrentProgramUpdatedListener}. * </p> */ - public void testCurrentProgramListener() throws Exception { + @Test + public void testCurrentProgramListener() throws InterruptedException { final long testChannelId = 1; ProgramInfo stub = ProgramInfo.create(); int index = stub.getIndex(mClock.currentTimeMillis(), testChannelId); // Set current time to few seconds before the current program ends, // so we can see if callback is called as expected. long nextProgramStartTimeMs = stub.getStartTimeMs(index + 1, testChannelId); - ProgramInfo nextProgramInfo = stub.build(getContext(), index + 1); + ProgramInfo nextProgramInfo = stub.build(InstrumentationRegistry.getContext(), index + 1); mClock.setCurrentTimeMillis(nextProgramStartTimeMs - (WAIT_TIME_OUT_MS / 2)); startAndWaitForComplete(); @@ -196,7 +206,8 @@ public class ProgramDataManagerTest extends AndroidTestCase { /** * Test if program data is refreshed after the program insertion. */ - public void testContentProviderUpdate() throws Exception { + @Test + public void testContentProviderUpdate() throws InterruptedException { final long testChannelId = 1; startAndWaitForComplete(); // Force program data manager to update program data whenever it's changes. @@ -217,7 +228,8 @@ public class ProgramDataManagerTest extends AndroidTestCase { /** * Test for {@link ProgramDataManager#setPauseProgramUpdate(boolean)}. */ - public void testSetPauseProgramUpdate() throws Exception { + @Test + public void testSetPauseProgramUpdate() throws InterruptedException { final long testChannelId = 1; startAndWaitForComplete(); // Force program data manager to update program data whenever it's changes. @@ -290,7 +302,7 @@ public class ProgramDataManagerTest extends AndroidTestCase { int index = stub.getIndex(startTimeMs, i); long programStartTimeMs = stub.getStartTimeMs(index, i); while (programStartTimeMs < endTimeMs) { - ProgramInfo programAt = stub.build(getContext(), index); + ProgramInfo programAt = stub.build(InstrumentationRegistry.getContext(), index); programInfoList.add( new ProgramInfoWrapper(index, programStartTimeMs, programAt)); index++; @@ -340,7 +352,8 @@ public class ProgramDataManagerTest extends AndroidTestCase { ProgramInfo stub = ProgramInfo.create(); ProgramInfoWrapper last = programList.get(programList.size() - 1); while (last.startTimeMs < endTimeMs) { - ProgramInfo nextProgramInfo = stub.build(getContext(), last.index + 1); + ProgramInfo nextProgramInfo = stub.build(InstrumentationRegistry.getContext(), + last.index + 1); ProgramInfoWrapper next = new ProgramInfoWrapper(last.index + 1, last.startTimeMs + last.programInfo.durationMs, nextProgramInfo); programList.add(next); diff --git a/tests/unit/src/com/android/tv/data/ProgramTest.java b/tests/unit/src/com/android/tv/data/ProgramTest.java index 7e474cd6..1d1f6c10 100644 --- a/tests/unit/src/com/android/tv/data/ProgramTest.java +++ b/tests/unit/src/com/android/tv/data/ProgramTest.java @@ -17,17 +17,18 @@ package com.android.tv.data; import static android.media.tv.TvContract.Programs.Genres.COMEDY; import static android.media.tv.TvContract.Programs.Genres.FAMILY_KIDS; - -import com.android.tv.data.Program.CriticScore; -import com.android.tv.dvr.SeriesRecording; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import android.media.tv.TvContentRating; import android.media.tv.TvContract.Programs.Genres; import android.os.Parcel; import android.support.test.filters.SmallTest; -import android.util.Log; -import junit.framework.TestCase; +import com.android.tv.data.Program.CriticScore; + +import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; @@ -37,19 +38,20 @@ import java.util.List; * Tests for {@link Program}. */ @SmallTest -public class ProgramTest extends TestCase { - +public class ProgramTest { private static final int NOT_FOUND_GENRE = 987; private static final int FAMILY_GENRE_ID = GenreItems.getId(FAMILY_KIDS); private static final int COMEDY_GENRE_ID = GenreItems.getId(COMEDY); + @Test public void testBuild() { Program program = new Program.Builder().build(); assertEquals("isValid", false, program.isValid()); } + @Test public void testNoGenres() { Program program = new Program.Builder() .setCanonicalGenres("") @@ -61,6 +63,7 @@ public class ProgramTest extends TestCase { assertHasGenre(program, GenreItems.ID_ALL_CHANNELS, true); } + @Test public void testFamilyGenre() { Program program = new Program.Builder() .setCanonicalGenres(FAMILY_KIDS) @@ -72,6 +75,7 @@ public class ProgramTest extends TestCase { assertHasGenre(program, GenreItems.ID_ALL_CHANNELS, true); } + @Test public void testFamilyComedyGenre() { Program program = new Program.Builder() .setCanonicalGenres(FAMILY_KIDS + ", " + COMEDY) @@ -83,6 +87,7 @@ public class ProgramTest extends TestCase { assertHasGenre(program, GenreItems.ID_ALL_CHANNELS, true); } + @Test public void testOtherGenre() { Program program = new Program.Builder() .setCanonicalGenres("other") @@ -94,7 +99,8 @@ public class ProgramTest extends TestCase { assertHasGenre(program, GenreItems.ID_ALL_CHANNELS, true); } - public void testParcelable() throws Exception { + @Test + public void testParcelable() { List<CriticScore> criticScores = new ArrayList<>(); criticScores.add(new CriticScore("1", "2", "3")); criticScores.add(new CriticScore("4", "5", "6")); @@ -139,6 +145,7 @@ public class ProgramTest extends TestCase { } } + @Test public void testParcelableWithCriticScore() { Program program = new Program.Builder() .setTitle("MyTitle") diff --git a/tests/unit/src/com/android/tv/data/TvInputNewComparatorTest.java b/tests/unit/src/com/android/tv/data/TvInputNewComparatorTest.java index f5504d48..b4682dd9 100644 --- a/tests/unit/src/com/android/tv/data/TvInputNewComparatorTest.java +++ b/tests/unit/src/com/android/tv/data/TvInputNewComparatorTest.java @@ -19,8 +19,6 @@ package com.android.tv.data; import android.content.pm.ResolveInfo; import android.media.tv.TvInputInfo; import android.support.test.filters.SmallTest; -import android.support.test.filters.Suppress; -import android.test.AndroidTestCase; import android.util.Pair; import com.android.tv.testing.ComparatorTester; @@ -28,6 +26,7 @@ import com.android.tv.util.SetupUtils; import com.android.tv.util.TestUtils; import com.android.tv.util.TvInputManagerHelper; +import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; @@ -40,16 +39,16 @@ import java.util.LinkedHashMap; * Test for {@link TvInputNewComparator} */ @SmallTest -public class TvInputNewComparatorTest extends AndroidTestCase { +public class TvInputNewComparatorTest { + @Test public void testComparator() throws Exception { - final LinkedHashMap<String, Pair<Boolean, Boolean>> INPUT_ID_TO_NEW_INPUT = - new LinkedHashMap<>(); - INPUT_ID_TO_NEW_INPUT.put("2_new_input", new Pair(true, false)); - INPUT_ID_TO_NEW_INPUT.put("4_new_input", new Pair(true, false)); - INPUT_ID_TO_NEW_INPUT.put("4_old_input", new Pair(false, false)); - INPUT_ID_TO_NEW_INPUT.put("0_old_input", new Pair(false, true)); - INPUT_ID_TO_NEW_INPUT.put("1_old_input", new Pair(false, true)); - INPUT_ID_TO_NEW_INPUT.put("3_old_input", new Pair(false, true)); + LinkedHashMap<String, Pair<Boolean, Boolean>> inputIdToNewInput = new LinkedHashMap<>(); + inputIdToNewInput.put("2_new_input", new Pair<>(true, false)); + inputIdToNewInput.put("4_new_input", new Pair<>(true, false)); + inputIdToNewInput.put("4_old_input", new Pair<>(false, false)); + inputIdToNewInput.put("0_old_input", new Pair<>(false, true)); + inputIdToNewInput.put("1_old_input", new Pair<>(false, true)); + inputIdToNewInput.put("3_old_input", new Pair<>(false, true)); SetupUtils setupUtils = Mockito.mock(SetupUtils.class); Mockito.when(setupUtils.isNewInput(Matchers.anyString())).thenAnswer( @@ -57,7 +56,7 @@ public class TvInputNewComparatorTest extends AndroidTestCase { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { String inputId = (String) invocation.getArguments()[0]; - return INPUT_ID_TO_NEW_INPUT.get(inputId).first; + return inputIdToNewInput.get(inputId).first; } } ); @@ -66,7 +65,7 @@ public class TvInputNewComparatorTest extends AndroidTestCase { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { String inputId = (String) invocation.getArguments()[0]; - return INPUT_ID_TO_NEW_INPUT.get(inputId).second; + return inputIdToNewInput.get(inputId).second; } } ); @@ -83,7 +82,7 @@ public class TvInputNewComparatorTest extends AndroidTestCase { ComparatorTester<TvInputInfo> comparatorTester = ComparatorTester.withoutEqualsTest(comparator); ResolveInfo resolveInfo = TestUtils.createResolveInfo("test", "test"); - for (String id : INPUT_ID_TO_NEW_INPUT.keySet()) { + for (String id : inputIdToNewInput.keySet()) { // Put mock resolveInfo to prevent NPE in {@link TvInputInfo#toString} TvInputInfo info1 = TestUtils.createTvInputInfo( resolveInfo, id, "test1", TvInputInfo.TYPE_TUNER, false); diff --git a/tests/unit/src/com/android/tv/data/WatchedHistoryManagerTest.java b/tests/unit/src/com/android/tv/data/WatchedHistoryManagerTest.java index c86bb724..7eea1be7 100644 --- a/tests/unit/src/com/android/tv/data/WatchedHistoryManagerTest.java +++ b/tests/unit/src/com/android/tv/data/WatchedHistoryManagerTest.java @@ -16,60 +16,57 @@ package com.android.tv.data; -import android.support.test.filters.SmallTest; -import android.support.test.filters.Suppress; -import android.test.AndroidTestCase; -import android.test.UiThreadTest; +import static android.support.test.InstrumentationRegistry.getTargetContext; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import android.os.Looper; +import android.support.test.filters.MediumTest; import com.android.tv.data.WatchedHistoryManager.WatchedRecord; -import com.android.tv.testing.Utils; -import java.util.concurrent.CountDownLatch; +import org.junit.Before; +import org.junit.Test; + import java.util.concurrent.TimeUnit; /** * Test for {@link com.android.tv.data.WatchedHistoryManagerTest} + * <p> + * This is a medium test because it load files which accessing SharedPreferences. */ -@SmallTest -@Suppress // http://b/27156462 -public class WatchedHistoryManagerTest extends AndroidTestCase { - private static final boolean DEBUG = false; - private static final String TAG = "WatchedHistoryManager"; - +@MediumTest +public class WatchedHistoryManagerTest { // Wait time for expected success. - private static final long WAIT_TIME_OUT_MS = 1000L; private static final int MAX_HISTORY_SIZE = 100; private WatchedHistoryManager mWatchedHistoryManager; private TestWatchedHistoryManagerListener mListener; - @Override - protected void setUp() throws Exception { - super.setUp(); - Utils.runOnMainSync(new Runnable() { - @Override - public void run() { - mWatchedHistoryManager = new WatchedHistoryManager(getContext(), MAX_HISTORY_SIZE); - mListener = new TestWatchedHistoryManagerListener(); - mWatchedHistoryManager.setListener(mListener); - } - }); + @Before + public void setUp() { + if (Looper.myLooper() == null) { + Looper.prepare(); + } + mWatchedHistoryManager = new WatchedHistoryManager(getTargetContext(), MAX_HISTORY_SIZE); + mListener = new TestWatchedHistoryManagerListener(); + mWatchedHistoryManager.setListener(mListener); } - private void startAndWaitForComplete() throws Exception { + private void startAndWaitForComplete() throws InterruptedException { mWatchedHistoryManager.start(); - assertTrue(mListener.loadFinishedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); + assertTrue(mListener.mLoadFinished); } - @UiThreadTest - public void testIsLoaded() throws Exception { - assertFalse(mWatchedHistoryManager.isLoaded()); + @Test + public void testIsLoaded() throws InterruptedException { startAndWaitForComplete(); assertTrue(mWatchedHistoryManager.isLoaded()); } - @UiThreadTest - public void testLogChannelViewStop() throws Exception { + @Test + public void testLogChannelViewStop() throws InterruptedException { startAndWaitForComplete(); long fakeId = 100000000; long time = System.currentTimeMillis(); @@ -86,8 +83,8 @@ public class WatchedHistoryManagerTest extends AndroidTestCase { assertEquals(record, recordFromSharedPreferences); } - @UiThreadTest - public void testCircularHistoryQueue() throws Exception { + @Test + public void testCircularHistoryQueue() throws InterruptedException { startAndWaitForComplete(); final long startChannelId = 100000000; long time = System.currentTimeMillis(); @@ -111,7 +108,7 @@ public class WatchedHistoryManagerTest extends AndroidTestCase { mWatchedHistoryManager.getRecordFromSharedPreferences(MAX_HISTORY_SIZE)); } - @UiThreadTest + @Test public void testWatchedRecordEquals() { assertTrue(new WatchedRecord(1, 2, 3).equals(new WatchedRecord(1, 2, 3))); assertFalse(new WatchedRecord(1, 2, 3).equals(new WatchedRecord(1, 2, 4))); @@ -119,8 +116,8 @@ public class WatchedHistoryManagerTest extends AndroidTestCase { assertFalse(new WatchedRecord(1, 2, 3).equals(new WatchedRecord(4, 2, 3))); } - @UiThreadTest - public void testEncodeDecodeWatchedRecord() throws Exception { + @Test + public void testEncodeDecodeWatchedRecord() { long fakeId = 100000000; long time = System.currentTimeMillis(); long duration = TimeUnit.MINUTES.toMillis(10); @@ -131,11 +128,11 @@ public class WatchedHistoryManagerTest extends AndroidTestCase { } private class TestWatchedHistoryManagerListener implements WatchedHistoryManager.Listener { - public final CountDownLatch loadFinishedLatch = new CountDownLatch(1); + boolean mLoadFinished; @Override public void onLoadFinished() { - loadFinishedLatch.countDown(); + mLoadFinished = true; } @Override diff --git a/tests/unit/src/com/android/tv/dvr/BaseDvrDataManagerTest.java b/tests/unit/src/com/android/tv/dvr/BaseDvrDataManagerTest.java index 1292759e..5f0ae15c 100644 --- a/tests/unit/src/com/android/tv/dvr/BaseDvrDataManagerTest.java +++ b/tests/unit/src/com/android/tv/dvr/BaseDvrDataManagerTest.java @@ -16,35 +16,51 @@ package com.android.tv.dvr; +import static android.support.test.InstrumentationRegistry.getContext; + +import android.os.Build; import android.support.annotation.NonNull; +import android.support.test.filters.SdkSuppress; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import android.test.MoreAsserts; +import com.android.tv.common.feature.CommonFeatures; +import com.android.tv.common.feature.TestableFeature; +import com.android.tv.dvr.data.ScheduledRecording; import com.android.tv.testing.FakeClock; import com.android.tv.testing.dvr.RecordingTestUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + import java.util.List; import java.util.concurrent.TimeUnit; -/** - * Tests for {@link BaseDvrDataManager} using {@link DvrDataManagerInMemoryImpl}. - */ +/** Tests for {@link BaseDvrDataManager} using {@link DvrDataManagerInMemoryImpl}. */ @SmallTest -public class BaseDvrDataManagerTest extends AndroidTestCase { +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) +public class BaseDvrDataManagerTest { private static final String INPUT_ID = "input_id"; private static final int CHANNEL_ID = 273; + private final TestableFeature mDvrFeature = CommonFeatures.DVR; private DvrDataManagerInMemoryImpl mDvrDataManager; private FakeClock mFakeClock; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { + mDvrFeature.enableForTest(); mFakeClock = FakeClock.createWithCurrentTime(); mDvrDataManager = new DvrDataManagerInMemoryImpl(getContext(), mFakeClock); } + @After + public void tearDown() { + mDvrFeature.resetForTests(); + } + + @Test public void testGetNonStartedScheduledRecordings() { ScheduledRecording recording = mDvrDataManager .addScheduledRecordingInternal(createNewScheduledRecordingStartingNow()); @@ -52,6 +68,7 @@ public class BaseDvrDataManagerTest extends AndroidTestCase { MoreAsserts.assertContentsInAnyOrder(result, recording); } + @Test public void testGetNonStartedScheduledRecordings_past() { mDvrDataManager.addScheduledRecordingInternal(createNewScheduledRecordingStartingNow()); mFakeClock.increment(TimeUnit.MINUTES, 6); diff --git a/tests/unit/src/com/android/tv/dvr/DvrDataManagerImplTest.java b/tests/unit/src/com/android/tv/dvr/DvrDataManagerImplTest.java index b822f164..9771a2e5 100644 --- a/tests/unit/src/com/android/tv/dvr/DvrDataManagerImplTest.java +++ b/tests/unit/src/com/android/tv/dvr/DvrDataManagerImplTest.java @@ -16,24 +16,29 @@ package com.android.tv.dvr; +import static org.junit.Assert.assertEquals; + +import android.os.Build; +import android.support.test.filters.SdkSuppress; import android.support.test.filters.SmallTest; +import com.android.tv.dvr.data.ScheduledRecording; import com.android.tv.testing.dvr.RecordingTestUtils; -import junit.framework.TestCase; +import org.junit.Test; import java.util.ArrayList; import java.util.List; -/** - * Tests for {@link DvrDataManagerImpl} - */ +/** Tests for {@link DvrDataManagerImpl} */ @SmallTest -public class DvrDataManagerImplTest extends TestCase { +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) +public class DvrDataManagerImplTest { private static final String INPUT_ID = "input_id"; private static final int CHANNEL_ID = 273; - public void testGetNextScheduledStartTimeAfter() throws Exception { + @Test + public void testGetNextScheduledStartTimeAfter() { long id = 1; List<ScheduledRecording> scheduledRecordings = new ArrayList<>(); assertNextStartTime(scheduledRecordings, 0L, DvrDataManager.NEXT_START_TIME_NOT_FOUND); diff --git a/tests/unit/src/com/android/tv/dvr/DvrDataManagerInMemoryImpl.java b/tests/unit/src/com/android/tv/dvr/DvrDataManagerInMemoryImpl.java index 85e35c4d..0a7ab46c 100644 --- a/tests/unit/src/com/android/tv/dvr/DvrDataManagerInMemoryImpl.java +++ b/tests/unit/src/com/android/tv/dvr/DvrDataManagerInMemoryImpl.java @@ -17,14 +17,19 @@ package com.android.tv.dvr; import android.content.Context; +import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; +import android.support.test.filters.SdkSuppress; import android.text.TextUtils; import android.util.Log; import android.util.Range; import com.android.tv.common.SoftPreconditions; -import com.android.tv.dvr.ScheduledRecording.RecordingState; +import com.android.tv.dvr.data.RecordedProgram; +import com.android.tv.dvr.data.ScheduledRecording; +import com.android.tv.dvr.data.ScheduledRecording.RecordingState; +import com.android.tv.dvr.data.SeriesRecording; import com.android.tv.util.Clock; import java.util.ArrayList; @@ -34,10 +39,9 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; -/** - * A DVR Data manager that stores values in memory suitable for testing. - */ -final class DvrDataManagerInMemoryImpl extends BaseDvrDataManager { +/** A DVR Data manager that stores values in memory suitable for testing. */ +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) +public final class DvrDataManagerInMemoryImpl extends BaseDvrDataManager { private final static String TAG = "DvrDataManagerInMemory"; private final AtomicLong mNextId = new AtomicLong(1); private final Map<Long, ScheduledRecording> mScheduledRecordings = new HashMap<>(); diff --git a/tests/unit/src/com/android/tv/dvr/DvrRecordingServiceTest.java b/tests/unit/src/com/android/tv/dvr/DvrRecordingServiceTest.java deleted file mode 100644 index 0a203ede..00000000 --- a/tests/unit/src/com/android/tv/dvr/DvrRecordingServiceTest.java +++ /dev/null @@ -1,68 +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.tv.dvr; - -import static org.mockito.Mockito.verify; - -import android.os.Build; -import android.support.test.filters.SdkSuppress; -import android.support.test.filters.SmallTest; -import android.test.ServiceTestCase; - -import com.android.tv.common.feature.CommonFeatures; -import com.android.tv.common.feature.TestableFeature; -import com.android.tv.testing.FakeClock; - -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -/** - * Tests for {@link DvrRecordingService}. - */ -@SmallTest -@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class DvrRecordingServiceTest extends ServiceTestCase<DvrRecordingService> { - @Mock Scheduler mMockScheduler; - private final TestableFeature mDvrFeature = CommonFeatures.DVR; - private final FakeClock mFakeClock = FakeClock.createWithCurrentTime(); - - @Override - protected void setUp() throws Exception { - super.setUp(); - mDvrFeature.enableForTest(); - MockitoAnnotations.initMocks(this); - setupService(); - DvrRecordingService service = getService(); - service.setScheduler(mMockScheduler); - } - - @Override - protected void tearDown() throws Exception { - mDvrFeature.resetForTests(); - super.tearDown(); - } - - public DvrRecordingServiceTest() { - super(DvrRecordingService.class); - } - - public void testStartService_null() throws Exception { - startService(null); - verify(mMockScheduler, Mockito.only()).update(); - } -}
\ No newline at end of file diff --git a/tests/unit/src/com/android/tv/dvr/DvrScheduleManagerTest.java b/tests/unit/src/com/android/tv/dvr/DvrScheduleManagerTest.java index 2850a5f7..1c77aa0e 100644 --- a/tests/unit/src/com/android/tv/dvr/DvrScheduleManagerTest.java +++ b/tests/unit/src/com/android/tv/dvr/DvrScheduleManagerTest.java @@ -16,32 +16,39 @@ package com.android.tv.dvr; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import android.os.Build; +import android.support.test.filters.SdkSuppress; import android.support.test.filters.SmallTest; import android.test.MoreAsserts; import android.util.Range; +import com.android.tv.dvr.DvrScheduleManager.ConflictInfo; +import com.android.tv.dvr.data.ScheduledRecording; import com.android.tv.testing.dvr.RecordingTestUtils; -import junit.framework.TestCase; +import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.Map; -/** - * Tests for {@link DvrScheduleManager} - */ +/** Tests for {@link DvrScheduleManager} */ @SmallTest -public class DvrScheduleManagerTest extends TestCase { +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) +public class DvrScheduleManagerTest { private static final String INPUT_ID = "input_id"; + @Test public void testGetConflictingSchedules_emptySchedule() { List<ScheduledRecording> schedules = new ArrayList<>(); MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 1)); } + @Test public void testGetConflictingSchedules_noConflict() { long priority = 0; long channelId = 0; @@ -68,6 +75,7 @@ public class DvrScheduleManagerTest extends TestCase { MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 3)); } + @Test public void testGetConflictingSchedules_noTuner() { long priority = 0; long channelId = 0; @@ -82,6 +90,7 @@ public class DvrScheduleManagerTest extends TestCase { assertEquals(schedules, DvrScheduleManager.getConflictingSchedules(schedules, 0)); } + @Test public void testGetConflictingSchedules_conflict() { long priority = 0; long channelId = 0; @@ -160,6 +169,7 @@ public class DvrScheduleManagerTest extends TestCase { MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 5)); } + @Test public void testGetConflictingSchedules_conflict2() { // The case when there is a long schedule. long priority = 0; @@ -186,6 +196,7 @@ public class DvrScheduleManagerTest extends TestCase { MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 2)); } + @Test public void testGetConflictingSchedules_reverseOrder() { long priority = 0; long channelId = 0; @@ -264,6 +275,7 @@ public class DvrScheduleManagerTest extends TestCase { MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 5)); } + @Test public void testGetConflictingSchedules_period1() { long priority = 0; long channelId = 0; @@ -281,6 +293,7 @@ public class DvrScheduleManagerTest extends TestCase { Collections.singletonList(new Range<>(110L, 120L))), r1); } + @Test public void testGetConflictingSchedules_period2() { long priority = 0; long channelId = 0; @@ -298,6 +311,7 @@ public class DvrScheduleManagerTest extends TestCase { Collections.singletonList(new Range<>(110L, 120L))), r1); } + @Test public void testGetConflictingSchedules_period3() { long priority = 0; long channelId = 0; @@ -328,6 +342,7 @@ public class DvrScheduleManagerTest extends TestCase { ranges), r2, r1); } + @Test public void testGetConflictingSchedules_addSchedules1() { long priority = 0; long channelId = 0; @@ -351,6 +366,7 @@ public class DvrScheduleManagerTest extends TestCase { schedules, 1), r1); } + @Test public void testGetConflictingSchedules_addSchedules2() { long priority = 0; long channelId = 0; @@ -374,6 +390,7 @@ public class DvrScheduleManagerTest extends TestCase { schedules, 1), r2, r1); } + @Test public void testGetConflictingSchedules_addLowestPriority() { long priority = 0; long channelId = 0; @@ -394,6 +411,7 @@ public class DvrScheduleManagerTest extends TestCase { schedules, 1), r1); } + @Test public void testGetConflictingSchedules_sameChannel() { long priority = 0; long channelId = 1; @@ -405,6 +423,7 @@ public class DvrScheduleManagerTest extends TestCase { MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 3)); } + @Test public void testGetConflictingSchedule_startEarlyAndFail() { long priority = 0; long channelId = 0; @@ -423,6 +442,7 @@ public class DvrScheduleManagerTest extends TestCase { r2); } + @Test public void testGetConflictingSchedule_startLate() { long priority = 0; long channelId = 0; @@ -441,6 +461,7 @@ public class DvrScheduleManagerTest extends TestCase { r2, r1); } + @Test public void testGetConflictingSchedulesForTune_canTune() { // Can tune to the recorded channel if tuner count is 1. long priority = 0; @@ -452,6 +473,7 @@ public class DvrScheduleManagerTest extends TestCase { channelId, 0L, priority + 1, schedules, 1)); } + @Test public void testGetConflictingSchedulesForTune_cannotTune() { // Can't tune to a channel if other channel is recording and tuner count is 1. long priority = 0; @@ -463,6 +485,7 @@ public class DvrScheduleManagerTest extends TestCase { INPUT_ID, channelId + 1, 0L, priority + 1, schedules, 1), schedules.get(0)); } + @Test public void testGetConflictingSchedulesForWatching_otherChannels() { // The other channels are to be recorded. long priority = 0; @@ -481,6 +504,7 @@ public class DvrScheduleManagerTest extends TestCase { INPUT_ID, channelToWatch, 0L, ++priority, schedules, 2), r1); } + @Test public void testGetConflictingSchedulesForWatching_sameChannel1() { long priority = 0; long channelToWatch = 1; @@ -498,6 +522,7 @@ public class DvrScheduleManagerTest extends TestCase { INPUT_ID, channelToWatch, 0L, ++priority, schedules, 1), r2); } + @Test public void testGetConflictingSchedulesForWatching_sameChannel2() { long priority = 0; long channelToWatch = 1; @@ -515,6 +540,7 @@ public class DvrScheduleManagerTest extends TestCase { INPUT_ID, channelToWatch, 0L, ++priority, schedules, 1), r1); } + @Test public void testGetConflictingSchedulesForWatching_sameChannelConflict1() { long priority = 0; long channelToWatch = 1; @@ -537,6 +563,7 @@ public class DvrScheduleManagerTest extends TestCase { INPUT_ID, channelToWatch, 0L, ++priority, schedules, 1), r2, r1); } + @Test public void testGetConflictingSchedulesForWatching_sameChannelConflict2() { long priority = 0; long channelToWatch = 1; @@ -559,6 +586,7 @@ public class DvrScheduleManagerTest extends TestCase { INPUT_ID, channelToWatch, 0L, ++priority, schedules, 1), r3, r1); } + @Test public void testPartiallyConflictingSchedules() { long priority = 100; long channelId = 0; @@ -586,49 +614,80 @@ public class DvrScheduleManagerTest extends TestCase { RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, --priority, 50L, 900L) )); - Map<ScheduledRecording, Boolean> conflictsInfo = DvrScheduleManager - .getConflictingSchedulesInfo(schedules, 1); - - assertNull(conflictsInfo.get(schedules.get(0))); - assertFalse(conflictsInfo.get(schedules.get(1))); - assertTrue(conflictsInfo.get(schedules.get(2))); - assertTrue(conflictsInfo.get(schedules.get(3))); - assertNull(conflictsInfo.get(schedules.get(4))); - assertTrue(conflictsInfo.get(schedules.get(5))); - assertNull(conflictsInfo.get(schedules.get(6))); - assertFalse(conflictsInfo.get(schedules.get(7))); - assertFalse(conflictsInfo.get(schedules.get(8))); - assertFalse(conflictsInfo.get(schedules.get(9))); - assertFalse(conflictsInfo.get(schedules.get(10))); - - conflictsInfo = DvrScheduleManager - .getConflictingSchedulesInfo(schedules, 2); - - assertNull(conflictsInfo.get(schedules.get(0))); - assertNull(conflictsInfo.get(schedules.get(1))); - assertNull(conflictsInfo.get(schedules.get(2))); - assertNull(conflictsInfo.get(schedules.get(3))); - assertNull(conflictsInfo.get(schedules.get(4))); - assertNull(conflictsInfo.get(schedules.get(5))); - assertNull(conflictsInfo.get(schedules.get(6))); - assertFalse(conflictsInfo.get(schedules.get(7))); - assertFalse(conflictsInfo.get(schedules.get(8))); - assertFalse(conflictsInfo.get(schedules.get(9))); - assertTrue(conflictsInfo.get(schedules.get(10))); - - conflictsInfo = DvrScheduleManager - .getConflictingSchedulesInfo(schedules, 3); - - assertNull(conflictsInfo.get(schedules.get(0))); - assertNull(conflictsInfo.get(schedules.get(1))); - assertNull(conflictsInfo.get(schedules.get(2))); - assertNull(conflictsInfo.get(schedules.get(3))); - assertNull(conflictsInfo.get(schedules.get(4))); - assertNull(conflictsInfo.get(schedules.get(5))); - assertNull(conflictsInfo.get(schedules.get(6))); - assertNull(conflictsInfo.get(schedules.get(7))); - assertTrue(conflictsInfo.get(schedules.get(8))); - assertNull(conflictsInfo.get(schedules.get(9))); - assertTrue(conflictsInfo.get(schedules.get(10))); + List<ConflictInfo> conflicts = DvrScheduleManager.getConflictingSchedulesInfo(schedules, 1); + + assertNotInList(schedules.get(0), conflicts); + assertFullConflict(schedules.get(1), conflicts); + assertPartialConflict(schedules.get(2), conflicts); + assertPartialConflict(schedules.get(3), conflicts); + assertNotInList(schedules.get(4), conflicts); + assertPartialConflict(schedules.get(5), conflicts); + assertNotInList(schedules.get(6), conflicts); + assertFullConflict(schedules.get(7), conflicts); + assertFullConflict(schedules.get(8), conflicts); + assertFullConflict(schedules.get(9), conflicts); + assertFullConflict(schedules.get(10), conflicts); + + conflicts = DvrScheduleManager.getConflictingSchedulesInfo(schedules, 2); + + assertNotInList(schedules.get(0), conflicts); + assertNotInList(schedules.get(1), conflicts); + assertNotInList(schedules.get(2), conflicts); + assertNotInList(schedules.get(3), conflicts); + assertNotInList(schedules.get(4), conflicts); + assertNotInList(schedules.get(5), conflicts); + assertNotInList(schedules.get(6), conflicts); + assertFullConflict(schedules.get(7), conflicts); + assertFullConflict(schedules.get(8), conflicts); + assertFullConflict(schedules.get(9), conflicts); + assertPartialConflict(schedules.get(10), conflicts); + + conflicts = DvrScheduleManager.getConflictingSchedulesInfo(schedules, 3); + + assertNotInList(schedules.get(0), conflicts); + assertNotInList(schedules.get(1), conflicts); + assertNotInList(schedules.get(2), conflicts); + assertNotInList(schedules.get(3), conflicts); + assertNotInList(schedules.get(4), conflicts); + assertNotInList(schedules.get(5), conflicts); + assertNotInList(schedules.get(6), conflicts); + assertNotInList(schedules.get(7), conflicts); + assertPartialConflict(schedules.get(8), conflicts); + assertNotInList(schedules.get(9), conflicts); + assertPartialConflict(schedules.get(10), conflicts); + } + + private void assertNotInList(ScheduledRecording schedule, List<ConflictInfo> conflicts) { + for (ConflictInfo conflictInfo : conflicts) { + if (conflictInfo.schedule.equals(schedule)) { + fail(schedule + " conflicts with others."); + } + } + } + + private void assertPartialConflict(ScheduledRecording schedule, List<ConflictInfo> conflicts) { + for (ConflictInfo conflictInfo : conflicts) { + if (conflictInfo.schedule.equals(schedule)) { + if (conflictInfo.partialConflict) { + return; + } else { + fail(schedule + " fully conflicts with others."); + } + } + } + fail(schedule + " doesn't conflict"); + } + + private void assertFullConflict(ScheduledRecording schedule, List<ConflictInfo> conflicts) { + for (ConflictInfo conflictInfo : conflicts) { + if (conflictInfo.schedule.equals(schedule)) { + if (!conflictInfo.partialConflict) { + return; + } else { + fail(schedule + " partially conflicts with others."); + } + } + } + fail(schedule + " doesn't conflict"); } }
\ No newline at end of file diff --git a/tests/unit/src/com/android/tv/dvr/EpisodicProgramLoadTaskTest.java b/tests/unit/src/com/android/tv/dvr/EpisodicProgramLoadTaskTest.java deleted file mode 100644 index 2172d488..00000000 --- a/tests/unit/src/com/android/tv/dvr/EpisodicProgramLoadTaskTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2016 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.tv.dvr; - -import android.os.Build; -import android.support.test.filters.SdkSuppress; -import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; - -import com.android.tv.dvr.EpisodicProgramLoadTask.ScheduledEpisode; - -import java.util.ArrayList; -import java.util.List; - -/** - * Tests for {@link EpisodicProgramLoadTask} - */ -@SmallTest -@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class EpisodicProgramLoadTaskTest extends AndroidTestCase { - private static final long SERIES_RECORDING_ID1 = 1; - private static final long SERIES_RECORDING_ID2 = 2; - private static final String SEASON_NUMBER1 = "SEASON NUMBER1"; - private static final String SEASON_NUMBER2 = "SEASON NUMBER2"; - private static final String EPISODE_NUMBER1 = "EPISODE NUMBER1"; - private static final String EPISODE_NUMBER2 = "EPISODE NUMBER2"; - - public void testEpisodeAlreadyScheduled_true() { - List<ScheduledEpisode> episodes = new ArrayList<>(); - ScheduledEpisode episode = new ScheduledEpisode(SERIES_RECORDING_ID1, SEASON_NUMBER1, - EPISODE_NUMBER1); - episodes.add(episode); - assertTrue(EpisodicProgramLoadTask.isEpisodeScheduled(episodes, - new ScheduledEpisode(SERIES_RECORDING_ID1, SEASON_NUMBER1, EPISODE_NUMBER1))); - } - - public void testEpisodeAlreadyScheduled_false() { - List<ScheduledEpisode> episodes = new ArrayList<>(); - ScheduledEpisode episode = new ScheduledEpisode(SERIES_RECORDING_ID1, SEASON_NUMBER1, - EPISODE_NUMBER1); - episodes.add(episode); - assertFalse(EpisodicProgramLoadTask.isEpisodeScheduled(episodes, - new ScheduledEpisode(SERIES_RECORDING_ID2, SEASON_NUMBER1, EPISODE_NUMBER1))); - assertFalse(EpisodicProgramLoadTask.isEpisodeScheduled(episodes, - new ScheduledEpisode(SERIES_RECORDING_ID1, SEASON_NUMBER2, EPISODE_NUMBER1))); - assertFalse(EpisodicProgramLoadTask.isEpisodeScheduled(episodes, - new ScheduledEpisode(SERIES_RECORDING_ID1, SEASON_NUMBER1, EPISODE_NUMBER2))); - } - - public void testEpisodeAlreadyScheduled_null() { - List<ScheduledEpisode> episodes = new ArrayList<>(); - ScheduledEpisode episode = new ScheduledEpisode(SERIES_RECORDING_ID1, SEASON_NUMBER1, - EPISODE_NUMBER1); - episodes.add(episode); - assertFalse(EpisodicProgramLoadTask.isEpisodeScheduled(episodes, - new ScheduledEpisode(SERIES_RECORDING_ID1, null, EPISODE_NUMBER1))); - assertFalse(EpisodicProgramLoadTask.isEpisodeScheduled(episodes, - new ScheduledEpisode(SERIES_RECORDING_ID1, SEASON_NUMBER1, null))); - assertFalse(EpisodicProgramLoadTask.isEpisodeScheduled(episodes, - new ScheduledEpisode(SERIES_RECORDING_ID1, null, null))); - } -} diff --git a/tests/unit/src/com/android/tv/dvr/ScheduledRecordingTest.java b/tests/unit/src/com/android/tv/dvr/ScheduledRecordingTest.java index 96036418..b98af603 100644 --- a/tests/unit/src/com/android/tv/dvr/ScheduledRecordingTest.java +++ b/tests/unit/src/com/android/tv/dvr/ScheduledRecordingTest.java @@ -16,34 +16,37 @@ package com.android.tv.dvr; -import static com.android.tv.testing.dvr.RecordingTestUtils - .createTestRecordingWithIdAndPeriod; +import static com.android.tv.testing.dvr.RecordingTestUtils.createTestRecordingWithIdAndPeriod; import static com.android.tv.testing.dvr.RecordingTestUtils.normalizePriority; +import static junit.framework.TestCase.assertEquals; +import android.os.Build; +import android.support.test.filters.SdkSuppress; import android.support.test.filters.SmallTest; import android.test.MoreAsserts; import android.util.Range; import com.android.tv.data.Channel; import com.android.tv.data.Program; +import com.android.tv.dvr.data.ScheduledRecording; import com.android.tv.testing.dvr.RecordingTestUtils; -import junit.framework.TestCase; +import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; -/** - * Tests for {@link ScheduledRecordingTest} - */ +/** Tests for {@link ScheduledRecordingTest} */ @SmallTest -public class ScheduledRecordingTest extends TestCase { +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) +public class ScheduledRecordingTest { private static final String INPUT_ID = "input_id"; private static final int CHANNEL_ID = 273; - public void testIsOverLapping() throws Exception { + @Test + public void testIsOverLapping() { ScheduledRecording r = createTestRecordingWithIdAndPeriod(1, INPUT_ID, CHANNEL_ID, 10L, 20L); assertOverLapping(false, 1L, 9L, r); @@ -59,6 +62,7 @@ public class ScheduledRecordingTest extends TestCase { assertOverLapping(false, 21L, 29L, r); } + @Test public void testBuildProgram() { Channel c = new Channel.Builder().build(); Program p = new Program.Builder().build(); @@ -67,12 +71,14 @@ public class ScheduledRecordingTest extends TestCase { assertEquals("type", ScheduledRecording.TYPE_PROGRAM, actual.getType()); } + @Test public void testBuildTime() { ScheduledRecording actual = createTestRecordingWithIdAndPeriod(1, INPUT_ID, CHANNEL_ID, 10L, 20L); assertEquals("type", ScheduledRecording.TYPE_TIMED, actual.getType()); } + @Test public void testBuildFrom() { ScheduledRecording expected = createTestRecordingWithIdAndPeriod(1, INPUT_ID, CHANNEL_ID, 10L, 20L); @@ -80,6 +86,7 @@ public class ScheduledRecordingTest extends TestCase { RecordingTestUtils.assertRecordingEquals(expected, actual); } + @Test public void testBuild_priority() { ScheduledRecording a = normalizePriority( createTestRecordingWithIdAndPeriod(1, INPUT_ID, CHANNEL_ID, 10L, 20L)); diff --git a/tests/unit/src/com/android/tv/dvr/SeriesRecordingTest.java b/tests/unit/src/com/android/tv/dvr/data/SeriesRecordingTest.java index c48fec02..790b2ee8 100644 --- a/tests/unit/src/com/android/tv/dvr/SeriesRecordingTest.java +++ b/tests/unit/src/com/android/tv/dvr/data/SeriesRecordingTest.java @@ -14,7 +14,9 @@ * limitations under the License */ -package com.android.tv.dvr; +package com.android.tv.dvr.data; + +import static org.junit.Assert.assertEquals; import android.os.Build; import android.os.Parcel; @@ -23,14 +25,14 @@ import android.support.test.filters.SmallTest; import com.android.tv.data.Program; -import junit.framework.TestCase; +import org.junit.Test; /** * Tests for {@link SeriesRecording}. */ @SmallTest @SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class SeriesRecordingTest extends TestCase { +public class SeriesRecordingTest { private static final String PROGRAM_TITLE = "MyProgram"; private static final long CHANNEL_ID = 123; private static final long OTHER_CHANNEL_ID = 321; @@ -46,7 +48,8 @@ public class SeriesRecordingTest extends TestCase { private final Program mBaseProgram = new Program.Builder().setTitle(PROGRAM_TITLE) .setChannelId(CHANNEL_ID).setSeriesId(SERIES_ID).build(); - public void testParcelable() throws Exception { + @Test + public void testParcelable() { SeriesRecording r1 = new SeriesRecording.Builder() .setId(1) .setChannelId(2) @@ -77,20 +80,24 @@ public class SeriesRecordingTest extends TestCase { } } + @Test public void testDoesProgramMatch_simpleMatch() { assertDoesProgramMatch(mBaseProgram, mBaseSeriesRecording, true); } + @Test public void testDoesProgramMatch_differentSeriesId() { Program program = new Program.Builder(mBaseProgram).setSeriesId(OTHER_SERIES_ID).build(); assertDoesProgramMatch(program, mBaseSeriesRecording, false); } + @Test public void testDoesProgramMatch_differentChannel() { Program program = new Program.Builder(mBaseProgram).setChannelId(OTHER_CHANNEL_ID).build(); assertDoesProgramMatch(program, mBaseSeriesRecording, false); } + @Test public void testDoesProgramMatch_startFromSeason2() { Program program = mBaseProgram; assertDoesProgramMatch(program, mSeriesRecordingSeason2, true); @@ -102,6 +109,7 @@ public class SeriesRecordingTest extends TestCase { assertDoesProgramMatch(program, mSeriesRecordingSeason2, true); } + @Test public void testDoesProgramMatch_startFromSeason2episode5() { Program program = mBaseProgram; assertDoesProgramMatch(program, mSeriesRecordingSeason2Episode5, true); diff --git a/tests/unit/src/com/android/tv/dvr/DvrDbSyncTest.java b/tests/unit/src/com/android/tv/dvr/provider/DvrDbSyncTest.java index 7cb3721c..94f88a51 100644 --- a/tests/unit/src/com/android/tv/dvr/DvrDbSyncTest.java +++ b/tests/unit/src/com/android/tv/dvr/provider/DvrDbSyncTest.java @@ -14,8 +14,10 @@ * limitations under the License */ -package com.android.tv.dvr; +package com.android.tv.dvr.provider; +import static android.support.test.InstrumentationRegistry.getContext; +import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; @@ -25,20 +27,26 @@ import static org.mockito.Mockito.when; import android.os.Build; import android.support.test.filters.SdkSuppress; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import com.android.tv.data.ChannelDataManager; import com.android.tv.data.Program; +import com.android.tv.dvr.DvrDataManagerImpl; +import com.android.tv.dvr.DvrManager; +import com.android.tv.dvr.data.ScheduledRecording; +import com.android.tv.dvr.data.SeriesRecording; +import com.android.tv.dvr.recorder.SeriesRecordingScheduler; +import org.junit.Before; +import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; /** - * Tests for {@link DvrScheduleManager} + * Tests for {@link com.android.tv.dvr.DvrScheduleManager} */ @SmallTest @SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class DvrDbSyncTest extends AndroidTestCase { +public class DvrDbSyncTest { private static final String INPUT_ID = "input_id"; private static final long BASE_PROGRAM_ID = 1; private static final long BASE_START_TIME_MS = 0; @@ -47,28 +55,39 @@ public class DvrDbSyncTest extends AndroidTestCase { private static final String BASE_EPISODE_NUMBER = "3"; private static final Program BASE_PROGRAM = new Program.Builder().setId(BASE_PROGRAM_ID) .setStartTimeUtcMillis(BASE_START_TIME_MS).setEndTimeUtcMillis(BASE_END_TIME_MS) + .build(); + private static final Program BASE_SERIES_PROGRAM = new Program.Builder().setId(BASE_PROGRAM_ID) + .setStartTimeUtcMillis(BASE_START_TIME_MS).setEndTimeUtcMillis(BASE_END_TIME_MS) .setSeasonNumber(BASE_SEASON_NUMBER).setEpisodeNumber(BASE_EPISODE_NUMBER).build(); private static final ScheduledRecording BASE_SCHEDULE = ScheduledRecording.builder(INPUT_ID, BASE_PROGRAM).build(); + private static final ScheduledRecording BASE_SERIES_SCHEDULE = + ScheduledRecording.builder(INPUT_ID, BASE_SERIES_PROGRAM).build(); private DvrDbSync mDbSync; + @Mock private DvrManager mDvrManager; @Mock private DvrDataManagerImpl mDataManager; @Mock private ChannelDataManager mChannelDataManager; + @Mock private SeriesRecordingScheduler mSeriesRecordingScheduler; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { MockitoAnnotations.initMocks(this); when(mChannelDataManager.isDbLoadFinished()).thenReturn(true); - mDbSync = new DvrDbSync(getContext(), mDataManager, mChannelDataManager); + when(mDvrManager.addSeriesRecording(anyObject(), anyObject(), anyInt())) + .thenReturn(SeriesRecording.builder(INPUT_ID, BASE_PROGRAM).build()); + mDbSync = new DvrDbSync(getContext(), mDataManager, mChannelDataManager, + mDvrManager, mSeriesRecordingScheduler); } + @Test public void testHandleUpdateProgram_null() { addSchedule(BASE_PROGRAM_ID, BASE_SCHEDULE); mDbSync.handleUpdateProgram(null, BASE_PROGRAM_ID); verify(mDataManager).removeScheduledRecording(BASE_SCHEDULE); } + @Test public void testHandleUpdateProgram_changeTimeNotStarted() { addSchedule(BASE_PROGRAM_ID, BASE_SCHEDULE); long startTimeMs = BASE_START_TIME_MS + 1; @@ -79,6 +98,7 @@ public class DvrDbSyncTest extends AndroidTestCase { assertUpdateScheduleCalled(program); } + @Test public void testHandleUpdateProgram_changeTimeInProgressNotCalled() { addSchedule(BASE_PROGRAM_ID, ScheduledRecording.buildFrom(BASE_SCHEDULE) .setState(ScheduledRecording.STATE_RECORDING_IN_PROGRESS).build()); @@ -89,22 +109,24 @@ public class DvrDbSyncTest extends AndroidTestCase { verify(mDataManager, never()).updateScheduledRecording(anyObject()); } + @Test public void testHandleUpdateProgram_changeSeason() { - addSchedule(BASE_PROGRAM_ID, BASE_SCHEDULE); + addSchedule(BASE_PROGRAM_ID, BASE_SERIES_SCHEDULE); String seasonNumber = BASE_SEASON_NUMBER + "1"; String episodeNumber = BASE_EPISODE_NUMBER + "1"; - Program program = new Program.Builder(BASE_PROGRAM).setSeasonNumber(seasonNumber) + Program program = new Program.Builder(BASE_SERIES_PROGRAM).setSeasonNumber(seasonNumber) .setEpisodeNumber(episodeNumber).build(); mDbSync.handleUpdateProgram(program, BASE_PROGRAM_ID); assertUpdateScheduleCalled(program); } + @Test public void testHandleUpdateProgram_finished() { - addSchedule(BASE_PROGRAM_ID, ScheduledRecording.buildFrom(BASE_SCHEDULE) + addSchedule(BASE_PROGRAM_ID, ScheduledRecording.buildFrom(BASE_SERIES_SCHEDULE) .setState(ScheduledRecording.STATE_RECORDING_FINISHED).build()); String seasonNumber = BASE_SEASON_NUMBER + "1"; String episodeNumber = BASE_EPISODE_NUMBER + "1"; - Program program = new Program.Builder(BASE_PROGRAM).setSeasonNumber(seasonNumber) + Program program = new Program.Builder(BASE_SERIES_PROGRAM).setSeasonNumber(seasonNumber) .setEpisodeNumber(episodeNumber).build(); mDbSync.handleUpdateProgram(program, BASE_PROGRAM_ID); verify(mDataManager, never()).updateScheduledRecording(anyObject()); diff --git a/tests/unit/src/com/android/tv/dvr/provider/EpisodicProgramLoadTaskTest.java b/tests/unit/src/com/android/tv/dvr/provider/EpisodicProgramLoadTaskTest.java new file mode 100644 index 00000000..216d4d5b --- /dev/null +++ b/tests/unit/src/com/android/tv/dvr/provider/EpisodicProgramLoadTaskTest.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2016 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.tv.dvr.provider; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import android.os.Build; +import android.support.test.filters.SdkSuppress; +import android.support.test.filters.SmallTest; + +import com.android.tv.dvr.data.SeasonEpisodeNumber; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +/** + * Tests for {@link EpisodicProgramLoadTask} + */ +@SmallTest +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) +public class EpisodicProgramLoadTaskTest { + private static final long SERIES_RECORDING_ID1 = 1; + private static final long SERIES_RECORDING_ID2 = 2; + private static final String SEASON_NUMBER1 = "SEASON NUMBER1"; + private static final String SEASON_NUMBER2 = "SEASON NUMBER2"; + private static final String EPISODE_NUMBER1 = "EPISODE NUMBER1"; + private static final String EPISODE_NUMBER2 = "EPISODE NUMBER2"; + + @Test + public void testEpisodeAlreadyScheduled_true() { + List<SeasonEpisodeNumber> seasonEpisodeNumbers = new ArrayList<>(); + SeasonEpisodeNumber seasonEpisodeNumber = new SeasonEpisodeNumber( + SERIES_RECORDING_ID1, SEASON_NUMBER1, EPISODE_NUMBER1); + seasonEpisodeNumbers.add(seasonEpisodeNumber); + assertTrue(seasonEpisodeNumbers.contains( + new SeasonEpisodeNumber(SERIES_RECORDING_ID1, SEASON_NUMBER1, EPISODE_NUMBER1))); + } + + @Test + public void testEpisodeAlreadyScheduled_false() { + List<SeasonEpisodeNumber> seasonEpisodeNumbers = new ArrayList<>(); + SeasonEpisodeNumber seasonEpisodeNumber = new SeasonEpisodeNumber( + SERIES_RECORDING_ID1, SEASON_NUMBER1, EPISODE_NUMBER1); + seasonEpisodeNumbers.add(seasonEpisodeNumber); + assertFalse(seasonEpisodeNumbers.contains( + new SeasonEpisodeNumber(SERIES_RECORDING_ID2, SEASON_NUMBER1, EPISODE_NUMBER1))); + assertFalse(seasonEpisodeNumbers.contains( + new SeasonEpisodeNumber(SERIES_RECORDING_ID1, SEASON_NUMBER2, EPISODE_NUMBER1))); + assertFalse(seasonEpisodeNumbers.contains( + new SeasonEpisodeNumber(SERIES_RECORDING_ID1, SEASON_NUMBER1, EPISODE_NUMBER2))); + } + + @Test + public void testEpisodeAlreadyScheduled_null() { + List<SeasonEpisodeNumber> seasonEpisodeNumbers = new ArrayList<>(); + SeasonEpisodeNumber seasonEpisodeNumber = new SeasonEpisodeNumber( + SERIES_RECORDING_ID1, SEASON_NUMBER1, EPISODE_NUMBER1); + seasonEpisodeNumbers.add(seasonEpisodeNumber); + assertFalse(seasonEpisodeNumbers.contains( + new SeasonEpisodeNumber(SERIES_RECORDING_ID1, null, EPISODE_NUMBER1))); + assertFalse(seasonEpisodeNumbers.contains( + new SeasonEpisodeNumber(SERIES_RECORDING_ID1, SEASON_NUMBER1, null))); + assertFalse(seasonEpisodeNumbers.contains( + new SeasonEpisodeNumber(SERIES_RECORDING_ID1, null, null))); + } +}
\ No newline at end of file diff --git a/tests/unit/src/com/android/tv/dvr/recorder/DvrRecordingServiceTest.java b/tests/unit/src/com/android/tv/dvr/recorder/DvrRecordingServiceTest.java new file mode 100644 index 00000000..8f7dcaf2 --- /dev/null +++ b/tests/unit/src/com/android/tv/dvr/recorder/DvrRecordingServiceTest.java @@ -0,0 +1,183 @@ +/* + * 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.tv.dvr.recorder; + +import static org.mockito.Mockito.verify; + +import android.content.Intent; +import android.os.Build; +import android.support.test.filters.SdkSuppress; +import android.support.test.filters.SmallTest; +import android.test.ServiceTestCase; + +import com.android.tv.common.feature.CommonFeatures; +import com.android.tv.common.feature.TestableFeature; + +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +/** + * Tests for {@link DvrRecordingService}. + */ +@SmallTest +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) +public class DvrRecordingServiceTest + extends ServiceTestCase<DvrRecordingServiceTest.MockDvrRecordingService> { + private final TestableFeature mDvrFeature = CommonFeatures.DVR; + + @Override + protected void setUp() throws Exception { + super.setUp(); + mDvrFeature.enableForTest(); + MockitoAnnotations.initMocks(this); + setupService(); + } + + @Override + protected void tearDown() throws Exception { + mDvrFeature.resetForTests(); + super.tearDown(); + } + + public DvrRecordingServiceTest() { + super(MockDvrRecordingService.class); + } + + public void testStartService_null() throws Exception { + // Not recording + startService(null); + assertFalse(getService().mInForeground); + + // Recording + getService().startRecording(); + startService(null); + assertTrue(getService().mInForeground); + assertTrue(getService().mIsRecording); + getService().reset(); + } + + public void testStartService_noUpcomingRecording() throws Exception { + Intent intent = new Intent(getContext(), DvrRecordingServiceTest.class); + intent.putExtra(DvrRecordingService.EXTRA_START_FOR_RECORDING, false); + + // Not recording + startService(intent); + assertTrue(getService().mInForeground); + assertFalse(getService().mForegroundForUpcomingRecording); + getService().stopForegroundIfNotRecordingInternal(); + assertFalse(getService().mInForeground); + + // Recording, ended quickly + getService().startRecording(); + startService(intent); + assertTrue(getService().mInForeground); + assertTrue(getService().mForegroundForUpcomingRecording); + assertTrue(getService().mIsRecording); + getService().stopRecording(); + assertFalse(getService().mInForeground); + assertFalse(getService().mIsRecording); + getService().stopForegroundIfNotRecordingInternal(); + assertFalse(getService().mInForeground); + assertFalse(getService().mIsRecording); + getService().reset(); + + // Recording, ended later + getService().startRecording(); + startService(intent); + assertTrue(getService().mInForeground); + assertTrue(getService().mForegroundForUpcomingRecording); + assertTrue(getService().mIsRecording); + getService().stopForegroundIfNotRecordingInternal(); + assertTrue(getService().mInForeground); + assertTrue(getService().mForegroundForUpcomingRecording); + assertTrue(getService().mIsRecording); + getService().stopRecording(); + assertFalse(getService().mInForeground); + assertFalse(getService().mIsRecording); + getService().reset(); + } + + public void testStartService_hasUpcomingRecording() throws Exception { + Intent intent = new Intent(getContext(), DvrRecordingServiceTest.class); + intent.putExtra(DvrRecordingService.EXTRA_START_FOR_RECORDING, true); + + // Not recording + startService(intent); + assertTrue(getService().mInForeground); + assertTrue(getService().mForegroundForUpcomingRecording); + assertFalse(getService().mIsRecording); + getService().startRecording(); + assertTrue(getService().mInForeground); + assertTrue(getService().mForegroundForUpcomingRecording); + assertTrue(getService().mIsRecording); + getService().stopRecording(); + assertFalse(getService().mInForeground); + assertFalse(getService().mIsRecording); + getService().reset(); + + // Recording + getService().startRecording(); + startService(intent); + assertTrue(getService().mInForeground); + assertTrue(getService().mForegroundForUpcomingRecording); + assertTrue(getService().mIsRecording); + getService().startRecording(); + assertTrue(getService().mInForeground); + assertTrue(getService().mForegroundForUpcomingRecording); + assertTrue(getService().mIsRecording); + getService().stopRecording(); + assertTrue(getService().mInForeground); + assertTrue(getService().mForegroundForUpcomingRecording); + assertTrue(getService().mIsRecording); + getService().stopRecording(); + assertFalse(getService().mInForeground); + assertFalse(getService().mIsRecording); + getService().reset(); + } + + public static class MockDvrRecordingService extends DvrRecordingService { + private int mRecordingCount = 0; + private boolean mInForeground; + private boolean mForegroundForUpcomingRecording; + + @Override + protected void startForegroundInternal(boolean hasUpcomingRecording) { + mForegroundForUpcomingRecording = hasUpcomingRecording; + mInForeground = true; + } + + @Override + protected void stopForegroundInternal() { + mInForeground = false; + } + + private void startRecording() { + mOnRecordingSessionChangeListener.onRecordingSessionChange(true, ++mRecordingCount); + } + + private void stopRecording() { + mOnRecordingSessionChangeListener.onRecordingSessionChange(false, --mRecordingCount); + } + + private void reset() { + mRecordingCount = 0; + mInForeground = false; + mIsRecording = false; + } + } +}
\ No newline at end of file diff --git a/tests/unit/src/com/android/tv/dvr/InputTaskSchedulerTest.java b/tests/unit/src/com/android/tv/dvr/recorder/InputTaskSchedulerTest.java index 85c78ce2..e5c27e2c 100644 --- a/tests/unit/src/com/android/tv/dvr/InputTaskSchedulerTest.java +++ b/tests/unit/src/com/android/tv/dvr/recorder/InputTaskSchedulerTest.java @@ -14,13 +14,15 @@ * limitations under the License */ -package com.android.tv.dvr; +package com.android.tv.dvr.recorder; +import static android.support.test.InstrumentationRegistry.getContext; +import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.after; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -28,21 +30,25 @@ import static org.mockito.Mockito.when; import android.app.AlarmManager; import android.media.tv.TvInputInfo; import android.os.Build; -import android.os.Handler; import android.os.Looper; +import android.os.SystemClock; import android.support.test.filters.SdkSuppress; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import com.android.tv.InputSessionManager; import com.android.tv.data.Channel; import com.android.tv.data.ChannelDataManager; -import com.android.tv.dvr.InputTaskScheduler.RecordingTaskFactory; +import com.android.tv.dvr.DvrManager; +import com.android.tv.dvr.WritableDvrDataManager; +import com.android.tv.dvr.data.ScheduledRecording; +import com.android.tv.dvr.recorder.InputTaskScheduler.RecordingTaskFactory; import com.android.tv.testing.FakeClock; import com.android.tv.testing.dvr.RecordingTestUtils; import com.android.tv.util.Clock; import com.android.tv.util.TestUtils; +import org.junit.Before; +import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -55,7 +61,7 @@ import java.util.concurrent.TimeUnit; */ @SmallTest @SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class InputTaskSchedulerTest extends AndroidTestCase { +public class InputTaskSchedulerTest { private static final String INPUT_ID = "input_id"; private static final int CHANNEL_ID = 1; private static final long LISTENER_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(1); @@ -73,21 +79,18 @@ public class InputTaskSchedulerTest extends AndroidTestCase { @Mock private ChannelDataManager mChannelDataManager; private List<RecordingTask> mRecordingTasks; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { if (Looper.myLooper() == null) { Looper.prepare(); } - Handler fakeMainHandler = new Handler(); - Handler workerThreadHandler = new Handler(); mRecordingTasks = new ArrayList(); MockitoAnnotations.initMocks(this); mFakeClock = FakeClock.createWithCurrentTime(); TvInputInfo input = createTvInputInfo(TUNER_COUNT_ONE); mScheduler = new InputTaskScheduler(getContext(), input, Looper.myLooper(), mChannelDataManager, mDvrManager, mDataManager, mSessionManager, mFakeClock, - fakeMainHandler, workerThreadHandler, new RecordingTaskFactory() { + new RecordingTaskFactory() { @Override public RecordingTask createRecordingTask(ScheduledRecording scheduledRecording, Channel channel, DvrManager dvrManager, @@ -102,12 +105,8 @@ public class InputTaskSchedulerTest extends AndroidTestCase { }); } - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testAddSchedule_past() throws Exception { + @Test + public void testAddSchedule_past() { ScheduledRecording r = RecordingTestUtils.createTestRecordingWithPeriod(INPUT_ID, CHANNEL_ID, 0L, 1L); when(mDataManager.getScheduledRecording(anyLong())).thenReturn(r); @@ -118,7 +117,8 @@ public class InputTaskSchedulerTest extends AndroidTestCase { eq(ScheduledRecording.STATE_RECORDING_FAILED)); } - public void testAddSchedule_start() throws Exception { + @Test + public void testAddSchedule_start() { mScheduler.handleAddSchedule(RecordingTestUtils.createTestRecordingWithPeriod(INPUT_ID, CHANNEL_ID, mFakeClock.currentTimeMillis(), mFakeClock.currentTimeMillis() + TimeUnit.HOURS.toMillis(1))); @@ -126,7 +126,8 @@ public class InputTaskSchedulerTest extends AndroidTestCase { verify(mRecordingTasks.get(0), timeout((int) LISTENER_TIMEOUT_MS).times(1)).start(); } - public void testAddSchedule_consecutiveNoStop() throws Exception { + @Test + public void testAddSchedule_consecutiveNoStop() { long startTimeMs = mFakeClock.currentTimeMillis(); long endTimeMs = startTimeMs + TimeUnit.SECONDS.toMillis(1); long id = 0; @@ -143,10 +144,12 @@ public class InputTaskSchedulerTest extends AndroidTestCase { verify(mRecordingTasks.get(0), timeout((int) LISTENER_TIMEOUT_MS).times(1)).start(); // The first schedule should not be stopped because the second one should wait for the end // of the first schedule. - verify(mRecordingTasks.get(0), after((int) LISTENER_TIMEOUT_MS).never()).stop(); + SystemClock.sleep(LISTENER_TIMEOUT_MS); + verify(mRecordingTasks.get(0), never()).stop(); } - public void testAddSchedule_consecutiveNoFail() throws Exception { + @Test + public void testAddSchedule_consecutiveNoFail() { long startTimeMs = mFakeClock.currentTimeMillis(); long endTimeMs = startTimeMs + TimeUnit.SECONDS.toMillis(1); long id = 0; @@ -163,13 +166,16 @@ public class InputTaskSchedulerTest extends AndroidTestCase { LOW_PRIORITY, startTimeMs, endTimeMs)); mScheduler.handleBuildSchedule(); verify(mRecordingTasks.get(0), timeout((int) LISTENER_TIMEOUT_MS).times(1)).start(); - verify(mRecordingTasks.get(0), after((int) LISTENER_TIMEOUT_MS).never()).stop(); + SystemClock.sleep(LISTENER_TIMEOUT_MS); + verify(mRecordingTasks.get(0), never()).stop(); // The second schedule should not fail because it can starts after the first one finishes. - verify(mDataManager, after((int) LISTENER_TIMEOUT_MS).never()) + SystemClock.sleep(LISTENER_TIMEOUT_MS); + verify(mDataManager, never()) .changeState(any(ScheduledRecording.class), eq(ScheduledRecording.STATE_RECORDING_FAILED)); } + @Test public void testAddSchedule_consecutiveUseLessSession() throws Exception { TvInputInfo input = createTvInputInfo(TUNER_COUNT_TWO); mScheduler.updateTvInputInfo(input); @@ -187,23 +193,27 @@ public class InputTaskSchedulerTest extends AndroidTestCase { HIGH_PRIORITY, startTimeMs, endTimeMs)); mScheduler.handleBuildSchedule(); verify(mRecordingTasks.get(0), timeout((int) LISTENER_TIMEOUT_MS).times(1)).start(); - verify(mRecordingTasks.get(0), after((int) LISTENER_TIMEOUT_MS).never()).stop(); + SystemClock.sleep(LISTENER_TIMEOUT_MS); + verify(mRecordingTasks.get(0), never()).stop(); // The second schedule should wait until the first one finishes rather than creating a new // session even though there are available tuners. assertTrue(mRecordingTasks.size() == 1); } - public void testUpdateSchedule_noCancel() throws Exception { + @Test + public void testUpdateSchedule_noCancel() { ScheduledRecording r = RecordingTestUtils.createTestRecordingWithPeriod(INPUT_ID, CHANNEL_ID, mFakeClock.currentTimeMillis(), mFakeClock.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)); mScheduler.handleAddSchedule(r); mScheduler.handleBuildSchedule(); mScheduler.handleUpdateSchedule(r); - verify(mRecordingTasks.get(0), after((int) LISTENER_TIMEOUT_MS).never()).cancel(); + SystemClock.sleep(LISTENER_TIMEOUT_MS); + verify(mRecordingTasks.get(0), never()).cancel(); } - public void testUpdateSchedule_cancel() throws Exception { + @Test + public void testUpdateSchedule_cancel() { ScheduledRecording r = RecordingTestUtils.createTestRecordingWithPeriod(INPUT_ID, CHANNEL_ID, mFakeClock.currentTimeMillis(), mFakeClock.currentTimeMillis() + TimeUnit.HOURS.toMillis(2)); diff --git a/tests/unit/src/com/android/tv/dvr/RecordingTaskTest.java b/tests/unit/src/com/android/tv/dvr/recorder/RecordingTaskTest.java index 7404a554..37561a42 100644 --- a/tests/unit/src/com/android/tv/dvr/RecordingTaskTest.java +++ b/tests/unit/src/com/android/tv/dvr/recorder/RecordingTaskTest.java @@ -14,17 +14,18 @@ * limitations under the License */ -package com.android.tv.dvr; +package com.android.tv.dvr.recorder; +import static android.support.test.InstrumentationRegistry.getContext; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import static org.mockito.hamcrest.MockitoHamcrest.longThat; import android.os.Build; import android.os.Handler; @@ -32,20 +33,24 @@ import android.os.Looper; import android.os.Message; import android.support.test.filters.SdkSuppress; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import com.android.tv.InputSessionManager; import com.android.tv.InputSessionManager.RecordingSession; +import com.android.tv.common.feature.CommonFeatures; +import com.android.tv.common.feature.TestableFeature; import com.android.tv.data.Channel; -import com.android.tv.dvr.RecordingTask.State; +import com.android.tv.dvr.DvrDataManagerInMemoryImpl; +import com.android.tv.dvr.DvrManager; +import com.android.tv.dvr.data.ScheduledRecording; +import com.android.tv.dvr.recorder.RecordingTask.State; import com.android.tv.testing.FakeClock; import com.android.tv.testing.dvr.RecordingTestUtils; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.compat.ArgumentMatcher; import java.util.concurrent.TimeUnit; @@ -54,9 +59,9 @@ import java.util.concurrent.TimeUnit; */ @SmallTest @SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class RecordingTaskTest extends AndroidTestCase { +public class RecordingTaskTest { private static final long DURATION = TimeUnit.MINUTES.toMillis(30); - private static final long START_OFFSET_MS = Scheduler.MS_TO_WAKE_BEFORE_START; + private static final long START_OFFSET_MS = RecordingScheduler.MS_TO_WAKE_BEFORE_START; private static final String INPUT_ID = "input_id"; private static final int CHANNEL_ID = 273; @@ -66,10 +71,11 @@ public class RecordingTaskTest extends AndroidTestCase { @Mock DvrManager mDvrManager; @Mock InputSessionManager mMockSessionManager; @Mock RecordingSession mMockRecordingSession; + private final TestableFeature mDvrFeature = CommonFeatures.DVR; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { + mDvrFeature.enableForTest(); if (Looper.myLooper() == null) { Looper.prepare(); } @@ -78,6 +84,12 @@ public class RecordingTaskTest extends AndroidTestCase { mDataManager = new DvrDataManagerInMemoryImpl(getContext(), mFakeClock); } + @After + public void tearDown() { + mDvrFeature.resetForTests(); + } + + @Test public void testHandle_init() { Channel channel = createTestChannel(); ScheduledRecording r = createRecording(channel); @@ -99,6 +111,7 @@ public class RecordingTaskTest extends AndroidTestCase { .setDisplayName("Test Ch " + CHANNEL_ID).build(); } + @Test public void testOnConnected() { Channel channel = createTestChannel(); ScheduledRecording r = createRecording(channel); @@ -127,40 +140,10 @@ public class RecordingTaskTest extends AndroidTestCase { return recordingTask; } - private void verifySendMessageAt(int what, long when) { - verify(mMockHandler).sendMessageAtTime(argThat(messageMatchesWhat(what)), delta(when, 100)); - } - - private static long delta(final long value, final long delta) { - return longThat(new BaseMatcher<Long>() { - @Override - public boolean matches(Object item) { - Long other = (Long) item; - return other >= value - delta && other <= value + delta; - } - - @Override - public void describeTo(Description description) { - description.appendText("eq " + value + "±" + delta); - - } - }); - } - private Message createMessage(int what) { Message msg = new Message(); msg.setTarget(mMockHandler); msg.what = what; return msg; } - - private static ArgumentMatcher<Message> messageMatchesWhat(final int what) { - return new ArgumentMatcher<Message>() { - @Override - public boolean matchesObject(Object argument) { - Message message = (Message) argument; - return message.what == what; - } - }; - } -} +}
\ No newline at end of file diff --git a/tests/unit/src/com/android/tv/dvr/ScheduledProgramReaperTest.java b/tests/unit/src/com/android/tv/dvr/recorder/ScheduledProgramReaperTest.java index 847540c2..ca72e13f 100644 --- a/tests/unit/src/com/android/tv/dvr/ScheduledProgramReaperTest.java +++ b/tests/unit/src/com/android/tv/dvr/recorder/ScheduledProgramReaperTest.java @@ -14,15 +14,27 @@ * limitations under the License. */ -package com.android.tv.dvr; +package com.android.tv.dvr.recorder; +import static android.support.test.InstrumentationRegistry.getContext; +import static org.junit.Assert.assertTrue; + +import android.os.Build; +import android.support.test.filters.SdkSuppress; +import android.support.test.filters.SmallTest; import android.test.MoreAsserts; +import com.android.tv.common.feature.CommonFeatures; +import com.android.tv.common.feature.TestableFeature; +import com.android.tv.dvr.DvrDataManagerInMemoryImpl; +import com.android.tv.dvr.DvrManager; +import com.android.tv.dvr.data.ScheduledRecording; import com.android.tv.testing.FakeClock; import com.android.tv.testing.dvr.RecordingTestUtils; -import junit.framework.TestCase; - +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -31,7 +43,9 @@ import java.util.concurrent.TimeUnit; /** * Tests for {@link ScheduledProgramReaper}. */ -public class ScheduledProgramReaperTest extends TestCase { +@SmallTest +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) +public class ScheduledProgramReaperTest { private static final String INPUT_ID = "input_id"; private static final int CHANNEL_ID = 273; private static final long DURATION = TimeUnit.HOURS.toMillis(1); @@ -40,23 +54,30 @@ public class ScheduledProgramReaperTest extends TestCase { private FakeClock mFakeClock; private DvrDataManagerInMemoryImpl mDvrDataManager; @Mock private DvrManager mDvrManager; + private final TestableFeature mDvrFeature = CommonFeatures.DVR; - - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { MockitoAnnotations.initMocks(this); + mDvrFeature.enableForTest(); mFakeClock = FakeClock.createWithTimeOne(); - mDvrDataManager = new DvrDataManagerInMemoryImpl(null, mFakeClock); + mDvrDataManager = new DvrDataManagerInMemoryImpl(getContext(), mFakeClock); mReaper = new ScheduledProgramReaper(mDvrDataManager, mFakeClock); } + @After + public void tearDown() { + mDvrFeature.resetForTests(); + } + + @Test public void testRun_noRecordings() { - MoreAsserts.assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings()); + assertTrue(mDvrDataManager.getAllScheduledRecordings().isEmpty()); mReaper.run(); - MoreAsserts.assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings()); + assertTrue(mDvrDataManager.getAllScheduledRecordings().isEmpty()); } + @Test public void testRun_oneRecordingsTomorrow() { ScheduledRecording recording = addNewScheduledRecordingForTomorrow(); MoreAsserts @@ -66,6 +87,7 @@ public class ScheduledProgramReaperTest extends TestCase { .assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings(), recording); } + @Test public void testRun_oneRecordingsStarted() { ScheduledRecording recording = addNewScheduledRecordingForTomorrow(); MoreAsserts @@ -76,6 +98,7 @@ public class ScheduledProgramReaperTest extends TestCase { .assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings(), recording); } + @Test public void testRun_oneRecordingsFinished() { ScheduledRecording recording = addNewScheduledRecordingForTomorrow(); MoreAsserts @@ -87,6 +110,7 @@ public class ScheduledProgramReaperTest extends TestCase { .assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings(), recording); } + @Test public void testRun_oneRecordingsExpired() { ScheduledRecording recording = addNewScheduledRecordingForTomorrow(); MoreAsserts @@ -97,10 +121,9 @@ public class ScheduledProgramReaperTest extends TestCase { mFakeClock.increment(TimeUnit.SECONDS, 1); mReaper.run(); - MoreAsserts.assertContentsInAnyOrder( - "Recordings after reaper at " + com.android.tv.util.Utils + assertTrue("Recordings after reaper at " + com.android.tv.util.Utils .toIsoDateTimeString(mFakeClock.currentTimeMillis()), - mDvrDataManager.getAllScheduledRecordings()); + mDvrDataManager.getAllScheduledRecordings().isEmpty()); } private ScheduledRecording addNewScheduledRecordingForTomorrow() { diff --git a/tests/unit/src/com/android/tv/dvr/SchedulerTest.java b/tests/unit/src/com/android/tv/dvr/recorder/SchedulerTest.java index 30ac1ff1..a5154729 100644 --- a/tests/unit/src/com/android/tv/dvr/SchedulerTest.java +++ b/tests/unit/src/com/android/tv/dvr/recorder/SchedulerTest.java @@ -14,8 +14,11 @@ * limitations under the License */ -package com.android.tv.dvr; +package com.android.tv.dvr.recorder; +import static android.support.test.InstrumentationRegistry.getTargetContext; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; @@ -27,14 +30,21 @@ import android.os.Build; import android.os.Looper; import android.support.test.filters.SdkSuppress; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import com.android.tv.InputSessionManager; +import com.android.tv.common.feature.CommonFeatures; +import com.android.tv.common.feature.TestableFeature; import com.android.tv.data.ChannelDataManager; +import com.android.tv.dvr.DvrDataManagerInMemoryImpl; +import com.android.tv.dvr.DvrManager; +import com.android.tv.dvr.data.ScheduledRecording; import com.android.tv.testing.FakeClock; import com.android.tv.testing.dvr.RecordingTestUtils; import com.android.tv.util.TvInputManagerHelper; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -42,61 +52,69 @@ import org.mockito.MockitoAnnotations; import java.util.concurrent.TimeUnit; /** - * Tests for {@link Scheduler}. + * Tests for {@link RecordingScheduler}. */ @SmallTest @SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class SchedulerTest extends AndroidTestCase { +public class SchedulerTest { private static final String INPUT_ID = "input_id"; private static final int CHANNEL_ID = 273; private FakeClock mFakeClock; private DvrDataManagerInMemoryImpl mDataManager; - private Scheduler mScheduler; + private RecordingScheduler mScheduler; @Mock DvrManager mDvrManager; @Mock InputSessionManager mSessionManager; @Mock AlarmManager mMockAlarmManager; @Mock ChannelDataManager mChannelDataManager; @Mock TvInputManagerHelper mInputManager; + private final TestableFeature mDvrFeature = CommonFeatures.DVR; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { MockitoAnnotations.initMocks(this); + mDvrFeature.enableForTest(); mFakeClock = FakeClock.createWithCurrentTime(); - mDataManager = new DvrDataManagerInMemoryImpl(getContext(), mFakeClock); + mDataManager = new DvrDataManagerInMemoryImpl(getTargetContext(), mFakeClock); Mockito.when(mChannelDataManager.isDbLoadFinished()).thenReturn(true); - mScheduler = new Scheduler(Looper.myLooper(), mDvrManager, mSessionManager, mDataManager, - mChannelDataManager, mInputManager, getContext(), mFakeClock, mMockAlarmManager); + mScheduler = new RecordingScheduler(Looper.myLooper(), mDvrManager, mSessionManager, mDataManager, + mChannelDataManager, mInputManager, getTargetContext(), mFakeClock, + mMockAlarmManager); } - public void testUpdate_none() throws Exception { - mScheduler.start(); - mScheduler.update(); + @After + public void tearDown() { + mDvrFeature.resetForTests(); + } + + @Test + public void testUpdate_none() { + mScheduler.updateAndStartServiceIfNeeded(); verifyZeroInteractions(mMockAlarmManager); } - public void testUpdate_nextIn12Hours() throws Exception { + @Test + public void testUpdate_nextIn12Hours() { long now = mFakeClock.currentTimeMillis(); long startTime = now + TimeUnit.HOURS.toMillis(12); ScheduledRecording r = RecordingTestUtils .createTestRecordingWithPeriod(INPUT_ID, CHANNEL_ID, startTime, startTime + TimeUnit.HOURS.toMillis(1)); mDataManager.addScheduledRecording(r); - mScheduler.start(); - verify(mMockAlarmManager).set( + verify(mMockAlarmManager).setExactAndAllowWhileIdle( eq(AlarmManager.RTC_WAKEUP), - eq(startTime - Scheduler.MS_TO_WAKE_BEFORE_START), + eq(startTime - RecordingScheduler.MS_TO_WAKE_BEFORE_START), any(PendingIntent.class)); Mockito.reset(mMockAlarmManager); - mScheduler.update(); - verify(mMockAlarmManager).set( + mScheduler.updateAndStartServiceIfNeeded(); + verify(mMockAlarmManager).setExactAndAllowWhileIdle( eq(AlarmManager.RTC_WAKEUP), - eq(startTime - Scheduler.MS_TO_WAKE_BEFORE_START), + eq(startTime - RecordingScheduler.MS_TO_WAKE_BEFORE_START), any(PendingIntent.class)); } - public void testStartsWithin() throws Exception { + @Test + public void testStartsWithin() { long now = mFakeClock.currentTimeMillis(); long startTime = now + 3; ScheduledRecording r = RecordingTestUtils diff --git a/tests/unit/src/com/android/tv/dvr/SeriesRecordingSchedulerTest.java b/tests/unit/src/com/android/tv/dvr/recorder/SeriesRecordingSchedulerTest.java index efefb93c..16fa1baf 100644 --- a/tests/unit/src/com/android/tv/dvr/SeriesRecordingSchedulerTest.java +++ b/tests/unit/src/com/android/tv/dvr/recorder/SeriesRecordingSchedulerTest.java @@ -14,18 +14,27 @@ * limitations under the License. */ -package com.android.tv.dvr; +package com.android.tv.dvr.recorder; + +import static android.support.test.InstrumentationRegistry.getContext; import android.os.Build; import android.support.test.filters.SdkSuppress; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import android.test.MoreAsserts; import android.util.LongSparseArray; +import com.android.tv.common.feature.CommonFeatures; +import com.android.tv.common.feature.TestableFeature; import com.android.tv.data.Program; +import com.android.tv.dvr.DvrDataManagerInMemoryImpl; +import com.android.tv.dvr.data.SeriesRecording; import com.android.tv.testing.FakeClock; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -35,7 +44,7 @@ import java.util.List; */ @SmallTest @SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class SeriesRecordingSchedulerTest extends AndroidTestCase { +public class SeriesRecordingSchedulerTest { private static final String PROGRAM_TITLE = "MyProgram"; private static final long CHANNEL_ID = 123; private static final long SERIES_RECORDING_ID1 = 1; @@ -49,16 +58,23 @@ public class SeriesRecordingSchedulerTest extends AndroidTestCase { .setTitle(PROGRAM_TITLE).setChannelId(CHANNEL_ID).setSeriesId(SERIES_ID).build(); private final Program mBaseProgram = new Program.Builder().setTitle(PROGRAM_TITLE) .setChannelId(CHANNEL_ID).setSeriesId(SERIES_ID).build(); + private final TestableFeature mDvrFeature = CommonFeatures.DVR; private DvrDataManagerInMemoryImpl mDataManager; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { + mDvrFeature.enableForTest(); FakeClock fakeClock = FakeClock.createWithCurrentTime(); mDataManager = new DvrDataManagerInMemoryImpl(getContext(), fakeClock); } + @After + public void tearDown() { + mDvrFeature.resetForTests(); + } + + @Test public void testPickOneProgramPerEpisode_onePerEpisode() { SeriesRecording seriesRecording = SeriesRecording.buildFrom(mBaseSeriesRecording) .setId(SERIES_RECORDING_ID1).build(); @@ -75,6 +91,7 @@ public class SeriesRecordingSchedulerTest extends AndroidTestCase { MoreAsserts.assertContentsInAnyOrder(result.get(SERIES_RECORDING_ID1), program1, program2); } + @Test public void testPickOneProgramPerEpisode_manyPerEpisode() { SeriesRecording seriesRecording = SeriesRecording.buildFrom(mBaseSeriesRecording) .setId(SERIES_RECORDING_ID1).build(); @@ -95,6 +112,7 @@ public class SeriesRecordingSchedulerTest extends AndroidTestCase { MoreAsserts.assertContentsInAnyOrder(result.get(SERIES_RECORDING_ID1), program1, program3); } + @Test public void testPickOneProgramPerEpisode_nullEpisode() { SeriesRecording seriesRecording = SeriesRecording.buildFrom(mBaseSeriesRecording) .setId(SERIES_RECORDING_ID1).build(); diff --git a/tests/unit/src/com/android/tv/dvr/ui/SortedArrayAdapterTest.java b/tests/unit/src/com/android/tv/dvr/ui/SortedArrayAdapterTest.java index a571e626..5667ee6b 100644 --- a/tests/unit/src/com/android/tv/dvr/ui/SortedArrayAdapterTest.java +++ b/tests/unit/src/com/android/tv/dvr/ui/SortedArrayAdapterTest.java @@ -22,6 +22,9 @@ import android.support.v17.leanback.widget.ObjectAdapter; import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; + import java.util.Arrays; import java.util.Comparator; import java.util.Objects; @@ -31,29 +34,30 @@ import java.util.Objects; */ @SmallTest public class SortedArrayAdapterTest extends TestCase { - - public static final TestData P1 = TestData.create(1, "one"); - public static final TestData P2 = TestData.create(2, "before"); - public static final TestData P3 = TestData.create(3, "other"); - public static final TestData EXTRA = TestData.create(4, "extra"); + public static final TestData P1 = TestData.create(1, "c"); + public static final TestData P2 = TestData.create(2, "b"); + public static final TestData P3 = TestData.create(3, "a"); + public static final TestData EXTRA = TestData.create(4, "k"); private TestSortedArrayAdapter mAdapter; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { mAdapter = new TestSortedArrayAdapter(Integer.MAX_VALUE, null); } + @Test public void testContents_empty() { assertEmpty(); } + @Test public void testAdd_one() { mAdapter.add(P1); assertNotEmpty(); assertContentsInOrder(mAdapter, P1); } + @Test public void testAdd_two() { mAdapter.add(P1); mAdapter.add(P2); @@ -61,12 +65,14 @@ public class SortedArrayAdapterTest extends TestCase { assertContentsInOrder(mAdapter, P2, P1); } + @Test public void testSetInitialItems_two() { mAdapter.setInitialItems(Arrays.asList(P1, P2)); assertNotEmpty(); assertContentsInOrder(mAdapter, P2, P1); } + @Test public void testMaxInitialCount() { mAdapter = new TestSortedArrayAdapter(1, null); mAdapter.setInitialItems(Arrays.asList(P1, P2)); @@ -75,6 +81,7 @@ public class SortedArrayAdapterTest extends TestCase { assertEquals(mAdapter.get(0), P2); } + @Test public void testExtraItem() { mAdapter = new TestSortedArrayAdapter(Integer.MAX_VALUE, EXTRA); mAdapter.setInitialItems(Arrays.asList(P1, P2)); @@ -88,6 +95,7 @@ public class SortedArrayAdapterTest extends TestCase { assertEquals(mAdapter.get(0), EXTRA); } + @Test public void testExtraItemWithMaxCount() { mAdapter = new TestSortedArrayAdapter(1, EXTRA); mAdapter.setInitialItems(Arrays.asList(P1, P2)); @@ -100,6 +108,7 @@ public class SortedArrayAdapterTest extends TestCase { assertEquals(mAdapter.get(0), EXTRA); } + @Test public void testRemove() { mAdapter.add(P1); mAdapter.add(P2); @@ -111,8 +120,47 @@ public class SortedArrayAdapterTest extends TestCase { assertContentsInOrder(mAdapter, P1); mAdapter.remove(P1); assertEmpty(); + mAdapter.add(P1); + mAdapter.add(P2); + mAdapter.add(P3); + assertContentsInOrder(mAdapter, P3, P2, P1); + mAdapter.removeItems(0, 2); + assertContentsInOrder(mAdapter, P1); + mAdapter.add(P2); + mAdapter.add(P3); + mAdapter.addExtraItem(EXTRA); + assertContentsInOrder(mAdapter, P3, P2, P1, EXTRA); + mAdapter.removeItems(1, 1); + assertContentsInOrder(mAdapter, P3, P1, EXTRA); + mAdapter.removeItems(1, 2); + assertContentsInOrder(mAdapter, P3); + mAdapter.addExtraItem(EXTRA); + mAdapter.addExtraItem(P2); + mAdapter.add(P1); + assertContentsInOrder(mAdapter, P3, P1, EXTRA, P2); + mAdapter.removeItems(1, 2); + assertContentsInOrder(mAdapter, P3, P2); + mAdapter.add(P1); + assertContentsInOrder(mAdapter, P3, P1, P2); + } + + @Test + public void testReplace() { + mAdapter.add(P1); + mAdapter.add(P2); + assertNotEmpty(); + assertContentsInOrder(mAdapter, P2, P1); + mAdapter.replace(1, P3); + assertContentsInOrder(mAdapter, P3, P2); + mAdapter.replace(0, P1); + assertContentsInOrder(mAdapter, P2, P1); + mAdapter.addExtraItem(EXTRA); + assertContentsInOrder(mAdapter, P2, P1, EXTRA); + mAdapter.replace(2, P3); + assertContentsInOrder(mAdapter, P2, P1, P3); } + @Test public void testChange_sorting() { TestData p2_changed = TestData.create(2, "z changed"); mAdapter.add(P1); @@ -123,6 +171,7 @@ public class SortedArrayAdapterTest extends TestCase { assertContentsInOrder(mAdapter, P1, p2_changed); } + @Test public void testChange_new() { mAdapter.change(P1); assertNotEmpty(); @@ -194,7 +243,7 @@ public class SortedArrayAdapterTest extends TestCase { } @Override - long getId(TestData item) { + protected long getId(TestData item) { return item.mId; } } diff --git a/tests/unit/src/com/android/tv/experiments/ExperimentsTest.java b/tests/unit/src/com/android/tv/experiments/ExperimentsTest.java new file mode 100644 index 00000000..3f827ce1 --- /dev/null +++ b/tests/unit/src/com/android/tv/experiments/ExperimentsTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2016 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.tv.experiments; + +import static org.junit.Assert.assertEquals; + +import android.support.test.filters.SmallTest; + +import com.android.tv.common.BuildConfig; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +/** + * Tests for {@link Experiments}. + */ +@SmallTest +public class ExperimentsTest { + @Before + public void setUp() { + ExperimentFlag.initForTest(); + } + + + @Test + public void testEngOnlyDefault() { + assertEquals("ENABLE_DEVELOPER_FEATURES", Boolean.valueOf(BuildConfig.ENG), + Experiments.ENABLE_DEVELOPER_FEATURES.get()); + } + + +} diff --git a/tests/unit/src/com/android/tv/menu/MenuTest.java b/tests/unit/src/com/android/tv/menu/MenuTest.java index 35e2a0fe..e8cfdbef 100644 --- a/tests/unit/src/com/android/tv/menu/MenuTest.java +++ b/tests/unit/src/com/android/tv/menu/MenuTest.java @@ -15,11 +15,16 @@ */ package com.android.tv.menu; +import static android.support.test.InstrumentationRegistry.getTargetContext; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import com.android.tv.menu.Menu.OnMenuVisibilityChangeListener; +import org.junit.Before; +import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; @@ -29,23 +34,23 @@ import org.mockito.stubbing.Answer; * Tests for {@link Menu}. */ @SmallTest -public class MenuTest extends AndroidTestCase { +public class MenuTest { private Menu mMenu; private IMenuView mMenuView; private OnMenuVisibilityChangeListener mVisibilityChangeListener; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { mMenuView = Mockito.mock(IMenuView.class); MenuRowFactory factory = Mockito.mock(MenuRowFactory.class); Mockito.when(factory.createMenuRow(Mockito.any(Menu.class), Mockito.any(Class.class))) .thenReturn(null); mVisibilityChangeListener = Mockito.mock(OnMenuVisibilityChangeListener.class); - mMenu = new Menu(getContext(), mMenuView, factory, mVisibilityChangeListener); + mMenu = new Menu(getTargetContext(), mMenuView, factory, mVisibilityChangeListener); mMenu.disableAnimationForTest(); } + @Test public void testScheduleHide() { mMenu.show(Menu.REASON_NONE); setMenuVisible(true); @@ -67,6 +72,7 @@ public class MenuTest extends AndroidTestCase { assertFalse("Hide is scheduled", mMenu.isHideScheduled()); } + @Test public void testShowHide_ReasonNone() { // Show with REASON_NONE mMenu.show(Menu.REASON_NONE); @@ -87,6 +93,7 @@ public class MenuTest extends AndroidTestCase { Mockito.verify(mMenuView).onHide(); } + @Test public void testShowHide_ReasonGuide() { // Show with REASON_GUIDE mMenu.show(Menu.REASON_GUIDE); @@ -107,6 +114,7 @@ public class MenuTest extends AndroidTestCase { Mockito.verify(mMenuView).onHide(); } + @Test public void testShowHide_ReasonPlayControlsFastForward() { // Show with REASON_PLAY_CONTROLS_FAST_FORWARD mMenu.show(Menu.REASON_PLAY_CONTROLS_FAST_FORWARD); diff --git a/tests/unit/src/com/android/tv/menu/TvOptionsRowAdapterTest.java b/tests/unit/src/com/android/tv/menu/TvOptionsRowAdapterTest.java index 6b0726d9..49ba8514 100644 --- a/tests/unit/src/com/android/tv/menu/TvOptionsRowAdapterTest.java +++ b/tests/unit/src/com/android/tv/menu/TvOptionsRowAdapterTest.java @@ -15,18 +15,24 @@ */ package com.android.tv.menu; +import static android.support.test.InstrumentationRegistry.getInstrumentation; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import android.media.tv.TvTrackInfo; import android.os.SystemClock; import android.support.test.filters.MediumTest; +import android.text.TextUtils; import com.android.tv.BaseMainActivityTestCase; -import com.android.tv.MainActivity; -import com.android.tv.customization.CustomAction; import com.android.tv.testing.Constants; -import com.android.tv.testing.Utils; +import com.android.tv.testing.testinput.ChannelState; import com.android.tv.testing.testinput.ChannelStateData; import com.android.tv.testing.testinput.TvTestInputConstants; +import org.junit.Before; +import org.junit.Test; + import java.util.Collections; import java.util.List; @@ -35,24 +41,22 @@ import java.util.List; */ @MediumTest public class TvOptionsRowAdapterTest extends BaseMainActivityTestCase { - private static final int WAIT_TRACK_SIZE_TIMEOUT_MS = 300; - public static final int TRACK_SIZE_CHECK_INTERVAL_MS = 10; + private static final int WAIT_TRACK_EVENT_TIMEOUT_MS = 300; + public static final int TRACK_CHECK_INTERVAL_MS = 10; // TODO: Refactor TvOptionsRowAdapter so it does not rely on MainActivity private TvOptionsRowAdapter mTvOptionsRowAdapter; - public TvOptionsRowAdapterTest() { - super(MainActivity.class); - } - @Override - protected void setUp() throws Exception { + @Before + public void setUp() { super.setUp(); mTvOptionsRowAdapter = new TvOptionsRowAdapter(mActivity, Collections.emptyList()); tuneToChannel(TvTestInputConstants.CH_1_DEFAULT_DONT_MODIFY); waitUntilAudioTracksHaveSize(1); + waitUntilAudioTrackSelected(ChannelState.DEFAULT.getSelectedAudioTrackId()); // update should be called on the main thread to avoid the multi-thread problem. - Utils.runOnMainSync(new Runnable() { + getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mTvOptionsRowAdapter.update(); @@ -60,11 +64,13 @@ public class TvOptionsRowAdapterTest extends BaseMainActivityTestCase { }); } + @Test public void testUpdateAudioAction_2tracks() { ChannelStateData data = new ChannelStateData(); data.mTvTrackInfos.add(Constants.GENERIC_AUDIO_TRACK); updateThenTune(data, TvTestInputConstants.CH_2); waitUntilAudioTracksHaveSize(2); + waitUntilAudioTrackSelected(Constants.EN_STEREO_AUDIO_TRACK.getId()); boolean result = mTvOptionsRowAdapter.updateMultiAudioAction(); assertEquals("update Action had change", true, result); @@ -72,46 +78,87 @@ public class TvOptionsRowAdapterTest extends BaseMainActivityTestCase { MenuAction.SELECT_AUDIO_LANGUAGE_ACTION.isEnabled()); } + @Test public void testUpdateAudioAction_1track() { ChannelStateData data = new ChannelStateData(); data.mTvTrackInfos.clear(); data.mTvTrackInfos.add(Constants.GENERIC_AUDIO_TRACK); + data.mSelectedVideoTrackId = null; + data.mSelectedAudioTrackId = Constants.GENERIC_AUDIO_TRACK.getId(); updateThenTune(data, TvTestInputConstants.CH_2); waitUntilAudioTracksHaveSize(1); + waitUntilAudioTrackSelected(Constants.GENERIC_AUDIO_TRACK.getId()); boolean result = mTvOptionsRowAdapter.updateMultiAudioAction(); - assertEquals("update Action had change", false, result); + assertEquals("update Action had change", true, result); assertEquals("Multi Audio enabled", false, MenuAction.SELECT_AUDIO_LANGUAGE_ACTION.isEnabled()); } + @Test public void testUpdateAudioAction_noTracks() { ChannelStateData data = new ChannelStateData(); data.mTvTrackInfos.clear(); + data.mTvTrackInfos.add(ChannelState.DEFAULT_VIDEO_TRACK); + data.mSelectedVideoTrackId = ChannelState.DEFAULT_VIDEO_TRACK.getId(); + data.mSelectedAudioTrackId = null; updateThenTune(data, TvTestInputConstants.CH_2); - waitUntilAudioTracksHaveSize(0); + // Wait for the video tracks, because there's no audio track. + waitUntilVideoTracksHaveSize(1); + waitUntilVideoTrackSelected(data.mSelectedVideoTrackId); boolean result = mTvOptionsRowAdapter.updateMultiAudioAction(); - assertEquals("update Action had change", false, result); + assertEquals("update Action had change", true, result); assertEquals("Multi Audio enabled", false, MenuAction.SELECT_AUDIO_LANGUAGE_ACTION.isEnabled()); } private void waitUntilAudioTracksHaveSize(int expected) { + waitUntilTracksHaveSize(TvTrackInfo.TYPE_AUDIO, expected); + } + + private void waitUntilVideoTracksHaveSize(int expected) { + waitUntilTracksHaveSize(TvTrackInfo.TYPE_VIDEO, expected); + } + + private void waitUntilTracksHaveSize(int trackType, int expected) { long start = SystemClock.elapsedRealtime(); int size = -1; - while (SystemClock.elapsedRealtime() < start + WAIT_TRACK_SIZE_TIMEOUT_MS) { + while (SystemClock.elapsedRealtime() < start + WAIT_TRACK_EVENT_TIMEOUT_MS) { getInstrumentation().waitForIdleSync(); - List<TvTrackInfo> tracks = mActivity.getTracks(TvTrackInfo.TYPE_AUDIO); + List<TvTrackInfo> tracks = mActivity.getTracks(trackType); if (tracks != null) { size = tracks.size(); if (size == expected) { return; } } - SystemClock.sleep(TRACK_SIZE_CHECK_INTERVAL_MS); + SystemClock.sleep(TRACK_CHECK_INTERVAL_MS); } - fail("Waited for " + WAIT_TRACK_SIZE_TIMEOUT_MS + " milliseconds for track size to be " + fail("Waited for " + WAIT_TRACK_EVENT_TIMEOUT_MS + " milliseconds for track size to be " + expected + " but was " + size); } + + private void waitUntilAudioTrackSelected(String trackId) { + waitUntilTrackSelected(TvTrackInfo.TYPE_AUDIO, trackId); + } + + private void waitUntilVideoTrackSelected(String trackId) { + waitUntilTrackSelected(TvTrackInfo.TYPE_VIDEO, trackId); + } + + private void waitUntilTrackSelected(int trackType, String trackId) { + long start = SystemClock.elapsedRealtime(); + String selectedTrackId = null; + while (SystemClock.elapsedRealtime() < start + WAIT_TRACK_EVENT_TIMEOUT_MS) { + getInstrumentation().waitForIdleSync(); + selectedTrackId = mActivity.getSelectedTrack(trackType); + if (TextUtils.equals(selectedTrackId, trackId)) { + return; + } + SystemClock.sleep(TRACK_CHECK_INTERVAL_MS); + } + fail("Waited for " + WAIT_TRACK_EVENT_TIMEOUT_MS + " milliseconds for track ID to be " + + trackId + " but was " + selectedTrackId); + } } diff --git a/tests/unit/src/com/android/tv/recommendation/ChannelRecordTest.java b/tests/unit/src/com/android/tv/recommendation/ChannelRecordTest.java index c76de8fb..db765109 100644 --- a/tests/unit/src/com/android/tv/recommendation/ChannelRecordTest.java +++ b/tests/unit/src/com/android/tv/recommendation/ChannelRecordTest.java @@ -16,11 +16,16 @@ package com.android.tv.recommendation; +import static android.support.test.InstrumentationRegistry.getContext; +import static org.junit.Assert.assertEquals; + import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import com.android.tv.testing.Utils; +import org.junit.Before; +import org.junit.Test; + import java.util.Random; import java.util.concurrent.TimeUnit; @@ -28,31 +33,33 @@ import java.util.concurrent.TimeUnit; * Unit tests for {@link ChannelRecord}. */ @SmallTest -public class ChannelRecordTest extends AndroidTestCase { +public class ChannelRecordTest { private static final int CHANNEL_RECORD_MAX_HISTORY_SIZE = ChannelRecord.MAX_HISTORY_SIZE; private Random mRandom; private ChannelRecord mChannelRecord; private long mLatestWatchEndTimeMs; - @Override - public void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { mLatestWatchEndTimeMs = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1); mChannelRecord = new ChannelRecord(getContext(), null, false); mRandom = Utils.createTestRandom(); } + @Test public void testGetLastWatchEndTime_noHistory() { assertEquals(0, mChannelRecord.getLastWatchEndTimeMs()); } + @Test public void testGetLastWatchEndTime_oneHistory() { addWatchLog(); assertEquals(mLatestWatchEndTimeMs, mChannelRecord.getLastWatchEndTimeMs()); } + @Test public void testGetLastWatchEndTime_maxHistories() { for (int i = 0; i < CHANNEL_RECORD_MAX_HISTORY_SIZE; ++i) { addWatchLog(); @@ -61,6 +68,7 @@ public class ChannelRecordTest extends AndroidTestCase { assertEquals(mLatestWatchEndTimeMs, mChannelRecord.getLastWatchEndTimeMs()); } + @Test public void testGetLastWatchEndTime_moreThanMaxHistories() { for (int i = 0; i < CHANNEL_RECORD_MAX_HISTORY_SIZE + 1; ++i) { addWatchLog(); @@ -69,16 +77,19 @@ public class ChannelRecordTest extends AndroidTestCase { assertEquals(mLatestWatchEndTimeMs, mChannelRecord.getLastWatchEndTimeMs()); } + @Test public void testGetTotalWatchDuration_noHistory() { assertEquals(0, mChannelRecord.getTotalWatchDurationMs()); } + @Test public void testGetTotalWatchDuration_oneHistory() { long durationMs = addWatchLog(); assertEquals(durationMs, mChannelRecord.getTotalWatchDurationMs()); } + @Test public void testGetTotalWatchDuration_maxHistories() { long totalWatchTimeMs = 0; for (int i = 0; i < CHANNEL_RECORD_MAX_HISTORY_SIZE; ++i) { @@ -89,6 +100,7 @@ public class ChannelRecordTest extends AndroidTestCase { assertEquals(totalWatchTimeMs, mChannelRecord.getTotalWatchDurationMs()); } + @Test public void testGetTotalWatchDuration_moreThanMaxHistories() { long totalWatchTimeMs = 0; long firstDurationMs = 0; diff --git a/tests/unit/src/com/android/tv/recommendation/EvaluatorTestCase.java b/tests/unit/src/com/android/tv/recommendation/EvaluatorTestCase.java index 0255947b..853fb245 100644 --- a/tests/unit/src/com/android/tv/recommendation/EvaluatorTestCase.java +++ b/tests/unit/src/com/android/tv/recommendation/EvaluatorTestCase.java @@ -16,30 +16,35 @@ package com.android.tv.recommendation; -import android.test.AndroidTestCase; +import static android.support.test.InstrumentationRegistry.getContext; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import com.android.tv.data.Channel; import com.android.tv.recommendation.RecommendationUtils.ChannelRecordSortedMapHelper; import com.android.tv.recommendation.Recommender.Evaluator; import com.android.tv.testing.Utils; +import org.junit.Before; + import java.util.ArrayList; import java.util.List; /** * Base test case for Recommendation Evaluator Unit tests. */ -public abstract class EvaluatorTestCase<T extends Evaluator> extends AndroidTestCase { +public abstract class EvaluatorTestCase<T extends Evaluator> { private static final long INVALID_CHANNEL_ID = -1; + private static final double SCORE_DELTA = 0.01; + private ChannelRecordSortedMapHelper mChannelRecordSortedMap; private RecommendationDataManager mDataManager; public T mEvaluator; - @Override - public void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { mChannelRecordSortedMap = new ChannelRecordSortedMapHelper(getContext()); mDataManager = RecommendationUtils .createMockRecommendationDataManager(mChannelRecordSortedMap); @@ -91,8 +96,9 @@ public abstract class EvaluatorTestCase<T extends Evaluator> extends AndroidTest * Check whether scores of each channels are valid. */ protected void assertChannelScoresValid() { - assertEquals(Evaluator.NOT_RECOMMENDED, mEvaluator.evaluateChannel(INVALID_CHANNEL_ID)); - assertEquals(Evaluator.NOT_RECOMMENDED, + assertEqualScores(Evaluator.NOT_RECOMMENDED, + mEvaluator.evaluateChannel(INVALID_CHANNEL_ID)); + assertEqualScores(Evaluator.NOT_RECOMMENDED, mEvaluator.evaluateChannel(mChannelRecordSortedMap.size())); for (long channelId : mChannelRecordSortedMap.keySet()) { @@ -109,6 +115,14 @@ public abstract class EvaluatorTestCase<T extends Evaluator> extends AndroidTest mEvaluator.onChannelRecordListChanged(new ArrayList<>(mChannelRecordSortedMap.values())); } + void assertEqualScores(double expected, double actual) { + assertEquals(expected, actual, SCORE_DELTA); + } + + void assertEqualScores(String message, double expected, double actual) { + assertEquals(message, expected, actual, SCORE_DELTA); + } + private class FakeRecommender extends Recommender { public FakeRecommender() { super(new Recommender.Listener() { @@ -120,7 +134,7 @@ public abstract class EvaluatorTestCase<T extends Evaluator> extends AndroidTest public void onRecommendationChanged() { } }, true, mDataManager); - } + } @Override public ChannelRecord getChannelRecord(long channelId) { diff --git a/tests/unit/src/com/android/tv/recommendation/FavoriteChannelEvaluatorTest.java b/tests/unit/src/com/android/tv/recommendation/FavoriteChannelEvaluatorTest.java index aae3a932..ac701af9 100644 --- a/tests/unit/src/com/android/tv/recommendation/FavoriteChannelEvaluatorTest.java +++ b/tests/unit/src/com/android/tv/recommendation/FavoriteChannelEvaluatorTest.java @@ -16,8 +16,12 @@ package com.android.tv.recommendation; +import static org.junit.Assert.assertTrue; + import android.support.test.filters.SmallTest; +import org.junit.Test; + import java.util.List; import java.util.concurrent.TimeUnit; @@ -38,14 +42,16 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan return new FavoriteChannelEvaluator(); } + @Test public void testOneChannelWithNoWatchLog() { long channelId = addChannel().getId(); notifyChannelAndWatchLogLoaded(); - assertEquals(Recommender.Evaluator.NOT_RECOMMENDED, + assertEqualScores(Recommender.Evaluator.NOT_RECOMMENDED, mEvaluator.evaluateChannel(channelId)); } + @Test public void testOneChannelWithRandomWatchLogs() { addChannel(); addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, @@ -55,17 +61,19 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan assertChannelScoresValid(); } + @Test public void testMultiChannelsWithNoWatchLog() { addChannels(DEFAULT_NUMBER_OF_CHANNELS); notifyChannelAndWatchLogLoaded(); List<Long> channelIdList = getChannelIdListSorted(); for (long channelId : channelIdList) { - assertEquals(Recommender.Evaluator.NOT_RECOMMENDED, + assertEqualScores(Recommender.Evaluator.NOT_RECOMMENDED, mEvaluator.evaluateChannel(channelId)); } } + @Test public void testMultiChannelsWithRandomWatchLogs() { addChannels(DEFAULT_NUMBER_OF_CHANNELS); addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, @@ -75,6 +83,7 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan assertChannelScoresValid(); } + @Test public void testMultiChannelsWithSimpleWatchLogs() { addChannels(DEFAULT_NUMBER_OF_CHANNELS); // For two channels which has ID x and y (x < y), the channel y is more watched @@ -99,6 +108,7 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan } } + @Test public void testTwoChannelsWithSameWatchDuration() { long channelOne = addChannel().getId(); long channelTwo = addChannel().getId(); @@ -112,6 +122,7 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan mEvaluator.evaluateChannel(channelTwo)); } + @Test public void testTwoChannelsWithDifferentWatchDuration() { long channelOne = addChannel().getId(); long channelTwo = addChannel().getId(); @@ -131,6 +142,7 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan assertTrue(mEvaluator.evaluateChannel(channelOne) > mEvaluator.evaluateChannel(channelTwo)); } + @Test public void testScoreIncreasesWithNewWatchLog() { long channelId = addChannel().getId(); addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, diff --git a/tests/unit/src/com/android/tv/recommendation/RecentChannelEvaluatorTest.java b/tests/unit/src/com/android/tv/recommendation/RecentChannelEvaluatorTest.java index 55a4e4ac..8f092238 100644 --- a/tests/unit/src/com/android/tv/recommendation/RecentChannelEvaluatorTest.java +++ b/tests/unit/src/com/android/tv/recommendation/RecentChannelEvaluatorTest.java @@ -16,8 +16,12 @@ package com.android.tv.recommendation; +import static org.junit.Assert.assertTrue; + import android.support.test.filters.SmallTest; +import org.junit.Test; + import java.util.HashMap; import java.util.List; import java.util.Map; @@ -40,14 +44,16 @@ public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelE return new RecentChannelEvaluator(); } + @Test public void testOneChannelWithNoWatchLog() { long channelId = addChannel().getId(); notifyChannelAndWatchLogLoaded(); - assertEquals(Recommender.Evaluator.NOT_RECOMMENDED, + assertEqualScores(Recommender.Evaluator.NOT_RECOMMENDED, mEvaluator.evaluateChannel(channelId)); } + @Test public void testOneChannelWithRandomWatchLogs() { addChannel(); addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, @@ -57,17 +63,19 @@ public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelE assertChannelScoresValid(); } + @Test public void testMultiChannelsWithNoWatchLog() { addChannels(DEFAULT_NUMBER_OF_CHANNELS); notifyChannelAndWatchLogLoaded(); List<Long> channelIdList = getChannelIdListSorted(); for (long channelId : channelIdList) { - assertEquals(Recommender.Evaluator.NOT_RECOMMENDED, + assertEqualScores(Recommender.Evaluator.NOT_RECOMMENDED, mEvaluator.evaluateChannel(channelId)); } } + @Test public void testMultiChannelsWithRandomWatchLogs() { addChannels(DEFAULT_NUMBER_OF_CHANNELS); addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, @@ -77,6 +85,7 @@ public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelE assertChannelScoresValid(); } + @Test public void testMultiChannelsWithSimpleWatchLogs() { addChannels(DEFAULT_NUMBER_OF_CHANNELS); // Every channel has one watch log with 1 hour. Also, for two channels @@ -99,6 +108,7 @@ public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelE } } + @Test public void testScoreIncreasesWithNewWatchLog() { addChannels(DEFAULT_NUMBER_OF_CHANNELS); addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, @@ -119,6 +129,7 @@ public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelE } } + @Test public void testScoreDecreasesWithIncrementOfWatchedLogUpdatedTime() { addChannels(DEFAULT_NUMBER_OF_CHANNELS); addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, diff --git a/tests/unit/src/com/android/tv/recommendation/RecommendationUtils.java b/tests/unit/src/com/android/tv/recommendation/RecommendationUtils.java index 4a613995..b00ed16b 100644 --- a/tests/unit/src/com/android/tv/recommendation/RecommendationUtils.java +++ b/tests/unit/src/com/android/tv/recommendation/RecommendationUtils.java @@ -34,7 +34,6 @@ import java.util.TreeMap; import java.util.concurrent.TimeUnit; public class RecommendationUtils { - private static final String TAG = "RecommendationUtils"; private static final long INVALID_CHANNEL_ID = -1; /** diff --git a/tests/unit/src/com/android/tv/recommendation/RecommenderTest.java b/tests/unit/src/com/android/tv/recommendation/RecommenderTest.java index 5270ffce..85524a82 100644 --- a/tests/unit/src/com/android/tv/recommendation/RecommenderTest.java +++ b/tests/unit/src/com/android/tv/recommendation/RecommenderTest.java @@ -16,14 +16,21 @@ package com.android.tv.recommendation; +import static android.support.test.InstrumentationRegistry.getContext; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import android.test.MoreAsserts; import com.android.tv.data.Channel; import com.android.tv.recommendation.RecommendationUtils.ChannelRecordSortedMapHelper; import com.android.tv.testing.Utils; +import org.junit.Before; +import org.junit.Test; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -34,7 +41,7 @@ import java.util.Map; import java.util.concurrent.TimeUnit; @SmallTest -public class RecommenderTest extends AndroidTestCase { +public class RecommenderTest { private static final int DEFAULT_NUMBER_OF_CHANNELS = 5; private static final long DEFAULT_WATCH_START_TIME_MS = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(2); @@ -72,16 +79,15 @@ public class RecommenderTest extends AndroidTestCase { private Channel mChannel_3; private Channel mChannel_4; - @Override - public void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() { mChannelRecordSortedMap = new ChannelRecordSortedMapHelper(getContext()); mDataManager = RecommendationUtils .createMockRecommendationDataManager(mChannelRecordSortedMap); mChannelRecordSortedMap.resetRandom(Utils.createTestRandom()); } + @Test public void testRecommendChannels_includeRecommendedOnly_allChannelsHaveNoScore() { createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); @@ -94,6 +100,7 @@ public class RecommenderTest extends AndroidTestCase { assertEquals(0, mRecommender.recommendChannels(5).size()); } + @Test public void testRecommendChannels_notIncludeRecommendedOnly_allChannelsHaveNoScore() { createRecommender(false, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); @@ -106,6 +113,7 @@ public class RecommenderTest extends AndroidTestCase { assertEquals(4, mRecommender.recommendChannels(5).size()); } + @Test public void testRecommendChannels_includeRecommendedOnly_allChannelsHaveScore() { createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); @@ -125,6 +133,7 @@ public class RecommenderTest extends AndroidTestCase { mChannel_4, mChannel_3, mChannel_2, mChannel_1); } + @Test public void testRecommendChannels_notIncludeRecommendedOnly_allChannelsHaveScore() { createRecommender(false, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); @@ -144,6 +153,7 @@ public class RecommenderTest extends AndroidTestCase { mChannel_4, mChannel_3, mChannel_2, mChannel_1); } + @Test public void testRecommendChannels_includeRecommendedOnly_fewChannelsHaveScore() { createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); @@ -163,6 +173,7 @@ public class RecommenderTest extends AndroidTestCase { mChannel_1, mChannel_2); } + @Test public void testRecommendChannels_notIncludeRecommendedOnly_fewChannelsHaveScore() { createRecommender(false, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); @@ -189,6 +200,7 @@ public class RecommenderTest extends AndroidTestCase { mChannel_1, mChannel_2); } + @Test public void testGetChannelSortKey_recommendAllChannels() { createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); @@ -203,6 +215,7 @@ public class RecommenderTest extends AndroidTestCase { assertSortKeyNotInvalid(channelList); } + @Test public void testGetChannelSortKey_recommendFewChannels() { // Test with recommending 3 channels. createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); @@ -221,6 +234,7 @@ public class RecommenderTest extends AndroidTestCase { assertSortKeyNotInvalid(channelList); } + @Test public void testListener_onRecommendationChanged() { createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); // FakeEvaluator doesn't recommend a channel with empty watch log. As every channel @@ -245,6 +259,7 @@ public class RecommenderTest extends AndroidTestCase { assertTrue(mOnRecommendationChanged); } + @Test public void testListener_onRecommenderReady() { createRecommender(true, new Runnable() { @Override diff --git a/tests/unit/src/com/android/tv/recommendation/RoutineWatchEvaluatorTest.java b/tests/unit/src/com/android/tv/recommendation/RoutineWatchEvaluatorTest.java index c9e21e9d..7b8e256d 100644 --- a/tests/unit/src/com/android/tv/recommendation/RoutineWatchEvaluatorTest.java +++ b/tests/unit/src/com/android/tv/recommendation/RoutineWatchEvaluatorTest.java @@ -16,12 +16,16 @@ package com.android.tv.recommendation; +import static org.junit.Assert.assertEquals; + import android.support.test.filters.SmallTest; import android.test.MoreAsserts; import com.android.tv.data.Program; import com.android.tv.recommendation.RoutineWatchEvaluator.ProgramTime; +import org.junit.Test; + import java.util.Arrays; import java.util.Calendar; import java.util.List; @@ -61,6 +65,7 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva return new RoutineWatchEvaluator(); } + @Test public void testSplitTextToWords() { assertSplitTextToWords(""); assertSplitTextToWords("Google", "Google"); @@ -71,6 +76,7 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva assertSplitTextToWords("A.I.", "A.I"); } + @Test public void testCalculateMaximumMatchedWordSequenceLength() { assertMaximumMatchedWordSequenceLength(0, "", "Google"); assertMaximumMatchedWordSequenceLength(2, "The Big Bang Theory", "Big Bang"); @@ -82,25 +88,29 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva assertMaximumMatchedWordSequenceLength(0, "Dexter", "Friends"); } + @Test public void testCalculateTitleMatchScore_empty() { - assertEquals(0.0, RoutineWatchEvaluator.calculateTitleMatchScore("", "")); - assertEquals(0.0, RoutineWatchEvaluator.calculateTitleMatchScore("foo", "")); - assertEquals(0.0, RoutineWatchEvaluator.calculateTitleMatchScore("", "foo")); + assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore("", "")); + assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore("foo", "")); + assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore("", "foo")); } + @Test public void testCalculateTitleMatchScore_spaces() { - assertEquals(0.0, RoutineWatchEvaluator.calculateTitleMatchScore(" ", " ")); - assertEquals(0.0, RoutineWatchEvaluator.calculateTitleMatchScore("foo", " ")); - assertEquals(0.0, RoutineWatchEvaluator.calculateTitleMatchScore(" ", "foo")); + assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore(" ", " ")); + assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore("foo", " ")); + assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore(" ", "foo")); } + @Test public void testCalculateTitleMatchScore_null() { - assertEquals(0.0, RoutineWatchEvaluator.calculateTitleMatchScore(null, null)); - assertEquals(0.0, RoutineWatchEvaluator.calculateTitleMatchScore("foo", null)); - assertEquals(0.0, RoutineWatchEvaluator.calculateTitleMatchScore(null, "foo")); + assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore(null, null)); + assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore("foo", null)); + assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore(null, "foo")); } + @Test public void testCalculateTitleMatchScore_longerMatchIsBetter() { String base = "foo bar baz"; assertInOrder( @@ -110,6 +120,7 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva score(base, "foo bar baz")); } + @Test public void testProgramTime_createFromProgram() { Calendar time = Calendar.getInstance(); int todayDayOfWeek = time.get(Calendar.DAY_OF_WEEK); @@ -149,6 +160,7 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva programTimeToday1800_3600); } + @Test public void testCalculateOverlappedIntervalScore() { // Today 21:00 - 24:00. ProgramTime programTimeToday2100_2400 = ProgramTime.createFromProgram( @@ -179,6 +191,7 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva programTimeTomorrow2000_2300); } + @Test public void testGetTimeOfDayInSec() { // Time was set as 00:00:00. So, getTimeOfDay must returns 0 (= 0 * 60 * 60 + 0 * 60 + 0). assertEquals("TimeOfDayInSec", hourMinuteToSec(0, 0), @@ -222,9 +235,9 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva score *= RoutineWatchEvaluator.MULTIPLIER_FOR_UNMATCHED_DAY_OF_WEEK; } // Two tests for testing commutative law. - assertEquals("OverlappedIntervalScore", score, + assertEqualScores("OverlappedIntervalScore", score, RoutineWatchEvaluator.calculateOverlappedIntervalScore(t1, t2)); - assertEquals("OverlappedIntervalScore", score, + assertEqualScores("OverlappedIntervalScore", score, RoutineWatchEvaluator.calculateOverlappedIntervalScore(t2, t1)); } diff --git a/tests/unit/src/com/android/tv/search/LocalSearchProviderTest.java b/tests/unit/src/com/android/tv/search/LocalSearchProviderTest.java new file mode 100644 index 00000000..b0d342c6 --- /dev/null +++ b/tests/unit/src/com/android/tv/search/LocalSearchProviderTest.java @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2017 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.tv.search; + +import static android.support.test.InstrumentationRegistry.getTargetContext; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.verify; + +import android.app.SearchManager; +import android.database.Cursor; +import android.net.Uri; +import android.support.test.filters.SmallTest; +import android.test.ProviderTestCase2; + +import com.android.tv.ApplicationSingletons; +import com.android.tv.TvApplication; +import com.android.tv.perf.PerformanceMonitor; +import com.android.tv.util.MockApplicationSingletons; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +/** Unit test for {@link LocalSearchProvider}. */ +@SmallTest +public class LocalSearchProviderTest extends ProviderTestCase2<LocalSearchProvider> { + private static final String AUTHORITY = "com.android.tv.search"; + private static final String KEYWORD = "keyword"; + private static final Uri BASE_SEARCH_URI = Uri.parse("content://" + AUTHORITY + "/" + + SearchManager.SUGGEST_URI_PATH_QUERY + "/" + KEYWORD); + private static final Uri WRONG_SERACH_URI = Uri.parse("content://" + AUTHORITY + "/wrong_path/" + + KEYWORD); + + private ApplicationSingletons mOldAppSingletons; + MockApplicationSingletons mMockAppSingletons; + @Mock PerformanceMonitor mMockPerformanceMointor; + @Mock SearchInterface mMockSearchInterface; + + public LocalSearchProviderTest() { + super(LocalSearchProvider.class, AUTHORITY); + } + + @Before + @Override + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + setContext(getTargetContext()); + mOldAppSingletons = TvApplication.sAppSingletons; + mMockAppSingletons = new MockApplicationSingletons(getTargetContext()); + mMockAppSingletons.setPerformanceMonitor(mMockPerformanceMointor); + TvApplication.sAppSingletons = mMockAppSingletons; + super.setUp(); + getProvider().setSearchInterface(mMockSearchInterface); + } + + @After + @Override + public void tearDown() throws Exception { + TvApplication.sAppSingletons = mOldAppSingletons; + super.tearDown(); + } + + @Test + public void testQuery_normalUri() { + verifyQueryWithArguments(null, null); + verifyQueryWithArguments(1, null); + verifyQueryWithArguments(null, 1); + verifyQueryWithArguments(1, 1); + } + + @Test + public void testQuery_invalidUri() { + try (Cursor c = getProvider().query(WRONG_SERACH_URI, null, null, null, null)) { + fail("Query with invalid URI should fail."); + } catch (IllegalArgumentException e) { + // Success. + } + } + + @Test + public void testQuery_invalidLimit() { + verifyQueryWithArguments(-1, null); + } + + @Test + public void testQuery_invalidAction() { + verifyQueryWithArguments(null, SearchInterface.ACTION_TYPE_START - 1); + verifyQueryWithArguments(null, SearchInterface.ACTION_TYPE_END + 1); + } + + private void verifyQueryWithArguments(Integer limit, Integer action) { + Uri uri = BASE_SEARCH_URI; + if (limit != null || action != null) { + Uri.Builder builder = uri.buildUpon(); + if (limit != null) { + builder.appendQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT, + limit.toString()); + } + if (action != null) { + builder.appendQueryParameter(LocalSearchProvider.SUGGEST_PARAMETER_ACTION, + action.toString()); + } + uri = builder.build(); + } + try (Cursor c = getProvider().query(uri, null, null, null, null)) { + // Do nothing. + } + int expectedLimit = limit == null || limit <= 0 ? + LocalSearchProvider.DEFAULT_SEARCH_LIMIT : limit; + int expectedAction = (action == null || action < SearchInterface.ACTION_TYPE_START + || action > SearchInterface.ACTION_TYPE_END) ? + LocalSearchProvider.DEFAULT_SEARCH_ACTION : action; + verify(mMockSearchInterface).search(KEYWORD, expectedLimit, expectedAction); + clearInvocations(mMockSearchInterface); + } +} diff --git a/tests/unit/src/com/android/tv/tests/TvActivityTest.java b/tests/unit/src/com/android/tv/tests/TvActivityTest.java index 3479785f..aa33f770 100644 --- a/tests/unit/src/com/android/tv/tests/TvActivityTest.java +++ b/tests/unit/src/com/android/tv/tests/TvActivityTest.java @@ -16,19 +16,28 @@ package com.android.tv.tests; +import static android.support.test.InstrumentationRegistry.getTargetContext; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import android.support.test.filters.MediumTest; -import android.test.ActivityInstrumentationTestCase2; +import android.support.test.rule.ActivityTestRule; import com.android.tv.TvActivity; +import com.android.tv.testing.Utils; -@MediumTest -public class TvActivityTest extends ActivityInstrumentationTestCase2<TvActivity> { +import org.junit.Rule; +import org.junit.Test; - public TvActivityTest() { - super(TvActivity.class); - } +@MediumTest +public class TvActivityTest { + @Rule + public ActivityTestRule<TvActivity> mActivityTestRule = + new ActivityTestRule<>(TvActivity.class, false, false); + @Test public void testLifeCycle() { - getActivity(); + assertTrue("TvActivity should be enabled.", Utils.isTvActivityEnabled(getTargetContext())); + assertNotNull(mActivityTestRule.launchActivity(null)); } } diff --git a/tests/unit/src/com/android/tv/util/ImageCacheTest.java b/tests/unit/src/com/android/tv/util/ImageCacheTest.java index e185d5f1..a76194b8 100644 --- a/tests/unit/src/com/android/tv/util/ImageCacheTest.java +++ b/tests/unit/src/com/android/tv/util/ImageCacheTest.java @@ -17,19 +17,21 @@ package com.android.tv.util; import static com.android.tv.util.BitmapUtils.createScaledBitmapInfo; +import static org.junit.Assert.assertSame; import android.graphics.Bitmap; import android.support.test.filters.MediumTest; import com.android.tv.util.BitmapUtils.ScaledBitmapInfo; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; /** * Tests for {@link ImageCache}. */ @MediumTest -public class ImageCacheTest extends TestCase { +public class ImageCacheTest { private static final Bitmap ORIG = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); private static final String KEY = "same"; @@ -40,14 +42,14 @@ public class ImageCacheTest extends TestCase { private ImageCache mImageCache; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { mImageCache = ImageCache.newInstance(0.1f); } //TODO: Empty the cache in the setup. Try using @VisibleForTesting + @Test public void testPutIfLarger_smaller() throws Exception { mImageCache.putIfNeeded( INFO_50); @@ -57,6 +59,7 @@ public class ImageCacheTest extends TestCase { assertSame("after", INFO_50, mImageCache.get(KEY)); } + @Test public void testPutIfLarger_larger() throws Exception { mImageCache.putIfNeeded( INFO_50); assertSame("before", INFO_50, mImageCache.get(KEY)); @@ -65,6 +68,7 @@ public class ImageCacheTest extends TestCase { assertSame("after", INFO_100, mImageCache.get(KEY)); } + @Test public void testPutIfLarger_alreadyMax() throws Exception { mImageCache.putIfNeeded( INFO_100); diff --git a/tests/unit/src/com/android/tv/util/MockApplicationSingletons.java b/tests/unit/src/com/android/tv/util/MockApplicationSingletons.java new file mode 100644 index 00000000..4cfc7f8a --- /dev/null +++ b/tests/unit/src/com/android/tv/util/MockApplicationSingletons.java @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2017 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.tv.util; + +import android.content.Context; + +import com.android.tv.ApplicationSingletons; +import com.android.tv.InputSessionManager; +import com.android.tv.MainActivityWrapper; +import com.android.tv.TvApplication; +import com.android.tv.analytics.Analytics; +import com.android.tv.analytics.Tracker; +import com.android.tv.config.RemoteConfig; +import com.android.tv.data.ChannelDataManager; +import com.android.tv.data.PreviewDataManager; +import com.android.tv.data.ProgramDataManager; +import com.android.tv.dvr.DvrDataManager; +import com.android.tv.dvr.DvrManager; +import com.android.tv.dvr.DvrScheduleManager; +import com.android.tv.dvr.DvrStorageStatusManager; +import com.android.tv.dvr.DvrWatchedPositionManager; +import com.android.tv.dvr.recorder.RecordingScheduler; +import com.android.tv.perf.PerformanceMonitor; + +/** + * Mock {@link ApplicationSingletons} class. + */ +public class MockApplicationSingletons implements ApplicationSingletons { + private final TvApplication mApp; + + private PerformanceMonitor mPerformanceMonitor; + + public MockApplicationSingletons(Context context) { + mApp = (TvApplication) context.getApplicationContext(); + } + + @Override + public Analytics getAnalytics() { + return mApp.getAnalytics(); + } + + @Override + public ChannelDataManager getChannelDataManager() { + return mApp.getChannelDataManager(); + } + + @Override + public boolean isChannelDataManagerLoadFinished() { + return mApp.isChannelDataManagerLoadFinished(); + } + + @Override + public ProgramDataManager getProgramDataManager() { + return mApp.getProgramDataManager(); + } + + @Override + public boolean isProgramDataManagerCurrentProgramsLoadFinished() { + return mApp.isProgramDataManagerCurrentProgramsLoadFinished(); + } + + @Override + public PreviewDataManager getPreviewDataManager() { + return mApp.getPreviewDataManager(); + } + + @Override + public DvrDataManager getDvrDataManager() { + return mApp.getDvrDataManager(); + } + + @Override + public DvrStorageStatusManager getDvrStorageStatusManager() { + return mApp.getDvrStorageStatusManager(); + } + + @Override + public DvrScheduleManager getDvrScheduleManager() { + return mApp.getDvrScheduleManager(); + } + + @Override + public DvrManager getDvrManager() { + return mApp.getDvrManager(); + } + + @Override + public RecordingScheduler getRecordingScheduler() { + return mApp.getRecordingScheduler(); + } + + @Override + public DvrWatchedPositionManager getDvrWatchedPositionManager() { + return mApp.getDvrWatchedPositionManager(); + } + + @Override + public InputSessionManager getInputSessionManager() { + return mApp.getInputSessionManager(); + } + + @Override + public Tracker getTracker() { + return mApp.getTracker(); + } + + @Override + public TvInputManagerHelper getTvInputManagerHelper() { + return mApp.getTvInputManagerHelper(); + } + + @Override + public MainActivityWrapper getMainActivityWrapper() { + return mApp.getMainActivityWrapper(); + } + + @Override + public AccountHelper getAccountHelper() { + return mApp.getAccountHelper(); + } + + @Override + public RemoteConfig getRemoteConfig() { + return mApp.getRemoteConfig(); + } + + @Override + public boolean isRunningInMainProcess() { + return mApp.isRunningInMainProcess(); + } + + @Override + public PerformanceMonitor getPerformanceMonitor() { + return mPerformanceMonitor != null ? mPerformanceMonitor : mApp.getPerformanceMonitor(); + } + + public void setPerformanceMonitor(PerformanceMonitor performanceMonitor) { + mPerformanceMonitor = performanceMonitor; + } +} diff --git a/tests/unit/src/com/android/tv/util/MultiLongSparseArrayTest.java b/tests/unit/src/com/android/tv/util/MultiLongSparseArrayTest.java index fe094fb3..7335f207 100644 --- a/tests/unit/src/com/android/tv/util/MultiLongSparseArrayTest.java +++ b/tests/unit/src/com/android/tv/util/MultiLongSparseArrayTest.java @@ -16,10 +16,13 @@ package com.android.tv.util; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + import android.support.test.filters.SmallTest; import android.test.MoreAsserts; -import junit.framework.TestCase; +import org.junit.Test; import java.util.Collections; @@ -27,19 +30,21 @@ import java.util.Collections; * Tests for {@link MultiLongSparseArray}. */ @SmallTest -public class MultiLongSparseArrayTest extends TestCase { - +public class MultiLongSparseArrayTest { + @Test public void testEmpty() { MultiLongSparseArray<String> sparseArray = new MultiLongSparseArray<>(); assertSame(Collections.EMPTY_SET, sparseArray.get(0)); } + @Test public void testOneElement() { MultiLongSparseArray<String> sparseArray = new MultiLongSparseArray<>(); sparseArray.put(0, "foo"); MoreAsserts.assertContentsInAnyOrder(sparseArray.get(0), "foo"); } + @Test public void testTwoElements() { MultiLongSparseArray<String> sparseArray = new MultiLongSparseArray<>(); sparseArray.put(0, "foo"); @@ -48,6 +53,7 @@ public class MultiLongSparseArrayTest extends TestCase { } + @Test public void testClearEmptyCache() { MultiLongSparseArray<String> sparseArray = new MultiLongSparseArray<>(); sparseArray.clearEmptyCache(); @@ -59,6 +65,7 @@ public class MultiLongSparseArrayTest extends TestCase { assertEquals(0, sparseArray.getEmptyCacheSize()); } + @Test public void testMaxEmptyCacheSize() { MultiLongSparseArray<String> sparseArray = new MultiLongSparseArray<>(); sparseArray.clearEmptyCache(); @@ -75,6 +82,7 @@ public class MultiLongSparseArrayTest extends TestCase { assertEquals(0, sparseArray.getEmptyCacheSize()); } + @Test public void testReuseEmptySets() { MultiLongSparseArray<String> sparseArray = new MultiLongSparseArray<>(); sparseArray.clearEmptyCache(); diff --git a/tests/unit/src/com/android/tv/util/ScaledBitmapInfoTest.java b/tests/unit/src/com/android/tv/util/ScaledBitmapInfoTest.java index 36d25a10..2714e2e9 100644 --- a/tests/unit/src/com/android/tv/util/ScaledBitmapInfoTest.java +++ b/tests/unit/src/com/android/tv/util/ScaledBitmapInfoTest.java @@ -1,24 +1,29 @@ package com.android.tv.util; +import static org.junit.Assert.assertEquals; + import android.graphics.Bitmap; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import com.android.tv.util.BitmapUtils.ScaledBitmapInfo; +import org.junit.Test; + /** * Tests for {@link ScaledBitmapInfo}. */ @SmallTest -public class ScaledBitmapInfoTest extends AndroidTestCase { +public class ScaledBitmapInfoTest { private static final Bitmap B80x100 = Bitmap.createBitmap(80, 100, Bitmap.Config.RGB_565); private static final Bitmap B960x1440 = Bitmap.createBitmap(960, 1440, Bitmap.Config.RGB_565); + @Test public void testSize_B100x100to50x50() { ScaledBitmapInfo actual = BitmapUtils.createScaledBitmapInfo("B80x100", B80x100, 50, 50); assertScaledBitmapSize(2, 40, 50, actual); } + @Test public void testNeedsToReload_B100x100to50x50() { ScaledBitmapInfo actual = BitmapUtils.createScaledBitmapInfo("B80x100", B80x100, 50, 50); assertNeedsToReload(false, actual, 25, 25); @@ -31,6 +36,7 @@ public class ScaledBitmapInfoTest extends AndroidTestCase { /** * Reproduces <a href="http://b/20488453">b/20488453</a>. */ + @Test public void testBug20488453() { ScaledBitmapInfo actual = BitmapUtils .createScaledBitmapInfo("B960x1440", B960x1440, 284, 160); diff --git a/tests/unit/src/com/android/tv/util/TestUtils.java b/tests/unit/src/com/android/tv/util/TestUtils.java index e3bda138..d200733d 100644 --- a/tests/unit/src/com/android/tv/util/TestUtils.java +++ b/tests/unit/src/com/android/tv/util/TestUtils.java @@ -21,8 +21,8 @@ import android.content.pm.ServiceInfo; import android.graphics.drawable.Icon; import android.hardware.hdmi.HdmiDeviceInfo; import android.media.tv.TvInputInfo; +import android.os.Build; import android.os.Bundle; -import android.support.v4.os.BuildCompat; import java.lang.reflect.Constructor; @@ -47,7 +47,11 @@ public class TestUtils { int type, boolean isHardwareInput, boolean canRecord, int tunerCount) throws Exception { // Create a mock TvInputInfo by using private constructor // Note that mockito doesn't support mock/spy on final object. - if (BuildCompat.isAtLeastN()) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + return createTvInputInfoForO(service, id, parentId, type, isHardwareInput, canRecord, + tunerCount); + + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return createTvInputInfoForNyc(service, id, parentId, type, isHardwareInput, canRecord, tunerCount); } @@ -57,6 +61,24 @@ public class TestUtils { /** * private TvInputInfo(ResolveInfo service, String id, int type, boolean isHardwareInput, * CharSequence label, int labelResId, Icon icon, Icon iconStandby, Icon iconDisconnected, + * String setupActivity, boolean canRecord, int tunerCount, HdmiDeviceInfo hdmiDeviceInfo, + * boolean isConnectedToHdmiSwitch, String parentId, Bundle extras) { + */ + private static TvInputInfo createTvInputInfoForO(ResolveInfo service, String id, + String parentId, int type, boolean isHardwareInput, boolean canRecord, int tunerCount) + throws Exception { + Constructor<TvInputInfo> constructor = TvInputInfo.class.getDeclaredConstructor( + ResolveInfo.class, String.class, int.class, boolean.class, CharSequence.class, + int.class, Icon.class, Icon.class, Icon.class, String.class, boolean.class, + int.class, HdmiDeviceInfo.class, boolean.class, String.class, Bundle.class); + constructor.setAccessible(true); + return constructor.newInstance(service, id, type, isHardwareInput, null, 0, null, null, + null, null, canRecord, tunerCount, null, false, parentId, null); + } + + /** + * private TvInputInfo(ResolveInfo service, String id, int type, boolean isHardwareInput, + * CharSequence label, int labelResId, Icon icon, Icon iconStandby, Icon iconDisconnected, * String setupActivity, String settingsActivity, boolean canRecord, int tunerCount, * HdmiDeviceInfo hdmiDeviceInfo, boolean isConnectedToHdmiSwitch, String parentId, * Bundle extras) { @@ -87,6 +109,7 @@ public class TestUtils { resolveInfo.serviceInfo = new ServiceInfo(); resolveInfo.serviceInfo.packageName = packageName; resolveInfo.serviceInfo.name = name; + resolveInfo.serviceInfo.metaData = new Bundle(); return resolveInfo; } } diff --git a/tests/unit/src/com/android/tv/util/TvInputManagerHelperTest.java b/tests/unit/src/com/android/tv/util/TvInputManagerHelperTest.java index ba1e0b0b..404ee5d3 100644 --- a/tests/unit/src/com/android/tv/util/TvInputManagerHelperTest.java +++ b/tests/unit/src/com/android/tv/util/TvInputManagerHelperTest.java @@ -16,58 +16,155 @@ package com.android.tv.util; +import static android.support.test.InstrumentationRegistry.getContext; + import android.content.pm.ResolveInfo; import android.media.tv.TvInputInfo; import android.support.test.filters.SmallTest; -import android.support.test.filters.Suppress; -import android.test.AndroidTestCase; import com.android.tv.testing.ComparatorTester; +import org.junit.Test; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.util.LinkedHashMap; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; /** * Test for {@link TvInputManagerHelper} */ @SmallTest -public class TvInputManagerHelperTest extends AndroidTestCase { - public void testComparator() throws Exception { - final LinkedHashMap<String, Boolean> INPUT_ID_TO_PARTNER_INPUT = new LinkedHashMap<>(); - INPUT_ID_TO_PARTNER_INPUT.put("2_partner_input", true); - INPUT_ID_TO_PARTNER_INPUT.put("3_partner_input", true); - INPUT_ID_TO_PARTNER_INPUT.put("1_3rd_party_input", false); - INPUT_ID_TO_PARTNER_INPUT.put("4_3rd_party_input", false); +public class TvInputManagerHelperTest { + final HashMap<String, TvInputInfoWrapper> TEST_INPUT_MAP = new HashMap<>(); + + @Test + public void testComparatorInternal() { + ResolveInfo resolveInfo = TestUtils.createResolveInfo("test", "test"); + + List<TvInputInfo> inputs = new ArrayList<>(); + inputs.add(createTvInputInfo(resolveInfo, "2_partner_input", null, 0, false, + "2_partner_input", null, true)); + inputs.add(createTvInputInfo(resolveInfo, "3_partner_input", null, 0, false, + "3_partner_input", null, true)); + inputs.add(createTvInputInfo(resolveInfo, "1_3rd_party_input", null, 0, false, + "1_3rd_party_input", null, false)); + inputs.add(createTvInputInfo(resolveInfo, "4_3rd_party_input", null, 0, false, + "4_3rd_party_input", null, false)); + + TvInputManagerHelper manager = createMockTvInputManager(); + + ComparatorTester<TvInputInfo> comparatorTester = ComparatorTester.withoutEqualsTest( + new TvInputManagerHelper.InputComparatorInternal(manager)); + for (TvInputInfo input : inputs) { + comparatorTester.addComparableGroup(input); + } + comparatorTester.test(); + } + + @Test + public void testHardwareInputComparatorHdmi() { + ResolveInfo resolveInfo = TestUtils.createResolveInfo("test", "test"); + + TvInputInfo hdmi1 = createTvInputInfo(resolveInfo, "HDMI1", null, TvInputInfo.TYPE_HDMI, + true, "HDMI1", null, false); + TvInputInfo hdmi2 = createTvInputInfo(resolveInfo, "HDMI2", null, TvInputInfo.TYPE_HDMI, + true, "HDMI2", "DVD", false); + TvInputInfo hdmi3 = createTvInputInfo(resolveInfo, "HDMI3", null, TvInputInfo.TYPE_HDMI, + true, "HDMI3", "Cable", false); + TvInputInfo hdmi4 = createTvInputInfo(resolveInfo, "HDMI4", null, TvInputInfo.TYPE_HDMI, + true, "HDMI4", null, false); + + TvInputManagerHelper manager = createMockTvInputManager(); + + ComparatorTester<TvInputInfo> comparatorTester = ComparatorTester.withoutEqualsTest( + new TvInputManagerHelper.HardwareInputComparator(getContext(), manager)); + comparatorTester.addComparableGroup(hdmi3) + .addComparableGroup(hdmi2) + .addComparableGroup(hdmi1) + .addComparableGroup(hdmi4) + .test(); + } + + @Test + public void testHardwareInputComparatorCec() { + ResolveInfo resolveInfo = TestUtils.createResolveInfo("test", "test"); + + TvInputInfo hdmi1 = createTvInputInfo(resolveInfo, "HDMI1", null, TvInputInfo.TYPE_HDMI, + true, "HDMI1", null, false); + TvInputInfo hdmi2 = createTvInputInfo(resolveInfo, "HDMI2", null, TvInputInfo.TYPE_HDMI, + true, "HDMI2", null, false); + TvInputInfo cec1 = createTvInputInfo(resolveInfo, "2_cec", "HDMI1", TvInputInfo.TYPE_HDMI, + true, "2_cec", null, false); + TvInputInfo cec2 = createTvInputInfo(resolveInfo, "1_cec", "HDMI2", TvInputInfo.TYPE_HDMI, + true, "1_cec", null, false); + + TvInputManagerHelper manager = createMockTvInputManager(); + + ComparatorTester<TvInputInfo> comparatorTester = ComparatorTester.withoutEqualsTest( + new TvInputManagerHelper.HardwareInputComparator(getContext(), manager)); + comparatorTester.addComparableGroup(cec1) + .addComparableGroup(cec2) + .test(); + } + + private TvInputManagerHelper createMockTvInputManager() { TvInputManagerHelper manager = Mockito.mock(TvInputManagerHelper.class); Mockito.doAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { TvInputInfo info = (TvInputInfo) invocation.getArguments()[0]; - return INPUT_ID_TO_PARTNER_INPUT.get(info.getId()); + return TEST_INPUT_MAP.get(info.getId()).mIsPartnerInput; } }).when(manager).isPartnerInput(Mockito.<TvInputInfo>any()); Mockito.doAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { TvInputInfo info = (TvInputInfo) invocation.getArguments()[0]; - return info.getId(); + return TEST_INPUT_MAP.get(info.getId()).mLabel; } }).when(manager).loadLabel(Mockito.<TvInputInfo>any()); + Mockito.doAnswer(new Answer<String>() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + TvInputInfo info = (TvInputInfo) invocation.getArguments()[0]; + return TEST_INPUT_MAP.get(info.getId()).mCustomLabel; + } + }).when(manager).loadCustomLabel(Mockito.<TvInputInfo>any()); + Mockito.doAnswer(new Answer<TvInputInfo>() { + @Override + public TvInputInfo answer(InvocationOnMock invocation) throws Throwable { + String inputId = (String) invocation.getArguments()[0]; + TvInputInfoWrapper inputWrapper = TEST_INPUT_MAP.get(inputId); + return inputWrapper == null ? null : inputWrapper.mInput; + } + }).when(manager).getTvInputInfo(Mockito.<String>any()); + return manager; + } - ComparatorTester<TvInputInfo> comparatorTester = - ComparatorTester.withoutEqualsTest( - new TvInputManagerHelper.TvInputInfoComparator(manager)); - ResolveInfo resolveInfo1 = TestUtils.createResolveInfo("1_test", "1_test"); - ResolveInfo resolveInfo2 = TestUtils.createResolveInfo("2_test", "2_test"); - for (String inputId : INPUT_ID_TO_PARTNER_INPUT.keySet()) { - TvInputInfo info1 = TestUtils.createTvInputInfo(resolveInfo1, inputId, null, 0, false); - TvInputInfo info2 = TestUtils.createTvInputInfo(resolveInfo2, inputId, null, 0, false); - comparatorTester.addComparableGroup(info1, info2); + private TvInputInfo createTvInputInfo(ResolveInfo service, String id, + String parentId, int type, boolean isHardwareInput, String label, String customLabel, + boolean isPartnerInput) { + TvInputInfoWrapper inputWrapper = new TvInputInfoWrapper(); + try { + inputWrapper.mInput = + TestUtils.createTvInputInfo(service, id, parentId, type, isHardwareInput); + } catch (Exception e) { } - comparatorTester.test(); + inputWrapper.mLabel = label; + inputWrapper.mIsPartnerInput = isPartnerInput; + inputWrapper.mCustomLabel = customLabel; + TEST_INPUT_MAP.put(id, inputWrapper); + return inputWrapper.mInput; + } + + private static class TvInputInfoWrapper { + TvInputInfo mInput; + String mLabel; + String mCustomLabel; + boolean mIsPartnerInput; } } diff --git a/tests/unit/src/com/android/tv/util/TvTrackInfoUtilsTest.java b/tests/unit/src/com/android/tv/util/TvTrackInfoUtilsTest.java index 9600fc0b..4512bb7d 100644 --- a/tests/unit/src/com/android/tv/util/TvTrackInfoUtilsTest.java +++ b/tests/unit/src/com/android/tv/util/TvTrackInfoUtilsTest.java @@ -16,13 +16,14 @@ package com.android.tv.util; import static com.android.tv.util.TvTrackInfoUtils.getBestTrackInfo; +import static org.junit.Assert.assertEquals; import android.media.tv.TvTrackInfo; import android.support.test.filters.SmallTest; import com.android.tv.testing.ComparatorTester; -import junit.framework.TestCase; +import org.junit.Test; import java.util.Arrays; import java.util.Collections; @@ -33,8 +34,7 @@ import java.util.List; * Tests for {@link com.android.tv.util.TvTrackInfoUtils}. */ @SmallTest -public class TvTrackInfoUtilsTest extends TestCase { - +public class TvTrackInfoUtilsTest { private static final String UN_MATCHED_ID = "no matching ID"; private static final TvTrackInfo INFO_1_EN_1 = create("1", "en", 1); @@ -59,46 +59,55 @@ public class TvTrackInfoUtilsTest extends TestCase { private static final List<TvTrackInfo> NULL_LANGUAGE_TRACKS = Arrays.asList(INFO_4_NULL_2, INFO_5_NULL_6); + @Test public void testGetBestTrackInfo_empty() { TvTrackInfo result = getBestTrackInfo(Collections.emptyList(), UN_MATCHED_ID, "en", 1); assertEquals("best track ", null, result); } + @Test public void testGetBestTrackInfo_exactMatch() { TvTrackInfo result = getBestTrackInfo(ALL, "1", "en", 1); assertEquals("best track ", INFO_1_EN_1, result); } + @Test public void testGetBestTrackInfo_langAndChannelCountMatch() { TvTrackInfo result = getBestTrackInfo(ALL, UN_MATCHED_ID, "en", 5); assertEquals("best track ", INFO_2_EN_5, result); } + @Test public void testGetBestTrackInfo_languageOnlyMatch() { TvTrackInfo result = getBestTrackInfo(ALL, UN_MATCHED_ID, "fr", 1); assertEquals("best track ", INFO_3_FR_8, result); } + @Test public void testGetBestTrackInfo_channelCountOnlyMatchWithNullLanguage() { TvTrackInfo result = getBestTrackInfo(ALL, UN_MATCHED_ID, null, 8); assertEquals("best track ", INFO_3_FR_8, result); } + @Test public void testGetBestTrackInfo_noMatches() { TvTrackInfo result = getBestTrackInfo(ALL, UN_MATCHED_ID, "kr", 1); assertEquals("best track ", INFO_1_EN_1, result); } + @Test public void testGetBestTrackInfo_noMatchesWithNullLanguage() { TvTrackInfo result = getBestTrackInfo(ALL, UN_MATCHED_ID, null, 0); assertEquals("best track ", INFO_1_EN_1, result); } + @Test public void testGetBestTrackInfo_channelCountAndIdMatch() { TvTrackInfo result = getBestTrackInfo(NULL_LANGUAGE_TRACKS, "5", null, 6); assertEquals("best track ", INFO_5_NULL_6, result); } + @Test public void testComparator() { Comparator<TvTrackInfo> comparator = TvTrackInfoUtils.createComparator("1", "en", 1); ComparatorTester.withoutEqualsTest(comparator) diff --git a/tests/unit/src/com/android/tv/util/UtilsTest_GetDurationString.java b/tests/unit/src/com/android/tv/util/UtilsTest_GetDurationString.java index 9dfb992e..e61802f5 100644 --- a/tests/unit/src/com/android/tv/util/UtilsTest_GetDurationString.java +++ b/tests/unit/src/com/android/tv/util/UtilsTest_GetDurationString.java @@ -15,10 +15,16 @@ */ package com.android.tv.util; +import static android.support.test.InstrumentationRegistry.getContext; +import static org.junit.Assert.assertEquals; + import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; import android.text.format.DateUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; @@ -32,7 +38,7 @@ import java.util.Locale; * and it should be defined in TV app, not this test. */ @SmallTest -public class UtilsTest_GetDurationString extends AndroidTestCase { +public class UtilsTest_GetDurationString { // TODO: Mock Context so we can specify current time and locale for test. private Locale mLocale; private static final long DATE_THIS_YEAR_2_1_MS = getFebOfThisYearInMillis(1, 0, 0); @@ -40,14 +46,19 @@ public class UtilsTest_GetDurationString extends AndroidTestCase { // All possible list for a parameter to test parameter independent result. private static final boolean[] PARAM_USE_SHORT_FORMAT = {false, true}; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { // Set locale to US mLocale = Locale.getDefault(); Locale.setDefault(Locale.US); } + @After + public void tearDown() { + // Revive system locale. + Locale.setDefault(mLocale); + } + /** * Return time in millis assuming that whose year is this year and month is Jan. */ @@ -76,6 +87,7 @@ public class UtilsTest_GetDurationString extends AndroidTestCase { return new GregorianCalendar().get(GregorianCalendar.YEAR); } + @Test public void testSameDateAndTime() { assertEquals("3:00 AM", Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, getFebOfThisYearInMillis(1, 3), getFebOfThisYearInMillis(1, 3), false, @@ -85,6 +97,7 @@ public class UtilsTest_GetDurationString extends AndroidTestCase { DateUtils.FORMAT_24HOUR)); } + @Test public void testDurationWithinToday() { assertEquals("12:00 – 3:00 AM", Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, DATE_THIS_YEAR_2_1_MS, @@ -96,6 +109,7 @@ public class UtilsTest_GetDurationString extends AndroidTestCase { DateUtils.FORMAT_24HOUR)); } + @Test public void testDurationFromYesterdayToToday() { assertEquals("Jan 31, 3:00 AM – Feb 1, 4:00 AM", Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, @@ -115,6 +129,7 @@ public class UtilsTest_GetDurationString extends AndroidTestCase { true, DateUtils.FORMAT_24HOUR)); } + @Test public void testDurationFromTodayToTomorrow() { assertEquals("Feb 1, 3:00 AM – Feb 2, 4:00 AM", Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, @@ -154,6 +169,7 @@ public class UtilsTest_GetDurationString extends AndroidTestCase { DateUtils.FORMAT_24HOUR)); } + @Test public void testDurationWithinTomorrow() { assertEquals("Feb 2, 2:00 – 4:00 AM", Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, @@ -173,6 +189,7 @@ public class UtilsTest_GetDurationString extends AndroidTestCase { DateUtils.FORMAT_24HOUR)); } + @Test public void testStartOfDay() { assertEquals("12:00 – 1:00 AM", Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, DATE_THIS_YEAR_2_1_MS, @@ -201,6 +218,7 @@ public class UtilsTest_GetDurationString extends AndroidTestCase { DateUtils.FORMAT_24HOUR)); } + @Test public void testEndOfDay() { for (boolean useShortFormat : PARAM_USE_SHORT_FORMAT) { assertEquals("11:00 PM – 12:00 AM", @@ -241,6 +259,7 @@ public class UtilsTest_GetDurationString extends AndroidTestCase { DateUtils.FORMAT_24HOUR)); } + @Test public void testMidnight() { for (boolean useShortFormat : PARAM_USE_SHORT_FORMAT) { assertEquals("12:00 AM", Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, @@ -251,11 +270,4 @@ public class UtilsTest_GetDurationString extends AndroidTestCase { DateUtils.FORMAT_24HOUR)); } } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - // Revive system locale. - Locale.setDefault(mLocale); - } } diff --git a/tests/unit/src/com/android/tv/util/UtilsTest_GetMultiAudioString.java b/tests/unit/src/com/android/tv/util/UtilsTest_GetMultiAudioString.java index 8a6f3e3b..1e75342b 100644 --- a/tests/unit/src/com/android/tv/util/UtilsTest_GetMultiAudioString.java +++ b/tests/unit/src/com/android/tv/util/UtilsTest_GetMultiAudioString.java @@ -16,21 +16,26 @@ package com.android.tv.util; +import static android.support.test.InstrumentationRegistry.getTargetContext; +import static org.junit.Assert.assertEquals; + import android.content.Context; import android.media.tv.TvTrackInfo; import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; + +import org.junit.Test; /** * Tests for {@link com.android.tv.util.Utils#getMultiAudioString}. */ @SmallTest -public class UtilsTest_GetMultiAudioString extends AndroidTestCase { +public class UtilsTest_GetMultiAudioString { private static final String TRACK_ID = "test_track_id"; private static final int AUDIO_SAMPLE_RATE = 48000; + @Test public void testAudioTrackLanguage() { - Context context = getContext(); + Context context = getTargetContext(); assertEquals("Korean", Utils.getMultiAudioString(context, createAudioTrackInfo("kor"), false)); assertEquals("English", @@ -42,8 +47,9 @@ public class UtilsTest_GetMultiAudioString extends AndroidTestCase { assertEquals("abc", Utils.getMultiAudioString(context, createAudioTrackInfo("abc"), false)); } + @Test public void testAudioTrackCount() { - Context context = getContext(); + Context context = getTargetContext(); assertEquals("English", Utils.getMultiAudioString(context, createAudioTrackInfo("eng", -1), false)); assertEquals("English", @@ -66,11 +72,14 @@ public class UtilsTest_GetMultiAudioString extends AndroidTestCase { Utils.getMultiAudioString(context, createAudioTrackInfo("eng", 8), false)); } + @Test public void testShowSampleRate() { assertEquals("Korean (48kHz)", - Utils.getMultiAudioString(getContext(), createAudioTrackInfo("kor", 0), true)); + Utils.getMultiAudioString(getTargetContext(), + createAudioTrackInfo("kor", 0), true)); assertEquals("Korean (7.1 surround, 48kHz)", - Utils.getMultiAudioString(getContext(), createAudioTrackInfo("kor", 8), true)); + Utils.getMultiAudioString(getTargetContext(), + createAudioTrackInfo("kor", 8), true)); } private static TvTrackInfo createAudioTrackInfo(String language) { diff --git a/tests/unit/src/com/android/tv/util/UtilsTest_IsInGivenDay.java b/tests/unit/src/com/android/tv/util/UtilsTest_IsInGivenDay.java index 926deb07..2b43abc1 100644 --- a/tests/unit/src/com/android/tv/util/UtilsTest_IsInGivenDay.java +++ b/tests/unit/src/com/android/tv/util/UtilsTest_IsInGivenDay.java @@ -16,8 +16,12 @@ package com.android.tv.util; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import android.support.test.filters.SmallTest; -import android.test.AndroidTestCase; + +import org.junit.Test; import java.util.Calendar; import java.util.GregorianCalendar; @@ -27,19 +31,22 @@ import java.util.TimeZone; * Tests for {@link com.android.tv.util.Utils#isInGivenDay}. */ @SmallTest -public class UtilsTest_IsInGivenDay extends AndroidTestCase { +public class UtilsTest_IsInGivenDay { + @Test public void testIsInGivenDay() { assertTrue(Utils.isInGivenDay( new GregorianCalendar(2015, Calendar.JANUARY, 1).getTimeInMillis(), new GregorianCalendar(2015, Calendar.JANUARY, 1, 0, 30).getTimeInMillis())); } + @Test public void testIsNotInGivenDay() { assertFalse(Utils.isInGivenDay( new GregorianCalendar(2015, Calendar.JANUARY, 1).getTimeInMillis(), new GregorianCalendar(2015, Calendar.JANUARY, 2).getTimeInMillis())); } + @Test public void testIfTimeZoneApplied() { TimeZone timeZone = TimeZone.getDefault(); |