diff options
Diffstat (limited to 'tests/unit/src')
52 files changed, 1684 insertions, 5871 deletions
diff --git a/tests/unit/src/com/android/tv/BaseMainActivityTestCase.java b/tests/unit/src/com/android/tv/BaseMainActivityTestCase.java deleted file mode 100644 index e6f1af7e..00000000 --- a/tests/unit/src/com/android/tv/BaseMainActivityTestCase.java +++ /dev/null @@ -1,143 +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; - -import static android.support.test.InstrumentationRegistry.getInstrumentation; - -import android.content.Context; -import android.os.SystemClock; -import android.support.test.rule.ActivityTestRule; -import android.text.TextUtils; - -import com.android.tv.data.Channel; -import com.android.tv.data.ChannelDataManager; -import com.android.tv.testing.ChannelInfo; -import com.android.tv.testing.testinput.ChannelStateData; -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 { - 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; - - @Before - public void setUp() { - mActivity = mActivityTestRule.getActivity(); - // TODO: ensure the SampleInputs are setup. - getInstrumentation().getTargetContext() - .bindService(TestInputControlUtils.createIntent(), mConnection, - Context.BIND_AUTO_CREATE); - } - - @Before - public void tearDown() { - if (mConnection.isBound()) { - getInstrumentation().getTargetContext().unbindService(mConnection); - } - } - - /** - * Tune to {@code channel}. - * - * @param channel the channel to tune to. - */ - protected void tuneToChannel(final Channel channel) { - // Run on UI thread so views can be modified - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mActivity.tuneToChannel(channel); - } - }); - } - - /** - * Sleep until @{@link ChannelDataManager#isDbLoadFinished()} is true. - */ - protected void waitUntilChannelLoadingFinish() { - ChannelDataManager channelDataManager = mActivity.getChannelDataManager(); - while (!channelDataManager.isDbLoadFinished()) { - getInstrumentation().waitForIdleSync(); - SystemClock.sleep(CHANNEL_LOADING_CHECK_INTERVAL_MS); - } - } - - /** - * Tune to the channel with {@code name}. - * - * @param name the name of the channel to find. - */ - protected void tuneToChannel(String name) { - Channel c = findChannelWithName(name); - tuneToChannel(c); - } - - /** - * Tune to channel. - */ - protected void tuneToChannel(ChannelInfo channel) { - tuneToChannel(channel.name); - } - - /** - * Update the channel state to {@code data} then tune to that channel. - * - * @param data the state to update the channel with. - * @param channel the channel to tune to - */ - protected void updateThenTune(ChannelStateData data, ChannelInfo channel) { - if (channel.equals(TvTestInputConstants.CH_1_DEFAULT_DONT_MODIFY)) { - throw new IllegalArgumentException( - "By convention " + TvTestInputConstants.CH_1_DEFAULT_DONT_MODIFY.name - + " should not be modified."); - } - mConnection.updateChannelState(channel, data); - tuneToChannel(channel); - } - - private Channel findChannelWithName(String displayName) { - waitUntilChannelLoadingFinish(); - Channel channel = null; - List <Channel> channelList = mActivity.getChannelDataManager().getChannelList(); - for (Channel c : channelList) { - if (TextUtils.equals(c.getDisplayName(), displayName)) { - channel = c; - break; - } - } - 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 f2917181..abadde31 100644 --- a/tests/unit/src/com/android/tv/CurrentPositionMediatorTest.java +++ b/tests/unit/src/com/android/tv/CurrentPositionMediatorTest.java @@ -18,16 +18,18 @@ 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 static com.google.common.truth.Truth.assertWithMessage; import android.support.test.annotation.UiThreadTest; import android.support.test.filters.MediumTest; - +import android.support.test.runner.AndroidJUnit4; +import com.android.tv.testing.activities.BaseMainActivityTestCase; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; @MediumTest +@RunWith(AndroidJUnit4.class) public class CurrentPositionMediatorTest extends BaseMainActivityTestCase { private TimeShiftManager.CurrentPositionMediator mMediator; @@ -51,8 +53,12 @@ public class CurrentPositionMediatorTest extends BaseMainActivityTestCase { public void testOnSeekRequested() { long seekToTimeMs = System.currentTimeMillis() - REQUEST_TIMEOUT_MS * 3; mMediator.onSeekRequested(seekToTimeMs); - assertNotSame("Seek request time", INVALID_TIME, mMediator.mSeekRequestTimeMs); - assertEquals("Current position", seekToTimeMs, mMediator.mCurrentPositionMs); + assertWithMessage("Seek request time") + .that(mMediator.mSeekRequestTimeMs) + .isNotSameAs(INVALID_TIME); + assertWithMessage("Current position") + .that(mMediator.mCurrentPositionMs) + .isEqualTo(seekToTimeMs); } @UiThreadTest @@ -62,9 +68,15 @@ public class CurrentPositionMediatorTest extends BaseMainActivityTestCase { long newCurrentTimeMs = seekToTimeMs + REQUEST_TIMEOUT_MS; mMediator.onSeekRequested(seekToTimeMs); mMediator.onCurrentPositionChanged(newCurrentTimeMs); - assertNotSame("Seek request time", INVALID_TIME, mMediator.mSeekRequestTimeMs); - assertNotSame("Current position", seekToTimeMs, mMediator.mCurrentPositionMs); - assertNotSame("Current position", newCurrentTimeMs, mMediator.mCurrentPositionMs); + assertWithMessage("Seek request time") + .that(mMediator.mSeekRequestTimeMs) + .isNotSameAs(INVALID_TIME); + assertWithMessage("Current position") + .that(mMediator.mCurrentPositionMs) + .isNotSameAs(seekToTimeMs); + assertWithMessage("Current position") + .that(mMediator.mCurrentPositionMs) + .isNotSameAs(newCurrentTimeMs); } @UiThreadTest @@ -77,9 +89,13 @@ public class CurrentPositionMediatorTest extends BaseMainActivityTestCase { assertCurrentPositionMediator(INVALID_TIME, newCurrentTimeMs); } - private void assertCurrentPositionMediator(long expectedSeekRequestTimeMs, - long expectedCurrentPositionMs) { - assertEquals("Seek request time", expectedSeekRequestTimeMs, mMediator.mSeekRequestTimeMs); - assertEquals("Current position", expectedCurrentPositionMs, mMediator.mCurrentPositionMs); + private void assertCurrentPositionMediator( + long expectedSeekRequestTimeMs, long expectedCurrentPositionMs) { + assertWithMessage("Seek request time") + .that(mMediator.mSeekRequestTimeMs) + .isEqualTo(expectedSeekRequestTimeMs); + assertWithMessage("Current position") + .that(mMediator.mCurrentPositionMs) + .isEqualTo(expectedCurrentPositionMs); } } diff --git a/tests/unit/src/com/android/tv/FeaturesTest.java b/tests/unit/src/com/android/tv/FeaturesTest.java index 9d61e757..e19f4b7c 100644 --- a/tests/unit/src/com/android/tv/FeaturesTest.java +++ b/tests/unit/src/com/android/tv/FeaturesTest.java @@ -16,21 +16,21 @@ package com.android.tv; -import static org.junit.Assert.assertFalse; +import static com.google.common.truth.Truth.assertThat; import android.support.test.filters.SmallTest; - +import android.support.test.runner.AndroidJUnit4; import org.junit.Test; +import org.junit.runner.RunWith; -/** - * Test for features. - */ +/** Test for features. */ @SmallTest +@RunWith(AndroidJUnit4.class) 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. - assertFalse(Features.TEST_FEATURE.isEnabled(null)); + assertThat(TvFeatures.TEST_FEATURE.isEnabled(null)).isFalse(); } } diff --git a/tests/unit/src/com/android/tv/MainActivityTest.java b/tests/unit/src/com/android/tv/MainActivityTest.java index 15805032..c5df21a9 100644 --- a/tests/unit/src/com/android/tv/MainActivityTest.java +++ b/tests/unit/src/com/android/tv/MainActivityTest.java @@ -16,31 +16,30 @@ package com.android.tv; import static android.support.test.InstrumentationRegistry.getInstrumentation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; import android.support.test.filters.MediumTest; +import android.support.test.runner.AndroidJUnit4; import android.view.View; import android.widget.TextView; - -import com.android.tv.data.Channel; +import com.android.tv.data.api.Channel; +import com.android.tv.testing.activities.BaseMainActivityTestCase; import com.android.tv.testing.testinput.TvTestInputConstants; import com.android.tv.ui.ChannelBannerView; - -import org.junit.Test; - import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; -/** - * Tests for {@link MainActivity}. - */ +/** Tests for {@link MainActivity}. */ @MediumTest +@RunWith(AndroidJUnit4.class) public class MainActivityTest extends BaseMainActivityTestCase { @Test public void testInitialConditions() { waitUntilChannelLoadingFinish(); List<Channel> channelList = mActivity.getChannelDataManager().getChannelList(); - assertTrue("Expected at least one channel", channelList.size() > 0); + assertWithMessage("Expected at least one channel").that(channelList.size() > 0).isTrue(); } @Test @@ -61,17 +60,19 @@ public class MainActivityTest extends BaseMainActivityTestCase { private void showProgramGuide() { // Run on UI thread so views can be modified - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mActivity.getOverlayManager().showProgramGuide(); - } - }); + getInstrumentation() + .runOnMainSync( + new Runnable() { + @Override + public void run() { + mActivity.getOverlayManager().showProgramGuide(); + } + }); } private void assertChannelName(String displayName) { TextView channelNameView = (TextView) mActivity.findViewById(R.id.channel_name); - assertEquals("Channel Name", displayName, channelNameView.getText()); + assertWithMessage("Channel Name").that(channelNameView.getText()).isEqualTo(displayName); } private void assertProgramGuide(boolean isShown) { @@ -83,12 +84,13 @@ public class MainActivityTest extends BaseMainActivityTestCase { return (ChannelBannerView) v; } - private View assertExpectedBannerSceneClassShown(Class<ChannelBannerView> expectedClass, - boolean expectedShown) { - View v = assertViewIsShown(expectedClass.getSimpleName(), R.id.scene_transition_common, - expectedShown); + private View assertExpectedBannerSceneClassShown( + Class<ChannelBannerView> expectedClass, boolean expectedShown) { + View v = + assertViewIsShown( + expectedClass.getSimpleName(), R.id.scene_transition_common, expectedShown); if (v != null) { - assertEquals(expectedClass, v.getClass()); + assertThat(v.getClass()).isEqualTo(expectedClass); } return v; } @@ -102,7 +104,7 @@ public class MainActivityTest extends BaseMainActivityTestCase { return null; } } - assertEquals(viewName + " shown", expected, view.isShown()); + assertWithMessage(viewName + " shown").that(view.isShown()).isEqualTo(expected); return view; } } diff --git a/tests/unit/src/com/android/tv/TimeShiftManagerTest.java b/tests/unit/src/com/android/tv/TimeShiftManagerTest.java index 052b5d19..cb523045 100644 --- a/tests/unit/src/com/android/tv/TimeShiftManagerTest.java +++ b/tests/unit/src/com/android/tv/TimeShiftManagerTest.java @@ -22,14 +22,17 @@ 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 static com.google.common.truth.Truth.assertWithMessage; import android.support.test.filters.MediumTest; - +import android.support.test.runner.AndroidJUnit4; +import com.android.tv.testing.activities.BaseMainActivityTestCase; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; @MediumTest +@RunWith(AndroidJUnit4.class) public class TimeShiftManagerTest extends BaseMainActivityTestCase { private TimeShiftManager mTimeShiftManager; @@ -85,19 +88,30 @@ public class TimeShiftManagerTest extends BaseMainActivityTestCase { mTimeShiftManager.enableAction(TIME_SHIFT_ACTION_ID_JUMP_TO_NEXT, enabled); } - private void assertActionState(boolean playEnabled, boolean pauseEnabled, boolean rewindEnabled, - boolean fastForwardEnabled, boolean jumpToPreviousEnabled, boolean jumpToNextEnabled) { - assertEquals("Play Action", playEnabled, - mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_PLAY)); - assertEquals("Pause Action", pauseEnabled, - mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_PAUSE)); - assertEquals("Rewind Action", rewindEnabled, - mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_REWIND)); - assertEquals("Fast Forward Action", fastForwardEnabled, - mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_FAST_FORWARD)); - assertEquals("Jump To Previous Action", jumpToPreviousEnabled, - mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_JUMP_TO_PREVIOUS)); - assertEquals("Jump To Next Action", jumpToNextEnabled, - mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_JUMP_TO_NEXT)); + private void assertActionState( + boolean playEnabled, + boolean pauseEnabled, + boolean rewindEnabled, + boolean fastForwardEnabled, + boolean jumpToPreviousEnabled, + boolean jumpToNextEnabled) { + assertWithMessage("Play Action") + .that(mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_PLAY)) + .isEqualTo(playEnabled); + assertWithMessage("Pause Action") + .that(mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_PAUSE)) + .isEqualTo(pauseEnabled); + assertWithMessage("Rewind Action") + .that(mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_REWIND)) + .isEqualTo(rewindEnabled); + assertWithMessage("Fast Forward Action") + .that(mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_FAST_FORWARD)) + .isEqualTo(fastForwardEnabled); + assertWithMessage("Jump To Previous Action") + .that(mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_JUMP_TO_PREVIOUS)) + .isEqualTo(jumpToPreviousEnabled); + assertWithMessage("Jump To Next Action") + .that(mTimeShiftManager.isActionEnabled(TIME_SHIFT_ACTION_ID_JUMP_TO_NEXT)) + .isEqualTo(jumpToNextEnabled); } } diff --git a/tests/unit/src/com/android/tv/data/ChannelDataManagerTest.java b/tests/unit/src/com/android/tv/data/ChannelDataManagerTest.java index 7a4a4982..96c1f7a1 100644 --- a/tests/unit/src/com/android/tv/data/ChannelDataManagerTest.java +++ b/tests/unit/src/com/android/tv/data/ChannelDataManagerTest.java @@ -18,9 +18,8 @@ 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 static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; import android.content.ContentProvider; import android.content.ContentUris; @@ -31,7 +30,9 @@ import android.database.Cursor; import android.media.tv.TvContract; import android.media.tv.TvContract.Channels; import android.net.Uri; +import android.os.AsyncTask; import android.support.test.filters.SmallTest; +import android.support.test.runner.AndroidJUnit4; import android.test.MoreAsserts; import android.test.mock.MockContentProvider; import android.test.mock.MockContentResolver; @@ -39,30 +40,30 @@ import android.test.mock.MockCursor; import android.text.TextUtils; import android.util.Log; import android.util.SparseArray; - -import com.android.tv.testing.ChannelInfo; -import com.android.tv.testing.Constants; +import com.android.tv.data.api.Channel; +import com.android.tv.testing.constants.Constants; +import com.android.tv.testing.data.ChannelInfo; 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; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; /** * Test for {@link ChannelDataManager} * - * A test method may include tests for multiple methods to minimize the DB access. - * Note that all the methods of {@link ChannelDataManager} should be called from the UI thread. + * <p>A test method may include tests for multiple methods to minimize the DB access. Note that all + * the methods of {@link ChannelDataManager} should be called from the UI thread. */ @SmallTest +@RunWith(AndroidJUnit4.class) public class ChannelDataManagerTest { private static final boolean DEBUG = false; private static final String TAG = "ChannelDataManagerTest"; @@ -80,73 +81,89 @@ public class ChannelDataManagerTest { @Before public void setUp() { - assertTrue("More than 2 channels to test", Constants.UNIT_TEST_CHANNEL_COUNT > 2); + assertWithMessage("More than 2 channels to test") + .that(Constants.UNIT_TEST_CHANNEL_COUNT > 2) + .isTrue(); mContentProvider = new FakeContentProvider(getTargetContext()); mContentResolver = new FakeContentResolver(); mContentResolver.addProvider(TvContract.AUTHORITY, mContentProvider); mListener = new TestChannelDataManagerListener(); - 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(getTargetContext(), mockHelper, - mContentResolver); - mChannelDataManager.addListener(mListener); - } - }); + 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( + getTargetContext(), + mockHelper, + AsyncTask.SERIAL_EXECUTOR, + mContentResolver); + mChannelDataManager.addListener(mListener); + } + }); } @After public void tearDown() { - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mChannelDataManager.stop(); - } - }); + getInstrumentation() + .runOnMainSync( + new Runnable() { + @Override + public void run() { + mChannelDataManager.stop(); + } + }); } 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)); + getInstrumentation() + .runOnMainSync( + new Runnable() { + @Override + public void run() { + mChannelDataManager.start(); + } + }); + assertThat(mListener.loadFinishedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)) + .isTrue(); } private void restart() throws InterruptedException { - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mChannelDataManager.stop(); - mListener.reset(); - } - }); + getInstrumentation() + .runOnMainSync( + new Runnable() { + @Override + public void run() { + mChannelDataManager.stop(); + mListener.reset(); + } + }); startAndWaitForComplete(); } @Test public void testIsDbLoadFinished() throws InterruptedException { startAndWaitForComplete(); - assertTrue(mChannelDataManager.isDbLoadFinished()); + assertThat(mChannelDataManager.isDbLoadFinished()).isTrue(); } /** - * Test for following methods - * - {@link ChannelDataManager#getChannelCount} - * - {@link ChannelDataManager#getChannelList} - * - {@link ChannelDataManager#getChannel} + * Test for following methods - {@link ChannelDataManager#getChannelCount} - {@link + * ChannelDataManager#getChannelList} - {@link ChannelDataManager#getChannel} */ @Test public void testGetChannels() throws InterruptedException { startAndWaitForComplete(); // Test {@link ChannelDataManager#getChannelCount} - assertEquals(Constants.UNIT_TEST_CHANNEL_COUNT, mChannelDataManager.getChannelCount()); + assertThat(mChannelDataManager.getChannelCount()) + .isEqualTo(Constants.UNIT_TEST_CHANNEL_COUNT); // Test {@link ChannelDataManager#getChannelList} List<ChannelInfo> channelInfoList = new ArrayList<>(); @@ -157,36 +174,32 @@ public class ChannelDataManagerTest { for (Channel channel : channelList) { boolean found = false; for (ChannelInfo channelInfo : channelInfoList) { - if (TextUtils.equals(channelInfo.name, channel.getDisplayName()) - && TextUtils.equals(channelInfo.name, channel.getDisplayName())) { + if (TextUtils.equals(channelInfo.name, channel.getDisplayName())) { found = true; channelInfoList.remove(channelInfo); break; } } - assertTrue("Cannot find (" + channel + ")", found); + assertWithMessage("Cannot find (" + channel + ")").that(found).isTrue(); } // Test {@link ChannelDataManager#getChannelIndex()} for (Channel channel : channelList) { - assertEquals(channel, mChannelDataManager.getChannel(channel.getId())); + assertThat(mChannelDataManager.getChannel(channel.getId())).isEqualTo(channel); } } - /** - * Test for {@link ChannelDataManager#getChannelCount} when no channel is available. - */ + /** Test for {@link ChannelDataManager#getChannelCount} when no channel is available. */ @Test public void testGetChannels_noChannels() throws InterruptedException { mContentProvider.clear(); startAndWaitForComplete(); - assertEquals(0, mChannelDataManager.getChannelCount()); + assertThat(mChannelDataManager.getChannelCount()).isEqualTo(0); } /** - * Test for following methods and channel listener with notifying change. - * - {@link ChannelDataManager#updateBrowsable} - * - {@link ChannelDataManager#applyUpdatedValuesToDb} + * Test for following methods and channel listener with notifying change. - {@link + * ChannelDataManager#updateBrowsable} - {@link ChannelDataManager#applyUpdatedValuesToDb} */ @Test public void testBrowsable() throws InterruptedException { @@ -197,9 +210,9 @@ public class ChannelDataManagerTest { List<Channel> browsableChannelList = mChannelDataManager.getBrowsableChannelList(); for (Channel browsableChannel : browsableChannelList) { boolean found = channelList.remove(browsableChannel); - assertTrue("Cannot find (" + browsableChannel + ")", found); + assertWithMessage("Cannot find (" + browsableChannel + ")").that(found).isTrue(); } - assertEquals(0, channelList.size()); + assertThat(channelList).isEmpty(); // Prepare for next tests. channelList = mChannelDataManager.getChannelList(); @@ -210,8 +223,8 @@ public class ChannelDataManagerTest { // Test {@link ChannelDataManager#updateBrowsable} & notification. mChannelDataManager.updateBrowsable(channel1.getId(), false, false); - assertTrue(mListener.channelBrowsableChangedCalled); - assertFalse(mChannelDataManager.getBrowsableChannelList().contains(channel1)); + assertThat(mListener.channelBrowsableChangedCalled).isTrue(); + assertThat(mChannelDataManager.getBrowsableChannelList()).doesNotContain(channel1); MoreAsserts.assertContentsInAnyOrder(channelListener.updatedChannels, channel1); channelListener.reset(); @@ -221,14 +234,13 @@ public class ChannelDataManagerTest { mChannelDataManager.applyUpdatedValuesToDb(); restart(); browsableChannelList = mChannelDataManager.getBrowsableChannelList(); - assertEquals(Constants.UNIT_TEST_CHANNEL_COUNT - 1, browsableChannelList.size()); - assertFalse(browsableChannelList.contains(channel1)); + assertThat(browsableChannelList).hasSize(Constants.UNIT_TEST_CHANNEL_COUNT - 1); + assertThat(browsableChannelList).doesNotContain(channel1); } /** - * Test for following methods and channel listener without notifying change. - * - {@link ChannelDataManager#updateBrowsable} - * - {@link ChannelDataManager#applyUpdatedValuesToDb} + * Test for following methods and channel listener without notifying change. - {@link + * ChannelDataManager#updateBrowsable} - {@link ChannelDataManager#applyUpdatedValuesToDb} */ @Test public void testBrowsable_skipNotification() throws InterruptedException { @@ -247,10 +259,10 @@ public class ChannelDataManagerTest { mChannelDataManager.updateBrowsable(channel1.getId(), false, true); mChannelDataManager.updateBrowsable(channel2.getId(), false, true); mChannelDataManager.updateBrowsable(channel1.getId(), true, true); - assertFalse(mListener.channelBrowsableChangedCalled); + assertThat(mListener.channelBrowsableChangedCalled).isFalse(); List<Channel> browsableChannelList = mChannelDataManager.getBrowsableChannelList(); - assertTrue(browsableChannelList.contains(channel1)); - assertFalse(browsableChannelList.contains(channel2)); + assertThat(browsableChannelList).contains(channel1); + assertThat(browsableChannelList).doesNotContain(channel2); // Test {@link ChannelDataManager#applyUpdatedValuesToDb} // Disable the update notification to avoid the unwanted call of "onLoadFinished". @@ -258,14 +270,13 @@ public class ChannelDataManagerTest { mChannelDataManager.applyUpdatedValuesToDb(); restart(); browsableChannelList = mChannelDataManager.getBrowsableChannelList(); - assertEquals(Constants.UNIT_TEST_CHANNEL_COUNT - 1, browsableChannelList.size()); - assertFalse(browsableChannelList.contains(channel2)); + assertThat(browsableChannelList).hasSize(Constants.UNIT_TEST_CHANNEL_COUNT - 1); + assertThat(browsableChannelList).doesNotContain(channel2); } /** - * Test for following methods and channel listener. - * - {@link ChannelDataManager#updateLocked} - * - {@link ChannelDataManager#applyUpdatedValuesToDb} + * Test for following methods and channel listener. - {@link ChannelDataManager#updateLocked} - + * {@link ChannelDataManager#applyUpdatedValuesToDb} */ @Test public void testLocked() throws InterruptedException { @@ -274,7 +285,7 @@ public class ChannelDataManagerTest { // Test if all channels aren't locked at the first time. List<Channel> channelList = mChannelDataManager.getChannelList(); for (Channel channel : channelList) { - assertFalse(channel + " is locked", channel.isLocked()); + assertWithMessage(channel + " is locked").that(channel.isLocked()).isFalse(); } // Prepare for next tests. @@ -282,22 +293,20 @@ public class ChannelDataManagerTest { // Test {@link ChannelDataManager#updateLocked} mChannelDataManager.updateLocked(channel.getId(), true); - assertTrue(mChannelDataManager.getChannel(channel.getId()).isLocked()); + assertThat(mChannelDataManager.getChannel(channel.getId()).isLocked()).isTrue(); // Test {@link ChannelDataManager#applyUpdatedValuesToDb}. // Disable the update notification to avoid the unwanted call of "onLoadFinished". mContentResolver.mNotifyDisabled = true; mChannelDataManager.applyUpdatedValuesToDb(); restart(); - assertTrue(mChannelDataManager.getChannel(channel.getId()).isLocked()); + assertThat(mChannelDataManager.getChannel(channel.getId()).isLocked()).isTrue(); // Cleanup mChannelDataManager.updateLocked(channel.getId(), false); } - /** - * Test ChannelDataManager when channels in TvContract are updated, removed, or added. - */ + /** Test ChannelDataManager when channels in TvContract are updated, removed, or added. */ @Test public void testChannelListChanged() throws InterruptedException { startAndWaitForComplete(); @@ -308,9 +317,10 @@ public class ChannelDataManagerTest { ChannelInfo testChannelInfo = ChannelInfo.create(getTargetContext(), (int) testChannelId); testChannelId = Constants.UNIT_TEST_CHANNEL_COUNT + 1; mContentProvider.simulateInsert(testChannelInfo); - assertTrue( - mListener.channelListUpdatedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); - assertEquals(Constants.UNIT_TEST_CHANNEL_COUNT + 1, mChannelDataManager.getChannelCount()); + assertThat(mListener.channelListUpdatedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)) + .isTrue(); + assertThat(mChannelDataManager.getChannelCount()) + .isEqualTo(Constants.UNIT_TEST_CHANNEL_COUNT + 1); // Test channel update mListener.reset(); @@ -319,39 +329,45 @@ public class ChannelDataManagerTest { mChannelDataManager.addChannelListener(testChannelId, channelListener); String newName = testChannelInfo.name + "_test"; mContentProvider.simulateUpdate(testChannelId, newName); - assertTrue( - mListener.channelListUpdatedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); - assertTrue( - channelListener.channelChangedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); - assertEquals(0, channelListener.removedChannels.size()); - assertEquals(1, channelListener.updatedChannels.size()); + assertThat(mListener.channelListUpdatedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)) + .isTrue(); + assertThat( + channelListener.channelChangedLatch.await( + WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)) + .isTrue(); + assertThat(channelListener.removedChannels).isEmpty(); + assertThat(channelListener.updatedChannels).hasSize(1); Channel updatedChannel = channelListener.updatedChannels.get(0); - assertEquals(testChannelId, updatedChannel.getId()); - assertEquals(testChannelInfo.number, updatedChannel.getDisplayNumber()); - assertEquals(newName, updatedChannel.getDisplayName()); - assertEquals(Constants.UNIT_TEST_CHANNEL_COUNT + 1, - mChannelDataManager.getChannelCount()); + assertThat(updatedChannel.getId()).isEqualTo(testChannelId); + assertThat(updatedChannel.getDisplayNumber()).isEqualTo(testChannelInfo.number); + assertThat(updatedChannel.getDisplayName()).isEqualTo(newName); + assertThat(mChannelDataManager.getChannelCount()) + .isEqualTo(Constants.UNIT_TEST_CHANNEL_COUNT + 1); // Test channel remove. mListener.reset(); channelListener.reset(); mContentProvider.simulateDelete(testChannelId); - assertTrue( - mListener.channelListUpdatedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); - assertTrue( - channelListener.channelChangedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); - assertEquals(1, channelListener.removedChannels.size()); - assertEquals(0, channelListener.updatedChannels.size()); + assertThat(mListener.channelListUpdatedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)) + .isTrue(); + assertThat( + channelListener.channelChangedLatch.await( + WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)) + .isTrue(); + assertThat(channelListener.removedChannels).hasSize(1); + assertThat(channelListener.updatedChannels).isEmpty(); Channel removedChannel = channelListener.removedChannels.get(0); - assertEquals(newName, removedChannel.getDisplayName()); - assertEquals(testChannelInfo.number, removedChannel.getDisplayNumber()); - assertEquals(Constants.UNIT_TEST_CHANNEL_COUNT, mChannelDataManager.getChannelCount()); + assertThat(removedChannel.getDisplayName()).isEqualTo(newName); + assertThat(removedChannel.getDisplayNumber()).isEqualTo(testChannelInfo.number); + assertThat(mChannelDataManager.getChannelCount()) + .isEqualTo(Constants.UNIT_TEST_CHANNEL_COUNT); } - private class ChannelInfoWrapper { + private static class ChannelInfoWrapper { public ChannelInfo channelInfo; public boolean browsable; public boolean locked; + public ChannelInfoWrapper(ChannelInfo channelInfo) { this.channelInfo = channelInfo; browsable = true; @@ -366,8 +382,14 @@ public class ChannelDataManagerTest { public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) { super.notifyChange(uri, observer, syncToNetwork); if (DEBUG) { - Log.d(TAG, "onChanged(uri=" + uri + ", observer=" + observer + ") - Notification " - + (mNotifyDisabled ? "disabled" : "enabled")); + Log.d( + TAG, + "onChanged(uri=" + + uri + + ", observer=" + + observer + + ") - Notification " + + (mNotifyDisabled ? "disabled" : "enabled")); } if (mNotifyDisabled) { return; @@ -390,19 +412,23 @@ public class ChannelDataManagerTest { public FakeContentProvider(Context context) { super(context); for (int i = 1; i <= Constants.UNIT_TEST_CHANNEL_COUNT; i++) { - mChannelInfoList.put(i, - new ChannelInfoWrapper(ChannelInfo.create(getTargetContext(), i))); + mChannelInfoList.put( + i, new ChannelInfoWrapper(ChannelInfo.create(getTargetContext(), i))); } } /** - * Implementation of {@link ContentProvider#query}. - * This assumes that {@link ChannelDataManager} queries channels - * with empty {@code selection}. (i.e. channels are always queries for all) + * Implementation of {@link ContentProvider#query}. This assumes that {@link + * ChannelDataManager} queries channels with empty {@code selection}. (i.e. channels are + * always queries for all) */ @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] - selectionArgs, String sortOrder) { + public Cursor query( + Uri uri, + String[] projection, + String selection, + String[] selectionArgs, + String sortOrder) { if (DEBUG) { Log.d(TAG, "dump query"); Log.d(TAG, " uri=" + uri); @@ -414,9 +440,8 @@ public class ChannelDataManagerTest { } /** - * Implementation of {@link ContentProvider#update}. - * This assumes that {@link ChannelDataManager} update channels - * only for changing browsable and locked. + * Implementation of {@link ContentProvider#update}. This assumes that {@link + * ChannelDataManager} update channels only for changing browsable and locked. */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { @@ -434,8 +459,9 @@ public class ChannelDataManagerTest { } } else { // See {@link Utils#buildSelectionForIds} for the syntax. - String selectionForId = selection.substring( - selection.indexOf("(") + 1, selection.lastIndexOf(")")); + String selectionForId = + selection.substring( + selection.indexOf("(") + 1, selection.lastIndexOf(")")); String[] ids = selectionForId.split(", "); if (ids != null) { for (String id : ids) { @@ -476,27 +502,25 @@ public class ChannelDataManagerTest { } /** - * Simulates channel data insert. - * This assigns original network ID (the same with channel number) to channel ID. + * Simulates channel data insert. This assigns original network ID (the same with channel + * number) to channel ID. */ public void simulateInsert(ChannelInfo testChannelInfo) { long channelId = testChannelInfo.originalNetworkId; - mChannelInfoList.put((int) channelId, new ChannelInfoWrapper( - ChannelInfo.create(getTargetContext(), (int) channelId))); + mChannelInfoList.put( + (int) channelId, + new ChannelInfoWrapper( + ChannelInfo.create(getTargetContext(), (int) channelId))); mContentResolver.notifyChange(TvContract.buildChannelUri(channelId), null); } - /** - * Simulates channel data delete. - */ + /** Simulates channel data delete. */ public void simulateDelete(long channelId) { mChannelInfoList.remove((int) channelId); mContentResolver.notifyChange(TvContract.buildChannelUri(channelId), null); } - /** - * Simulates channel data update. - */ + /** Simulates channel data update. */ public void simulateUpdate(long channelId, String newName) { ChannelInfoWrapper channel = mChannelInfoList.get((int) channelId); ChannelInfo.Builder builder = new ChannelInfo.Builder(channel.channelInfo); @@ -506,8 +530,9 @@ public class ChannelDataManagerTest { } private void assertChannelUri(Uri uri) { - assertTrue("Uri(" + uri + ") isn't channel uri", - uri.toString().startsWith(Channels.CONTENT_URI.toString())); + assertWithMessage("Uri(" + uri + ") isn't channel uri") + .that(uri.toString().startsWith(Channels.CONTENT_URI.toString())) + .isTrue(); } public void clear() { @@ -528,20 +553,21 @@ public class ChannelDataManagerTest { } private class FakeCursor extends MockCursor { - private final String[] ALL_COLUMNS = { - Channels._ID, - Channels.COLUMN_DISPLAY_NAME, - Channels.COLUMN_DISPLAY_NUMBER, - Channels.COLUMN_INPUT_ID, - Channels.COLUMN_VIDEO_FORMAT, - Channels.COLUMN_ORIGINAL_NETWORK_ID, - COLUMN_BROWSABLE, - COLUMN_LOCKED}; + private final String[] allColumns = { + Channels._ID, + Channels.COLUMN_DISPLAY_NAME, + Channels.COLUMN_DISPLAY_NUMBER, + Channels.COLUMN_INPUT_ID, + Channels.COLUMN_VIDEO_FORMAT, + Channels.COLUMN_ORIGINAL_NETWORK_ID, + COLUMN_BROWSABLE, + COLUMN_LOCKED + }; private final String[] mColumns; private int mPosition; public FakeCursor(String[] columns) { - mColumns = (columns == null) ? ALL_COLUMNS : columns; + mColumns = (columns == null) ? allColumns : columns; mPosition = -1; } @@ -566,6 +592,7 @@ public class ChannelDataManagerTest { switch (columnName) { case Channels._ID: return mContentProvider.keyAt(mPosition); + default: // fall out } if (DEBUG) { Log.d(TAG, "Column (" + columnName + ") is ignored in getLong()"); @@ -586,6 +613,7 @@ public class ChannelDataManagerTest { return DUMMY_INPUT_ID; case Channels.COLUMN_VIDEO_FORMAT: return channel.channelInfo.getVideoFormat(); + default: // fall out } if (DEBUG) { Log.d(TAG, "Column (" + columnName + ") is ignored in getString()"); @@ -604,6 +632,7 @@ public class ChannelDataManagerTest { return channel.browsable ? 1 : 0; case COLUMN_LOCKED: return channel.locked ? 1 : 0; + default: // fall out } if (DEBUG) { Log.d(TAG, "Column (" + columnName + ") is ignored in getInt()"); @@ -627,7 +656,7 @@ public class ChannelDataManagerTest { } } - private class TestChannelDataManagerListener implements ChannelDataManager.Listener { + private static class TestChannelDataManagerListener implements ChannelDataManager.Listener { public CountDownLatch loadFinishedLatch = new CountDownLatch(1); public CountDownLatch channelListUpdatedLatch = new CountDownLatch(1); public boolean channelBrowsableChangedCalled; @@ -654,7 +683,7 @@ public class ChannelDataManagerTest { } } - private class TestChannelDataManagerChannelListener + private static class TestChannelDataManagerChannelListener implements ChannelDataManager.ChannelListener { public CountDownLatch channelChangedLatch = new CountDownLatch(1); public final List<Channel> removedChannels = new ArrayList<>(); diff --git a/tests/unit/src/com/android/tv/data/ChannelImplTest.java b/tests/unit/src/com/android/tv/data/ChannelImplTest.java new file mode 100644 index 00000000..b791a7e4 --- /dev/null +++ b/tests/unit/src/com/android/tv/data/ChannelImplTest.java @@ -0,0 +1,381 @@ +/* + * 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.data; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +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.support.test.runner.AndroidJUnit4; +import com.android.tv.data.api.Channel; +import com.android.tv.testing.ComparatorTester; +import com.android.tv.util.TvInputManagerHelper; +import java.util.Comparator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +/** Tests for {@link ChannelImpl}. */ +@SmallTest +@RunWith(AndroidJUnit4.class) +public class ChannelImplTest { + // 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 = "com.android.tv.invalid_tv_input"; + // Used for testing TV inputs defined inside of Live TV. + private static final String LIVE_CHANNELS_PACKAGE_NAME = "com.android.tv"; + // Used for testing a TV input which doesn't have its leanback launcher activity. + private static final String NONE_LEANBACK_TV_INPUT_PACKAGE_NAME = + "com.android.tv.none_leanback_tv_input"; + // Used for testing a TV input which has its leanback launcher activity. + private static final String LEANBACK_TV_INPUT_PACKAGE_NAME = "com.android.tv.leanback_tv_input"; + private static final String TEST_APP_LINK_TEXT = "test_app_link_text"; + private static final String PARTNER_INPUT_ID = "partner"; + private static final ActivityInfo TEST_ACTIVITY_INFO = new ActivityInfo(); + + private Context mMockContext; + private Intent mInvalidIntent; + private Intent mValidIntent; + + @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); + mValidIntent.setComponent(new ComponentName(LEANBACK_TV_INPUT_PACKAGE_NAME, ".test")); + Intent liveChannelsIntent = new Intent(Intent.ACTION_VIEW); + liveChannelsIntent.setComponent( + new ComponentName(LIVE_CHANNELS_PACKAGE_NAME, ".MainActivity")); + Intent leanbackTvInputIntent = new Intent(Intent.ACTION_VIEW); + leanbackTvInputIntent.setComponent( + new ComponentName(LEANBACK_TV_INPUT_PACKAGE_NAME, ".test")); + + PackageManager mockPackageManager = Mockito.mock(PackageManager.class); + Mockito.when( + mockPackageManager.getLeanbackLaunchIntentForPackage( + INVALID_TV_INPUT_PACKAGE_NAME)) + .thenReturn(null); + Mockito.when( + mockPackageManager.getLeanbackLaunchIntentForPackage( + LIVE_CHANNELS_PACKAGE_NAME)) + .thenReturn(liveChannelsIntent); + Mockito.when( + mockPackageManager.getLeanbackLaunchIntentForPackage( + NONE_LEANBACK_TV_INPUT_PACKAGE_NAME)) + .thenReturn(null); + Mockito.when( + mockPackageManager.getLeanbackLaunchIntentForPackage( + LEANBACK_TV_INPUT_PACKAGE_NAME)) + .thenReturn(leanbackTvInputIntent); + + // Channel.getAppLinkIntent() calls initAppLinkTypeAndIntent() which calls + // Intent.resolveActivityInfo() which calls PackageManager.getActivityInfo(). + Mockito.doAnswer( + new Answer<ActivityInfo>() { + @Override + public ActivityInfo answer(InvocationOnMock invocation) { + // We only check the package name, since the class name can be + // changed + // when an intent is changed to an uri and created from the uri. + // (ex, ".className" -> "packageName.className") + return mValidIntent + .getComponent() + .getPackageName() + .equals( + ((ComponentName) + invocation + .getArguments()[0]) + .getPackageName()) + ? TEST_ACTIVITY_INFO + : null; + } + }) + .when(mockPackageManager) + .getActivityInfo(Mockito.<ComponentName>any(), Mockito.anyInt()); + + mMockContext = Mockito.mock(Context.class); + Mockito.when(mMockContext.getApplicationContext()).thenReturn(mMockContext); + Mockito.when(mMockContext.getPackageName()).thenReturn(LIVE_CHANNELS_PACKAGE_NAME); + 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); + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, null, null); + assertAppLinkType(Channel.APP_LINK_TYPE_APP, LEANBACK_TV_INPUT_PACKAGE_NAME, null, null); + } + + @Test + public void testGetAppLinkType_NoText_InvalidIntent() { + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, INVALID_TV_INPUT_PACKAGE_NAME, null, mInvalidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, LIVE_CHANNELS_PACKAGE_NAME, null, mInvalidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, + NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, + null, + mInvalidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_APP, LEANBACK_TV_INPUT_PACKAGE_NAME, null, mInvalidIntent); + } + + @Test + public void testGetAppLinkType_NoText_ValidIntent() { + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, INVALID_TV_INPUT_PACKAGE_NAME, null, mValidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, LIVE_CHANNELS_PACKAGE_NAME, null, mValidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, + NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, + null, + mValidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_APP, LEANBACK_TV_INPUT_PACKAGE_NAME, null, mValidIntent); + } + + @Test + public void testGetAppLinkType_HasText_NoIntent() { + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, + INVALID_TV_INPUT_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + null); + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, LIVE_CHANNELS_PACKAGE_NAME, TEST_APP_LINK_TEXT, null); + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, + NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + null); + assertAppLinkType( + Channel.APP_LINK_TYPE_APP, + LEANBACK_TV_INPUT_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + null); + } + + @Test + public void testGetAppLinkType_HasText_InvalidIntent() { + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, + INVALID_TV_INPUT_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + mInvalidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, + LIVE_CHANNELS_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + mInvalidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_NONE, + NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + mInvalidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_APP, + LEANBACK_TV_INPUT_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + mInvalidIntent); + } + + @Test + public void testGetAppLinkType_HasText_ValidIntent() { + assertAppLinkType( + Channel.APP_LINK_TYPE_CHANNEL, + INVALID_TV_INPUT_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + mValidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_CHANNEL, + LIVE_CHANNELS_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + mValidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_CHANNEL, + NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + mValidIntent); + assertAppLinkType( + Channel.APP_LINK_TYPE_CHANNEL, + LEANBACK_TV_INPUT_PACKAGE_NAME, + TEST_APP_LINK_TEXT, + mValidIntent); + } + + private void assertAppLinkType( + int expectedType, String inputPackageName, String appLinkText, Intent appLinkIntent) { + // In ChannelImpl, Intent.URI_INTENT_SCHEME is used to parse the URI. So the same flag + // should be + // used when the URI is created. + ChannelImpl testChannel = + new ChannelImpl.Builder() + .setPackageName(inputPackageName) + .setAppLinkText(appLinkText) + .setAppLinkIntentUri( + appLinkIntent == null + ? null + : appLinkIntent.toUri(Intent.URI_INTENT_SCHEME)) + .build(); + assertWithMessage("Unexpected app-link type for for " + testChannel) + .that(testChannel.getAppLinkType(mMockContext)) + .isEqualTo(expectedType); + } + + @Test + public void testComparator() { + TvInputManagerHelper manager = Mockito.mock(TvInputManagerHelper.class); + Mockito.when(manager.isPartnerInput(Matchers.anyString())) + .thenAnswer( + new Answer<Boolean>() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + String inputId = (String) invocation.getArguments()[0]; + return PARTNER_INPUT_ID.equals(inputId); + } + }); + Comparator<Channel> comparator = new TestChannelComparator(manager); + ComparatorTester<Channel> comparatorTester = ComparatorTester.withoutEqualsTest(comparator); + comparatorTester.addComparableGroup( + new ChannelImpl.Builder().setInputId(PARTNER_INPUT_ID).build()); + comparatorTester.addComparableGroup(new ChannelImpl.Builder().setInputId("1").build()); + comparatorTester.addComparableGroup( + new ChannelImpl.Builder().setInputId("1").setDisplayNumber("2").build()); + comparatorTester.addComparableGroup( + new ChannelImpl.Builder().setInputId("2").setDisplayNumber("1.0").build()); + + // display name does not affect comparator + comparatorTester.addComparableGroup( + new ChannelImpl.Builder() + .setInputId("2") + .setDisplayNumber("1.62") + .setDisplayName("test1") + .build(), + new ChannelImpl.Builder() + .setInputId("2") + .setDisplayNumber("1.62") + .setDisplayName("test2") + .build(), + new ChannelImpl.Builder() + .setInputId("2") + .setDisplayNumber("1.62") + .setDisplayName("test3") + .build()); + comparatorTester.addComparableGroup( + new ChannelImpl.Builder().setInputId("2").setDisplayNumber("2.0").build()); + // Numeric display number sorting + comparatorTester.addComparableGroup( + new ChannelImpl.Builder().setInputId("2").setDisplayNumber("12.2").build()); + comparatorTester.test(); + } + + /** + * Test Input Label handled by {@link ChannelImpl.DefaultComparator}. + * + * <p>Sort partner inputs first, then sort by input label, then by input id. See <a + * href="http://b/23031603">b/23031603</a>. + */ + @Test + public void testComparatorLabel() { + TvInputManagerHelper manager = Mockito.mock(TvInputManagerHelper.class); + Mockito.when(manager.isPartnerInput(Matchers.anyString())) + .thenAnswer( + new Answer<Boolean>() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + String inputId = (String) invocation.getArguments()[0]; + return PARTNER_INPUT_ID.equals(inputId); + } + }); + Comparator<Channel> comparator = new ChannelComparatorWithDescriptionAsLabel(manager); + ComparatorTester<Channel> comparatorTester = ComparatorTester.withoutEqualsTest(comparator); + + comparatorTester.addComparableGroup( + new ChannelImpl.Builder().setInputId(PARTNER_INPUT_ID).setDescription("A").build()); + + // The description is used as a label for this test. + comparatorTester.addComparableGroup( + new ChannelImpl.Builder().setDescription("A").setInputId("1").build()); + comparatorTester.addComparableGroup( + new ChannelImpl.Builder().setDescription("A").setInputId("2").build()); + comparatorTester.addComparableGroup( + new ChannelImpl.Builder().setDescription("B").setInputId("1").build()); + + comparatorTester.test(); + } + + @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) { + assertThat(ChannelImpl.normalizeDisplayNumber(displayNumber)).isEqualTo(normalized); + } + + private static final class TestChannelComparator extends ChannelImpl.DefaultComparator { + public TestChannelComparator(TvInputManagerHelper manager) { + super(null, manager); + } + + @Override + public String getInputLabelForChannel(Channel channel) { + return channel.getInputId(); + } + } + + private static final class ChannelComparatorWithDescriptionAsLabel + extends ChannelImpl.DefaultComparator { + public ChannelComparatorWithDescriptionAsLabel(TvInputManagerHelper manager) { + super(null, manager); + } + + @Override + public String getInputLabelForChannel(Channel channel) { + return channel.getDescription(); + } + } +} diff --git a/tests/unit/src/com/android/tv/data/ChannelNumberTest.java b/tests/unit/src/com/android/tv/data/ChannelNumberTest.java deleted file mode 100644 index 827dcdbd..00000000 --- a/tests/unit/src/com/android/tv/data/ChannelNumberTest.java +++ /dev/null @@ -1,97 +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.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 org.junit.Test; - -/** - * Tests for {@link ChannelNumber}. - */ -@SmallTest -public class ChannelNumberTest { - /** - * Test method for {@link ChannelNumber#ChannelNumber()}. - */ - @Test - public void testChannelNumber() { - assertChannelEquals(new ChannelNumber(), "", false, ""); - } - - /** - * Test method for - * {@link com.android.tv.data.ChannelNumber#parseChannelNumber(java.lang.String)}. - */ - @Test - public void testParseChannelNumber() { - 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("3-4"), "3", true, "4"); - 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")) - .addEquivalentGroup(parseChannelNumber("2-2")) - .addEquivalentGroup(parseChannelNumber("2-10")) - .addEquivalentGroup(parseChannelNumber("3")) - .addEquivalentGroup(parseChannelNumber("4"), parseChannelNumber("4-0")) - .addEquivalentGroup(parseChannelNumber("10")) - .addEquivalentGroup(parseChannelNumber("100")) - .test(); - } - - /** - * 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)); - assertEquals("compareTo(1,1)", 0, ChannelNumber.compare("1", "1")); - assertEquals("compareTo(null,1)<0", true, ChannelNumber.compare(null, "1") < 0); - assertEquals("compareTo(mal-formatted,1)<0", true, ChannelNumber.compare("abcd", "1") < 0); - assertEquals("compareTo(mal-formatted,1)<0", true, ChannelNumber.compare(".4", "1") < 0); - assertEquals("compareTo(1,null)>0", true, ChannelNumber.compare("1", null) > 0); - } - - private void assertChannelEquals(ChannelNumber actual, String expectedMajor, - boolean expectedHasDelimiter, String expectedMinor) { - assertEquals(actual + " major", actual.majorNumber, expectedMajor); - assertEquals(actual + " hasDelimiter", actual.hasDelimiter, expectedHasDelimiter); - assertEquals(actual + " minor", actual.minorNumber, expectedMinor); - } - -} diff --git a/tests/unit/src/com/android/tv/data/ChannelTest.java b/tests/unit/src/com/android/tv/data/ChannelTest.java deleted file mode 100644 index 69fcb858..00000000 --- a/tests/unit/src/com/android/tv/data/ChannelTest.java +++ /dev/null @@ -1,312 +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.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 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; -import org.mockito.stubbing.Answer; - -import java.util.Comparator; - -/** - * Tests for {@link Channel}. - */ -@SmallTest -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 = - "com.android.tv.invalid_tv_input"; - // Used for testing TV inputs defined inside of Live TV. - private static final String LIVE_CHANNELS_PACKAGE_NAME = "com.android.tv"; - // Used for testing a TV input which doesn't have its leanback launcher activity. - private static final String NONE_LEANBACK_TV_INPUT_PACKAGE_NAME = - "com.android.tv.none_leanback_tv_input"; - // Used for testing a TV input which has its leanback launcher activity. - private static final String LEANBACK_TV_INPUT_PACKAGE_NAME = - "com.android.tv.leanback_tv_input"; - private static final String TEST_APP_LINK_TEXT = "test_app_link_text"; - private static final String PARTNER_INPUT_ID = "partner"; - private static final ActivityInfo TEST_ACTIVITY_INFO = new ActivityInfo(); - - private Context mMockContext; - private Intent mInvalidIntent; - private Intent mValidIntent; - - @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); - mValidIntent.setComponent(new ComponentName(LEANBACK_TV_INPUT_PACKAGE_NAME, ".test")); - Intent liveChannelsIntent = new Intent(Intent.ACTION_VIEW); - liveChannelsIntent.setComponent( - new ComponentName(LIVE_CHANNELS_PACKAGE_NAME, ".MainActivity")); - Intent leanbackTvInputIntent = new Intent(Intent.ACTION_VIEW); - leanbackTvInputIntent.setComponent( - new ComponentName(LEANBACK_TV_INPUT_PACKAGE_NAME, ".test")); - - PackageManager mockPackageManager = Mockito.mock(PackageManager.class); - Mockito.when(mockPackageManager.getLeanbackLaunchIntentForPackage( - INVALID_TV_INPUT_PACKAGE_NAME)).thenReturn(null); - Mockito.when(mockPackageManager.getLeanbackLaunchIntentForPackage( - LIVE_CHANNELS_PACKAGE_NAME)).thenReturn(liveChannelsIntent); - Mockito.when(mockPackageManager.getLeanbackLaunchIntentForPackage( - NONE_LEANBACK_TV_INPUT_PACKAGE_NAME)).thenReturn(null); - Mockito.when(mockPackageManager.getLeanbackLaunchIntentForPackage( - LEANBACK_TV_INPUT_PACKAGE_NAME)).thenReturn(leanbackTvInputIntent); - - // Channel.getAppLinkIntent() calls initAppLinkTypeAndIntent() which calls - // Intent.resolveActivityInfo() which calls PackageManager.getActivityInfo(). - Mockito.doAnswer(new Answer<ActivityInfo>() { - @Override - public ActivityInfo answer(InvocationOnMock invocation) { - // We only check the package name, since the class name can be changed - // when an intent is changed to an uri and created from the uri. - // (ex, ".className" -> "packageName.className") - return mValidIntent.getComponent().getPackageName().equals( - ((ComponentName)invocation.getArguments()[0]).getPackageName()) - ? TEST_ACTIVITY_INFO : null; - } - }).when(mockPackageManager).getActivityInfo(Mockito.<ComponentName>any(), Mockito.anyInt()); - - mMockContext = Mockito.mock(Context.class); - Mockito.when(mMockContext.getApplicationContext()).thenReturn(mMockContext); - Mockito.when(mMockContext.getPackageName()).thenReturn(LIVE_CHANNELS_PACKAGE_NAME); - 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); - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, null, - null); - assertAppLinkType(Channel.APP_LINK_TYPE_APP, LEANBACK_TV_INPUT_PACKAGE_NAME, null, null); - } - - @Test - public void testGetAppLinkType_NoText_InvalidIntent() { - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, INVALID_TV_INPUT_PACKAGE_NAME, null, - mInvalidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, LIVE_CHANNELS_PACKAGE_NAME, null, - mInvalidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, null, - mInvalidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_APP, LEANBACK_TV_INPUT_PACKAGE_NAME, null, - mInvalidIntent); - } - - @Test - public void testGetAppLinkType_NoText_ValidIntent() { - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, INVALID_TV_INPUT_PACKAGE_NAME, null, - mValidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, LIVE_CHANNELS_PACKAGE_NAME, null, - mValidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, null, - mValidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_APP, LEANBACK_TV_INPUT_PACKAGE_NAME, null, - mValidIntent); - } - - @Test - public void testGetAppLinkType_HasText_NoIntent() { - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, INVALID_TV_INPUT_PACKAGE_NAME, - TEST_APP_LINK_TEXT, null); - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, LIVE_CHANNELS_PACKAGE_NAME, - TEST_APP_LINK_TEXT, null); - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, - TEST_APP_LINK_TEXT, null); - assertAppLinkType(Channel.APP_LINK_TYPE_APP, LEANBACK_TV_INPUT_PACKAGE_NAME, - TEST_APP_LINK_TEXT, null); - } - - @Test - public void testGetAppLinkType_HasText_InvalidIntent() { - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, INVALID_TV_INPUT_PACKAGE_NAME, - TEST_APP_LINK_TEXT, mInvalidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, LIVE_CHANNELS_PACKAGE_NAME, - TEST_APP_LINK_TEXT, mInvalidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_NONE, NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, - TEST_APP_LINK_TEXT, mInvalidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_APP, LEANBACK_TV_INPUT_PACKAGE_NAME, - TEST_APP_LINK_TEXT, mInvalidIntent); - } - - @Test - public void testGetAppLinkType_HasText_ValidIntent() { - assertAppLinkType(Channel.APP_LINK_TYPE_CHANNEL, INVALID_TV_INPUT_PACKAGE_NAME, - TEST_APP_LINK_TEXT, mValidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_CHANNEL, LIVE_CHANNELS_PACKAGE_NAME, - TEST_APP_LINK_TEXT, mValidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_CHANNEL, NONE_LEANBACK_TV_INPUT_PACKAGE_NAME, - TEST_APP_LINK_TEXT, mValidIntent); - assertAppLinkType(Channel.APP_LINK_TYPE_CHANNEL, LEANBACK_TV_INPUT_PACKAGE_NAME, - TEST_APP_LINK_TEXT, mValidIntent); - } - - private void assertAppLinkType(int expectedType, String inputPackageName, String appLinkText, - Intent appLinkIntent) { - // In Channel, Intent.URI_INTENT_SCHEME is used to parse the URI. So the same flag should be - // used when the URI is created. - Channel testChannel = new Channel.Builder() - .setPackageName(inputPackageName) - .setAppLinkText(appLinkText) - .setAppLinkIntentUri(appLinkIntent == null ? null : appLinkIntent.toUri( - Intent.URI_INTENT_SCHEME)) - .build(); - assertEquals("Unexpected app-link type for for " + testChannel, - expectedType, testChannel.getAppLinkType(mMockContext)); - } - - @Test - public void testComparator() { - - TvInputManagerHelper manager = Mockito.mock(TvInputManagerHelper.class); - Mockito.when(manager.isPartnerInput(Matchers.anyString())).thenAnswer( - new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - String inputId = (String) invocation.getArguments()[0]; - return PARTNER_INPUT_ID.equals(inputId); - } - }); - Comparator<Channel> comparator = new TestChannelComparator(manager); - ComparatorTester<Channel> comparatorTester = - ComparatorTester.withoutEqualsTest(comparator); - comparatorTester.addComparableGroup( - new Channel.Builder().setInputId(PARTNER_INPUT_ID).build()); - comparatorTester.addComparableGroup( - new Channel.Builder().setInputId("1").build()); - comparatorTester.addComparableGroup( - new Channel.Builder().setInputId("1").setDisplayNumber("2").build()); - comparatorTester.addComparableGroup( - new Channel.Builder().setInputId("2").setDisplayNumber("1.0").build()); - - // display name does not affect comparator - comparatorTester.addComparableGroup( - new Channel.Builder().setInputId("2").setDisplayNumber("1.62") - .setDisplayName("test1").build(), - new Channel.Builder().setInputId("2").setDisplayNumber("1.62") - .setDisplayName("test2").build(), - new Channel.Builder().setInputId("2").setDisplayNumber("1.62") - .setDisplayName("test3").build()); - comparatorTester.addComparableGroup( - new Channel.Builder().setInputId("2").setDisplayNumber("2.0").build()); - // Numeric display number sorting - comparatorTester.addComparableGroup( - new Channel.Builder().setInputId("2").setDisplayNumber("12.2").build()); - comparatorTester.test(); - } - - /** - * Test Input Label handled by {@link com.android.tv.data.Channel.DefaultComparator}. - * - * <p>Sort partner inputs first, then sort by input label, then by input id. - * See <a href="http://b/23031603">b/23031603</a>. - */ - @Test - public void testComparatorLabel() { - TvInputManagerHelper manager = Mockito.mock(TvInputManagerHelper.class); - Mockito.when(manager.isPartnerInput(Matchers.anyString())).thenAnswer( - new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - String inputId = (String) invocation.getArguments()[0]; - return PARTNER_INPUT_ID.equals(inputId); - } - }); - Comparator<Channel> comparator = new ChannelComparatorWithDescriptionAsLabel(manager); - ComparatorTester<Channel> comparatorTester = - ComparatorTester.withoutEqualsTest(comparator); - - comparatorTester.addComparableGroup( - new Channel.Builder().setInputId(PARTNER_INPUT_ID).setDescription("A").build()); - - // The description is used as a label for this test. - comparatorTester.addComparableGroup( - new Channel.Builder().setDescription("A").setInputId("1").build()); - comparatorTester.addComparableGroup( - new Channel.Builder().setDescription("A").setInputId("2").build()); - comparatorTester.addComparableGroup( - new Channel.Builder().setDescription("B").setInputId("1").build()); - - comparatorTester.test(); - } - - @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); - } - - @Override - public String getInputLabelForChannel(Channel channel) { - return channel.getInputId(); - } - } - - private static class ChannelComparatorWithDescriptionAsLabel extends Channel.DefaultComparator { - public ChannelComparatorWithDescriptionAsLabel(TvInputManagerHelper manager) { - super(null, manager); - } - - @Override - public String getInputLabelForChannel(Channel channel) { - return channel.getDescription(); - } - } -} diff --git a/tests/unit/src/com/android/tv/data/GenreItemTest.java b/tests/unit/src/com/android/tv/data/GenreItemTest.java deleted file mode 100644 index fdbcb599..00000000 --- a/tests/unit/src/com/android/tv/data/GenreItemTest.java +++ /dev/null @@ -1,94 +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.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 org.junit.Test; - -/** - * Tests for {@link Channel}. - */ -@SmallTest -public class GenreItemTest { - private static final String INVALID_GENRE = "INVALID GENRE"; - - @Test - public void testGetLabels() { - // Checks if no exception is thrown. - GenreItems.getLabels(getTargetContext()); - } - - @Test - public void testGetCanonicalGenre() { - int count = GenreItems.getGenreCount(); - assertNull(GenreItems.getCanonicalGenre(GenreItems.ID_ALL_CHANNELS)); - for (int i = 1; i < count; ++i) { - assertNotNull(GenreItems.getCanonicalGenre(i)); - } - } - - @Test - public void testGetId_base() { - int count = GenreItems.getGenreCount(); - assertEquals(GenreItems.ID_ALL_CHANNELS, GenreItems.getId(null)); - assertEquals(GenreItems.ID_ALL_CHANNELS, GenreItems.getId(INVALID_GENRE)); - assertInRange(GenreItems.getId(Genres.FAMILY_KIDS), 1, count - 1); - assertInRange(GenreItems.getId(Genres.SPORTS), 1, count - 1); - assertInRange(GenreItems.getId(Genres.SHOPPING), 1, count - 1); - assertInRange(GenreItems.getId(Genres.MOVIES), 1, count - 1); - assertInRange(GenreItems.getId(Genres.COMEDY), 1, count - 1); - assertInRange(GenreItems.getId(Genres.TRAVEL), 1, count - 1); - assertInRange(GenreItems.getId(Genres.DRAMA), 1, count - 1); - assertInRange(GenreItems.getId(Genres.EDUCATION), 1, count - 1); - assertInRange(GenreItems.getId(Genres.ANIMAL_WILDLIFE), 1, count - 1); - assertInRange(GenreItems.getId(Genres.NEWS), 1, count - 1); - 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)); - assertEquals(GenreItems.ID_ALL_CHANNELS, GenreItems.getId(Genres.ENTERTAINMENT)); - assertEquals(GenreItems.ID_ALL_CHANNELS, GenreItems.getId(Genres.LIFE_STYLE)); - assertEquals(GenreItems.ID_ALL_CHANNELS, GenreItems.getId(Genres.MUSIC)); - assertEquals(GenreItems.ID_ALL_CHANNELS, GenreItems.getId(Genres.PREMIER)); - assertEquals(GenreItems.ID_ALL_CHANNELS, GenreItems.getId(Genres.TECH_SCIENCE)); - } else { - int count = GenreItems.getGenreCount(); - assertInRange(GenreItems.getId(Genres.ARTS), 1, count - 1); - assertInRange(GenreItems.getId(Genres.ENTERTAINMENT), 1, count - 1); - assertInRange(GenreItems.getId(Genres.LIFE_STYLE), 1, count - 1); - assertInRange(GenreItems.getId(Genres.MUSIC), 1, count - 1); - assertInRange(GenreItems.getId(Genres.PREMIER), 1, count - 1); - assertInRange(GenreItems.getId(Genres.TECH_SCIENCE), 1, count - 1); - } - } - - private void assertInRange(int value, int lower, int upper) { - assertTrue(value >= lower && value <= upper); - } -} diff --git a/tests/unit/src/com/android/tv/data/ProgramDataManagerTest.java b/tests/unit/src/com/android/tv/data/ProgramDataManagerTest.java deleted file mode 100644 index 5457051f..00000000 --- a/tests/unit/src/com/android/tv/data/ProgramDataManagerTest.java +++ /dev/null @@ -1,542 +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.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.mock.MockContentProvider; -import android.test.mock.MockContentResolver; -import android.test.mock.MockCursor; -import android.util.Log; -import android.util.SparseArray; - -import com.android.tv.testing.Constants; -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; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Test for {@link com.android.tv.data.ProgramDataManager} - */ -@SmallTest -public class ProgramDataManagerTest { - private static final boolean DEBUG = false; - private static final String TAG = "ProgramDataManagerTest"; - - // Wait time for expected success. - private static final long WAIT_TIME_OUT_MS = 1000L; - // Wait time for expected failure. - private static final long FAILURE_TIME_OUT_MS = 300L; - - // TODO: Use TvContract constants, once they become public. - private static final String PARAM_CHANNEL = "channel"; - private static final String PARAM_START_TIME = "start_time"; - private static final String PARAM_END_TIME = "end_time"; - - private ProgramDataManager mProgramDataManager; - private FakeClock mClock; - private HandlerThread mHandlerThread; - private TestProgramDataManagerListener mListener; - private FakeContentResolver mContentResolver; - private FakeContentProvider mContentProvider; - - @Before - public void setUp() { - mClock = FakeClock.createWithCurrentTime(); - mListener = new TestProgramDataManagerListener(); - 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()); - mProgramDataManager.setPrefetchEnabled(true); - mProgramDataManager.addListener(mListener); - } - - @After - public void tearDown() { - mHandlerThread.quitSafely(); - mProgramDataManager.stop(); - } - - private void startAndWaitForComplete() throws InterruptedException { - mProgramDataManager.start(); - assertTrue(mListener.programUpdatedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); - } - - /** - * 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(InstrumentationRegistry.getContext(), index); - assertTrue(startTimeMs <= mClock.currentTimeMillis()); - assertTrue(mClock.currentTimeMillis() < startTimeMs + programAt.durationMs); - } - } - - /** - * Test for following methods. - * - * <p> - * {@link ProgramDataManager#getCurrentProgram(long)}, - * {@link ProgramDataManager#getPrograms(long, long)}, - * {@link ProgramDataManager#setPrefetchTimeRange(long)}. - * </p> - */ - @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; - mClock.setCurrentTimeMillis(prefetchTimeRangeStartMs + preventSnapDelayMs); - mProgramDataManager.setPrefetchTimeRange(prefetchTimeRangeStartMs); - - startAndWaitForComplete(); - - for (long channelId = 1; channelId <= Constants.UNIT_TEST_CHANNEL_COUNT; channelId++) { - Program currentProgram = mProgramDataManager.getCurrentProgram(channelId); - // Test {@link ProgramDataManager#getCurrentProgram(long)}. - assertTrue(currentProgram.getStartTimeUtcMillis() <= mClock.currentTimeMillis() - && mClock.currentTimeMillis() <= currentProgram.getEndTimeUtcMillis()); - - // Test {@link ProgramDataManager#getPrograms(long)}. - // Case #1: Normal case - List<Program> programs = - mProgramDataManager.getPrograms(channelId, mClock.currentTimeMillis()); - ProgramInfo stub = ProgramInfo.create(); - int index = stub.getIndex(mClock.currentTimeMillis(), channelId); - for (Program program : programs) { - ProgramInfo programInfoAt = stub.build(InstrumentationRegistry.getContext(), index); - long startTimeMs = stub.getStartTimeMs(index, channelId); - assertProgramEquals(startTimeMs, programInfoAt, program); - index++; - } - // Case #2: Corner cases where there's a program that starts at the start of the range. - long startTimeMs = programs.get(0).getStartTimeUtcMillis(); - programs = mProgramDataManager.getPrograms(channelId, startTimeMs); - assertEquals(startTimeMs, programs.get(0).getStartTimeUtcMillis()); - - // Test {@link ProgramDataManager#setPrefetchTimeRange(long)}. - programs = mProgramDataManager.getPrograms(channelId, - prefetchTimeRangeStartMs - TimeUnit.HOURS.toMillis(1)); - for (Program program : programs) { - assertTrue(program.getEndTimeUtcMillis() >= prefetchTimeRangeStartMs); - } - } - } - - /** - * Test for following methods. - * - * <p> - * {@link ProgramDataManager#addOnCurrentProgramUpdatedListener}, - * {@link ProgramDataManager#removeOnCurrentProgramUpdatedListener}. - * </p> - */ - @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(InstrumentationRegistry.getContext(), index + 1); - mClock.setCurrentTimeMillis(nextProgramStartTimeMs - (WAIT_TIME_OUT_MS / 2)); - - startAndWaitForComplete(); - // Note that changing current time doesn't affect the current program - // because current program is updated after waiting for the program's duration. - // See {@link ProgramDataManager#updateCurrentProgram}. - mClock.setCurrentTimeMillis(mClock.currentTimeMillis() + WAIT_TIME_OUT_MS); - TestProgramDataManagerOnCurrentProgramUpdatedListener listener = - new TestProgramDataManagerOnCurrentProgramUpdatedListener(); - mProgramDataManager.addOnCurrentProgramUpdatedListener(testChannelId, listener); - assertTrue( - listener.currentProgramUpdatedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); - assertEquals(testChannelId, listener.updatedChannelId); - Program currentProgram = mProgramDataManager.getCurrentProgram(testChannelId); - assertProgramEquals(nextProgramStartTimeMs, nextProgramInfo, currentProgram); - assertEquals(listener.updatedProgram, currentProgram); - } - - /** - * Test if program data is refreshed after the program insertion. - */ - @Test - public void testContentProviderUpdate() throws InterruptedException { - final long testChannelId = 1; - startAndWaitForComplete(); - // Force program data manager to update program data whenever it's changes. - mProgramDataManager.setProgramPrefetchUpdateWait(0); - mListener.reset(); - List<Program> programList = - mProgramDataManager.getPrograms(testChannelId, mClock.currentTimeMillis()); - assertNotNull(programList); - long lastProgramEndTime = programList.get(programList.size() - 1).getEndTimeUtcMillis(); - // Make change in content provider - mContentProvider.simulateAppend(testChannelId); - assertTrue(mListener.programUpdatedLatch.await(WAIT_TIME_OUT_MS, TimeUnit.MILLISECONDS)); - programList = mProgramDataManager.getPrograms(testChannelId, mClock.currentTimeMillis()); - assertTrue( - lastProgramEndTime < programList.get(programList.size() - 1).getEndTimeUtcMillis()); - } - - /** - * Test for {@link ProgramDataManager#setPauseProgramUpdate(boolean)}. - */ - @Test - public void testSetPauseProgramUpdate() throws InterruptedException { - final long testChannelId = 1; - startAndWaitForComplete(); - // Force program data manager to update program data whenever it's changes. - mProgramDataManager.setProgramPrefetchUpdateWait(0); - mListener.reset(); - mProgramDataManager.setPauseProgramUpdate(true); - mContentProvider.simulateAppend(testChannelId); - assertFalse(mListener.programUpdatedLatch.await(FAILURE_TIME_OUT_MS, - TimeUnit.MILLISECONDS)); - } - - public static void assertProgramEquals(long expectedStartTime, ProgramInfo expectedInfo, - Program actualProgram) { - assertEquals("title", expectedInfo.title, actualProgram.getTitle()); - assertEquals("episode", expectedInfo.episode, actualProgram.getEpisodeTitle()); - assertEquals("description", expectedInfo.description, actualProgram.getDescription()); - assertEquals("startTime", expectedStartTime, actualProgram.getStartTimeUtcMillis()); - assertEquals("endTime", expectedStartTime + expectedInfo.durationMs, - actualProgram.getEndTimeUtcMillis()); - } - - private class FakeContentResolver extends MockContentResolver { - @Override - public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) { - super.notifyChange(uri, observer, syncToNetwork); - if (DEBUG) { - Log.d(TAG, "onChanged(uri=" + uri + ")"); - } - if (observer != null) { - observer.dispatchChange(false, uri); - } else { - mProgramDataManager.getContentObserver().dispatchChange(false, uri); - } - } - } - - private static class ProgramInfoWrapper { - private final int index; - private final long startTimeMs; - private final ProgramInfo programInfo; - - public ProgramInfoWrapper(int index, long startTimeMs, ProgramInfo programInfo) { - this.index = index; - this.startTimeMs = startTimeMs; - this.programInfo = programInfo; - } - } - - // This implements the minimal methods in content resolver - // and detailed assumptions are written in each method. - private class FakeContentProvider extends MockContentProvider { - private final SparseArray<List<ProgramInfoWrapper>> mProgramInfoList = new SparseArray<>(); - - /** - * Constructor for FakeContentProvider - * <p> - * This initializes program info assuming that - * channel IDs are 1, 2, 3, ... {@link Constants#UNIT_TEST_CHANNEL_COUNT}. - * </p> - */ - public FakeContentProvider(Context context) { - super(context); - long startTimeMs = Utils.floorTime( - mClock.currentTimeMillis() - ProgramDataManager.PROGRAM_GUIDE_SNAP_TIME_MS, - ProgramDataManager.PROGRAM_GUIDE_SNAP_TIME_MS); - long endTimeMs = startTimeMs + (ProgramDataManager.PROGRAM_GUIDE_MAX_TIME_RANGE / 2); - for (int i = 1; i <= Constants.UNIT_TEST_CHANNEL_COUNT; i++) { - List<ProgramInfoWrapper> programInfoList = new ArrayList<>(); - ProgramInfo stub = ProgramInfo.create(); - int index = stub.getIndex(startTimeMs, i); - long programStartTimeMs = stub.getStartTimeMs(index, i); - while (programStartTimeMs < endTimeMs) { - ProgramInfo programAt = stub.build(InstrumentationRegistry.getContext(), index); - programInfoList.add( - new ProgramInfoWrapper(index, programStartTimeMs, programAt)); - index++; - programStartTimeMs += programAt.durationMs; - } - mProgramInfoList.put(i, programInfoList); - } - } - - @Override - public Cursor query(Uri uri, String[] projection, String selection, - String[] selectionArgs, String sortOrder) { - if (DEBUG) { - Log.d(TAG, "dump query"); - Log.d(TAG, " uri=" + uri); - Log.d(TAG, " projection=" + Arrays.toString(projection)); - Log.d(TAG, " selection=" + selection); - } - long startTimeMs = Long.parseLong(uri.getQueryParameter(PARAM_START_TIME)); - long endTimeMs = Long.parseLong(uri.getQueryParameter(PARAM_END_TIME)); - if (startTimeMs == 0 || endTimeMs == 0) { - throw new UnsupportedOperationException(); - } - assertProgramUri(uri); - long channelId; - try { - channelId = Long.parseLong(uri.getQueryParameter(PARAM_CHANNEL)); - } catch (NumberFormatException e) { - channelId = -1; - } - return new FakeCursor(projection, channelId, startTimeMs, endTimeMs); - } - - /** - * Simulate program data appends at the end of the existing programs. - * This appends programs until the maximum program query range - * ({@link ProgramDataManager#PROGRAM_GUIDE_MAX_TIME_RANGE}) - * where we started with the inserting half of it. - */ - public void simulateAppend(long channelId) { - long endTimeMs = - mClock.currentTimeMillis() + ProgramDataManager.PROGRAM_GUIDE_MAX_TIME_RANGE; - List<ProgramInfoWrapper> programList = mProgramInfoList.get((int) channelId); - if (mProgramInfoList == null) { - return; - } - ProgramInfo stub = ProgramInfo.create(); - ProgramInfoWrapper last = programList.get(programList.size() - 1); - while (last.startTimeMs < endTimeMs) { - 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); - last = next; - } - mContentResolver.notifyChange(TvContract.Programs.CONTENT_URI, null); - } - - private void assertProgramUri(Uri uri) { - assertTrue("Uri(" + uri + ") isn't channel uri", - uri.toString().startsWith(TvContract.Programs.CONTENT_URI.toString())); - } - - public ProgramInfoWrapper get(long channelId, int position) { - List<ProgramInfoWrapper> programList = mProgramInfoList.get((int) channelId); - if (programList == null || position >= programList.size()) { - return null; - } - return programList.get(position); - } - } - - private class FakeCursor extends MockCursor { - private final String[] ALL_COLUMNS = { - TvContract.Programs.COLUMN_CHANNEL_ID, - TvContract.Programs.COLUMN_TITLE, - TvContract.Programs.COLUMN_SHORT_DESCRIPTION, - TvContract.Programs.COLUMN_EPISODE_TITLE, - TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS, - TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS}; - private final String[] mColumns; - private final boolean mIsQueryForSingleChannel; - private final long mStartTimeMs; - private final long mEndTimeMs; - private final int mCount; - private long mChannelId; - private int mProgramPosition; - private ProgramInfoWrapper mCurrentProgram; - - /** - * Constructor - * @param columns the same as projection passed from {@link FakeContentProvider#query}. - * Can be null for query all. - * @param channelId channel ID to query programs belongs to the specified channel. - * Can be negative to indicate all channels. - * @param startTimeMs start of the time range to query programs. - * @param endTimeMs end of the time range to query programs. - */ - public FakeCursor(String[] columns, long channelId, long startTimeMs, long endTimeMs) { - mColumns = (columns == null) ? ALL_COLUMNS : columns; - mIsQueryForSingleChannel = (channelId > 0); - mChannelId = channelId; - mProgramPosition = -1; - mStartTimeMs = startTimeMs; - mEndTimeMs = endTimeMs; - int count = 0; - while (moveToNext()) { - count++; - } - mCount = count; - // Rewind channel Id and program index. - mChannelId = channelId; - mProgramPosition = -1; - if (DEBUG) { - Log.d(TAG, "FakeCursor(columns=" + Arrays.toString(columns) - + ", channelId=" + channelId + ", startTimeMs=" + startTimeMs - + ", endTimeMs=" + endTimeMs + ") has mCount=" + mCount); - } - } - - @Override - public String getColumnName(int columnIndex) { - return mColumns[columnIndex]; - } - - @Override - public int getColumnIndex(String columnName) { - for (int i = 0; i < mColumns.length; i++) { - if (mColumns[i].equalsIgnoreCase(columnName)) { - return i; - } - } - return -1; - } - - @Override - public int getInt(int columnIndex) { - if (DEBUG) { - Log.d(TAG, "Column (" + getColumnName(columnIndex) + ") is ignored in getInt()"); - } - return 0; - } - - @Override - public long getLong(int columnIndex) { - String columnName = getColumnName(columnIndex); - switch (columnName) { - case TvContract.Programs.COLUMN_CHANNEL_ID: - return mChannelId; - case TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS: - return mCurrentProgram.startTimeMs; - case TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS: - return mCurrentProgram.startTimeMs + mCurrentProgram.programInfo.durationMs; - } - if (DEBUG) { - Log.d(TAG, "Column (" + columnName + ") is ignored in getLong()"); - } - return 0; - } - - @Override - public String getString(int columnIndex) { - String columnName = getColumnName(columnIndex); - switch (columnName) { - case TvContract.Programs.COLUMN_TITLE: - return mCurrentProgram.programInfo.title; - case TvContract.Programs.COLUMN_SHORT_DESCRIPTION: - return mCurrentProgram.programInfo.description; - case TvContract.Programs.COLUMN_EPISODE_TITLE: - return mCurrentProgram.programInfo.episode; - } - if (DEBUG) { - Log.d(TAG, "Column (" + columnName + ") is ignored in getString()"); - } - return null; - } - - @Override - public int getCount() { - return mCount; - } - - @Override - public boolean moveToNext() { - while (true) { - ProgramInfoWrapper program = mContentProvider.get(mChannelId, ++mProgramPosition); - if (program == null || program.startTimeMs >= mEndTimeMs) { - if (mIsQueryForSingleChannel) { - return false; - } else { - if (++mChannelId > Constants.UNIT_TEST_CHANNEL_COUNT) { - return false; - } - mProgramPosition = -1; - } - } else if (program.startTimeMs + program.programInfo.durationMs >= mStartTimeMs) { - mCurrentProgram = program; - break; - } - } - return true; - } - - @Override - public void close() { - // No-op. - } - } - - private class TestProgramDataManagerListener implements ProgramDataManager.Listener { - public CountDownLatch programUpdatedLatch = new CountDownLatch(1); - - @Override - public void onProgramUpdated() { - programUpdatedLatch.countDown(); - } - - public void reset() { - programUpdatedLatch = new CountDownLatch(1); - } - } - - private class TestProgramDataManagerOnCurrentProgramUpdatedListener implements - OnCurrentProgramUpdatedListener { - public final CountDownLatch currentProgramUpdatedLatch = new CountDownLatch(1); - public long updatedChannelId = -1; - public Program updatedProgram = null; - - @Override - public void onCurrentProgramUpdated(long channelId, Program program) { - updatedChannelId = channelId; - updatedProgram = program; - currentProgramUpdatedLatch.countDown(); - } - } -} diff --git a/tests/unit/src/com/android/tv/data/ProgramTest.java b/tests/unit/src/com/android/tv/data/ProgramTest.java deleted file mode 100644 index 1d1f6c10..00000000 --- a/tests/unit/src/com/android/tv/data/ProgramTest.java +++ /dev/null @@ -1,182 +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.data; - -import static android.media.tv.TvContract.Programs.Genres.COMEDY; -import static android.media.tv.TvContract.Programs.Genres.FAMILY_KIDS; -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 com.android.tv.data.Program.CriticScore; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Tests for {@link Program}. - */ -@SmallTest -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("") - .build(); - assertNullCanonicalGenres(program); - assertHasGenre(program, NOT_FOUND_GENRE, false); - assertHasGenre(program, FAMILY_GENRE_ID, false); - assertHasGenre(program, COMEDY_GENRE_ID, false); - assertHasGenre(program, GenreItems.ID_ALL_CHANNELS, true); - } - - @Test - public void testFamilyGenre() { - Program program = new Program.Builder() - .setCanonicalGenres(FAMILY_KIDS) - .build(); - assertCanonicalGenres(program, FAMILY_KIDS); - assertHasGenre(program, NOT_FOUND_GENRE, false); - assertHasGenre(program, FAMILY_GENRE_ID, true); - assertHasGenre(program, COMEDY_GENRE_ID, false); - assertHasGenre(program, GenreItems.ID_ALL_CHANNELS, true); - } - - @Test - public void testFamilyComedyGenre() { - Program program = new Program.Builder() - .setCanonicalGenres(FAMILY_KIDS + ", " + COMEDY) - .build(); - assertCanonicalGenres(program, FAMILY_KIDS, COMEDY); - assertHasGenre(program, NOT_FOUND_GENRE, false); - assertHasGenre(program, FAMILY_GENRE_ID, true); - assertHasGenre(program, COMEDY_GENRE_ID, true); - assertHasGenre(program, GenreItems.ID_ALL_CHANNELS, true); - } - - @Test - public void testOtherGenre() { - Program program = new Program.Builder() - .setCanonicalGenres("other") - .build(); - assertCanonicalGenres(program); - assertHasGenre(program, NOT_FOUND_GENRE, false); - assertHasGenre(program, FAMILY_GENRE_ID, false); - assertHasGenre(program, COMEDY_GENRE_ID, false); - assertHasGenre(program, GenreItems.ID_ALL_CHANNELS, true); - } - - @Test - public void testParcelable() { - List<CriticScore> criticScores = new ArrayList<>(); - criticScores.add(new CriticScore("1", "2", "3")); - criticScores.add(new CriticScore("4", "5", "6")); - TvContentRating[] ratings = new TvContentRating[2]; - ratings[0] = TvContentRating.unflattenFromString("1/2/3"); - ratings[1] = TvContentRating.unflattenFromString("4/5/6"); - Program p = new Program.Builder() - .setId(1) - .setPackageName("2") - .setChannelId(3) - .setTitle("4") - .setSeriesId("5") - .setEpisodeTitle("6") - .setSeasonNumber("7") - .setSeasonTitle("8") - .setEpisodeNumber("9") - .setStartTimeUtcMillis(10) - .setEndTimeUtcMillis(11) - .setDescription("12") - .setLongDescription("12-long") - .setVideoWidth(13) - .setVideoHeight(14) - .setCriticScores(criticScores) - .setPosterArtUri("15") - .setThumbnailUri("16") - .setCanonicalGenres(Genres.encode(Genres.SPORTS, Genres.SHOPPING)) - .setContentRatings(ratings) - .setRecordingProhibited(true) - .build(); - Parcel p1 = Parcel.obtain(); - Parcel p2 = Parcel.obtain(); - try { - p.writeToParcel(p1, 0); - byte[] bytes = p1.marshall(); - p2.unmarshall(bytes, 0, bytes.length); - p2.setDataPosition(0); - Program r2 = Program.fromParcel(p2); - assertEquals(p, r2); - } finally { - p1.recycle(); - p2.recycle(); - } - } - - @Test - public void testParcelableWithCriticScore() { - Program program = new Program.Builder() - .setTitle("MyTitle") - .addCriticScore(new CriticScore( - "default source", - "5/10", - "https://testurl/testimage.jpg")) - .build(); - Parcel parcel = Parcel.obtain(); - program.writeToParcel(parcel, 0); - parcel.setDataPosition(0); - Program programFromParcel = Program.CREATOR.createFromParcel(parcel); - - assertNotNull(programFromParcel.getCriticScores()); - assertEquals(programFromParcel.getCriticScores().get(0).source, "default source"); - assertEquals(programFromParcel.getCriticScores().get(0).score, "5/10"); - assertEquals(programFromParcel.getCriticScores().get(0).logoUrl, - "https://testurl/testimage.jpg"); - } - - private static void assertNullCanonicalGenres(Program program) { - String[] actual = program.getCanonicalGenres(); - assertNull("Expected null canonical genres but was " + Arrays.toString(actual), actual); - } - - private static void assertCanonicalGenres(Program program, String... expected) { - assertEquals("canonical genres", Arrays.asList(expected), - Arrays.asList(program.getCanonicalGenres())); - } - - private static void assertHasGenre(Program program, int genreId, boolean expected) { - assertEquals("hasGenre(" + genreId + ")", expected, program.hasGenre(genreId)); - } -} diff --git a/tests/unit/src/com/android/tv/data/TvInputNewComparatorTest.java b/tests/unit/src/com/android/tv/data/TvInputNewComparatorTest.java index b4682dd9..8e892cce 100644 --- a/tests/unit/src/com/android/tv/data/TvInputNewComparatorTest.java +++ b/tests/unit/src/com/android/tv/data/TvInputNewComparatorTest.java @@ -19,26 +19,24 @@ 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.runner.AndroidJUnit4; import android.util.Pair; - import com.android.tv.testing.ComparatorTester; +import com.android.tv.testing.utils.TestUtils; import com.android.tv.util.SetupUtils; -import com.android.tv.util.TestUtils; import com.android.tv.util.TvInputManagerHelper; - +import java.util.Comparator; +import java.util.LinkedHashMap; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.util.Comparator; -import java.util.LinkedHashMap; - -/** - * Test for {@link TvInputNewComparator} - */ +/** Test for {@link TvInputNewComparator} */ @SmallTest +@RunWith(AndroidJUnit4.class) public class TvInputNewComparatorTest { @Test public void testComparator() throws Exception { @@ -51,45 +49,48 @@ public class TvInputNewComparatorTest { inputIdToNewInput.put("3_old_input", new Pair<>(false, true)); SetupUtils setupUtils = Mockito.mock(SetupUtils.class); - Mockito.when(setupUtils.isNewInput(Matchers.anyString())).thenAnswer( - new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - String inputId = (String) invocation.getArguments()[0]; - return inputIdToNewInput.get(inputId).first; - } - } - ); - Mockito.when(setupUtils.isSetupDone(Matchers.anyString())).thenAnswer( - new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - String inputId = (String) invocation.getArguments()[0]; - return inputIdToNewInput.get(inputId).second; - } - } - ); + Mockito.when(setupUtils.isNewInput(Matchers.anyString())) + .thenAnswer( + new Answer<Boolean>() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + String inputId = (String) invocation.getArguments()[0]; + return inputIdToNewInput.get(inputId).first; + } + }); + Mockito.when(setupUtils.isSetupDone(Matchers.anyString())) + .thenAnswer( + new Answer<Boolean>() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + String inputId = (String) invocation.getArguments()[0]; + return inputIdToNewInput.get(inputId).second; + } + }); TvInputManagerHelper inputManager = Mockito.mock(TvInputManagerHelper.class); - Mockito.when(inputManager.getDefaultTvInputInfoComparator()).thenReturn( - new Comparator<TvInputInfo>() { - @Override - public int compare(TvInputInfo lhs, TvInputInfo rhs) { - return lhs.getId().compareTo(rhs.getId()); - } - } - ); + Mockito.when(inputManager.getDefaultTvInputInfoComparator()) + .thenReturn( + new Comparator<TvInputInfo>() { + @Override + public int compare(TvInputInfo lhs, TvInputInfo rhs) { + return lhs.getId().compareTo(rhs.getId()); + } + }); TvInputNewComparator comparator = new TvInputNewComparator(setupUtils, inputManager); ComparatorTester<TvInputInfo> comparatorTester = ComparatorTester.withoutEqualsTest(comparator); ResolveInfo resolveInfo = TestUtils.createResolveInfo("test", "test"); 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); - TvInputInfo info2 = TestUtils.createTvInputInfo( - resolveInfo, id, "test2", TvInputInfo.TYPE_DISPLAY_PORT, true); - TvInputInfo info3 = TestUtils.createTvInputInfo( - resolveInfo, id, "test", TvInputInfo.TYPE_HDMI, true); + TvInputInfo info1 = + TestUtils.createTvInputInfo( + resolveInfo, id, "test1", TvInputInfo.TYPE_TUNER, false); + TvInputInfo info2 = + TestUtils.createTvInputInfo( + resolveInfo, id, "test2", TvInputInfo.TYPE_DISPLAY_PORT, true); + TvInputInfo info3 = + TestUtils.createTvInputInfo( + resolveInfo, id, "test", TvInputInfo.TYPE_HDMI, true); comparatorTester.addComparableGroup(info1, info2, info3); } comparatorTester.test(); diff --git a/tests/unit/src/com/android/tv/data/WatchedHistoryManagerTest.java b/tests/unit/src/com/android/tv/data/WatchedHistoryManagerTest.java index 7eea1be7..43bfde09 100644 --- a/tests/unit/src/com/android/tv/data/WatchedHistoryManagerTest.java +++ b/tests/unit/src/com/android/tv/data/WatchedHistoryManagerTest.java @@ -17,26 +17,24 @@ 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.assertTrue; +import static com.google.common.truth.Truth.assertThat; import android.os.Looper; import android.support.test.filters.MediumTest; - +import android.support.test.runner.AndroidJUnit4; import com.android.tv.data.WatchedHistoryManager.WatchedRecord; - +import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; - -import java.util.concurrent.TimeUnit; +import org.junit.runner.RunWith; /** * Test for {@link com.android.tv.data.WatchedHistoryManagerTest} - * <p> - * This is a medium test because it load files which accessing SharedPreferences. + * + * <p>This is a medium test because it load files which accessing SharedPreferences. */ @MediumTest +@RunWith(AndroidJUnit4.class) public class WatchedHistoryManagerTest { // Wait time for expected success. private static final int MAX_HISTORY_SIZE = 100; @@ -56,13 +54,13 @@ public class WatchedHistoryManagerTest { private void startAndWaitForComplete() throws InterruptedException { mWatchedHistoryManager.start(); - assertTrue(mListener.mLoadFinished); + assertThat(mListener.mLoadFinished).isTrue(); } @Test public void testIsLoaded() throws InterruptedException { startAndWaitForComplete(); - assertTrue(mWatchedHistoryManager.isLoaded()); + assertThat(mWatchedHistoryManager.isLoaded()).isTrue(); } @Test @@ -71,16 +69,16 @@ public class WatchedHistoryManagerTest { long fakeId = 100000000; long time = System.currentTimeMillis(); long duration = TimeUnit.MINUTES.toMillis(10); - Channel channel = new Channel.Builder().setId(fakeId).build(); + ChannelImpl channel = new ChannelImpl.Builder().setId(fakeId).build(); mWatchedHistoryManager.logChannelViewStop(channel, time, duration); WatchedRecord record = mWatchedHistoryManager.getRecord(0); WatchedRecord recordFromSharedPreferences = mWatchedHistoryManager.getRecordFromSharedPreferences(0); - assertEquals(record.channelId, fakeId); - assertEquals(record.watchedStartTime, time - duration); - assertEquals(record.duration, duration); - assertEquals(record, recordFromSharedPreferences); + assertThat(fakeId).isEqualTo(record.channelId); + assertThat(time - duration).isEqualTo(record.watchedStartTime); + assertThat(duration).isEqualTo(record.duration); + assertThat(recordFromSharedPreferences).isEqualTo(record); } @Test @@ -92,28 +90,28 @@ public class WatchedHistoryManagerTest { int size = MAX_HISTORY_SIZE * 2; for (int i = 0; i < size; ++i) { - Channel channel = new Channel.Builder().setId(startChannelId + i).build(); + ChannelImpl channel = new ChannelImpl.Builder().setId(startChannelId + i).build(); mWatchedHistoryManager.logChannelViewStop(channel, time + duration * i, duration); } for (int i = 0; i < MAX_HISTORY_SIZE; ++i) { WatchedRecord record = mWatchedHistoryManager.getRecord(i); WatchedRecord recordFromSharedPreferences = mWatchedHistoryManager.getRecordFromSharedPreferences(i); - assertEquals(record, recordFromSharedPreferences); - assertEquals(record.channelId, startChannelId + size - 1 - i); + assertThat(recordFromSharedPreferences).isEqualTo(record); + assertThat(startChannelId + size - 1 - i).isEqualTo(record.channelId); } // Since the WatchedHistory is a circular queue, the value for 0 and maxHistorySize // are same. - assertEquals(mWatchedHistoryManager.getRecordFromSharedPreferences(0), - mWatchedHistoryManager.getRecordFromSharedPreferences(MAX_HISTORY_SIZE)); + assertThat(mWatchedHistoryManager.getRecordFromSharedPreferences(MAX_HISTORY_SIZE)) + .isEqualTo(mWatchedHistoryManager.getRecordFromSharedPreferences(0)); } @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))); - assertFalse(new WatchedRecord(1, 2, 3).equals(new WatchedRecord(1, 4, 3))); - assertFalse(new WatchedRecord(1, 2, 3).equals(new WatchedRecord(4, 2, 3))); + assertThat(new WatchedRecord(1, 2, 3).equals(new WatchedRecord(1, 2, 3))).isTrue(); + assertThat(new WatchedRecord(1, 2, 3).equals(new WatchedRecord(1, 2, 4))).isFalse(); + assertThat(new WatchedRecord(1, 2, 3).equals(new WatchedRecord(1, 4, 3))).isFalse(); + assertThat(new WatchedRecord(1, 2, 3).equals(new WatchedRecord(4, 2, 3))).isFalse(); } @Test @@ -122,12 +120,13 @@ public class WatchedHistoryManagerTest { long time = System.currentTimeMillis(); long duration = TimeUnit.MINUTES.toMillis(10); WatchedRecord record = new WatchedRecord(fakeId, time, duration); - WatchedRecord sameRecord = mWatchedHistoryManager.decode( - mWatchedHistoryManager.encode(record)); - assertEquals(record, sameRecord); + WatchedRecord sameRecord = + mWatchedHistoryManager.decode(mWatchedHistoryManager.encode(record)); + assertThat(sameRecord).isEqualTo(record); } - private class TestWatchedHistoryManagerListener implements WatchedHistoryManager.Listener { + private static final class TestWatchedHistoryManagerListener + implements WatchedHistoryManager.Listener { boolean mLoadFinished; @Override @@ -136,6 +135,6 @@ public class WatchedHistoryManagerTest { } @Override - public void onNewRecordAdded(WatchedRecord watchedRecord) { } + public void onNewRecordAdded(WatchedRecord watchedRecord) {} } } diff --git a/tests/unit/src/com/android/tv/dvr/BaseDvrDataManagerTest.java b/tests/unit/src/com/android/tv/dvr/BaseDvrDataManagerTest.java deleted file mode 100644 index 5f0ae15c..00000000 --- a/tests/unit/src/com/android/tv/dvr/BaseDvrDataManagerTest.java +++ /dev/null @@ -1,90 +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 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.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}. */ -@SmallTest -@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; - - @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()); - List<ScheduledRecording> result = mDvrDataManager.getNonStartedScheduledRecordings(); - MoreAsserts.assertContentsInAnyOrder(result, recording); - } - - @Test - public void testGetNonStartedScheduledRecordings_past() { - mDvrDataManager.addScheduledRecordingInternal(createNewScheduledRecordingStartingNow()); - mFakeClock.increment(TimeUnit.MINUTES, 6); - List<ScheduledRecording> result = mDvrDataManager.getNonStartedScheduledRecordings(); - MoreAsserts.assertContentsInAnyOrder(result); - } - - @NonNull - private ScheduledRecording createNewScheduledRecordingStartingNow() { - return ScheduledRecording.buildFrom(RecordingTestUtils - .createTestRecordingWithIdAndPeriod( - ScheduledRecording.ID_NOT_SET, - INPUT_ID, CHANNEL_ID, - mFakeClock.currentTimeMillis(), - mFakeClock.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5))) - .setState(ScheduledRecording.STATE_RECORDING_NOT_STARTED) - .build(); - } -} diff --git a/tests/unit/src/com/android/tv/dvr/DvrDataManagerImplTest.java b/tests/unit/src/com/android/tv/dvr/DvrDataManagerImplTest.java deleted file mode 100644 index 9771a2e5..00000000 --- a/tests/unit/src/com/android/tv/dvr/DvrDataManagerImplTest.java +++ /dev/null @@ -1,76 +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.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 org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -/** Tests for {@link DvrDataManagerImpl} */ -@SmallTest -@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class DvrDataManagerImplTest { - private static final String INPUT_ID = "input_id"; - private static final int CHANNEL_ID = 273; - - @Test - public void testGetNextScheduledStartTimeAfter() { - long id = 1; - List<ScheduledRecording> scheduledRecordings = new ArrayList<>(); - assertNextStartTime(scheduledRecordings, 0L, DvrDataManager.NEXT_START_TIME_NOT_FOUND); - scheduledRecordings.add(RecordingTestUtils - .createTestRecordingWithIdAndPeriod(id++, INPUT_ID, CHANNEL_ID, 10L, 20L)); - assertNextStartTime(scheduledRecordings, 9L, 10L); - assertNextStartTime(scheduledRecordings, 10L, DvrDataManager.NEXT_START_TIME_NOT_FOUND); - scheduledRecordings.add(RecordingTestUtils - .createTestRecordingWithIdAndPeriod(id++, INPUT_ID, CHANNEL_ID, 20L, 30L)); - assertNextStartTime(scheduledRecordings, 9L, 10L); - assertNextStartTime(scheduledRecordings, 10L, 20L); - assertNextStartTime(scheduledRecordings, 20L, DvrDataManager.NEXT_START_TIME_NOT_FOUND); - scheduledRecordings.add(RecordingTestUtils - .createTestRecordingWithIdAndPeriod(id++, INPUT_ID, CHANNEL_ID, 30L, 40L)); - assertNextStartTime(scheduledRecordings, 9L, 10L); - assertNextStartTime(scheduledRecordings, 10L, 20L); - assertNextStartTime(scheduledRecordings, 20L, 30L); - assertNextStartTime(scheduledRecordings, 30L, DvrDataManager.NEXT_START_TIME_NOT_FOUND); - scheduledRecordings.clear(); - scheduledRecordings.add(RecordingTestUtils - .createTestRecordingWithIdAndPeriod(id++, INPUT_ID, CHANNEL_ID, 10L, 20L)); - scheduledRecordings.add(RecordingTestUtils - .createTestRecordingWithIdAndPeriod(id++, INPUT_ID, CHANNEL_ID, 10L, 20L)); - scheduledRecordings.add(RecordingTestUtils - .createTestRecordingWithIdAndPeriod(id++, INPUT_ID, CHANNEL_ID, 10L, 20L)); - assertNextStartTime(scheduledRecordings, 9L, 10L); - assertNextStartTime(scheduledRecordings, 10L, DvrDataManager.NEXT_START_TIME_NOT_FOUND); - } - - private void assertNextStartTime(List<ScheduledRecording> scheduledRecordings, long startTime, - long expected) { - assertEquals("getNextScheduledStartTimeAfter()", expected, - DvrDataManagerImpl.getNextStartTimeAfter(scheduledRecordings, startTime)); - } -}
\ No newline at end of file diff --git a/tests/unit/src/com/android/tv/dvr/DvrDataManagerInMemoryImpl.java b/tests/unit/src/com/android/tv/dvr/DvrDataManagerInMemoryImpl.java deleted file mode 100644 index 0a7ab46c..00000000 --- a/tests/unit/src/com/android/tv/dvr/DvrDataManagerInMemoryImpl.java +++ /dev/null @@ -1,311 +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 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.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; -import java.util.Collections; -import java.util.HashMap; -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. */ -@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<>(); - private final Map<Long, RecordedProgram> mRecordedPrograms = new HashMap<>(); - private final Map<Long, SeriesRecording> mSeriesRecordings = new HashMap<>(); - - public DvrDataManagerInMemoryImpl(Context context, Clock clock) { - super(context, clock); - } - - @Override - public boolean isInitialized() { - return true; - } - - @Override - public boolean isDvrScheduleLoadFinished() { - return true; - } - - @Override - public boolean isRecordedProgramLoadFinished() { - return true; - } - - private List<ScheduledRecording> getScheduledRecordingsPrograms() { - return new ArrayList<>(mScheduledRecordings.values()); - } - - @Override - public List<RecordedProgram> getRecordedPrograms() { - return new ArrayList<>(mRecordedPrograms.values()); - } - - @Override - public List<ScheduledRecording> getAllScheduledRecordings() { - return new ArrayList<>(mScheduledRecordings.values()); - } - - public List<SeriesRecording> getSeriesRecordings() { - return new ArrayList<>(mSeriesRecordings.values()); - } - - @Override - public List<SeriesRecording> getSeriesRecordings(String inputId) { - List<SeriesRecording> result = new ArrayList<>(); - for (SeriesRecording r : mSeriesRecordings.values()) { - if (TextUtils.equals(r.getInputId(), inputId)) { - result.add(r); - } - } - return result; - } - - @Override - public long getNextScheduledStartTimeAfter(long startTime) { - - List<ScheduledRecording> temp = getNonStartedScheduledRecordings(); - Collections.sort(temp, ScheduledRecording.START_TIME_COMPARATOR); - for (ScheduledRecording r : temp) { - if (r.getStartTimeMs() > startTime) { - return r.getStartTimeMs(); - } - } - return DvrDataManager.NEXT_START_TIME_NOT_FOUND; - } - - @Override - public List<ScheduledRecording> getScheduledRecordings(Range<Long> period, - @RecordingState int state) { - List<ScheduledRecording> temp = getScheduledRecordingsPrograms(); - List<ScheduledRecording> result = new ArrayList<>(); - for (ScheduledRecording r : temp) { - if (r.isOverLapping(period) && r.getState() == state) { - result.add(r); - } - } - return result; - } - - @Override - public List<ScheduledRecording> getScheduledRecordings(long seriesRecordingId) { - List<ScheduledRecording> result = new ArrayList<>(); - for (ScheduledRecording r : mScheduledRecordings.values()) { - if (r.getSeriesRecordingId() == seriesRecordingId) { - result.add(r); - } - } - return result; - } - - @Override - public List<ScheduledRecording> getScheduledRecordings(String inputId) { - List<ScheduledRecording> result = new ArrayList<>(); - for (ScheduledRecording r : mScheduledRecordings.values()) { - if (TextUtils.equals(r.getInputId(), inputId)) { - result.add(r); - } - } - return result; - } - - /** - * Add a new scheduled recording. - */ - @Override - public void addScheduledRecording(ScheduledRecording... scheduledRecordings) { - for (ScheduledRecording r : scheduledRecordings) { - addScheduledRecordingInternal(r); - } - } - - - public void addRecordedProgram(RecordedProgram recordedProgram) { - addRecordedProgramInternal(recordedProgram); - } - - public void updateRecordedProgram(RecordedProgram r) { - long id = r.getId(); - if (mRecordedPrograms.containsKey(id)) { - mRecordedPrograms.put(id, r); - notifyRecordedProgramsChanged(r); - } else { - throw new IllegalArgumentException("Recording not found:" + r); - } - } - - public void removeRecordedProgram(RecordedProgram scheduledRecording) { - mRecordedPrograms.remove(scheduledRecording.getId()); - notifyRecordedProgramsRemoved(scheduledRecording); - } - - - public ScheduledRecording addScheduledRecordingInternal(ScheduledRecording scheduledRecording) { - SoftPreconditions - .checkState(scheduledRecording.getId() == ScheduledRecording.ID_NOT_SET, TAG, - "expected id of " + ScheduledRecording.ID_NOT_SET + " but was " - + scheduledRecording); - scheduledRecording = ScheduledRecording.buildFrom(scheduledRecording) - .setId(mNextId.incrementAndGet()) - .build(); - mScheduledRecordings.put(scheduledRecording.getId(), scheduledRecording); - notifyScheduledRecordingAdded(scheduledRecording); - return scheduledRecording; - } - - public RecordedProgram addRecordedProgramInternal(RecordedProgram recordedProgram) { - SoftPreconditions.checkState(recordedProgram.getId() == RecordedProgram.ID_NOT_SET, TAG, - "expected id of " + RecordedProgram.ID_NOT_SET + " but was " + recordedProgram); - recordedProgram = RecordedProgram.buildFrom(recordedProgram) - .setId(mNextId.incrementAndGet()) - .build(); - mRecordedPrograms.put(recordedProgram.getId(), recordedProgram); - notifyRecordedProgramsAdded(recordedProgram); - return recordedProgram; - } - - @Override - public void addSeriesRecording(SeriesRecording... seriesRecordings) { - for (SeriesRecording r : seriesRecordings) { - mSeriesRecordings.put(r.getId(), r); - } - notifySeriesRecordingAdded(seriesRecordings); - } - - @Override - public void removeScheduledRecording(ScheduledRecording... scheduledRecordings) { - for (ScheduledRecording r : scheduledRecordings) { - mScheduledRecordings.remove(r.getId()); - } - notifyScheduledRecordingRemoved(scheduledRecordings); - } - - @Override - public void removeScheduledRecording(boolean forceRemove, ScheduledRecording... schedule) { - removeScheduledRecording(schedule); - } - - @Override - public void removeSeriesRecording(SeriesRecording... seriesRecordings) { - for (SeriesRecording r : seriesRecordings) { - mSeriesRecordings.remove(r.getId()); - } - notifySeriesRecordingRemoved(seriesRecordings); - } - - @Override - public void updateScheduledRecording(ScheduledRecording... scheduledRecordings) { - for (ScheduledRecording r : scheduledRecordings) { - long id = r.getId(); - if (mScheduledRecordings.containsKey(id)) { - mScheduledRecordings.put(id, r); - } else { - Log.d(TAG, "Recording not found:" + r); - } - } - notifyScheduledRecordingStatusChanged(scheduledRecordings); - } - - @Override - public void updateSeriesRecording(SeriesRecording... seriesRecordings) { - for (SeriesRecording r : seriesRecordings) { - long id = r.getId(); - if (mSeriesRecordings.containsKey(id)) { - mSeriesRecordings.put(id, r); - } else { - throw new IllegalArgumentException("Recording not found:" + r); - } - } - notifySeriesRecordingChanged(seriesRecordings); - } - - @Nullable - @Override - public ScheduledRecording getScheduledRecording(long id) { - return mScheduledRecordings.get(id); - } - - @Nullable - @Override - public ScheduledRecording getScheduledRecordingForProgramId(long programId) { - for (ScheduledRecording r : mScheduledRecordings.values()) { - if (r.getProgramId() == programId) { - return r; - } - } - return null; - } - - @Nullable - @Override - public SeriesRecording getSeriesRecording(long seriesRecordingId) { - return mSeriesRecordings.get(seriesRecordingId); - } - - @Nullable - @Override - public SeriesRecording getSeriesRecording(String seriesId) { - for (SeriesRecording r : mSeriesRecordings.values()) { - if (r.getSeriesId().equals(seriesId)) { - return r; - } - } - return null; - } - - @Nullable - @Override - public RecordedProgram getRecordedProgram(long recordingId) { - return mRecordedPrograms.get(recordingId); - } - - @Override - @NonNull - protected List<ScheduledRecording> getRecordingsWithState(int... states) { - ArrayList<ScheduledRecording> result = new ArrayList<>(); - for (ScheduledRecording r : mScheduledRecordings.values()) { - for (int state : states) { - if (r.getState() == state) { - result.add(r); - break; - } - } - } - return result; - } -} diff --git a/tests/unit/src/com/android/tv/dvr/DvrScheduleManagerTest.java b/tests/unit/src/com/android/tv/dvr/DvrScheduleManagerTest.java deleted file mode 100644 index 1c77aa0e..00000000 --- a/tests/unit/src/com/android/tv/dvr/DvrScheduleManagerTest.java +++ /dev/null @@ -1,693 +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 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 org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** Tests for {@link DvrScheduleManager} */ -@SmallTest -@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; - List<ScheduledRecording> schedules = new ArrayList<>(); - - schedules.add(RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - ++priority, 0L, 200L)); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 1)); - - schedules.add(RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - ++priority, 0L, 100L)); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 2)); - - schedules.add(RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - ++priority, 100L, 200L)); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 2)); - - schedules.add(RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - ++priority, 0L, 100L)); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 3)); - - schedules.add(RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - ++priority, 100L, 200L)); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 3)); - } - - @Test - public void testGetConflictingSchedules_noTuner() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 0)); - - schedules.add(RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - ++priority, 0L, 200L)); - assertEquals(schedules, DvrScheduleManager.getConflictingSchedules(schedules, 0)); - schedules.add(0, RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - ++priority, 0L, 100L)); - assertEquals(schedules, DvrScheduleManager.getConflictingSchedules(schedules, 0)); - } - - @Test - public void testGetConflictingSchedules_conflict() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 1)); - - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 100L); - schedules.add(r2); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 2)); - - ScheduledRecording r3 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(r3); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 2)); - - ScheduledRecording r4 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 100L); - schedules.add(r4); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 2), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 3)); - - ScheduledRecording r5 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(r5); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 2), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 3)); - - ScheduledRecording r6 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 10L, 90L); - schedules.add(r6); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r4, r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 2), - r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 3), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 4)); - - ScheduledRecording r7 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 110L, 190L); - schedules.add(r7); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r5, r4, r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 2), - r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 3), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 4)); - - ScheduledRecording r8 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 50L, 150L); - schedules.add(r8); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r7, r6, r5, r4, r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 2), - r5, r4, r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 3), - r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 4), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 5)); - } - - @Test - public void testGetConflictingSchedules_conflict2() { - // The case when there is a long schedule. - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 1000L); - schedules.add(r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 1)); - - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 100L); - schedules.add(r2); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 2)); - - ScheduledRecording r3 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(r3); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 2)); - } - - @Test - public void testGetConflictingSchedules_reverseOrder() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(0, r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 1)); - - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 100L); - schedules.add(0, r2); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 2)); - - ScheduledRecording r3 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(0, r3); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 2)); - - ScheduledRecording r4 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 100L); - schedules.add(0, r4); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 2), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 3)); - - ScheduledRecording r5 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(0, r5); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 2), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 3)); - - ScheduledRecording r6 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 10L, 90L); - schedules.add(0, r6); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r4, r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 2), - r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 3), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 4)); - - ScheduledRecording r7 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 110L, 190L); - schedules.add(0, r7); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r5, r4, r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 2), - r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 3), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 4)); - - ScheduledRecording r8 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 50L, 150L); - schedules.add(0, r8); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r7, r6, r5, r4, r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 2), - r5, r4, r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 3), - r3, r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 4), - r1); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 5)); - } - - @Test - public void testGetConflictingSchedules_period1() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 100L); - schedules.add(r2); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1, - Collections.singletonList(new Range<>(10L, 20L))), r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1, - Collections.singletonList(new Range<>(110L, 120L))), r1); - } - - @Test - public void testGetConflictingSchedules_period2() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(r2); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1, - Collections.singletonList(new Range<>(10L, 20L))), r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1, - Collections.singletonList(new Range<>(110L, 120L))), r1); - } - - @Test - public void testGetConflictingSchedules_period3() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 100L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(r2); - ScheduledRecording r3 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 100L); - schedules.add(r3); - ScheduledRecording r4 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(r4); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1, - Collections.singletonList(new Range<>(10L, 20L))), r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1, - Collections.singletonList(new Range<>(110L, 120L))), r2); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1, - Collections.singletonList(new Range<>(50L, 150L))), r2, r1); - List<Range<Long>> ranges = new ArrayList<>(); - ranges.add(new Range<>(10L, 20L)); - ranges.add(new Range<>(110L, 120L)); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1, - ranges), r2, r1); - } - - @Test - public void testGetConflictingSchedules_addSchedules1() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 100L); - schedules.add(r2); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules( - Collections.singletonList( - ScheduledRecording.builder(INPUT_ID, ++channelId, 10L, 20L) - .setPriority(++priority).build()), - schedules, 1), r2, r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules( - Collections.singletonList( - ScheduledRecording.builder(INPUT_ID, ++channelId, 110L, 120L) - .setPriority(++priority).build()), - schedules, 1), r1); - } - - @Test - public void testGetConflictingSchedules_addSchedules2() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(r2); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules( - Collections.singletonList( - ScheduledRecording.builder(INPUT_ID, ++channelId, 10L, 20L) - .setPriority(++priority).build()), - schedules, 1), r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules( - Collections.singletonList( - ScheduledRecording.builder(INPUT_ID, ++channelId, 110L, 120L) - .setPriority(++priority).build()), - schedules, 1), r2, r1); - } - - @Test - public void testGetConflictingSchedules_addLowestPriority() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 400L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(r2); - // Returning r1 even though r1 has the higher priority than the new one. That's because r1 - // starts at 0 and stops at 100, and the new one will be recorded successfully. - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules( - Collections.singletonList( - ScheduledRecording.builder(INPUT_ID, ++channelId, 200L, 300L) - .setPriority(0).build()), - schedules, 1), r1); - } - - @Test - public void testGetConflictingSchedules_sameChannel() { - long priority = 0; - long channelId = 1; - List<ScheduledRecording> schedules = new ArrayList<>(); - schedules.add(RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(channelId, - ++priority, 0L, 200L)); - schedules.add(RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(channelId, - ++priority, 0L, 200L)); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedules(schedules, 3)); - } - - @Test - public void testGetConflictingSchedule_startEarlyAndFail() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 200L, 300L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 400L); - schedules.add(r2); - ScheduledRecording r3 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 200L); - schedules.add(r3); - // r2 starts recording and fails when r3 starts. r1 is recorded successfully. - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r2); - } - - @Test - public void testGetConflictingSchedule_startLate() { - long priority = 0; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(); - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 200L, 400L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 100L, 300L); - schedules.add(r2); - ScheduledRecording r3 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r3); - // r2 and r1 are clipped. - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedules(schedules, 1), - r2, r1); - } - - @Test - public void testGetConflictingSchedulesForTune_canTune() { - // Can tune to the recorded channel if tuner count is 1. - long priority = 0; - long channelId = 1; - List<ScheduledRecording> schedules = new ArrayList<>(); - schedules.add(RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(channelId, - ++priority, 0L, 200L)); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedulesForTune(INPUT_ID, - 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; - long channelId = 1; - List<ScheduledRecording> schedules = new ArrayList<>(); - schedules.add(RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(channelId, - ++priority, 0L, 200L)); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedulesForTune( - 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; - long channelToWatch = 1; - long channelId = 1; - List<ScheduledRecording> schedules = new ArrayList<>(); - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r2); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 3)); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 2), r1); - } - - @Test - public void testGetConflictingSchedulesForWatching_sameChannel1() { - long priority = 0; - long channelToWatch = 1; - long channelId = 1; - List<ScheduledRecording> schedules = new ArrayList<>(); - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - channelToWatch, ++priority, 0L, 200L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r2); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 2)); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 1), r2); - } - - @Test - public void testGetConflictingSchedulesForWatching_sameChannel2() { - long priority = 0; - long channelToWatch = 1; - long channelId = 1; - List<ScheduledRecording> schedules = new ArrayList<>(); - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - channelToWatch, ++priority, 0L, 200L); - schedules.add(r2); - MoreAsserts.assertEmpty(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 2)); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 1), r1); - } - - @Test - public void testGetConflictingSchedulesForWatching_sameChannelConflict1() { - long priority = 0; - long channelToWatch = 1; - long channelId = 1; - List<ScheduledRecording> schedules = new ArrayList<>(); - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - channelToWatch, ++priority, 0L, 200L); - schedules.add(r2); - ScheduledRecording r3 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - channelToWatch, ++priority, 0L, 200L); - schedules.add(r3); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 3), r2); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 2), r2); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 1), r2, r1); - } - - @Test - public void testGetConflictingSchedulesForWatching_sameChannelConflict2() { - long priority = 0; - long channelToWatch = 1; - long channelId = 1; - List<ScheduledRecording> schedules = new ArrayList<>(); - ScheduledRecording r1 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - channelToWatch, ++priority, 0L, 200L); - schedules.add(r1); - ScheduledRecording r2 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - channelToWatch, ++priority, 0L, 200L); - schedules.add(r2); - ScheduledRecording r3 = RecordingTestUtils.createTestRecordingWithPriorityAndPeriod( - ++channelId, ++priority, 0L, 200L); - schedules.add(r3); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 3), r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 2), r1); - MoreAsserts.assertContentsInOrder(DvrScheduleManager.getConflictingSchedulesForWatching( - INPUT_ID, channelToWatch, 0L, ++priority, schedules, 1), r3, r1); - } - - @Test - public void testPartiallyConflictingSchedules() { - long priority = 100; - long channelId = 0; - List<ScheduledRecording> schedules = new ArrayList<>(Arrays.asList( - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 0L, 400L), - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 0L, 200L), - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 200L, 500L), - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 400L, 600L), - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 700L, 800L), - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 600L, 900L), - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 800L, 900L), - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 800L, 900L), - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 750L, 850L), - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 300L, 450L), - RecordingTestUtils.createTestRecordingWithPriorityAndPeriod(++channelId, - --priority, 50L, 900L) - )); - 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/ScheduledRecordingTest.java b/tests/unit/src/com/android/tv/dvr/ScheduledRecordingTest.java deleted file mode 100644 index b98af603..00000000 --- a/tests/unit/src/com/android/tv/dvr/ScheduledRecordingTest.java +++ /dev/null @@ -1,117 +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 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 org.junit.Test; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -/** Tests for {@link ScheduledRecordingTest} */ -@SmallTest -@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class ScheduledRecordingTest { - private static final String INPUT_ID = "input_id"; - private static final int CHANNEL_ID = 273; - - @Test - public void testIsOverLapping() { - ScheduledRecording r = createTestRecordingWithIdAndPeriod(1, INPUT_ID, CHANNEL_ID, - 10L, 20L); - assertOverLapping(false, 1L, 9L, r); - - assertOverLapping(true, 1L, 20L, r); - assertOverLapping(false, 1L, 10L, r); - assertOverLapping(true, 10L, 19L, r); - assertOverLapping(true, 10L, 20L, r); - assertOverLapping(true, 11L, 20L, r); - assertOverLapping(true, 11L, 21L, r); - assertOverLapping(false, 20L, 21L, r); - - assertOverLapping(false, 21L, 29L, r); - } - - @Test - public void testBuildProgram() { - Channel c = new Channel.Builder().build(); - Program p = new Program.Builder().build(); - ScheduledRecording actual = ScheduledRecording.builder(INPUT_ID, p) - .setChannelId(c.getId()).build(); - 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); - ScheduledRecording actual = ScheduledRecording.buildFrom(expected).build(); - RecordingTestUtils.assertRecordingEquals(expected, actual); - } - - @Test - public void testBuild_priority() { - ScheduledRecording a = normalizePriority( - createTestRecordingWithIdAndPeriod(1, INPUT_ID, CHANNEL_ID, 10L, 20L)); - ScheduledRecording b = normalizePriority( - createTestRecordingWithIdAndPeriod(2, INPUT_ID, CHANNEL_ID, 10L, 20L)); - ScheduledRecording c = normalizePriority( - createTestRecordingWithIdAndPeriod(3, INPUT_ID, CHANNEL_ID, 10L, 20L)); - - // default priority - MoreAsserts.assertContentsInOrder(sortByPriority(c, b, a), a, b, c); - - // make A preferred over B - a = ScheduledRecording.buildFrom(a).setPriority(b.getPriority() + 2).build(); - MoreAsserts.assertContentsInOrder(sortByPriority(a, b, c), b, c, a); - } - - public Collection<ScheduledRecording> sortByPriority(ScheduledRecording a, ScheduledRecording b, - ScheduledRecording c) { - List<ScheduledRecording> list = Arrays.asList(a, b, c); - Collections.sort(list, ScheduledRecording.PRIORITY_COMPARATOR); - return list; - } - - private void assertOverLapping(boolean expected, long lower, long upper, ScheduledRecording r) { - assertEquals("isOverlapping(Range(" + lower + "," + upper + "), recording " + r, expected, - r.isOverLapping(new Range<>(lower, upper))); - } -} diff --git a/tests/unit/src/com/android/tv/dvr/data/SeriesRecordingTest.java b/tests/unit/src/com/android/tv/dvr/data/SeriesRecordingTest.java deleted file mode 100644 index 790b2ee8..00000000 --- a/tests/unit/src/com/android/tv/dvr/data/SeriesRecordingTest.java +++ /dev/null @@ -1,133 +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.data; - -import static org.junit.Assert.assertEquals; - -import android.os.Build; -import android.os.Parcel; -import android.support.test.filters.SdkSuppress; -import android.support.test.filters.SmallTest; - -import com.android.tv.data.Program; - -import org.junit.Test; - -/** - * Tests for {@link SeriesRecording}. - */ -@SmallTest -@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -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; - private static final String SERIES_ID = "SERIES_ID"; - private static final String OTHER_SERIES_ID = "OTHER_SERIES_ID"; - - private final SeriesRecording mBaseSeriesRecording = new SeriesRecording.Builder() - .setTitle(PROGRAM_TITLE).setChannelId(CHANNEL_ID).setSeriesId(SERIES_ID).build(); - private final SeriesRecording mSeriesRecordingSeason2 = SeriesRecording - .buildFrom(mBaseSeriesRecording).setStartFromSeason(2).build(); - private final SeriesRecording mSeriesRecordingSeason2Episode5 = SeriesRecording - .buildFrom(mSeriesRecordingSeason2).setStartFromEpisode(5).build(); - private final Program mBaseProgram = new Program.Builder().setTitle(PROGRAM_TITLE) - .setChannelId(CHANNEL_ID).setSeriesId(SERIES_ID).build(); - - @Test - public void testParcelable() { - SeriesRecording r1 = new SeriesRecording.Builder() - .setId(1) - .setChannelId(2) - .setPriority(3) - .setTitle("4") - .setDescription("5") - .setLongDescription("5-long") - .setSeriesId("6") - .setStartFromEpisode(7) - .setStartFromSeason(8) - .setChannelOption(SeriesRecording.OPTION_CHANNEL_ALL) - .setCanonicalGenreIds(new int[] {9, 10}) - .setPosterUri("11") - .setPhotoUri("12") - .build(); - Parcel p1 = Parcel.obtain(); - Parcel p2 = Parcel.obtain(); - try { - r1.writeToParcel(p1, 0); - byte[] bytes = p1.marshall(); - p2.unmarshall(bytes, 0, bytes.length); - p2.setDataPosition(0); - SeriesRecording r2 = SeriesRecording.fromParcel(p2); - assertEquals(r1, r2); - } finally { - p1.recycle(); - p2.recycle(); - } - } - - @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); - program = new Program.Builder(program).setSeasonNumber("1").build(); - assertDoesProgramMatch(program, mSeriesRecordingSeason2, false); - program = new Program.Builder(program).setSeasonNumber("2").build(); - assertDoesProgramMatch(program, mSeriesRecordingSeason2, true); - program = new Program.Builder(program).setSeasonNumber("3").build(); - assertDoesProgramMatch(program, mSeriesRecordingSeason2, true); - } - - @Test - public void testDoesProgramMatch_startFromSeason2episode5() { - Program program = mBaseProgram; - assertDoesProgramMatch(program, mSeriesRecordingSeason2Episode5, true); - program = new Program.Builder(program).setSeasonNumber("2").build(); - assertDoesProgramMatch(program, mSeriesRecordingSeason2Episode5, true); - program = new Program.Builder(program).setEpisodeNumber("4").build(); - assertDoesProgramMatch(program, mSeriesRecordingSeason2Episode5, false); - program = new Program.Builder(program).setEpisodeNumber("5").build(); - assertDoesProgramMatch(program, mSeriesRecordingSeason2Episode5, true); - program = new Program.Builder(program).setEpisodeNumber("6").build(); - assertDoesProgramMatch(program, mSeriesRecordingSeason2Episode5, true); - program = new Program.Builder(program).setSeasonNumber("3").setEpisodeNumber("1").build(); - assertDoesProgramMatch(program, mSeriesRecordingSeason2Episode5, true); - } - - private void assertDoesProgramMatch(Program p, SeriesRecording seriesRecording, - boolean expected) { - assertEquals(seriesRecording + " doesProgramMatch " + p, expected, - seriesRecording.matchProgram(p)); - } -} diff --git a/tests/unit/src/com/android/tv/dvr/provider/DvrDbSyncTest.java b/tests/unit/src/com/android/tv/dvr/provider/DvrDbSyncTest.java deleted file mode 100644 index 94f88a51..00000000 --- a/tests/unit/src/com/android/tv/dvr/provider/DvrDbSyncTest.java +++ /dev/null @@ -1,143 +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.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; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.os.Build; -import android.support.test.filters.SdkSuppress; -import android.support.test.filters.SmallTest; - -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 com.android.tv.dvr.DvrScheduleManager} - */ -@SmallTest -@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -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; - private static final long BASE_END_TIME_MS = 1; - private static final String BASE_SEASON_NUMBER = "2"; - 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; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - when(mChannelDataManager.isDbLoadFinished()).thenReturn(true); - 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; - long endTimeMs = BASE_END_TIME_MS + 1; - Program program = new Program.Builder(BASE_PROGRAM).setStartTimeUtcMillis(startTimeMs) - .setEndTimeUtcMillis(endTimeMs).build(); - mDbSync.handleUpdateProgram(program, BASE_PROGRAM_ID); - assertUpdateScheduleCalled(program); - } - - @Test - public void testHandleUpdateProgram_changeTimeInProgressNotCalled() { - addSchedule(BASE_PROGRAM_ID, ScheduledRecording.buildFrom(BASE_SCHEDULE) - .setState(ScheduledRecording.STATE_RECORDING_IN_PROGRESS).build()); - long startTimeMs = BASE_START_TIME_MS + 1; - Program program = new Program.Builder(BASE_PROGRAM).setStartTimeUtcMillis(startTimeMs) - .build(); - mDbSync.handleUpdateProgram(program, BASE_PROGRAM_ID); - verify(mDataManager, never()).updateScheduledRecording(anyObject()); - } - - @Test - public void testHandleUpdateProgram_changeSeason() { - 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_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_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_SERIES_PROGRAM).setSeasonNumber(seasonNumber) - .setEpisodeNumber(episodeNumber).build(); - mDbSync.handleUpdateProgram(program, BASE_PROGRAM_ID); - verify(mDataManager, never()).updateScheduledRecording(anyObject()); - } - - private void addSchedule(long programId, ScheduledRecording schedule) { - when(mDataManager.getScheduledRecordingForProgramId(programId)).thenReturn(schedule); - } - - private void assertUpdateScheduleCalled(Program program) { - verify(mDataManager).updateScheduledRecording( - eq(ScheduledRecording.builder(INPUT_ID, program).build())); - } -} diff --git a/tests/unit/src/com/android/tv/dvr/provider/EpisodicProgramLoadTaskTest.java b/tests/unit/src/com/android/tv/dvr/provider/EpisodicProgramLoadTaskTest.java deleted file mode 100644 index 216d4d5b..00000000 --- a/tests/unit/src/com/android/tv/dvr/provider/EpisodicProgramLoadTaskTest.java +++ /dev/null @@ -1,83 +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.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 index 8f7dcaf2..d510da32 100644 --- a/tests/unit/src/com/android/tv/dvr/recorder/DvrRecordingServiceTest.java +++ b/tests/unit/src/com/android/tv/dvr/recorder/DvrRecordingServiceTest.java @@ -16,24 +16,18 @@ package com.android.tv.dvr.recorder; -import static org.mockito.Mockito.verify; +import static com.google.common.truth.Truth.assertThat; 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}. - */ +/** Tests for {@link DvrRecordingService}. */ @SmallTest @SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) public class DvrRecordingServiceTest @@ -61,13 +55,13 @@ public class DvrRecordingServiceTest public void testStartService_null() throws Exception { // Not recording startService(null); - assertFalse(getService().mInForeground); + assertThat(getService().mInForeground).isFalse(); // Recording getService().startRecording(); startService(null); - assertTrue(getService().mInForeground); - assertTrue(getService().mIsRecording); + assertThat(getService().mInForeground).isTrue(); + assertThat(getService().mIsRecording).isTrue(); getService().reset(); } @@ -77,38 +71,38 @@ public class DvrRecordingServiceTest // Not recording startService(intent); - assertTrue(getService().mInForeground); - assertFalse(getService().mForegroundForUpcomingRecording); + assertThat(getService().mInForeground).isTrue(); + assertThat(getService().mForegroundForUpcomingRecording).isFalse(); getService().stopForegroundIfNotRecordingInternal(); - assertFalse(getService().mInForeground); + assertThat(getService().mInForeground).isFalse(); // Recording, ended quickly getService().startRecording(); startService(intent); - assertTrue(getService().mInForeground); - assertTrue(getService().mForegroundForUpcomingRecording); - assertTrue(getService().mIsRecording); + assertThat(getService().mInForeground).isTrue(); + assertThat(getService().mForegroundForUpcomingRecording).isTrue(); + assertThat(getService().mIsRecording).isTrue(); getService().stopRecording(); - assertFalse(getService().mInForeground); - assertFalse(getService().mIsRecording); + assertThat(getService().mInForeground).isFalse(); + assertThat(getService().mIsRecording).isFalse(); getService().stopForegroundIfNotRecordingInternal(); - assertFalse(getService().mInForeground); - assertFalse(getService().mIsRecording); + assertThat(getService().mInForeground).isFalse(); + assertThat(getService().mIsRecording).isFalse(); getService().reset(); // Recording, ended later getService().startRecording(); startService(intent); - assertTrue(getService().mInForeground); - assertTrue(getService().mForegroundForUpcomingRecording); - assertTrue(getService().mIsRecording); + assertThat(getService().mInForeground).isTrue(); + assertThat(getService().mForegroundForUpcomingRecording).isTrue(); + assertThat(getService().mIsRecording).isTrue(); getService().stopForegroundIfNotRecordingInternal(); - assertTrue(getService().mInForeground); - assertTrue(getService().mForegroundForUpcomingRecording); - assertTrue(getService().mIsRecording); + assertThat(getService().mInForeground).isTrue(); + assertThat(getService().mForegroundForUpcomingRecording).isTrue(); + assertThat(getService().mIsRecording).isTrue(); getService().stopRecording(); - assertFalse(getService().mInForeground); - assertFalse(getService().mIsRecording); + assertThat(getService().mInForeground).isFalse(); + assertThat(getService().mIsRecording).isFalse(); getService().reset(); } @@ -118,38 +112,39 @@ public class DvrRecordingServiceTest // Not recording startService(intent); - assertTrue(getService().mInForeground); - assertTrue(getService().mForegroundForUpcomingRecording); - assertFalse(getService().mIsRecording); + assertThat(getService().mInForeground).isTrue(); + assertThat(getService().mForegroundForUpcomingRecording).isTrue(); + assertThat(getService().mIsRecording).isFalse(); getService().startRecording(); - assertTrue(getService().mInForeground); - assertTrue(getService().mForegroundForUpcomingRecording); - assertTrue(getService().mIsRecording); + assertThat(getService().mInForeground).isTrue(); + assertThat(getService().mForegroundForUpcomingRecording).isTrue(); + assertThat(getService().mIsRecording).isTrue(); getService().stopRecording(); - assertFalse(getService().mInForeground); - assertFalse(getService().mIsRecording); + assertThat(getService().mInForeground).isFalse(); + assertThat(getService().mIsRecording).isFalse(); getService().reset(); // Recording getService().startRecording(); startService(intent); - assertTrue(getService().mInForeground); - assertTrue(getService().mForegroundForUpcomingRecording); - assertTrue(getService().mIsRecording); + assertThat(getService().mInForeground).isTrue(); + assertThat(getService().mForegroundForUpcomingRecording).isTrue(); + assertThat(getService().mIsRecording).isTrue(); getService().startRecording(); - assertTrue(getService().mInForeground); - assertTrue(getService().mForegroundForUpcomingRecording); - assertTrue(getService().mIsRecording); + assertThat(getService().mInForeground).isTrue(); + assertThat(getService().mForegroundForUpcomingRecording).isTrue(); + assertThat(getService().mIsRecording).isTrue(); getService().stopRecording(); - assertTrue(getService().mInForeground); - assertTrue(getService().mForegroundForUpcomingRecording); - assertTrue(getService().mIsRecording); + assertThat(getService().mInForeground).isTrue(); + assertThat(getService().mForegroundForUpcomingRecording).isTrue(); + assertThat(getService().mIsRecording).isTrue(); getService().stopRecording(); - assertFalse(getService().mInForeground); - assertFalse(getService().mIsRecording); + assertThat(getService().mInForeground).isFalse(); + assertThat(getService().mIsRecording).isFalse(); getService().reset(); } + /** Mock {@link DvrRecordingService}. */ public static class MockDvrRecordingService extends DvrRecordingService { private int mRecordingCount = 0; private boolean mInForeground; @@ -180,4 +175,4 @@ public class DvrRecordingServiceTest mIsRecording = false; } } -}
\ No newline at end of file +} diff --git a/tests/unit/src/com/android/tv/dvr/recorder/InputTaskSchedulerTest.java b/tests/unit/src/com/android/tv/dvr/recorder/InputTaskSchedulerTest.java deleted file mode 100644 index e5c27e2c..00000000 --- a/tests/unit/src/com/android/tv/dvr/recorder/InputTaskSchedulerTest.java +++ /dev/null @@ -1,231 +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.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.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; - -import android.app.AlarmManager; -import android.media.tv.TvInputInfo; -import android.os.Build; -import android.os.Looper; -import android.os.SystemClock; -import android.support.test.filters.SdkSuppress; -import android.support.test.filters.SmallTest; - -import com.android.tv.InputSessionManager; -import com.android.tv.data.Channel; -import com.android.tv.data.ChannelDataManager; -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; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -/** - * Tests for {@link InputTaskScheduler}. - */ -@SmallTest -@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -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); - private static final int TUNER_COUNT_ONE = 1; - private static final int TUNER_COUNT_TWO = 2; - private static final long LOW_PRIORITY = 1; - private static final long HIGH_PRIORITY = 2; - - private FakeClock mFakeClock; - private InputTaskScheduler mScheduler; - @Mock private DvrManager mDvrManager; - @Mock private WritableDvrDataManager mDataManager; - @Mock private InputSessionManager mSessionManager; - @Mock private AlarmManager mMockAlarmManager; - @Mock private ChannelDataManager mChannelDataManager; - private List<RecordingTask> mRecordingTasks; - - @Before - public void setUp() throws Exception { - if (Looper.myLooper() == null) { - Looper.prepare(); - } - 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, - new RecordingTaskFactory() { - @Override - public RecordingTask createRecordingTask(ScheduledRecording scheduledRecording, - Channel channel, DvrManager dvrManager, - InputSessionManager sessionManager, WritableDvrDataManager dataManager, - Clock clock) { - RecordingTask task = mock(RecordingTask.class); - when(task.getPriority()).thenReturn(scheduledRecording.getPriority()); - when(task.getEndTimeMs()).thenReturn(scheduledRecording.getEndTimeMs()); - mRecordingTasks.add(task); - return task; - } - }); - } - - @Test - public void testAddSchedule_past() { - ScheduledRecording r = RecordingTestUtils.createTestRecordingWithPeriod(INPUT_ID, - CHANNEL_ID, 0L, 1L); - when(mDataManager.getScheduledRecording(anyLong())).thenReturn(r); - mScheduler.handleAddSchedule(r); - mScheduler.handleBuildSchedule(); - verify(mDataManager, timeout((int) LISTENER_TIMEOUT_MS).times(1)) - .changeState(any(ScheduledRecording.class), - eq(ScheduledRecording.STATE_RECORDING_FAILED)); - } - - @Test - public void testAddSchedule_start() { - mScheduler.handleAddSchedule(RecordingTestUtils.createTestRecordingWithPeriod(INPUT_ID, - CHANNEL_ID, mFakeClock.currentTimeMillis(), - mFakeClock.currentTimeMillis() + TimeUnit.HOURS.toMillis(1))); - mScheduler.handleBuildSchedule(); - verify(mRecordingTasks.get(0), timeout((int) LISTENER_TIMEOUT_MS).times(1)).start(); - } - - @Test - public void testAddSchedule_consecutiveNoStop() { - long startTimeMs = mFakeClock.currentTimeMillis(); - long endTimeMs = startTimeMs + TimeUnit.SECONDS.toMillis(1); - long id = 0; - mScheduler.handleAddSchedule( - RecordingTestUtils.createTestRecordingWithIdAndPriorityAndPeriod(++id, CHANNEL_ID, - LOW_PRIORITY, startTimeMs, endTimeMs)); - mScheduler.handleBuildSchedule(); - startTimeMs = endTimeMs; - endTimeMs = startTimeMs + TimeUnit.SECONDS.toMillis(1); - mScheduler.handleAddSchedule( - RecordingTestUtils.createTestRecordingWithIdAndPriorityAndPeriod(++id, CHANNEL_ID, - HIGH_PRIORITY, startTimeMs, endTimeMs)); - mScheduler.handleBuildSchedule(); - 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. - SystemClock.sleep(LISTENER_TIMEOUT_MS); - verify(mRecordingTasks.get(0), never()).stop(); - } - - @Test - public void testAddSchedule_consecutiveNoFail() { - long startTimeMs = mFakeClock.currentTimeMillis(); - long endTimeMs = startTimeMs + TimeUnit.SECONDS.toMillis(1); - long id = 0; - when(mDataManager.getScheduledRecording(anyLong())).thenReturn(ScheduledRecording - .builder(INPUT_ID, CHANNEL_ID, 0L, 0L).build()); - mScheduler.handleAddSchedule( - RecordingTestUtils.createTestRecordingWithIdAndPriorityAndPeriod(++id, CHANNEL_ID, - HIGH_PRIORITY, startTimeMs, endTimeMs)); - mScheduler.handleBuildSchedule(); - startTimeMs = endTimeMs; - endTimeMs = startTimeMs + TimeUnit.SECONDS.toMillis(1); - mScheduler.handleAddSchedule( - RecordingTestUtils.createTestRecordingWithIdAndPriorityAndPeriod(++id, CHANNEL_ID, - LOW_PRIORITY, startTimeMs, endTimeMs)); - mScheduler.handleBuildSchedule(); - verify(mRecordingTasks.get(0), timeout((int) LISTENER_TIMEOUT_MS).times(1)).start(); - 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. - 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); - long startTimeMs = mFakeClock.currentTimeMillis(); - long endTimeMs = startTimeMs + TimeUnit.SECONDS.toMillis(1); - long id = 0; - mScheduler.handleAddSchedule( - RecordingTestUtils.createTestRecordingWithIdAndPriorityAndPeriod(++id, CHANNEL_ID, - LOW_PRIORITY, startTimeMs, endTimeMs)); - mScheduler.handleBuildSchedule(); - startTimeMs = endTimeMs; - endTimeMs = startTimeMs + TimeUnit.SECONDS.toMillis(1); - mScheduler.handleAddSchedule( - RecordingTestUtils.createTestRecordingWithIdAndPriorityAndPeriod(++id, CHANNEL_ID, - HIGH_PRIORITY, startTimeMs, endTimeMs)); - mScheduler.handleBuildSchedule(); - verify(mRecordingTasks.get(0), timeout((int) LISTENER_TIMEOUT_MS).times(1)).start(); - 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); - } - - @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); - SystemClock.sleep(LISTENER_TIMEOUT_MS); - verify(mRecordingTasks.get(0), never()).cancel(); - } - - @Test - public void testUpdateSchedule_cancel() { - ScheduledRecording r = RecordingTestUtils.createTestRecordingWithPeriod(INPUT_ID, - CHANNEL_ID, mFakeClock.currentTimeMillis(), - mFakeClock.currentTimeMillis() + TimeUnit.HOURS.toMillis(2)); - mScheduler.handleAddSchedule(r); - mScheduler.handleBuildSchedule(); - mScheduler.handleUpdateSchedule(ScheduledRecording.buildFrom(r) - .setStartTimeMs(mFakeClock.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)) - .build()); - verify(mRecordingTasks.get(0), timeout((int) LISTENER_TIMEOUT_MS).times(1)).cancel(); - } - - private TvInputInfo createTvInputInfo(int tunerCount) throws Exception { - return TestUtils.createTvInputInfo(null, null, null, 0, false, true, tunerCount); - } -} diff --git a/tests/unit/src/com/android/tv/dvr/recorder/RecordingTaskTest.java b/tests/unit/src/com/android/tv/dvr/recorder/RecordingTaskTest.java deleted file mode 100644 index 37561a42..00000000 --- a/tests/unit/src/com/android/tv/dvr/recorder/RecordingTaskTest.java +++ /dev/null @@ -1,149 +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.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.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import android.os.Build; -import android.os.Handler; -import android.os.Looper; -import android.os.Message; -import android.support.test.filters.SdkSuppress; -import android.support.test.filters.SmallTest; - -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.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.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.concurrent.TimeUnit; - -/** - * Tests for {@link RecordingTask}. - */ -@SmallTest -@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -public class RecordingTaskTest { - private static final long DURATION = TimeUnit.MINUTES.toMillis(30); - 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; - - private FakeClock mFakeClock; - private DvrDataManagerInMemoryImpl mDataManager; - @Mock Handler mMockHandler; - @Mock DvrManager mDvrManager; - @Mock InputSessionManager mMockSessionManager; - @Mock RecordingSession mMockRecordingSession; - private final TestableFeature mDvrFeature = CommonFeatures.DVR; - - @Before - public void setUp() { - mDvrFeature.enableForTest(); - if (Looper.myLooper() == null) { - Looper.prepare(); - } - MockitoAnnotations.initMocks(this); - mFakeClock = FakeClock.createWithCurrentTime(); - mDataManager = new DvrDataManagerInMemoryImpl(getContext(), mFakeClock); - } - - @After - public void tearDown() { - mDvrFeature.resetForTests(); - } - - @Test - public void testHandle_init() { - Channel channel = createTestChannel(); - ScheduledRecording r = createRecording(channel); - RecordingTask task = createRecordingTask(r, channel); - String inputId = channel.getInputId(); - when(mMockSessionManager.createRecordingSession(eq(inputId), anyString(), eq(task), - eq(mMockHandler), anyLong())).thenReturn(mMockRecordingSession); - when(mMockHandler.sendMessageAtTime(anyObject(), anyLong())).thenReturn(true); - assertTrue(task.handleMessage(createMessage(RecordingTask.MSG_INITIALIZE))); - assertEquals(State.CONNECTION_PENDING, task.getState()); - verify(mMockSessionManager).createRecordingSession(eq(inputId), anyString(), eq(task), - eq(mMockHandler), anyLong()); - verify(mMockRecordingSession).tune(eq(inputId), eq(channel.getUri())); - verifyNoMoreInteractions(mMockHandler, mMockRecordingSession, mMockSessionManager); - } - - private static Channel createTestChannel() { - return new Channel.Builder().setInputId(INPUT_ID).setId(CHANNEL_ID) - .setDisplayName("Test Ch " + CHANNEL_ID).build(); - } - - @Test - public void testOnConnected() { - Channel channel = createTestChannel(); - ScheduledRecording r = createRecording(channel); - mDataManager.addScheduledRecording(r); - RecordingTask task = createRecordingTask(r, channel); - String inputId = channel.getInputId(); - when(mMockSessionManager.createRecordingSession(eq(inputId), anyString(), eq(task), - eq(mMockHandler), anyLong())).thenReturn(mMockRecordingSession); - when(mMockHandler.sendMessageAtTime(anyObject(), anyLong())).thenReturn(true); - task.handleMessage(createMessage(RecordingTask.MSG_INITIALIZE)); - task.onTuned(channel.getUri()); - assertEquals(State.CONNECTED, task.getState()); - } - - private ScheduledRecording createRecording(Channel c) { - long startTime = mFakeClock.currentTimeMillis() + START_OFFSET_MS; - long endTime = startTime + DURATION; - return RecordingTestUtils.createTestRecordingWithPeriod(c.getInputId(), c.getId(), - startTime, endTime); - } - - private RecordingTask createRecordingTask(ScheduledRecording r, Channel channel) { - RecordingTask recordingTask = new RecordingTask(getContext(), r, channel, mDvrManager, - mMockSessionManager, mDataManager, mFakeClock); - recordingTask.setHandler(mMockHandler); - return recordingTask; - } - - private Message createMessage(int what) { - Message msg = new Message(); - msg.setTarget(mMockHandler); - msg.what = what; - return msg; - } -}
\ No newline at end of file diff --git a/tests/unit/src/com/android/tv/dvr/recorder/ScheduledProgramReaperTest.java b/tests/unit/src/com/android/tv/dvr/recorder/ScheduledProgramReaperTest.java deleted file mode 100644 index ca72e13f..00000000 --- a/tests/unit/src/com/android/tv/dvr/recorder/ScheduledProgramReaperTest.java +++ /dev/null @@ -1,137 +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.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 org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.concurrent.TimeUnit; - -/** - * Tests for {@link ScheduledProgramReaper}. - */ -@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); - - private ScheduledProgramReaper mReaper; - private FakeClock mFakeClock; - private DvrDataManagerInMemoryImpl mDvrDataManager; - @Mock private DvrManager mDvrManager; - private final TestableFeature mDvrFeature = CommonFeatures.DVR; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - mDvrFeature.enableForTest(); - mFakeClock = FakeClock.createWithTimeOne(); - mDvrDataManager = new DvrDataManagerInMemoryImpl(getContext(), mFakeClock); - mReaper = new ScheduledProgramReaper(mDvrDataManager, mFakeClock); - } - - @After - public void tearDown() { - mDvrFeature.resetForTests(); - } - - @Test - public void testRun_noRecordings() { - assertTrue(mDvrDataManager.getAllScheduledRecordings().isEmpty()); - mReaper.run(); - assertTrue(mDvrDataManager.getAllScheduledRecordings().isEmpty()); - } - - @Test - public void testRun_oneRecordingsTomorrow() { - ScheduledRecording recording = addNewScheduledRecordingForTomorrow(); - MoreAsserts - .assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings(), recording); - mReaper.run(); - MoreAsserts - .assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings(), recording); - } - - @Test - public void testRun_oneRecordingsStarted() { - ScheduledRecording recording = addNewScheduledRecordingForTomorrow(); - MoreAsserts - .assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings(), recording); - mFakeClock.increment(TimeUnit.DAYS); - mReaper.run(); - MoreAsserts - .assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings(), recording); - } - - @Test - public void testRun_oneRecordingsFinished() { - ScheduledRecording recording = addNewScheduledRecordingForTomorrow(); - MoreAsserts - .assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings(), recording); - mFakeClock.increment(TimeUnit.DAYS); - mFakeClock.increment(TimeUnit.MINUTES, 2); - mReaper.run(); - MoreAsserts - .assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings(), recording); - } - - @Test - public void testRun_oneRecordingsExpired() { - ScheduledRecording recording = addNewScheduledRecordingForTomorrow(); - MoreAsserts - .assertContentsInAnyOrder(mDvrDataManager.getAllScheduledRecordings(), recording); - mFakeClock.increment(TimeUnit.DAYS, 1 + ScheduledProgramReaper.DAYS); - mFakeClock.increment(TimeUnit.MILLISECONDS, DURATION); - // After the cutoff and enough so we can see on the clock - mFakeClock.increment(TimeUnit.SECONDS, 1); - - mReaper.run(); - assertTrue("Recordings after reaper at " + com.android.tv.util.Utils - .toIsoDateTimeString(mFakeClock.currentTimeMillis()), - mDvrDataManager.getAllScheduledRecordings().isEmpty()); - } - - private ScheduledRecording addNewScheduledRecordingForTomorrow() { - long startTime = mFakeClock.currentTimeMillis() + TimeUnit.DAYS.toMillis(1); - ScheduledRecording recording = RecordingTestUtils.createTestRecordingWithPeriod(INPUT_ID, - CHANNEL_ID, startTime, startTime + DURATION); - return mDvrDataManager.addScheduledRecordingInternal( - ScheduledRecording.buildFrom(recording) - .setState(ScheduledRecording.STATE_RECORDING_FINISHED).build()); - } -} diff --git a/tests/unit/src/com/android/tv/dvr/recorder/SchedulerTest.java b/tests/unit/src/com/android/tv/dvr/recorder/SchedulerTest.java deleted file mode 100644 index a5154729..00000000 --- a/tests/unit/src/com/android/tv/dvr/recorder/SchedulerTest.java +++ /dev/null @@ -1,125 +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.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; -import static org.mockito.Mockito.verifyZeroInteractions; - -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.os.Build; -import android.os.Looper; -import android.support.test.filters.SdkSuppress; -import android.support.test.filters.SmallTest; - -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; - -import java.util.concurrent.TimeUnit; - -/** - * Tests for {@link RecordingScheduler}. - */ -@SmallTest -@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -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 RecordingScheduler mScheduler; - @Mock DvrManager mDvrManager; - @Mock InputSessionManager mSessionManager; - @Mock AlarmManager mMockAlarmManager; - @Mock ChannelDataManager mChannelDataManager; - @Mock TvInputManagerHelper mInputManager; - private final TestableFeature mDvrFeature = CommonFeatures.DVR; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - mDvrFeature.enableForTest(); - mFakeClock = FakeClock.createWithCurrentTime(); - mDataManager = new DvrDataManagerInMemoryImpl(getTargetContext(), mFakeClock); - Mockito.when(mChannelDataManager.isDbLoadFinished()).thenReturn(true); - mScheduler = new RecordingScheduler(Looper.myLooper(), mDvrManager, mSessionManager, mDataManager, - mChannelDataManager, mInputManager, getTargetContext(), mFakeClock, - mMockAlarmManager); - } - - @After - public void tearDown() { - mDvrFeature.resetForTests(); - } - - @Test - public void testUpdate_none() { - mScheduler.updateAndStartServiceIfNeeded(); - verifyZeroInteractions(mMockAlarmManager); - } - - @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); - verify(mMockAlarmManager).setExactAndAllowWhileIdle( - eq(AlarmManager.RTC_WAKEUP), - eq(startTime - RecordingScheduler.MS_TO_WAKE_BEFORE_START), - any(PendingIntent.class)); - Mockito.reset(mMockAlarmManager); - mScheduler.updateAndStartServiceIfNeeded(); - verify(mMockAlarmManager).setExactAndAllowWhileIdle( - eq(AlarmManager.RTC_WAKEUP), - eq(startTime - RecordingScheduler.MS_TO_WAKE_BEFORE_START), - any(PendingIntent.class)); - } - - @Test - public void testStartsWithin() { - long now = mFakeClock.currentTimeMillis(); - long startTime = now + 3; - ScheduledRecording r = RecordingTestUtils - .createTestRecordingWithPeriod(INPUT_ID, CHANNEL_ID, startTime, startTime + 100); - assertFalse(mScheduler.startsWithin(r, 2)); - assertTrue(mScheduler.startsWithin(r, 3)); - } -}
\ No newline at end of file diff --git a/tests/unit/src/com/android/tv/dvr/recorder/SeriesRecordingSchedulerTest.java b/tests/unit/src/com/android/tv/dvr/recorder/SeriesRecordingSchedulerTest.java deleted file mode 100644 index 16fa1baf..00000000 --- a/tests/unit/src/com/android/tv/dvr/recorder/SeriesRecordingSchedulerTest.java +++ /dev/null @@ -1,129 +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.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.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; - -/** - * Tests for {@link SeriesRecordingScheduler} - */ -@SmallTest -@SdkSuppress(minSdkVersion = Build.VERSION_CODES.N) -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; - private static final String SERIES_ID = "SERIES_ID"; - 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"; - - private final SeriesRecording mBaseSeriesRecording = new SeriesRecording.Builder() - .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; - - @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(); - mDataManager.addSeriesRecording(seriesRecording); - List<Program> programs = new ArrayList<>(); - Program program1 = new Program.Builder(mBaseProgram).setSeasonNumber(SEASON_NUMBER1) - .setEpisodeNumber(EPISODE_NUMBER1).build(); - programs.add(program1); - Program program2 = new Program.Builder(mBaseProgram).setSeasonNumber(SEASON_NUMBER2) - .setEpisodeNumber(EPISODE_NUMBER2).build(); - programs.add(program2); - LongSparseArray<List<Program>> result = SeriesRecordingScheduler.pickOneProgramPerEpisode( - mDataManager, Collections.singletonList(seriesRecording), programs); - MoreAsserts.assertContentsInAnyOrder(result.get(SERIES_RECORDING_ID1), program1, program2); - } - - @Test - public void testPickOneProgramPerEpisode_manyPerEpisode() { - SeriesRecording seriesRecording = SeriesRecording.buildFrom(mBaseSeriesRecording) - .setId(SERIES_RECORDING_ID1).build(); - mDataManager.addSeriesRecording(seriesRecording); - List<Program> programs = new ArrayList<>(); - Program program1 = new Program.Builder(mBaseProgram).setSeasonNumber(SEASON_NUMBER1) - .setEpisodeNumber(EPISODE_NUMBER1).setStartTimeUtcMillis(0).build(); - programs.add(program1); - Program program2 = new Program.Builder(program1).setStartTimeUtcMillis(1).build(); - programs.add(program2); - Program program3 = new Program.Builder(mBaseProgram).setSeasonNumber(SEASON_NUMBER2) - .setEpisodeNumber(EPISODE_NUMBER2).build(); - programs.add(program3); - Program program4 = new Program.Builder(program1).setStartTimeUtcMillis(1).build(); - programs.add(program4); - LongSparseArray<List<Program>> result = SeriesRecordingScheduler.pickOneProgramPerEpisode( - mDataManager, Collections.singletonList(seriesRecording), programs); - MoreAsserts.assertContentsInAnyOrder(result.get(SERIES_RECORDING_ID1), program1, program3); - } - - @Test - public void testPickOneProgramPerEpisode_nullEpisode() { - SeriesRecording seriesRecording = SeriesRecording.buildFrom(mBaseSeriesRecording) - .setId(SERIES_RECORDING_ID1).build(); - mDataManager.addSeriesRecording(seriesRecording); - List<Program> programs = new ArrayList<>(); - Program program1 = new Program.Builder(mBaseProgram).setStartTimeUtcMillis(0).build(); - programs.add(program1); - Program program2 = new Program.Builder(mBaseProgram).setStartTimeUtcMillis(1).build(); - programs.add(program2); - LongSparseArray<List<Program>> result = SeriesRecordingScheduler.pickOneProgramPerEpisode( - mDataManager, Collections.singletonList(seriesRecording), programs); - MoreAsserts.assertContentsInAnyOrder(result.get(SERIES_RECORDING_ID1), program1, program2); - } -} diff --git a/tests/unit/src/com/android/tv/dvr/ui/SortedArrayAdapterTest.java b/tests/unit/src/com/android/tv/dvr/ui/SortedArrayAdapterTest.java deleted file mode 100644 index 5667ee6b..00000000 --- a/tests/unit/src/com/android/tv/dvr/ui/SortedArrayAdapterTest.java +++ /dev/null @@ -1,250 +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.ui; - -import android.support.test.filters.SmallTest; -import android.support.v17.leanback.widget.ClassPresenterSelector; -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; - -/** - * Tests for {@link SortedArrayAdapter}. - */ -@SmallTest -public class SortedArrayAdapterTest extends TestCase { - 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; - - @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); - assertNotEmpty(); - 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)); - assertNotEmpty(); - assertEquals(mAdapter.size(), 1); - assertEquals(mAdapter.get(0), P2); - } - - @Test - public void testExtraItem() { - mAdapter = new TestSortedArrayAdapter(Integer.MAX_VALUE, EXTRA); - mAdapter.setInitialItems(Arrays.asList(P1, P2)); - assertNotEmpty(); - assertEquals(mAdapter.size(), 3); - assertEquals(mAdapter.get(0), P2); - assertEquals(mAdapter.get(2), EXTRA); - mAdapter.remove(P2); - mAdapter.remove(P1); - assertEquals(mAdapter.size(), 1); - assertEquals(mAdapter.get(0), EXTRA); - } - - @Test - public void testExtraItemWithMaxCount() { - mAdapter = new TestSortedArrayAdapter(1, EXTRA); - mAdapter.setInitialItems(Arrays.asList(P1, P2)); - assertNotEmpty(); - assertEquals(mAdapter.size(), 2); - assertEquals(mAdapter.get(0), P2); - assertEquals(mAdapter.get(1), EXTRA); - mAdapter.remove(P2); - assertEquals(mAdapter.size(), 1); - assertEquals(mAdapter.get(0), EXTRA); - } - - @Test - public void testRemove() { - mAdapter.add(P1); - mAdapter.add(P2); - assertNotEmpty(); - assertContentsInOrder(mAdapter, P2, P1); - mAdapter.remove(P3); - assertContentsInOrder(mAdapter, P2, P1); - mAdapter.remove(P2); - 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); - mAdapter.add(P2); - assertNotEmpty(); - assertContentsInOrder(mAdapter, P2, P1); - mAdapter.change(p2_changed); - assertContentsInOrder(mAdapter, P1, p2_changed); - } - - @Test - public void testChange_new() { - mAdapter.change(P1); - assertNotEmpty(); - assertContentsInOrder(mAdapter, P1); - } - - private void assertEmpty() { - assertEquals("empty", true, mAdapter.isEmpty()); - } - - private void assertNotEmpty() { - assertEquals("empty", false, mAdapter.isEmpty()); - } - - private static void assertContentsInOrder(ObjectAdapter adapter, Object... contents) { - int ex = contents.length; - assertEquals("size", ex, adapter.size()); - for (int i = 0; i < ex; i++) { - assertEquals("element " + 1, contents[i], adapter.get(i)); - } - } - - private static class TestData { - @Override - public String toString() { - return "TestData[" + mId + "]{" + mText + '}'; - } - - static TestData create(long first, String text) { - return new TestData(first, text); - } - - private final long mId; - private final String mText; - - private TestData(long id, String second) { - this.mId = id; - this.mText = second; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof TestData)) return false; - TestData that = (TestData) o; - return mId == that.mId && Objects.equals(mText, that.mText); - } - - @Override - public int hashCode() { - return Objects.hash(mId, mText); - } - } - - private static class TestSortedArrayAdapter extends SortedArrayAdapter<TestData> { - - private static final Comparator<TestData> TEXT_COMPARATOR = new Comparator<TestData>() { - @Override - public int compare(TestData lhs, TestData rhs) { - return lhs.mText.compareTo(rhs.mText); - } - }; - - TestSortedArrayAdapter(int maxInitialCount, Object extra) { - super(new ClassPresenterSelector(), TEXT_COMPARATOR, maxInitialCount); - if (extra != null) { - addExtraItem((TestData) extra); - } - } - - @Override - protected long getId(TestData item) { - return item.mId; - } - } -}
\ No newline at end of file diff --git a/tests/unit/src/com/android/tv/experiments/ExperimentsTest.java b/tests/unit/src/com/android/tv/experiments/ExperimentsTest.java deleted file mode 100644 index 3f827ce1..00000000 --- a/tests/unit/src/com/android/tv/experiments/ExperimentsTest.java +++ /dev/null @@ -1,53 +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.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 e8cfdbef..028a185d 100644 --- a/tests/unit/src/com/android/tv/menu/MenuTest.java +++ b/tests/unit/src/com/android/tv/menu/MenuTest.java @@ -16,24 +16,23 @@ 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 static com.google.common.truth.Truth.assertWithMessage; import android.support.test.filters.SmallTest; - +import android.support.test.runner.AndroidJUnit4; import com.android.tv.menu.Menu.OnMenuVisibilityChangeListener; - import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -/** - * Tests for {@link Menu}. - */ +/** Tests for {@link Menu}. */ @SmallTest +@RunWith(AndroidJUnit4.class) public class MenuTest { private Menu mMenu; private IMenuView mMenuView; @@ -50,26 +49,27 @@ public class MenuTest { mMenu.disableAnimationForTest(); } + @Ignore("b/73727914") @Test public void testScheduleHide() { mMenu.show(Menu.REASON_NONE); setMenuVisible(true); - assertTrue("Hide is not scheduled", mMenu.isHideScheduled()); + assertWithMessage("Hide is not scheduled").that(mMenu.isHideScheduled()).isTrue(); mMenu.hide(false); setMenuVisible(false); - assertFalse("Hide is scheduled", mMenu.isHideScheduled()); + assertWithMessage("Hide is scheduled").that(mMenu.isHideScheduled()).isFalse(); mMenu.setKeepVisible(true); mMenu.show(Menu.REASON_NONE); setMenuVisible(true); - assertFalse("Hide is scheduled", mMenu.isHideScheduled()); + assertWithMessage("Hide is scheduled").that(mMenu.isHideScheduled()).isFalse(); mMenu.setKeepVisible(false); - assertTrue("Hide is not scheduled", mMenu.isHideScheduled()); + assertWithMessage("Hide is not scheduled").that(mMenu.isHideScheduled()).isTrue(); mMenu.setKeepVisible(true); - assertFalse("Hide is scheduled", mMenu.isHideScheduled()); + assertWithMessage("Hide is scheduled").that(mMenu.isHideScheduled()).isFalse(); mMenu.hide(false); setMenuVisible(false); - assertFalse("Hide is scheduled", mMenu.isHideScheduled()); + assertWithMessage("Hide is scheduled").that(mMenu.isHideScheduled()).isFalse(); } @Test @@ -83,8 +83,11 @@ public class MenuTest { Mockito.verify(mVisibilityChangeListener, Mockito.never()) .onMenuVisibilityChange(Matchers.eq(false)); // IMenuView.show should be called with the same parameter. - Mockito.verify(mMenuView).onShow(Matchers.eq(Menu.REASON_NONE), - Matchers.isNull(String.class), Matchers.isNull(Runnable.class)); + Mockito.verify(mMenuView) + .onShow( + Matchers.eq(Menu.REASON_NONE), + Matchers.isNull(String.class), + Matchers.isNull(Runnable.class)); mMenu.hide(true); setMenuVisible(false); // Listener should be called with "false" argument. @@ -104,8 +107,11 @@ public class MenuTest { Mockito.verify(mVisibilityChangeListener, Mockito.never()) .onMenuVisibilityChange(Matchers.eq(false)); // IMenuView.show should be called with the same parameter. - Mockito.verify(mMenuView).onShow(Matchers.eq(Menu.REASON_GUIDE), - Matchers.eq(ChannelsRow.ID), Matchers.isNull(Runnable.class)); + Mockito.verify(mMenuView) + .onShow( + Matchers.eq(Menu.REASON_GUIDE), + Matchers.eq(ChannelsRow.ID), + Matchers.isNull(Runnable.class)); mMenu.hide(false); setMenuVisible(false); // Listener should be called with "false" argument. @@ -125,8 +131,11 @@ public class MenuTest { Mockito.verify(mVisibilityChangeListener, Mockito.never()) .onMenuVisibilityChange(Matchers.eq(false)); // IMenuView.show should be called with the same parameter. - Mockito.verify(mMenuView).onShow(Matchers.eq(Menu.REASON_PLAY_CONTROLS_FAST_FORWARD), - Matchers.eq(PlayControlsRow.ID), Matchers.isNull(Runnable.class)); + Mockito.verify(mMenuView) + .onShow( + Matchers.eq(Menu.REASON_PLAY_CONTROLS_FAST_FORWARD), + Matchers.eq(PlayControlsRow.ID), + Matchers.isNull(Runnable.class)); mMenu.hide(false); setMenuVisible(false); // Listener should be called with "false" argument. @@ -136,11 +145,13 @@ public class MenuTest { } private void setMenuVisible(final boolean visible) { - Mockito.when(mMenuView.isVisible()).thenAnswer(new Answer<Boolean>() { - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - return visible; - } - }); + Mockito.when(mMenuView.isVisible()) + .thenAnswer( + new Answer<Boolean>() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + return visible; + } + }); } } diff --git a/tests/unit/src/com/android/tv/menu/TvOptionsRowAdapterTest.java b/tests/unit/src/com/android/tv/menu/TvOptionsRowAdapterTest.java index 49ba8514..0f815a7a 100644 --- a/tests/unit/src/com/android/tv/menu/TvOptionsRowAdapterTest.java +++ b/tests/unit/src/com/android/tv/menu/TvOptionsRowAdapterTest.java @@ -16,30 +16,28 @@ package com.android.tv.menu; import static android.support.test.InstrumentationRegistry.getInstrumentation; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.fail; import android.media.tv.TvTrackInfo; import android.os.SystemClock; import android.support.test.filters.MediumTest; +import android.support.test.runner.AndroidJUnit4; import android.text.TextUtils; - -import com.android.tv.BaseMainActivityTestCase; -import com.android.tv.testing.Constants; +import com.android.tv.testing.activities.BaseMainActivityTestCase; +import com.android.tv.testing.constants.Constants; 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; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; -/** - * Tests for {@link TvOptionsRowAdapter}. - */ +/** Tests for {@link TvOptionsRowAdapter}. */ @MediumTest +@RunWith(AndroidJUnit4.class) public class TvOptionsRowAdapterTest extends BaseMainActivityTestCase { private static final int WAIT_TRACK_EVENT_TIMEOUT_MS = 300; public static final int TRACK_CHECK_INTERVAL_MS = 10; @@ -56,12 +54,14 @@ public class TvOptionsRowAdapterTest extends BaseMainActivityTestCase { waitUntilAudioTracksHaveSize(1); waitUntilAudioTrackSelected(ChannelState.DEFAULT.getSelectedAudioTrackId()); // update should be called on the main thread to avoid the multi-thread problem. - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mTvOptionsRowAdapter.update(); - } - }); + getInstrumentation() + .runOnMainSync( + new Runnable() { + @Override + public void run() { + mTvOptionsRowAdapter.update(); + } + }); } @Test @@ -73,9 +73,10 @@ public class TvOptionsRowAdapterTest extends BaseMainActivityTestCase { waitUntilAudioTrackSelected(Constants.EN_STEREO_AUDIO_TRACK.getId()); boolean result = mTvOptionsRowAdapter.updateMultiAudioAction(); - assertEquals("update Action had change", true, result); - assertEquals("Multi Audio enabled", true, - MenuAction.SELECT_AUDIO_LANGUAGE_ACTION.isEnabled()); + assertWithMessage("update Action had change").that(result).isTrue(); + assertWithMessage("Multi Audio enabled") + .that(MenuAction.SELECT_AUDIO_LANGUAGE_ACTION.isEnabled()) + .isTrue(); } @Test @@ -90,9 +91,10 @@ public class TvOptionsRowAdapterTest extends BaseMainActivityTestCase { waitUntilAudioTrackSelected(Constants.GENERIC_AUDIO_TRACK.getId()); boolean result = mTvOptionsRowAdapter.updateMultiAudioAction(); - assertEquals("update Action had change", true, result); - assertEquals("Multi Audio enabled", false, - MenuAction.SELECT_AUDIO_LANGUAGE_ACTION.isEnabled()); + assertWithMessage("update Action had change").that(result).isTrue(); + assertWithMessage("Multi Audio enabled") + .that(MenuAction.SELECT_AUDIO_LANGUAGE_ACTION.isEnabled()) + .isFalse(); } @Test @@ -108,9 +110,10 @@ public class TvOptionsRowAdapterTest extends BaseMainActivityTestCase { waitUntilVideoTrackSelected(data.mSelectedVideoTrackId); boolean result = mTvOptionsRowAdapter.updateMultiAudioAction(); - assertEquals("update Action had change", true, result); - assertEquals("Multi Audio enabled", false, - MenuAction.SELECT_AUDIO_LANGUAGE_ACTION.isEnabled()); + assertWithMessage("update Action had change").that(result).isTrue(); + assertWithMessage("Multi Audio enabled") + .that(MenuAction.SELECT_AUDIO_LANGUAGE_ACTION.isEnabled()) + .isFalse(); } private void waitUntilAudioTracksHaveSize(int expected) { @@ -135,8 +138,13 @@ public class TvOptionsRowAdapterTest extends BaseMainActivityTestCase { } SystemClock.sleep(TRACK_CHECK_INTERVAL_MS); } - fail("Waited for " + WAIT_TRACK_EVENT_TIMEOUT_MS + " milliseconds for track size to be " - + expected + " but was " + size); + fail( + "Waited for " + + WAIT_TRACK_EVENT_TIMEOUT_MS + + " milliseconds for track size to be " + + expected + + " but was " + + size); } private void waitUntilAudioTrackSelected(String trackId) { @@ -158,7 +166,12 @@ public class TvOptionsRowAdapterTest extends BaseMainActivityTestCase { } SystemClock.sleep(TRACK_CHECK_INTERVAL_MS); } - fail("Waited for " + WAIT_TRACK_EVENT_TIMEOUT_MS + " milliseconds for track ID to be " - + trackId + " but was " + selectedTrackId); + 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 db765109..e63bdc3a 100644 --- a/tests/unit/src/com/android/tv/recommendation/ChannelRecordTest.java +++ b/tests/unit/src/com/android/tv/recommendation/ChannelRecordTest.java @@ -17,22 +17,20 @@ package com.android.tv.recommendation; import static android.support.test.InstrumentationRegistry.getContext; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import android.support.test.filters.SmallTest; - -import com.android.tv.testing.Utils; - -import org.junit.Before; -import org.junit.Test; - +import android.support.test.runner.AndroidJUnit4; +import com.android.tv.testing.utils.Utils; import java.util.Random; import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; -/** - * Unit tests for {@link ChannelRecord}. - */ +/** Unit tests for {@link ChannelRecord}. */ @SmallTest +@RunWith(AndroidJUnit4.class) public class ChannelRecordTest { private static final int CHANNEL_RECORD_MAX_HISTORY_SIZE = ChannelRecord.MAX_HISTORY_SIZE; @@ -49,14 +47,14 @@ public class ChannelRecordTest { @Test public void testGetLastWatchEndTime_noHistory() { - assertEquals(0, mChannelRecord.getLastWatchEndTimeMs()); + assertThat(mChannelRecord.getLastWatchEndTimeMs()).isEqualTo(0); } @Test public void testGetLastWatchEndTime_oneHistory() { addWatchLog(); - assertEquals(mLatestWatchEndTimeMs, mChannelRecord.getLastWatchEndTimeMs()); + assertThat(mChannelRecord.getLastWatchEndTimeMs()).isEqualTo(mLatestWatchEndTimeMs); } @Test @@ -65,7 +63,7 @@ public class ChannelRecordTest { addWatchLog(); } - assertEquals(mLatestWatchEndTimeMs, mChannelRecord.getLastWatchEndTimeMs()); + assertThat(mChannelRecord.getLastWatchEndTimeMs()).isEqualTo(mLatestWatchEndTimeMs); } @Test @@ -74,19 +72,19 @@ public class ChannelRecordTest { addWatchLog(); } - assertEquals(mLatestWatchEndTimeMs, mChannelRecord.getLastWatchEndTimeMs()); + assertThat(mChannelRecord.getLastWatchEndTimeMs()).isEqualTo(mLatestWatchEndTimeMs); } @Test public void testGetTotalWatchDuration_noHistory() { - assertEquals(0, mChannelRecord.getTotalWatchDurationMs()); + assertThat(mChannelRecord.getTotalWatchDurationMs()).isEqualTo(0); } @Test public void testGetTotalWatchDuration_oneHistory() { long durationMs = addWatchLog(); - assertEquals(durationMs, mChannelRecord.getTotalWatchDurationMs()); + assertThat(mChannelRecord.getTotalWatchDurationMs()).isEqualTo(durationMs); } @Test @@ -97,7 +95,7 @@ public class ChannelRecordTest { totalWatchTimeMs += durationMs; } - assertEquals(totalWatchTimeMs, mChannelRecord.getTotalWatchDurationMs()); + assertThat(mChannelRecord.getTotalWatchDurationMs()).isEqualTo(totalWatchTimeMs); } @Test @@ -112,8 +110,9 @@ public class ChannelRecordTest { } } - // Only latest CHANNEL_RECORD_MAX_HISTORY_SIZE logs are remained. - assertEquals(totalWatchTimeMs - firstDurationMs, mChannelRecord.getTotalWatchDurationMs()); + // Only latest CHANNEL_RECORD_MAX_HISTORY_SIZE logs are remained. + assertThat(mChannelRecord.getTotalWatchDurationMs()) + .isEqualTo(totalWatchTimeMs - firstDurationMs); } /** @@ -126,8 +125,9 @@ public class ChannelRecordTest { mLatestWatchEndTimeMs += TimeUnit.SECONDS.toMillis(mRandom.nextInt(60) + 1); long durationMs = TimeUnit.SECONDS.toMillis(mRandom.nextInt(60) + 1); - mChannelRecord.logWatchHistory(new WatchedProgram(null, - mLatestWatchEndTimeMs, mLatestWatchEndTimeMs + durationMs)); + mChannelRecord.logWatchHistory( + new WatchedProgram( + null, mLatestWatchEndTimeMs, mLatestWatchEndTimeMs + durationMs)); mLatestWatchEndTimeMs += durationMs; return durationMs; diff --git a/tests/unit/src/com/android/tv/recommendation/EvaluatorTestCase.java b/tests/unit/src/com/android/tv/recommendation/EvaluatorTestCase.java index 853fb245..f62a5e05 100644 --- a/tests/unit/src/com/android/tv/recommendation/EvaluatorTestCase.java +++ b/tests/unit/src/com/android/tv/recommendation/EvaluatorTestCase.java @@ -20,19 +20,15 @@ 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.data.api.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 com.android.tv.testing.utils.Utils; import java.util.ArrayList; import java.util.List; +import org.junit.Before; -/** - * Base test case for Recommendation Evaluator Unit tests. - */ +/** Base test case for Recommendation Evaluator Unit tests. */ public abstract class EvaluatorTestCase<T extends Evaluator> { private static final long INVALID_CHANNEL_ID = -1; @@ -46,8 +42,8 @@ public abstract class EvaluatorTestCase<T extends Evaluator> { @Before public void setUp() { mChannelRecordSortedMap = new ChannelRecordSortedMapHelper(getContext()); - mDataManager = RecommendationUtils - .createMockRecommendationDataManager(mChannelRecordSortedMap); + mDataManager = + RecommendationUtils.createMockRecommendationDataManager(mChannelRecordSortedMap); Recommender mRecommender = new FakeRecommender(); mEvaluator = createEvaluator(); mEvaluator.setRecommender(mRecommender); @@ -55,9 +51,7 @@ public abstract class EvaluatorTestCase<T extends Evaluator> { mChannelRecordSortedMap.resetRandom(Utils.createTestRandom()); } - /** - * Each evaluator test has to create Evaluator in {@code mEvaluator}. - */ + /** Each evaluator test has to create Evaluator in {@code mEvaluator}. */ public abstract T createEvaluator(); public void addChannels(int numberOfChannels) { @@ -68,15 +62,16 @@ public abstract class EvaluatorTestCase<T extends Evaluator> { return mChannelRecordSortedMap.addChannel(); } - public void addRandomWatchLogs(long watchStartTimeMs, long watchEndTimeMs, - long maxWatchDurationMs) { - assertTrue(mChannelRecordSortedMap.addRandomWatchLogs(watchStartTimeMs, watchEndTimeMs, - maxWatchDurationMs)); + public void addRandomWatchLogs( + long watchStartTimeMs, long watchEndTimeMs, long maxWatchDurationMs) { + assertTrue( + mChannelRecordSortedMap.addRandomWatchLogs( + watchStartTimeMs, watchEndTimeMs, maxWatchDurationMs)); } public void addWatchLog(long channelId, long watchStartTimeMs, long durationTimeMs) { - assertTrue(mChannelRecordSortedMap.addWatchLog(channelId, watchStartTimeMs, - durationTimeMs)); + assertTrue( + mChannelRecordSortedMap.addWatchLog(channelId, watchStartTimeMs, durationTimeMs)); } public List<Long> getChannelIdListSorted() { @@ -86,31 +81,29 @@ public abstract class EvaluatorTestCase<T extends Evaluator> { public long getLatestWatchEndTimeMs() { long latestWatchEndTimeMs = 0; for (ChannelRecord channelRecord : mChannelRecordSortedMap.values()) { - latestWatchEndTimeMs = Math.max(latestWatchEndTimeMs, - channelRecord.getLastWatchEndTimeMs()); + latestWatchEndTimeMs = + Math.max(latestWatchEndTimeMs, channelRecord.getLastWatchEndTimeMs()); } return latestWatchEndTimeMs; } - /** - * Check whether scores of each channels are valid. - */ + /** Check whether scores of each channels are valid. */ protected void assertChannelScoresValid() { - assertEqualScores(Evaluator.NOT_RECOMMENDED, - mEvaluator.evaluateChannel(INVALID_CHANNEL_ID)); - assertEqualScores(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()) { double score = mEvaluator.evaluateChannel(channelId); - assertTrue("Channel " + channelId + " score of " + score + "is not valid", + assertTrue( + "Channel " + channelId + " score of " + score + "is not valid", score == Evaluator.NOT_RECOMMENDED || (0.0 <= score && score <= 1.0)); } } - /** - * Notify that loading channels and watch logs are finished. - */ + /** Notify that loading channels and watch logs are finished. */ protected void notifyChannelAndWatchLogLoaded() { mEvaluator.onChannelRecordListChanged(new ArrayList<>(mChannelRecordSortedMap.values())); } @@ -125,15 +118,16 @@ public abstract class EvaluatorTestCase<T extends Evaluator> { private class FakeRecommender extends Recommender { public FakeRecommender() { - super(new Recommender.Listener() { - @Override - public void onRecommenderReady() { - } - - @Override - public void onRecommendationChanged() { - } - }, true, mDataManager); + super( + new Recommender.Listener() { + @Override + public void onRecommenderReady() {} + + @Override + public void onRecommendationChanged() {} + }, + true, + mDataManager); } @Override diff --git a/tests/unit/src/com/android/tv/recommendation/FavoriteChannelEvaluatorTest.java b/tests/unit/src/com/android/tv/recommendation/FavoriteChannelEvaluatorTest.java index ac701af9..e14320f0 100644 --- a/tests/unit/src/com/android/tv/recommendation/FavoriteChannelEvaluatorTest.java +++ b/tests/unit/src/com/android/tv/recommendation/FavoriteChannelEvaluatorTest.java @@ -16,19 +16,18 @@ package com.android.tv.recommendation; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import android.support.test.filters.SmallTest; - -import org.junit.Test; - +import android.support.test.runner.AndroidJUnit4; import java.util.List; import java.util.concurrent.TimeUnit; +import org.junit.Test; +import org.junit.runner.RunWith; -/** - * Unit tests for {@link FavoriteChannelEvaluator}. - */ +/** Unit tests for {@link FavoriteChannelEvaluator}. */ @SmallTest +@RunWith(AndroidJUnit4.class) public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChannelEvaluator> { private static final int DEFAULT_NUMBER_OF_CHANNELS = 4; private static final long DEFAULT_WATCH_START_TIME_MS = @@ -47,14 +46,16 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan long channelId = addChannel().getId(); notifyChannelAndWatchLogLoaded(); - assertEqualScores(Recommender.Evaluator.NOT_RECOMMENDED, - mEvaluator.evaluateChannel(channelId)); + assertEqualScores( + Recommender.Evaluator.NOT_RECOMMENDED, mEvaluator.evaluateChannel(channelId)); } @Test public void testOneChannelWithRandomWatchLogs() { addChannel(); - addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, + addRandomWatchLogs( + DEFAULT_WATCH_START_TIME_MS, + DEFAULT_WATCH_END_TIME_MS, DEFAULT_MAX_WATCH_DURATION_MS); notifyChannelAndWatchLogLoaded(); @@ -68,15 +69,17 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan List<Long> channelIdList = getChannelIdListSorted(); for (long channelId : channelIdList) { - assertEqualScores(Recommender.Evaluator.NOT_RECOMMENDED, - mEvaluator.evaluateChannel(channelId)); + 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, + addRandomWatchLogs( + DEFAULT_WATCH_START_TIME_MS, + DEFAULT_WATCH_END_TIME_MS, DEFAULT_MAX_WATCH_DURATION_MS); notifyChannelAndWatchLogLoaded(); @@ -103,7 +106,7 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan double previousScore = Recommender.Evaluator.NOT_RECOMMENDED; for (long channelId : channelIdList) { double score = mEvaluator.evaluateChannel(channelId); - assertTrue(previousScore <= score); + assertThat(previousScore).isAtMost(score); previousScore = score; } } @@ -112,40 +115,54 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan public void testTwoChannelsWithSameWatchDuration() { long channelOne = addChannel().getId(); long channelTwo = addChannel().getId(); - addWatchLog(channelOne, System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1), + addWatchLog( + channelOne, + System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1), TimeUnit.MINUTES.toMillis(30)); - addWatchLog(channelTwo, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(30), + addWatchLog( + channelTwo, + System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(30), TimeUnit.MINUTES.toMillis(30)); notifyChannelAndWatchLogLoaded(); - assertTrue(mEvaluator.evaluateChannel(channelOne) == - mEvaluator.evaluateChannel(channelTwo)); + assertThat(mEvaluator.evaluateChannel(channelOne) == mEvaluator.evaluateChannel(channelTwo)) + .isTrue(); } @Test public void testTwoChannelsWithDifferentWatchDuration() { long channelOne = addChannel().getId(); long channelTwo = addChannel().getId(); - addWatchLog(channelOne, System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3), + addWatchLog( + channelOne, + System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3), TimeUnit.MINUTES.toMillis(30)); - addWatchLog(channelTwo, System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2), + addWatchLog( + channelTwo, + System.currentTimeMillis() - TimeUnit.HOURS.toMillis(2), TimeUnit.HOURS.toMillis(1)); notifyChannelAndWatchLogLoaded(); - // Channel two was watched longer than channel one, so it's score is bigger. - assertTrue(mEvaluator.evaluateChannel(channelOne) < mEvaluator.evaluateChannel(channelTwo)); + // Channel two was watched longer than channel one, so it's score is bigger. + assertThat(mEvaluator.evaluateChannel(channelOne)) + .isLessThan(mEvaluator.evaluateChannel(channelTwo)); - addWatchLog(channelOne, System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1), + addWatchLog( + channelOne, + System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1), TimeUnit.HOURS.toMillis(1)); - // Now, channel one was watched longer than channel two, so it's score is bigger. - assertTrue(mEvaluator.evaluateChannel(channelOne) > mEvaluator.evaluateChannel(channelTwo)); + // Now, channel one was watched longer than channel two, so it's score is bigger. + assertThat(mEvaluator.evaluateChannel(channelOne)) + .isGreaterThan(mEvaluator.evaluateChannel(channelTwo)); } @Test public void testScoreIncreasesWithNewWatchLog() { long channelId = addChannel().getId(); - addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, + addRandomWatchLogs( + DEFAULT_WATCH_START_TIME_MS, + DEFAULT_WATCH_END_TIME_MS, DEFAULT_MAX_WATCH_DURATION_MS); notifyChannelAndWatchLogLoaded(); @@ -154,7 +171,7 @@ public class FavoriteChannelEvaluatorTest extends EvaluatorTestCase<FavoriteChan addWatchLog(channelId, latestWatchEndTimeMs, TimeUnit.MINUTES.toMillis(10)); - // Score must be increased because total watch duration of the channel increases. - assertTrue(previousScore <= mEvaluator.evaluateChannel(channelId)); + // Score must be increased because total watch duration of the channel increases. + assertThat(previousScore).isAtMost(mEvaluator.evaluateChannel(channelId)); } } diff --git a/tests/unit/src/com/android/tv/recommendation/RecentChannelEvaluatorTest.java b/tests/unit/src/com/android/tv/recommendation/RecentChannelEvaluatorTest.java index 8f092238..f8d6b220 100644 --- a/tests/unit/src/com/android/tv/recommendation/RecentChannelEvaluatorTest.java +++ b/tests/unit/src/com/android/tv/recommendation/RecentChannelEvaluatorTest.java @@ -16,21 +16,20 @@ package com.android.tv.recommendation; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import android.support.test.filters.SmallTest; - -import org.junit.Test; - +import android.support.test.runner.AndroidJUnit4; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; +import org.junit.Test; +import org.junit.runner.RunWith; -/** - * Unit tests for {@link RecentChannelEvaluator}. - */ +/** Unit tests for {@link RecentChannelEvaluator}. */ @SmallTest +@RunWith(AndroidJUnit4.class) public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelEvaluator> { private static final int DEFAULT_NUMBER_OF_CHANNELS = 4; private static final long DEFAULT_WATCH_START_TIME_MS = @@ -49,14 +48,16 @@ public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelE long channelId = addChannel().getId(); notifyChannelAndWatchLogLoaded(); - assertEqualScores(Recommender.Evaluator.NOT_RECOMMENDED, - mEvaluator.evaluateChannel(channelId)); + assertEqualScores( + Recommender.Evaluator.NOT_RECOMMENDED, mEvaluator.evaluateChannel(channelId)); } @Test public void testOneChannelWithRandomWatchLogs() { addChannel(); - addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, + addRandomWatchLogs( + DEFAULT_WATCH_START_TIME_MS, + DEFAULT_WATCH_END_TIME_MS, DEFAULT_MAX_WATCH_DURATION_MS); notifyChannelAndWatchLogLoaded(); @@ -70,15 +71,17 @@ public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelE List<Long> channelIdList = getChannelIdListSorted(); for (long channelId : channelIdList) { - assertEqualScores(Recommender.Evaluator.NOT_RECOMMENDED, - mEvaluator.evaluateChannel(channelId)); + 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, + addRandomWatchLogs( + DEFAULT_WATCH_START_TIME_MS, + DEFAULT_WATCH_END_TIME_MS, DEFAULT_MAX_WATCH_DURATION_MS); notifyChannelAndWatchLogLoaded(); @@ -103,7 +106,7 @@ public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelE double previousScore = Recommender.Evaluator.NOT_RECOMMENDED; for (long channelId : channelIdList) { double score = mEvaluator.evaluateChannel(channelId); - assertTrue(previousScore <= score); + assertThat(previousScore).isAtMost(score); previousScore = score; } } @@ -111,7 +114,9 @@ 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, + addRandomWatchLogs( + DEFAULT_WATCH_START_TIME_MS, + DEFAULT_WATCH_END_TIME_MS, DEFAULT_MAX_WATCH_DURATION_MS); notifyChannelAndWatchLogLoaded(); @@ -124,15 +129,17 @@ public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelE addWatchLog(channelId, latestWatchEndTimeMs, durationMs); latestWatchEndTimeMs += durationMs; - // Score must be increased because recentness of the log increases. - assertTrue(previousScore <= mEvaluator.evaluateChannel(channelId)); + // Score must be increased because recentness of the log increases. + assertThat(previousScore).isAtMost(mEvaluator.evaluateChannel(channelId)); } } @Test public void testScoreDecreasesWithIncrementOfWatchedLogUpdatedTime() { addChannels(DEFAULT_NUMBER_OF_CHANNELS); - addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, DEFAULT_WATCH_END_TIME_MS, + addRandomWatchLogs( + DEFAULT_WATCH_START_TIME_MS, + DEFAULT_WATCH_END_TIME_MS, DEFAULT_MAX_WATCH_DURATION_MS); notifyChannelAndWatchLogLoaded(); @@ -148,8 +155,8 @@ public class RecentChannelEvaluatorTest extends EvaluatorTestCase<RecentChannelE addWatchLog(newChannelId, latestWatchedEndTimeMs, TimeUnit.MINUTES.toMillis(10)); for (long channelId : channelIdList) { - // Score must be decreased because LastWatchLogUpdateTime increases by new log. - assertTrue(mEvaluator.evaluateChannel(channelId) <= scores.get(channelId)); + // Score must be decreased because LastWatchLogUpdateTime increases by new log. + assertThat(mEvaluator.evaluateChannel(channelId)).isAtMost(scores.get(channelId)); } } } diff --git a/tests/unit/src/com/android/tv/recommendation/RecommendationUtils.java b/tests/unit/src/com/android/tv/recommendation/RecommendationUtils.java index b00ed16b..b929a0ae 100644 --- a/tests/unit/src/com/android/tv/recommendation/RecommendationUtils.java +++ b/tests/unit/src/com/android/tv/recommendation/RecommendationUtils.java @@ -17,50 +17,57 @@ package com.android.tv.recommendation; import android.content.Context; - -import com.android.tv.data.Channel; -import com.android.tv.testing.Utils; - -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - +import com.android.tv.data.ChannelImpl; +import com.android.tv.data.api.Channel; +import com.android.tv.testing.utils.Utils; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.TreeMap; import java.util.concurrent.TimeUnit; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; public class RecommendationUtils { private static final long INVALID_CHANNEL_ID = -1; - /** - * Create a mock RecommendationDataManager backed by a {@link ChannelRecordSortedMapHelper}. - */ + /** Create a mock RecommendationDataManager backed by a {@link ChannelRecordSortedMapHelper}. */ public static RecommendationDataManager createMockRecommendationDataManager( final ChannelRecordSortedMapHelper channelRecordSortedMap) { RecommendationDataManager dataManager = Mockito.mock(RecommendationDataManager.class); - Mockito.doAnswer(new Answer<Integer>() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - return channelRecordSortedMap.size(); - } - }).when(dataManager).getChannelRecordCount(); - Mockito.doAnswer(new Answer<Collection<ChannelRecord>>() { - @Override - public Collection<ChannelRecord> answer(InvocationOnMock invocation) throws Throwable { - return channelRecordSortedMap.values(); - } - }).when(dataManager).getChannelRecords(); - Mockito.doAnswer(new Answer<ChannelRecord>() { - @Override - public ChannelRecord answer(InvocationOnMock invocation) throws Throwable { - long channelId = (long) invocation.getArguments()[0]; - return channelRecordSortedMap.get(channelId); - } - }).when(dataManager).getChannelRecord(Matchers.anyLong()); + Mockito.doAnswer( + new Answer<Integer>() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return channelRecordSortedMap.size(); + } + }) + .when(dataManager) + .getChannelRecordCount(); + Mockito.doAnswer( + new Answer<Collection<ChannelRecord>>() { + @Override + public Collection<ChannelRecord> answer(InvocationOnMock invocation) + throws Throwable { + return channelRecordSortedMap.values(); + } + }) + .when(dataManager) + .getChannelRecords(); + Mockito.doAnswer( + new Answer<ChannelRecord>() { + @Override + public ChannelRecord answer(InvocationOnMock invocation) + throws Throwable { + long channelId = (long) invocation.getArguments()[0]; + return channelRecordSortedMap.get(channelId); + } + }) + .when(dataManager) + .getChannelRecord(Matchers.anyLong()); return dataManager; } @@ -82,9 +89,9 @@ public class RecommendationUtils { } /** - * Add new {@code numberOfChannels} channels by adding channel record to - * {@code channelRecordMap} with no history. - * This action corresponds to loading channels in the RecommendationDataManger. + * Add new {@code numberOfChannels} channels by adding channel record to {@code + * channelRecordMap} with no history. This action corresponds to loading channels in the + * RecommendationDataManger. */ public void addChannels(int numberOfChannels) { for (int i = 0; i < numberOfChannels; ++i) { @@ -100,21 +107,21 @@ public class RecommendationUtils { */ public Channel addChannel() { long channelId = size(); - Channel channel = new Channel.Builder().setId(channelId).build(); + ChannelImpl channel = new ChannelImpl.Builder().setId(channelId).build(); ChannelRecord channelRecord = new ChannelRecord(mContext, channel, false); put(channelId, channelRecord); return channel; } /** - * Add the watch logs which its durationTime is under {@code maxWatchDurationMs}. - * Add until latest watch end time becomes bigger than {@code watchEndTimeMs}, - * starting from {@code watchStartTimeMs}. + * Add the watch logs which its durationTime is under {@code maxWatchDurationMs}. Add until + * latest watch end time becomes bigger than {@code watchEndTimeMs}, starting from {@code + * watchStartTimeMs}. * * @return true if adding watch log success, otherwise false. */ - public boolean addRandomWatchLogs(long watchStartTimeMs, long watchEndTimeMs, - long maxWatchDurationMs) { + public boolean addRandomWatchLogs( + long watchStartTimeMs, long watchEndTimeMs, long maxWatchDurationMs) { long latestWatchEndTimeMs = watchStartTimeMs; long previousChannelId = INVALID_CHANNEL_ID; List<Long> channelIdList = new ArrayList<>(keySet()); @@ -143,13 +150,13 @@ public class RecommendationUtils { */ public boolean addWatchLog(long channelId, long watchStartTimeMs, long durationTimeMs) { ChannelRecord channelRecord = get(channelId); - if (channelRecord == null || - watchStartTimeMs + durationTimeMs > System.currentTimeMillis()) { + if (channelRecord == null + || watchStartTimeMs + durationTimeMs > System.currentTimeMillis()) { return false; } - channelRecord.logWatchHistory(new WatchedProgram(null, watchStartTimeMs, - watchStartTimeMs + durationTimeMs)); + channelRecord.logWatchHistory( + new WatchedProgram(null, watchStartTimeMs, watchStartTimeMs + durationTimeMs)); if (mRecommender != null) { mRecommender.onNewWatchLog(channelRecord); } diff --git a/tests/unit/src/com/android/tv/recommendation/RecommenderTest.java b/tests/unit/src/com/android/tv/recommendation/RecommenderTest.java index 85524a82..812a3eb1 100644 --- a/tests/unit/src/com/android/tv/recommendation/RecommenderTest.java +++ b/tests/unit/src/com/android/tv/recommendation/RecommenderTest.java @@ -17,20 +17,14 @@ 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 static com.google.common.truth.Truth.assertThat; import android.support.test.filters.SmallTest; +import android.support.test.runner.AndroidJUnit4; import android.test.MoreAsserts; - -import com.android.tv.data.Channel; +import com.android.tv.data.api.Channel; import com.android.tv.recommendation.RecommendationUtils.ChannelRecordSortedMapHelper; -import com.android.tv.testing.Utils; - -import org.junit.Before; -import org.junit.Test; - +import com.android.tv.testing.utils.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -39,8 +33,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; @SmallTest +@RunWith(AndroidJUnit4.class) public class RecommenderTest { private static final int DEFAULT_NUMBER_OF_CHANNELS = 5; private static final long DEFAULT_WATCH_START_TIME_MS = @@ -49,24 +47,27 @@ public class RecommenderTest { System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1); private static final long DEFAULT_MAX_WATCH_DURATION_MS = TimeUnit.HOURS.toMillis(1); - private final Comparator<Channel> CHANNEL_SORT_KEY_COMPARATOR = new Comparator<Channel>() { - @Override - public int compare(Channel lhs, Channel rhs) { - return mRecommender.getChannelSortKey(lhs.getId()) - .compareTo(mRecommender.getChannelSortKey(rhs.getId())); - } - }; - private final Runnable START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS = new Runnable() { - @Override - public void run() { - // Add 4 channels in ChannelRecordMap for testing. Store the added channels to - // mChannels_1 ~ mChannels_4. They are sorted by channel id in increasing order. - mChannel_1 = mChannelRecordSortedMap.addChannel(); - mChannel_2 = mChannelRecordSortedMap.addChannel(); - mChannel_3 = mChannelRecordSortedMap.addChannel(); - mChannel_4 = mChannelRecordSortedMap.addChannel(); - } - }; + private final Comparator<Channel> mChannelSortKeyComparator = + new Comparator<Channel>() { + @Override + public int compare(Channel lhs, Channel rhs) { + return mRecommender + .getChannelSortKey(lhs.getId()) + .compareTo(mRecommender.getChannelSortKey(rhs.getId())); + } + }; + private final Runnable mStartDatamanagerRunnableAddFourChannels = + new Runnable() { + @Override + public void run() { + // Add 4 channels in ChannelRecordMap for testing. Store the added channels to + // mChannels_1 ~ mChannels_4. They are sorted by channel id in increasing order. + mChannel_1 = mChannelRecordSortedMap.addChannel(); + mChannel_2 = mChannelRecordSortedMap.addChannel(); + mChannel_3 = mChannelRecordSortedMap.addChannel(); + mChannel_4 = mChannelRecordSortedMap.addChannel(); + } + }; private RecommendationDataManager mDataManager; private Recommender mRecommender; @@ -82,133 +83,133 @@ public class RecommenderTest { @Before public void setUp() { mChannelRecordSortedMap = new ChannelRecordSortedMapHelper(getContext()); - mDataManager = RecommendationUtils - .createMockRecommendationDataManager(mChannelRecordSortedMap); + mDataManager = + RecommendationUtils.createMockRecommendationDataManager(mChannelRecordSortedMap); mChannelRecordSortedMap.resetRandom(Utils.createTestRandom()); } @Test public void testRecommendChannels_includeRecommendedOnly_allChannelsHaveNoScore() { - createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); - - // Recommender doesn't recommend any channels because all channels are not recommended. - assertEquals(0, mRecommender.recommendChannels().size()); - assertEquals(0, mRecommender.recommendChannels(-5).size()); - assertEquals(0, mRecommender.recommendChannels(0).size()); - assertEquals(0, mRecommender.recommendChannels(3).size()); - assertEquals(0, mRecommender.recommendChannels(4).size()); - assertEquals(0, mRecommender.recommendChannels(5).size()); + createRecommender(true, mStartDatamanagerRunnableAddFourChannels); + + // Recommender doesn't recommend any channels because all channels are not recommended. + assertThat(mRecommender.recommendChannels()).isEmpty(); + assertThat(mRecommender.recommendChannels(-5)).isEmpty(); + assertThat(mRecommender.recommendChannels(0)).isEmpty(); + assertThat(mRecommender.recommendChannels(3)).isEmpty(); + assertThat(mRecommender.recommendChannels(4)).isEmpty(); + assertThat(mRecommender.recommendChannels(5)).isEmpty(); } @Test public void testRecommendChannels_notIncludeRecommendedOnly_allChannelsHaveNoScore() { - createRecommender(false, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); - - // Recommender recommends every channel because it recommends not-recommended channels too. - assertEquals(4, mRecommender.recommendChannels().size()); - assertEquals(0, mRecommender.recommendChannels(-5).size()); - assertEquals(0, mRecommender.recommendChannels(0).size()); - assertEquals(3, mRecommender.recommendChannels(3).size()); - assertEquals(4, mRecommender.recommendChannels(4).size()); - assertEquals(4, mRecommender.recommendChannels(5).size()); + createRecommender(false, mStartDatamanagerRunnableAddFourChannels); + + // Recommender recommends every channel because it recommends not-recommended channels too. + assertThat(mRecommender.recommendChannels()).hasSize(4); + assertThat(mRecommender.recommendChannels(-5)).isEmpty(); + assertThat(mRecommender.recommendChannels(0)).isEmpty(); + assertThat(mRecommender.recommendChannels(3)).hasSize(3); + assertThat(mRecommender.recommendChannels(4)).hasSize(4); + assertThat(mRecommender.recommendChannels(5)).hasSize(4); } @Test public void testRecommendChannels_includeRecommendedOnly_allChannelsHaveScore() { - createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); + createRecommender(true, mStartDatamanagerRunnableAddFourChannels); setChannelScores_scoreIncreasesAsChannelIdIncreases(); // recommendChannels must be sorted by score in decreasing order. // (i.e. sorted by channel ID in decreasing order in this case) - MoreAsserts.assertContentsInOrder(mRecommender.recommendChannels(), - mChannel_4, mChannel_3, mChannel_2, mChannel_1); - assertEquals(0, mRecommender.recommendChannels(-5).size()); - assertEquals(0, mRecommender.recommendChannels(0).size()); - MoreAsserts.assertContentsInOrder(mRecommender.recommendChannels(3), - mChannel_4, mChannel_3, mChannel_2); - MoreAsserts.assertContentsInOrder(mRecommender.recommendChannels(4), - mChannel_4, mChannel_3, mChannel_2, mChannel_1); - MoreAsserts.assertContentsInOrder(mRecommender.recommendChannels(5), - mChannel_4, mChannel_3, mChannel_2, mChannel_1); + MoreAsserts.assertContentsInOrder( + mRecommender.recommendChannels(), mChannel_4, mChannel_3, mChannel_2, mChannel_1); + assertThat(mRecommender.recommendChannels(-5)).isEmpty(); + assertThat(mRecommender.recommendChannels(0)).isEmpty(); + MoreAsserts.assertContentsInOrder( + mRecommender.recommendChannels(3), mChannel_4, mChannel_3, mChannel_2); + MoreAsserts.assertContentsInOrder( + mRecommender.recommendChannels(4), mChannel_4, mChannel_3, mChannel_2, mChannel_1); + MoreAsserts.assertContentsInOrder( + mRecommender.recommendChannels(5), mChannel_4, mChannel_3, mChannel_2, mChannel_1); } @Test public void testRecommendChannels_notIncludeRecommendedOnly_allChannelsHaveScore() { - createRecommender(false, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); + createRecommender(false, mStartDatamanagerRunnableAddFourChannels); setChannelScores_scoreIncreasesAsChannelIdIncreases(); // recommendChannels must be sorted by score in decreasing order. // (i.e. sorted by channel ID in decreasing order in this case) - MoreAsserts.assertContentsInOrder(mRecommender.recommendChannels(), - mChannel_4, mChannel_3, mChannel_2, mChannel_1); - assertEquals(0, mRecommender.recommendChannels(-5).size()); - assertEquals(0, mRecommender.recommendChannels(0).size()); - MoreAsserts.assertContentsInOrder(mRecommender.recommendChannels(3), - mChannel_4, mChannel_3, mChannel_2); - MoreAsserts.assertContentsInOrder(mRecommender.recommendChannels(4), - mChannel_4, mChannel_3, mChannel_2, mChannel_1); - MoreAsserts.assertContentsInOrder(mRecommender.recommendChannels(5), - mChannel_4, mChannel_3, mChannel_2, mChannel_1); + MoreAsserts.assertContentsInOrder( + mRecommender.recommendChannels(), mChannel_4, mChannel_3, mChannel_2, mChannel_1); + assertThat(mRecommender.recommendChannels(-5)).isEmpty(); + assertThat(mRecommender.recommendChannels(0)).isEmpty(); + MoreAsserts.assertContentsInOrder( + mRecommender.recommendChannels(3), mChannel_4, mChannel_3, mChannel_2); + MoreAsserts.assertContentsInOrder( + mRecommender.recommendChannels(4), mChannel_4, mChannel_3, mChannel_2, mChannel_1); + MoreAsserts.assertContentsInOrder( + mRecommender.recommendChannels(5), mChannel_4, mChannel_3, mChannel_2, mChannel_1); } @Test public void testRecommendChannels_includeRecommendedOnly_fewChannelsHaveScore() { - createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); + createRecommender(true, mStartDatamanagerRunnableAddFourChannels); mEvaluator.setChannelScore(mChannel_1.getId(), 1.0); mEvaluator.setChannelScore(mChannel_2.getId(), 1.0); // Only two channels are recommended because recommender doesn't recommend other channels. - MoreAsserts.assertContentsInAnyOrder(mRecommender.recommendChannels(), - mChannel_1, mChannel_2); - assertEquals(0, mRecommender.recommendChannels(-5).size()); - assertEquals(0, mRecommender.recommendChannels(0).size()); - MoreAsserts.assertContentsInAnyOrder(mRecommender.recommendChannels(3), - mChannel_1, mChannel_2); - MoreAsserts.assertContentsInAnyOrder(mRecommender.recommendChannels(4), - mChannel_1, mChannel_2); - MoreAsserts.assertContentsInAnyOrder(mRecommender.recommendChannels(5), - mChannel_1, mChannel_2); + MoreAsserts.assertContentsInAnyOrder( + mRecommender.recommendChannels(), mChannel_1, mChannel_2); + assertThat(mRecommender.recommendChannels(-5)).isEmpty(); + assertThat(mRecommender.recommendChannels(0)).isEmpty(); + MoreAsserts.assertContentsInAnyOrder( + mRecommender.recommendChannels(3), mChannel_1, mChannel_2); + MoreAsserts.assertContentsInAnyOrder( + mRecommender.recommendChannels(4), mChannel_1, mChannel_2); + MoreAsserts.assertContentsInAnyOrder( + mRecommender.recommendChannels(5), mChannel_1, mChannel_2); } @Test public void testRecommendChannels_notIncludeRecommendedOnly_fewChannelsHaveScore() { - createRecommender(false, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); + createRecommender(false, mStartDatamanagerRunnableAddFourChannels); mEvaluator.setChannelScore(mChannel_1.getId(), 1.0); mEvaluator.setChannelScore(mChannel_2.getId(), 1.0); - assertEquals(4, mRecommender.recommendChannels().size()); - MoreAsserts.assertContentsInAnyOrder(mRecommender.recommendChannels().subList(0, 2), - mChannel_1, mChannel_2); + assertThat(mRecommender.recommendChannels()).hasSize(4); + MoreAsserts.assertContentsInAnyOrder( + mRecommender.recommendChannels().subList(0, 2), mChannel_1, mChannel_2); - assertEquals(0, mRecommender.recommendChannels(-5).size()); - assertEquals(0, mRecommender.recommendChannels(0).size()); + assertThat(mRecommender.recommendChannels(-5)).isEmpty(); + assertThat(mRecommender.recommendChannels(0)).isEmpty(); - assertEquals(3, mRecommender.recommendChannels(3).size()); - MoreAsserts.assertContentsInAnyOrder(mRecommender.recommendChannels(3).subList(0, 2), - mChannel_1, mChannel_2); + assertThat(mRecommender.recommendChannels(3)).hasSize(3); + MoreAsserts.assertContentsInAnyOrder( + mRecommender.recommendChannels(3).subList(0, 2), mChannel_1, mChannel_2); - assertEquals(4, mRecommender.recommendChannels(4).size()); - MoreAsserts.assertContentsInAnyOrder(mRecommender.recommendChannels(4).subList(0, 2), - mChannel_1, mChannel_2); + assertThat(mRecommender.recommendChannels(4)).hasSize(4); + MoreAsserts.assertContentsInAnyOrder( + mRecommender.recommendChannels(4).subList(0, 2), mChannel_1, mChannel_2); - assertEquals(4, mRecommender.recommendChannels(5).size()); - MoreAsserts.assertContentsInAnyOrder(mRecommender.recommendChannels(5).subList(0, 2), - mChannel_1, mChannel_2); + assertThat(mRecommender.recommendChannels(5)).hasSize(4); + MoreAsserts.assertContentsInAnyOrder( + mRecommender.recommendChannels(5).subList(0, 2), mChannel_1, mChannel_2); } @Test public void testGetChannelSortKey_recommendAllChannels() { - createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); + createRecommender(true, mStartDatamanagerRunnableAddFourChannels); setChannelScores_scoreIncreasesAsChannelIdIncreases(); List<Channel> expectedChannelList = mRecommender.recommendChannels(); List<Channel> channelList = Arrays.asList(mChannel_1, mChannel_2, mChannel_3, mChannel_4); - Collections.sort(channelList, CHANNEL_SORT_KEY_COMPARATOR); + Collections.sort(channelList, mChannelSortKeyComparator); // Recommended channel list and channel list sorted by sort key must be the same. MoreAsserts.assertContentsInOrder(channelList, expectedChannelList.toArray()); @@ -218,17 +219,17 @@ public class RecommenderTest { @Test public void testGetChannelSortKey_recommendFewChannels() { // Test with recommending 3 channels. - createRecommender(true, START_DATAMANAGER_RUNNABLE_ADD_FOUR_CHANNELS); + createRecommender(true, mStartDatamanagerRunnableAddFourChannels); setChannelScores_scoreIncreasesAsChannelIdIncreases(); List<Channel> expectedChannelList = mRecommender.recommendChannels(3); - // A channel which is not recommended by the recommender has to get an invalid sort key. - assertEquals(Recommender.INVALID_CHANNEL_SORT_KEY, - mRecommender.getChannelSortKey(mChannel_1.getId())); + // A channel which is not recommended by the recommender has to get an invalid sort key. + assertThat(mRecommender.getChannelSortKey(mChannel_1.getId())) + .isEqualTo(Recommender.INVALID_CHANNEL_SORT_KEY); List<Channel> channelList = Arrays.asList(mChannel_2, mChannel_3, mChannel_4); - Collections.sort(channelList, CHANNEL_SORT_KEY_COMPARATOR); + Collections.sort(channelList, mChannelSortKeyComparator); MoreAsserts.assertContentsInOrder(channelList, expectedChannelList.toArray()); assertSortKeyNotInvalid(channelList); @@ -236,10 +237,10 @@ public class RecommenderTest { @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 - // doesn't have a watch log, nothing is recommended and recommendation isn't changed. - assertFalse(mOnRecommendationChanged); + createRecommender(true, mStartDatamanagerRunnableAddFourChannels); + // FakeEvaluator doesn't recommend a channel with empty watch log. As every channel + // doesn't have a watch log, nothing is recommended and recommendation isn't changed. + assertThat(mOnRecommendationChanged).isFalse(); // Set lastRecommendationUpdatedTimeUtcMs to check recommendation changed because, // recommender has a minimum recommendation update period. @@ -248,51 +249,63 @@ public class RecommenderTest { long latestWatchEndTimeMs = DEFAULT_WATCH_START_TIME_MS; for (long channelId : mChannelRecordSortedMap.keySet()) { mEvaluator.setChannelScore(channelId, 1.0); - // Add a log to recalculate the recommendation score. - assertTrue(mChannelRecordSortedMap.addWatchLog(channelId, latestWatchEndTimeMs, - TimeUnit.MINUTES.toMillis(10))); + // Add a log to recalculate the recommendation score. + assertThat( + mChannelRecordSortedMap.addWatchLog( + channelId, latestWatchEndTimeMs, TimeUnit.MINUTES.toMillis(10))) + .isTrue(); latestWatchEndTimeMs += TimeUnit.MINUTES.toMillis(10); } - // onRecommendationChanged must be called, because recommend channels are not empty, - // by setting score to each channel. - assertTrue(mOnRecommendationChanged); + // onRecommendationChanged must be called, because recommend channels are not empty, + // by setting score to each channel. + assertThat(mOnRecommendationChanged).isTrue(); } @Test public void testListener_onRecommenderReady() { - createRecommender(true, new Runnable() { - @Override - public void run() { - mChannelRecordSortedMap.addChannels(DEFAULT_NUMBER_OF_CHANNELS); - mChannelRecordSortedMap.addRandomWatchLogs(DEFAULT_WATCH_START_TIME_MS, - DEFAULT_WATCH_END_TIME_MS, DEFAULT_MAX_WATCH_DURATION_MS); - } - }); - - // After loading channels and watch logs are finished, recommender must be available to use. - assertTrue(mOnRecommenderReady); + createRecommender( + true, + new Runnable() { + @Override + public void run() { + mChannelRecordSortedMap.addChannels(DEFAULT_NUMBER_OF_CHANNELS); + mChannelRecordSortedMap.addRandomWatchLogs( + DEFAULT_WATCH_START_TIME_MS, + DEFAULT_WATCH_END_TIME_MS, + DEFAULT_MAX_WATCH_DURATION_MS); + } + }); + + // After loading channels and watch logs are finished, recommender must be available to use. + assertThat(mOnRecommenderReady).isTrue(); } private void assertSortKeyNotInvalid(List<Channel> channelList) { for (Channel channel : channelList) { - MoreAsserts.assertNotEqual(Recommender.INVALID_CHANNEL_SORT_KEY, + MoreAsserts.assertNotEqual( + Recommender.INVALID_CHANNEL_SORT_KEY, mRecommender.getChannelSortKey(channel.getId())); } } - private void createRecommender(boolean includeRecommendedOnly, - Runnable startDataManagerRunnable) { - mRecommender = new Recommender(new Recommender.Listener() { - @Override - public void onRecommenderReady() { - mOnRecommenderReady = true; - } - @Override - public void onRecommendationChanged() { - mOnRecommendationChanged = true; - } - }, includeRecommendedOnly, mDataManager); + private void createRecommender( + boolean includeRecommendedOnly, Runnable startDataManagerRunnable) { + mRecommender = + new Recommender( + new Recommender.Listener() { + @Override + public void onRecommenderReady() { + mOnRecommenderReady = true; + } + + @Override + public void onRecommendationChanged() { + mOnRecommendationChanged = true; + } + }, + includeRecommendedOnly, + mDataManager); mEvaluator = new FakeEvaluator(); mRecommender.registerEvaluator(mEvaluator); diff --git a/tests/unit/src/com/android/tv/recommendation/RoutineWatchEvaluatorTest.java b/tests/unit/src/com/android/tv/recommendation/RoutineWatchEvaluatorTest.java index 7b8e256d..39e6e9c5 100644 --- a/tests/unit/src/com/android/tv/recommendation/RoutineWatchEvaluatorTest.java +++ b/tests/unit/src/com/android/tv/recommendation/RoutineWatchEvaluatorTest.java @@ -16,23 +16,22 @@ package com.android.tv.recommendation; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; import android.support.test.filters.SmallTest; -import android.test.MoreAsserts; - +import android.support.test.runner.AndroidJUnit4; 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; -import java.util.TreeSet; import java.util.concurrent.TimeUnit; +import org.junit.Test; +import org.junit.runner.RunWith; +/** Tests for {@link RoutineWatchEvaluator}. */ @SmallTest +@RunWith(AndroidJUnit4.class) public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEvaluator> { private static class ScoredItem implements Comparable<ScoredItem> { private final String mBase; @@ -67,13 +66,23 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva @Test public void testSplitTextToWords() { - assertSplitTextToWords(""); - assertSplitTextToWords("Google", "Google"); - assertSplitTextToWords("The Big Bang Theory", "The", "Big", "Bang", "Theory"); - assertSplitTextToWords("Hello, world!", "Hello", "world"); - assertSplitTextToWords("Adam's Rib", "Adam's", "Rib"); - assertSplitTextToWords("G.I. Joe", "G.I", "Joe"); - assertSplitTextToWords("A.I.", "A.I"); + assertThat(RoutineWatchEvaluator.splitTextToWords("")).containsExactly().inOrder(); + assertThat(RoutineWatchEvaluator.splitTextToWords("Google")) + .containsExactly("Google") + .inOrder(); + assertThat(RoutineWatchEvaluator.splitTextToWords("The Big Bang Theory")) + .containsExactly("The", "Big", "Bang", "Theory") + .inOrder(); + assertThat(RoutineWatchEvaluator.splitTextToWords("Hello, world!")) + .containsExactly("Hello", "world") + .inOrder(); + assertThat(RoutineWatchEvaluator.splitTextToWords("Adam's Rib")) + .containsExactly("Adam's", "Rib") + .inOrder(); + assertThat(RoutineWatchEvaluator.splitTextToWords("G.I. Joe")) + .containsExactly("G.I", "Joe") + .inOrder(); + assertThat(RoutineWatchEvaluator.splitTextToWords("A.I.")).containsExactly("A.I").inOrder(); } @Test @@ -102,7 +111,6 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore(" ", "foo")); } - @Test public void testCalculateTitleMatchScore_null() { assertEqualScores(0.0, RoutineWatchEvaluator.calculateTitleMatchScore(null, null)); @@ -113,11 +121,15 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva @Test public void testCalculateTitleMatchScore_longerMatchIsBetter() { String base = "foo bar baz"; - assertInOrder( - score(base, ""), - score(base, "bar"), - score(base, "foo bar"), - score(base, "foo bar baz")); + assertThat( + new ScoredItem[] { + score(base, ""), + score(base, "bar"), + score(base, "foo bar"), + score(base, "foo bar baz") + }) + .asList() + .isOrdered(); } @Test @@ -128,116 +140,154 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva int tomorrowDayOfWeek = (todayDayOfWeek % 7) + 1; // Today 00:00 - 01:00. - ProgramTime programTimeToday0000_0100 = ProgramTime.createFromProgram( - createDummyProgram(todayAtHourMin(0, 0), TimeUnit.HOURS.toMillis(1))); - assertProgramTime(todayDayOfWeek, hourMinuteToSec(0, 0), hourMinuteToSec(1, 0), - programTimeToday0000_0100); + ProgramTime programTimeToday0000to0100 = + ProgramTime.createFromProgram( + createDummyProgram(todayAtHourMin(0, 0), TimeUnit.HOURS.toMillis(1))); + assertProgramTime( + todayDayOfWeek, + hourMinuteToSec(0, 0), + hourMinuteToSec(1, 0), + programTimeToday0000to0100); // Today 23:30 - 24:30. - ProgramTime programTimeToday2330_2430 = ProgramTime.createFromProgram( - createDummyProgram(todayAtHourMin(23, 30), TimeUnit.HOURS.toMillis(1))); - assertProgramTime(todayDayOfWeek, hourMinuteToSec(23, 30), hourMinuteToSec(24, 30), - programTimeToday2330_2430); + ProgramTime programTimeToday2330to2430 = + ProgramTime.createFromProgram( + createDummyProgram(todayAtHourMin(23, 30), TimeUnit.HOURS.toMillis(1))); + assertProgramTime( + todayDayOfWeek, + hourMinuteToSec(23, 30), + hourMinuteToSec(24, 30), + programTimeToday2330to2430); // Tomorrow 00:00 - 01:00. - ProgramTime programTimeTomorrow0000_0100 = ProgramTime.createFromProgram( - createDummyProgram(tomorrowAtHourMin(0, 0), TimeUnit.HOURS.toMillis(1))); - assertProgramTime(tomorrowDayOfWeek, hourMinuteToSec(0, 0), hourMinuteToSec(1, 0), - programTimeTomorrow0000_0100); + ProgramTime programTimeTomorrow0000to0100 = + ProgramTime.createFromProgram( + createDummyProgram(tomorrowAtHourMin(0, 0), TimeUnit.HOURS.toMillis(1))); + assertProgramTime( + tomorrowDayOfWeek, + hourMinuteToSec(0, 0), + hourMinuteToSec(1, 0), + programTimeTomorrow0000to0100); // Tomorrow 23:30 - 24:30. - ProgramTime programTimeTomorrow2330_2430 = ProgramTime.createFromProgram( - createDummyProgram(tomorrowAtHourMin(23, 30), TimeUnit.HOURS.toMillis(1))); - assertProgramTime(tomorrowDayOfWeek, hourMinuteToSec(23, 30), hourMinuteToSec(24, 30), - programTimeTomorrow2330_2430); + ProgramTime programTimeTomorrow2330to2430 = + ProgramTime.createFromProgram( + createDummyProgram(tomorrowAtHourMin(23, 30), TimeUnit.HOURS.toMillis(1))); + assertProgramTime( + tomorrowDayOfWeek, + hourMinuteToSec(23, 30), + hourMinuteToSec(24, 30), + programTimeTomorrow2330to2430); // Today 18:00 - Tomorrow 12:00. - ProgramTime programTimeToday1800_3600 = ProgramTime.createFromProgram( - createDummyProgram(todayAtHourMin(18, 0), TimeUnit.HOURS.toMillis(18))); + ProgramTime programTimeToday1800to3600 = + ProgramTime.createFromProgram( + createDummyProgram(todayAtHourMin(18, 0), TimeUnit.HOURS.toMillis(18))); // Maximum duration of ProgramTime is 12 hours. // So, this program looks like it ends at Tomorrow 06:00 (30:00). - assertProgramTime(todayDayOfWeek, hourMinuteToSec(18, 0), hourMinuteToSec(30, 0), - programTimeToday1800_3600); + assertProgramTime( + todayDayOfWeek, + hourMinuteToSec(18, 0), + hourMinuteToSec(30, 0), + programTimeToday1800to3600); } @Test public void testCalculateOverlappedIntervalScore() { // Today 21:00 - 24:00. - ProgramTime programTimeToday2100_2400 = ProgramTime.createFromProgram( - createDummyProgram(todayAtHourMin(21, 0), TimeUnit.HOURS.toMillis(3))); + ProgramTime programTimeToday2100to2400 = + ProgramTime.createFromProgram( + createDummyProgram(todayAtHourMin(21, 0), TimeUnit.HOURS.toMillis(3))); // Today 22:00 - 01:00. - ProgramTime programTimeToday2200_0100 = ProgramTime.createFromProgram( - createDummyProgram(todayAtHourMin(22, 0), TimeUnit.HOURS.toMillis(3))); + ProgramTime programTimeToday2200to0100 = + ProgramTime.createFromProgram( + createDummyProgram(todayAtHourMin(22, 0), TimeUnit.HOURS.toMillis(3))); // Tomorrow 00:00 - 03:00. - ProgramTime programTimeTomorrow0000_0300 = ProgramTime.createFromProgram( - createDummyProgram(tomorrowAtHourMin(0, 0), TimeUnit.HOURS.toMillis(3))); + ProgramTime programTimeTomorrow0000to0300 = + ProgramTime.createFromProgram( + createDummyProgram(tomorrowAtHourMin(0, 0), TimeUnit.HOURS.toMillis(3))); // Tomorrow 20:00 - Tomorrow 23:00. - ProgramTime programTimeTomorrow2000_2300 = ProgramTime.createFromProgram( - createDummyProgram(tomorrowAtHourMin(20, 0), TimeUnit.HOURS.toMillis(3))); + ProgramTime programTimeTomorrow2000to2300 = + ProgramTime.createFromProgram( + createDummyProgram(tomorrowAtHourMin(20, 0), TimeUnit.HOURS.toMillis(3))); // Check intersection time and commutative law in all cases. int oneHourInSec = hourMinuteToSec(1, 0); - assertOverlappedIntervalScore(2 * oneHourInSec, true, programTimeToday2100_2400, - programTimeToday2200_0100); - assertOverlappedIntervalScore(0, false, programTimeToday2100_2400, - programTimeTomorrow0000_0300); - assertOverlappedIntervalScore(2 * oneHourInSec, false, programTimeToday2100_2400, - programTimeTomorrow2000_2300); - assertOverlappedIntervalScore(oneHourInSec, true, programTimeToday2200_0100, - programTimeTomorrow0000_0300); - assertOverlappedIntervalScore(oneHourInSec, false, programTimeToday2200_0100, - programTimeTomorrow2000_2300); - assertOverlappedIntervalScore(0, false, programTimeTomorrow0000_0300, - programTimeTomorrow2000_2300); + assertOverlappedIntervalScore( + 2 * oneHourInSec, true, programTimeToday2100to2400, programTimeToday2200to0100); + assertOverlappedIntervalScore( + 0, false, programTimeToday2100to2400, programTimeTomorrow0000to0300); + assertOverlappedIntervalScore( + 2 * oneHourInSec, false, programTimeToday2100to2400, programTimeTomorrow2000to2300); + assertOverlappedIntervalScore( + oneHourInSec, true, programTimeToday2200to0100, programTimeTomorrow0000to0300); + assertOverlappedIntervalScore( + oneHourInSec, false, programTimeToday2200to0100, programTimeTomorrow2000to2300); + assertOverlappedIntervalScore( + 0, false, programTimeTomorrow0000to0300, programTimeTomorrow2000to2300); } @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), + assertEquals( + "TimeOfDayInSec", + hourMinuteToSec(0, 0), RoutineWatchEvaluator.getTimeOfDayInSec(todayAtHourMin(0, 0))); // Time was set as 23:59:59. So, getTimeOfDay must returns 23 * 60 + 60 + 59 * 60 + 59. - assertEquals("TimeOfDayInSec", hourMinuteSecondToSec(23, 59, 59), + assertEquals( + "TimeOfDayInSec", + hourMinuteSecondToSec(23, 59, 59), RoutineWatchEvaluator.getTimeOfDayInSec(todayAtHourMinSec(23, 59, 59))); } - private void assertSplitTextToWords(String text, String... words) { - List<String> wordList = RoutineWatchEvaluator.splitTextToWords(text); - MoreAsserts.assertContentsInOrder(wordList, words); - } - - private void assertMaximumMatchedWordSequenceLength(int expectedLength, String text1, - String text2) { + private void assertMaximumMatchedWordSequenceLength( + int expectedLength, String text1, String text2) { List<String> wordList1 = RoutineWatchEvaluator.splitTextToWords(text1); List<String> wordList2 = RoutineWatchEvaluator.splitTextToWords(text2); - assertEquals("MaximumMatchedWordSequenceLength", expectedLength, + assertEquals( + "MaximumMatchedWordSequenceLength", + expectedLength, RoutineWatchEvaluator.calculateMaximumMatchedWordSequenceLength( wordList1, wordList2)); - assertEquals("MaximumMatchedWordSequenceLength", expectedLength, + assertEquals( + "MaximumMatchedWordSequenceLength", + expectedLength, RoutineWatchEvaluator.calculateMaximumMatchedWordSequenceLength( wordList2, wordList1)); } - private void assertProgramTime(int expectedWeekDay, int expectedStartTimeOfDayInSec, - int expectedEndTimeOfDayInSec, ProgramTime actualProgramTime) { + private void assertProgramTime( + int expectedWeekDay, + int expectedStartTimeOfDayInSec, + int expectedEndTimeOfDayInSec, + ProgramTime actualProgramTime) { assertEquals("Weekday", expectedWeekDay, actualProgramTime.weekDay); - assertEquals("StartTimeOfDayInSec", expectedStartTimeOfDayInSec, + assertEquals( + "StartTimeOfDayInSec", + expectedStartTimeOfDayInSec, actualProgramTime.startTimeOfDayInSec); - assertEquals("EndTimeOfDayInSec", expectedEndTimeOfDayInSec, + assertEquals( + "EndTimeOfDayInSec", + expectedEndTimeOfDayInSec, actualProgramTime.endTimeOfDayInSec); } - private void assertOverlappedIntervalScore(int expectedSeconds, boolean overlappedOnSameDay, - ProgramTime t1, ProgramTime t2) { + private void assertOverlappedIntervalScore( + int expectedSeconds, boolean overlappedOnSameDay, ProgramTime t1, ProgramTime t2) { double score = expectedSeconds; if (!overlappedOnSameDay) { score *= RoutineWatchEvaluator.MULTIPLIER_FOR_UNMATCHED_DAY_OF_WEEK; } // Two tests for testing commutative law. - assertEqualScores("OverlappedIntervalScore", score, + assertEqualScores( + "OverlappedIntervalScore", + score, RoutineWatchEvaluator.calculateOverlappedIntervalScore(t1, t2)); - assertEqualScores("OverlappedIntervalScore", score, + assertEqualScores( + "OverlappedIntervalScore", + score, RoutineWatchEvaluator.calculateOverlappedIntervalScore(t2, t1)); } @@ -270,12 +320,9 @@ public class RoutineWatchEvaluatorTest extends EvaluatorTestCase<RoutineWatchEva private Program createDummyProgram(Calendar startTime, long programDurationMs) { long startTimeMs = startTime.getTimeInMillis(); - return new Program.Builder().setStartTimeUtcMillis(startTimeMs) - .setEndTimeUtcMillis(startTimeMs + programDurationMs).build(); - } - - private static <T> void assertInOrder(T... items) { - TreeSet<T> copy = new TreeSet<>(Arrays.asList(items)); - MoreAsserts.assertContentsInOrder(copy, items); + return new Program.Builder() + .setStartTimeUtcMillis(startTimeMs) + .setEndTimeUtcMillis(startTimeMs + programDurationMs) + .build(); } } diff --git a/tests/unit/src/com/android/tv/search/LocalSearchProviderTest.java b/tests/unit/src/com/android/tv/search/LocalSearchProviderTest.java deleted file mode 100644 index b0d342c6..00000000 --- a/tests/unit/src/com/android/tv/search/LocalSearchProviderTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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 deleted file mode 100644 index aa33f770..00000000 --- a/tests/unit/src/com/android/tv/tests/TvActivityTest.java +++ /dev/null @@ -1,43 +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.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.support.test.rule.ActivityTestRule; - -import com.android.tv.TvActivity; -import com.android.tv.testing.Utils; - -import org.junit.Rule; -import org.junit.Test; - -@MediumTest -public class TvActivityTest { - @Rule - public ActivityTestRule<TvActivity> mActivityTestRule = - new ActivityTestRule<>(TvActivity.class, false, false); - - @Test - public void testLifeCycle() { - assertTrue("TvActivity should be enabled.", Utils.isTvActivityEnabled(getTargetContext())); - assertNotNull(mActivityTestRule.launchActivity(null)); - } -} diff --git a/tests/unit/src/com/android/tv/util/MockApplicationSingletons.java b/tests/unit/src/com/android/tv/util/MockTvSingletons.java index 4cfc7f8a..6de1eb3e 100644 --- a/tests/unit/src/com/android/tv/util/MockApplicationSingletons.java +++ b/tests/unit/src/com/android/tv/util/MockTvSingletons.java @@ -17,34 +17,41 @@ package com.android.tv.util; import android.content.Context; - -import com.android.tv.ApplicationSingletons; +import android.content.Intent; import com.android.tv.InputSessionManager; import com.android.tv.MainActivityWrapper; import com.android.tv.TvApplication; +import com.android.tv.TvSingletons; import com.android.tv.analytics.Analytics; import com.android.tv.analytics.Tracker; -import com.android.tv.config.RemoteConfig; +import com.android.tv.common.config.api.RemoteConfig; +import com.android.tv.common.experiments.ExperimentLoader; +import com.android.tv.common.recording.RecordingStorageStatusManager; +import com.android.tv.common.util.Clock; import com.android.tv.data.ChannelDataManager; import com.android.tv.data.PreviewDataManager; import com.android.tv.data.ProgramDataManager; +import com.android.tv.data.epg.EpgFetcher; +import com.android.tv.data.epg.EpgReader; 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; +import com.android.tv.testing.FakeClock; +import com.android.tv.tuner.TunerInputController; +import java.util.concurrent.Executor; +import javax.inject.Provider; -/** - * Mock {@link ApplicationSingletons} class. - */ -public class MockApplicationSingletons implements ApplicationSingletons { - private final TvApplication mApp; +/** Mock {@link TvSingletons} class. */ +public class MockTvSingletons implements TvSingletons { + public final FakeClock fakeClock = FakeClock.createWithCurrentTime(); + private final TvApplication mApp; private PerformanceMonitor mPerformanceMonitor; - public MockApplicationSingletons(Context context) { + public MockTvSingletons(Context context) { mApp = (TvApplication) context.getApplicationContext(); } @@ -54,6 +61,9 @@ public class MockApplicationSingletons implements ApplicationSingletons { } @Override + public void handleInputCountChanged() {} + + @Override public ChannelDataManager getChannelDataManager() { return mApp.getChannelDataManager(); } @@ -84,8 +94,13 @@ public class MockApplicationSingletons implements ApplicationSingletons { } @Override - public DvrStorageStatusManager getDvrStorageStatusManager() { - return mApp.getDvrStorageStatusManager(); + public Clock getClock() { + return fakeClock; + } + + @Override + public RecordingStorageStatusManager getRecordingStorageStatusManager() { + return mApp.getRecordingStorageStatusManager(); } @Override @@ -124,12 +139,37 @@ public class MockApplicationSingletons implements ApplicationSingletons { } @Override + public Provider<EpgReader> providesEpgReader() { + return mApp.providesEpgReader(); + } + + @Override + public EpgFetcher getEpgFetcher() { + return mApp.getEpgFetcher(); + } + + @Override + public SetupUtils getSetupUtils() { + return mApp.getSetupUtils(); + } + + @Override + public TunerInputController getTunerInputController() { + return mApp.getTunerInputController(); + } + + @Override + public ExperimentLoader getExperimentLoader() { + return mApp.getExperimentLoader(); + } + + @Override public MainActivityWrapper getMainActivityWrapper() { return mApp.getMainActivityWrapper(); } @Override - public AccountHelper getAccountHelper() { + public com.android.tv.util.account.AccountHelper getAccountHelper() { return mApp.getAccountHelper(); } @@ -139,6 +179,11 @@ public class MockApplicationSingletons implements ApplicationSingletons { } @Override + public Intent getTunerSetupIntent(Context context) { + return mApp.getTunerSetupIntent(context); + } + + @Override public boolean isRunningInMainProcess() { return mApp.isRunningInMainProcess(); } @@ -151,4 +196,14 @@ public class MockApplicationSingletons implements ApplicationSingletons { public void setPerformanceMonitor(PerformanceMonitor performanceMonitor) { mPerformanceMonitor = performanceMonitor; } + + @Override + public String getEmbeddedTunerInputId() { + return "com.android.tv/.tuner.tvinput.LiveTvTunerTvInputService"; + } + + @Override + public Executor getDbExecutor() { + return mApp.getDbExecutor(); + } } diff --git a/tests/unit/src/com/android/tv/util/MultiLongSparseArrayTest.java b/tests/unit/src/com/android/tv/util/MultiLongSparseArrayTest.java deleted file mode 100644 index 7335f207..00000000 --- a/tests/unit/src/com/android/tv/util/MultiLongSparseArrayTest.java +++ /dev/null @@ -1,108 +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.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; - -import android.support.test.filters.SmallTest; -import android.test.MoreAsserts; - -import org.junit.Test; - -import java.util.Collections; - -/** - * Tests for {@link MultiLongSparseArray}. - */ -@SmallTest -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"); - sparseArray.put(0, "bar"); - MoreAsserts.assertContentsInAnyOrder(sparseArray.get(0), "foo", "bar"); - } - - - @Test - public void testClearEmptyCache() { - MultiLongSparseArray<String> sparseArray = new MultiLongSparseArray<>(); - sparseArray.clearEmptyCache(); - assertEquals(0, sparseArray.getEmptyCacheSize()); - sparseArray.put(0, "foo"); - sparseArray.remove(0, "foo"); - assertEquals(1, sparseArray.getEmptyCacheSize()); - sparseArray.clearEmptyCache(); - assertEquals(0, sparseArray.getEmptyCacheSize()); - } - - @Test - public void testMaxEmptyCacheSize() { - MultiLongSparseArray<String> sparseArray = new MultiLongSparseArray<>(); - sparseArray.clearEmptyCache(); - assertEquals(0, sparseArray.getEmptyCacheSize()); - for (int i = 0; i <= MultiLongSparseArray.DEFAULT_MAX_EMPTIES_KEPT + 2; i++) { - sparseArray.put(i, "foo"); - } - for (int i = 0; i <= MultiLongSparseArray.DEFAULT_MAX_EMPTIES_KEPT + 2; i++) { - sparseArray.remove(i, "foo"); - } - assertEquals(MultiLongSparseArray.DEFAULT_MAX_EMPTIES_KEPT, - sparseArray.getEmptyCacheSize()); - sparseArray.clearEmptyCache(); - assertEquals(0, sparseArray.getEmptyCacheSize()); - } - - @Test - public void testReuseEmptySets() { - MultiLongSparseArray<String> sparseArray = new MultiLongSparseArray<>(); - sparseArray.clearEmptyCache(); - assertEquals(0, sparseArray.getEmptyCacheSize()); - // create a bunch of sets - for (int i = 0; i <= MultiLongSparseArray.DEFAULT_MAX_EMPTIES_KEPT + 2; i++) { - sparseArray.put(i, "foo"); - } - // remove them so they are all put in the cache. - for (int i = 0; i <= MultiLongSparseArray.DEFAULT_MAX_EMPTIES_KEPT + 2; i++) { - sparseArray.remove(i, "foo"); - } - assertEquals(MultiLongSparseArray.DEFAULT_MAX_EMPTIES_KEPT, - sparseArray.getEmptyCacheSize()); - - // now create elements, that use the cached empty sets. - for (int i = 0; i < MultiLongSparseArray.DEFAULT_MAX_EMPTIES_KEPT; i++) { - sparseArray.put(10 + i, "bar"); - assertEquals(MultiLongSparseArray.DEFAULT_MAX_EMPTIES_KEPT - i - 1, - sparseArray.getEmptyCacheSize()); - } - } -} diff --git a/tests/unit/src/com/android/tv/util/ScaledBitmapInfoTest.java b/tests/unit/src/com/android/tv/util/ScaledBitmapInfoTest.java deleted file mode 100644 index 2714e2e9..00000000 --- a/tests/unit/src/com/android/tv/util/ScaledBitmapInfoTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.android.tv.util; - -import static org.junit.Assert.assertEquals; - -import android.graphics.Bitmap; -import android.support.test.filters.SmallTest; - -import com.android.tv.util.BitmapUtils.ScaledBitmapInfo; - -import org.junit.Test; - -/** - * Tests for {@link ScaledBitmapInfo}. - */ -@SmallTest -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); - assertNeedsToReload(false, actual, 50, 50); - assertNeedsToReload(false, actual, 99, 99); - assertNeedsToReload(true, actual, 100, 100); - assertNeedsToReload(true, actual, 101, 101); - } - - /** - * Reproduces <a href="http://b/20488453">b/20488453</a>. - */ - @Test - public void testBug20488453() { - ScaledBitmapInfo actual = BitmapUtils - .createScaledBitmapInfo("B960x1440", B960x1440, 284, 160); - assertScaledBitmapSize(8, 107, 160, actual); - assertNeedsToReload(false, actual, 284, 160); - } - - private static void assertNeedsToReload(boolean expected, ScaledBitmapInfo scaledBitmap, - int reqWidth, int reqHeight) { - assertEquals(scaledBitmap.id + " needToReload(" + reqWidth + "," + reqHeight + ")", - expected, scaledBitmap.needToReload(reqWidth, reqHeight)); - } - - private static void assertScaledBitmapSize(int expectedInSampleSize, int expectedWidth, - int expectedHeight, ScaledBitmapInfo actual) { - assertEquals(actual.id + " inSampleSize", expectedInSampleSize, actual.inSampleSize); - assertEquals(actual.id + " width", expectedWidth, actual.bitmap.getWidth()); - assertEquals(actual.id + " height", expectedHeight, actual.bitmap.getHeight()); - } -} diff --git a/tests/unit/src/com/android/tv/util/TestUtils.java b/tests/unit/src/com/android/tv/util/TestUtils.java deleted file mode 100644 index d200733d..00000000 --- a/tests/unit/src/com/android/tv/util/TestUtils.java +++ /dev/null @@ -1,115 +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.util; - -import android.content.pm.ResolveInfo; -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 java.lang.reflect.Constructor; - -/** - * A class that includes convenience methods for testing. - */ -public class TestUtils { - /** - * Creates a {@link TvInputInfo}. - */ - public static TvInputInfo createTvInputInfo(ResolveInfo service, String id, String parentId, - int type, boolean isHardwareInput) throws Exception { - return createTvInputInfo(service, id, parentId, type, isHardwareInput, false, 0); - } - - /** - * Creates a {@link TvInputInfo}. - * <p> - * If this is called on MNC, {@code canRecord} and {@code tunerCount} are ignored. - */ - public static TvInputInfo createTvInputInfo(ResolveInfo service, String id, String parentId, - 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 (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); - } - return createTvInputInfoForMnc(service, id, parentId, type, isHardwareInput); - } - - /** - * 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) { - */ - private static TvInputInfo createTvInputInfoForNyc(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, 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, null, canRecord, tunerCount, null, false, parentId, null); - } - - private static TvInputInfo createTvInputInfoForMnc(ResolveInfo service, String id, - String parentId, int type, boolean isHardwareInput) throws Exception { - Constructor<TvInputInfo> constructor = TvInputInfo.class.getDeclaredConstructor( - ResolveInfo.class, String.class, String.class, int.class, boolean.class); - constructor.setAccessible(true); - return constructor.newInstance(service, id, parentId, type, isHardwareInput); - } - - public static ResolveInfo createResolveInfo(String packageName, String name) { - ResolveInfo resolveInfo = new ResolveInfo(); - 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 404ee5d3..6dfed64a 100644 --- a/tests/unit/src/com/android/tv/util/TvInputManagerHelperTest.java +++ b/tests/unit/src/com/android/tv/util/TvInputManagerHelperTest.java @@ -21,22 +21,21 @@ 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.runner.AndroidJUnit4; import com.android.tv.testing.ComparatorTester; - +import com.android.tv.testing.utils.TestUtils; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -/** - * Test for {@link TvInputManagerHelper} - */ +/** Test for {@link TvInputManagerHelper} */ @SmallTest +@RunWith(AndroidJUnit4.class) public class TvInputManagerHelperTest { final HashMap<String, TvInputInfoWrapper> TEST_INPUT_MAP = new HashMap<>(); @@ -45,18 +44,51 @@ public class TvInputManagerHelperTest { 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)); + 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( + ComparatorTester<TvInputInfo> comparatorTester = + ComparatorTester.withoutEqualsTest( new TvInputManagerHelper.InputComparatorInternal(manager)); for (TvInputInfo input : inputs) { comparatorTester.addComparableGroup(input); @@ -68,20 +100,54 @@ public class TvInputManagerHelperTest { 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); + 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( + ComparatorTester<TvInputInfo> comparatorTester = + ComparatorTester.withoutEqualsTest( new TvInputManagerHelper.HardwareInputComparator(getContext(), manager)); - comparatorTester.addComparableGroup(hdmi3) + comparatorTester + .addComparableGroup(hdmi3) .addComparableGroup(hdmi2) .addComparableGroup(hdmi1) .addComparableGroup(hdmi4) @@ -92,61 +158,111 @@ public class TvInputManagerHelperTest { 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 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); + 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( + ComparatorTester<TvInputInfo> comparatorTester = + ComparatorTester.withoutEqualsTest( new TvInputManagerHelper.HardwareInputComparator(getContext(), manager)); - comparatorTester.addComparableGroup(cec1) - .addComparableGroup(cec2) - .test(); + 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 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 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()); + Mockito.doAnswer( + new Answer<Boolean>() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + TvInputInfo info = (TvInputInfo) invocation.getArguments()[0]; + 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 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; } - private TvInputInfo createTvInputInfo(ResolveInfo service, String id, - String parentId, int type, boolean isHardwareInput, String label, String customLabel, + private TvInputInfo createTvInputInfo( + ResolveInfo service, + String id, + String parentId, + int type, + boolean isHardwareInput, + String label, + String customLabel, boolean isPartnerInput) { TvInputInfoWrapper inputWrapper = new TvInputInfoWrapper(); try { diff --git a/tests/unit/src/com/android/tv/util/TvTrackInfoUtilsTest.java b/tests/unit/src/com/android/tv/util/TvTrackInfoUtilsTest.java index 4512bb7d..d84a90d4 100644 --- a/tests/unit/src/com/android/tv/util/TvTrackInfoUtilsTest.java +++ b/tests/unit/src/com/android/tv/util/TvTrackInfoUtilsTest.java @@ -16,24 +16,22 @@ package com.android.tv.util; import static com.android.tv.util.TvTrackInfoUtils.getBestTrackInfo; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertWithMessage; import android.media.tv.TvTrackInfo; import android.support.test.filters.SmallTest; - +import android.support.test.runner.AndroidJUnit4; import com.android.tv.testing.ComparatorTester; - -import org.junit.Test; - import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; -/** - * Tests for {@link com.android.tv.util.TvTrackInfoUtils}. - */ +/** Tests for {@link com.android.tv.util.TvTrackInfoUtils}. */ @SmallTest +@RunWith(AndroidJUnit4.class) public class TvTrackInfoUtilsTest { private static final String UN_MATCHED_ID = "no matching ID"; @@ -54,57 +52,57 @@ public class TvTrackInfoUtilsTest { .build(); } - private static final List<TvTrackInfo> ALL = Arrays.asList(INFO_1_EN_1, INFO_2_EN_5, - INFO_3_FR_8, INFO_4_NULL_2, INFO_5_NULL_6); - private static final List<TvTrackInfo> NULL_LANGUAGE_TRACKS = Arrays.asList(INFO_4_NULL_2, - INFO_5_NULL_6); + private static final List<TvTrackInfo> ALL = + Arrays.asList(INFO_1_EN_1, INFO_2_EN_5, INFO_3_FR_8, INFO_4_NULL_2, INFO_5_NULL_6); + 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); + assertWithMessage("best track ").that(result).isEqualTo(null); } @Test public void testGetBestTrackInfo_exactMatch() { TvTrackInfo result = getBestTrackInfo(ALL, "1", "en", 1); - assertEquals("best track ", INFO_1_EN_1, result); + assertWithMessage("best track ").that(result).isEqualTo(INFO_1_EN_1); } @Test public void testGetBestTrackInfo_langAndChannelCountMatch() { TvTrackInfo result = getBestTrackInfo(ALL, UN_MATCHED_ID, "en", 5); - assertEquals("best track ", INFO_2_EN_5, result); + assertWithMessage("best track ").that(result).isEqualTo(INFO_2_EN_5); } @Test public void testGetBestTrackInfo_languageOnlyMatch() { TvTrackInfo result = getBestTrackInfo(ALL, UN_MATCHED_ID, "fr", 1); - assertEquals("best track ", INFO_3_FR_8, result); + assertWithMessage("best track ").that(result).isEqualTo(INFO_3_FR_8); } @Test public void testGetBestTrackInfo_channelCountOnlyMatchWithNullLanguage() { TvTrackInfo result = getBestTrackInfo(ALL, UN_MATCHED_ID, null, 8); - assertEquals("best track ", INFO_3_FR_8, result); + assertWithMessage("best track ").that(result).isEqualTo(INFO_3_FR_8); } @Test public void testGetBestTrackInfo_noMatches() { TvTrackInfo result = getBestTrackInfo(ALL, UN_MATCHED_ID, "kr", 1); - assertEquals("best track ", INFO_1_EN_1, result); + assertWithMessage("best track ").that(result).isEqualTo(INFO_1_EN_1); } @Test public void testGetBestTrackInfo_noMatchesWithNullLanguage() { TvTrackInfo result = getBestTrackInfo(ALL, UN_MATCHED_ID, null, 0); - assertEquals("best track ", INFO_1_EN_1, result); + assertWithMessage("best track ").that(result).isEqualTo(INFO_1_EN_1); } @Test public void testGetBestTrackInfo_channelCountAndIdMatch() { TvTrackInfo result = getBestTrackInfo(NULL_LANGUAGE_TRACKS, "5", null, 6); - assertEquals("best track ", INFO_5_NULL_6, result); + assertWithMessage("best track ").that(result).isEqualTo(INFO_5_NULL_6); } @Test @@ -112,15 +110,17 @@ public class TvTrackInfoUtilsTest { Comparator<TvTrackInfo> comparator = TvTrackInfoUtils.createComparator("1", "en", 1); ComparatorTester.withoutEqualsTest(comparator) // lang not match - .addComparableGroup(create("1", "kr", 1), create("2", "kr", 2), + .addComparableGroup( + create("1", "kr", 1), + create("2", "kr", 2), create("1", "ja", 1), create("1", "ch", 1)) - // lang match not count match - .addComparableGroup(create("2", "en", 2), create("3", "en", 3), - create("1", "en", 2)) - // lang and count match + // lang match not count match + .addComparableGroup( + create("2", "en", 2), create("3", "en", 3), create("1", "en", 2)) + // lang and count match .addComparableGroup(create("2", "en", 1), create("3", "en", 1)) - // all match + // all match .addComparableGroup(create("1", "en", 1), create("1", "en", 1)) .test(); } diff --git a/tests/unit/src/com/android/tv/util/UtilsTest_GetDurationString.java b/tests/unit/src/com/android/tv/util/UtilsTest_GetDurationString.java deleted file mode 100644 index e61802f5..00000000 --- a/tests/unit/src/com/android/tv/util/UtilsTest_GetDurationString.java +++ /dev/null @@ -1,273 +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.util; - -import static android.support.test.InstrumentationRegistry.getContext; -import static org.junit.Assert.assertEquals; - -import android.support.test.filters.SmallTest; -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; - -/** - * Tests for {@link com.android.tv.util.Utils#getDurationString}. - * <p/> - * This test uses deprecated flags {@link DateUtils#FORMAT_12HOUR} and - * {@link DateUtils#FORMAT_24HOUR} to run this test independent to system's 12/24h format. - * Note that changing system setting requires permission android.permission.WRITE_SETTINGS - * and it should be defined in TV app, not this test. - */ -@SmallTest -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); - - // All possible list for a parameter to test parameter independent result. - private static final boolean[] PARAM_USE_SHORT_FORMAT = {false, true}; - - @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. - */ - private static long getJanOfThisYearInMillis(int date, int hour, int minutes) { - return new GregorianCalendar(getThisYear(), Calendar.JANUARY, date, hour, minutes) - .getTimeInMillis(); - } - - private static long getJanOfThisYearInMillis(int date, int hour) { - return getJanOfThisYearInMillis(date, hour, 0); - } - - /** - * Return time in millis assuming that whose year is this year and month is Feb. - */ - private static long getFebOfThisYearInMillis(int date, int hour, int minutes) { - return new GregorianCalendar(getThisYear(), Calendar.FEBRUARY, date, hour, minutes) - .getTimeInMillis(); - } - - private static long getFebOfThisYearInMillis(int date, int hour) { - return getFebOfThisYearInMillis(date, hour, 0); - } - - private static int getThisYear() { - 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, - DateUtils.FORMAT_12HOUR)); - assertEquals("03:00", Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 3), getFebOfThisYearInMillis(1, 3), false, - 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, - getFebOfThisYearInMillis(1, 3), false, - DateUtils.FORMAT_12HOUR)); - assertEquals("00:00 – 03:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 3), false, - 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, - getJanOfThisYearInMillis(31, 3), getFebOfThisYearInMillis(1, 4), false, - DateUtils.FORMAT_12HOUR)); - assertEquals("Jan 31, 03:00 – Feb 1, 04:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getJanOfThisYearInMillis(31, 3), getFebOfThisYearInMillis(1, 4), false, - DateUtils.FORMAT_24HOUR)); - assertEquals("1/31, 11:30 PM – 12:30 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getJanOfThisYearInMillis(31, 23, 30), getFebOfThisYearInMillis(1, 0, 30), - true, DateUtils.FORMAT_12HOUR)); - assertEquals("1/31, 23:30 – 00:30", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getJanOfThisYearInMillis(31, 23, 30), getFebOfThisYearInMillis(1, 0, 30), - 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, - getFebOfThisYearInMillis(1, 3), getFebOfThisYearInMillis(2, 4), false, - DateUtils.FORMAT_12HOUR)); - assertEquals("Feb 1, 03:00 – Feb 2, 04:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 3), getFebOfThisYearInMillis(2, 4), false, - DateUtils.FORMAT_24HOUR)); - assertEquals("2/1, 3:00 AM – 2/2, 4:00 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 3), getFebOfThisYearInMillis(2, 4), true, - DateUtils.FORMAT_12HOUR)); - assertEquals("2/1, 03:00 – 2/2, 04:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 3), getFebOfThisYearInMillis(2, 4), true, - DateUtils.FORMAT_24HOUR)); - - assertEquals("Feb 1, 11:30 PM – Feb 2, 12:30 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 23, 30), getFebOfThisYearInMillis(2, 0, 30), - false, - DateUtils.FORMAT_12HOUR)); - assertEquals("Feb 1, 23:30 – Feb 2, 00:30", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 23, 30), getFebOfThisYearInMillis(2, 0, 30), - false, - DateUtils.FORMAT_24HOUR)); - assertEquals("11:30 PM – 12:30 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 23, 30), getFebOfThisYearInMillis(2, 0, 30), - true, - DateUtils.FORMAT_12HOUR)); - assertEquals("23:30 – 00:30", Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 23, 30), getFebOfThisYearInMillis(2, 0, 30), - true, - DateUtils.FORMAT_24HOUR)); - } - - @Test - public void testDurationWithinTomorrow() { - assertEquals("Feb 2, 2:00 – 4:00 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 2), getFebOfThisYearInMillis(2, 4), false, - DateUtils.FORMAT_12HOUR)); - assertEquals("Feb 2, 02:00 – 04:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 2), getFebOfThisYearInMillis(2, 4), false, - DateUtils.FORMAT_24HOUR)); - assertEquals("2/2, 2:00 – 4:00 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 2), getFebOfThisYearInMillis(2, 4), true, - DateUtils.FORMAT_12HOUR)); - assertEquals("2/2, 02:00 – 04:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 2), getFebOfThisYearInMillis(2, 4), true, - 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, - getFebOfThisYearInMillis(1, 1), false, - DateUtils.FORMAT_12HOUR)); - assertEquals("00:00 – 01:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 1), false, - DateUtils.FORMAT_24HOUR)); - - assertEquals("Feb 2, 12:00 – 1:00 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 0), getFebOfThisYearInMillis(2, 1), false, - DateUtils.FORMAT_12HOUR)); - assertEquals("Feb 2, 00:00 – 01:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 0), getFebOfThisYearInMillis(2, 1), false, - DateUtils.FORMAT_24HOUR)); - assertEquals("2/2, 12:00 – 1:00 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 0), getFebOfThisYearInMillis(2, 1), true, - DateUtils.FORMAT_12HOUR)); - assertEquals("2/2, 00:00 – 01:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 0), getFebOfThisYearInMillis(2, 1), true, - DateUtils.FORMAT_24HOUR)); - } - - @Test - public void testEndOfDay() { - for (boolean useShortFormat : PARAM_USE_SHORT_FORMAT) { - assertEquals("11:00 PM – 12:00 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 23), getFebOfThisYearInMillis(2, 0), - useShortFormat, - DateUtils.FORMAT_12HOUR)); - assertEquals("23:00 – 00:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(1, 23), getFebOfThisYearInMillis(2, 0), - useShortFormat, - DateUtils.FORMAT_24HOUR)); - } - - assertEquals("Feb 2, 11:00 PM – 12:00 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 23), getFebOfThisYearInMillis(3, 0), false, - DateUtils.FORMAT_12HOUR)); - assertEquals("Feb 2, 23:00 – 00:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 23), getFebOfThisYearInMillis(3, 0), false, - DateUtils.FORMAT_24HOUR)); - assertEquals("2/2, 11:00 PM – 12:00 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 23), getFebOfThisYearInMillis(3, 0), true, - DateUtils.FORMAT_12HOUR)); - assertEquals("2/2, 23:00 – 00:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 23), getFebOfThisYearInMillis(3, 0), true, - DateUtils.FORMAT_24HOUR)); - assertEquals("2/2, 12:00 AM – 2/3, 12:00 AM", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 0), getFebOfThisYearInMillis(3, 0), true, - DateUtils.FORMAT_12HOUR)); - assertEquals("2/2, 00:00 – 2/3, 00:00", - Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - getFebOfThisYearInMillis(2, 0), getFebOfThisYearInMillis(3, 0), true, - 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, - DATE_THIS_YEAR_2_1_MS, DATE_THIS_YEAR_2_1_MS, useShortFormat, - DateUtils.FORMAT_12HOUR)); - assertEquals("00:00", Utils.getDurationString(getContext(), DATE_THIS_YEAR_2_1_MS, - DATE_THIS_YEAR_2_1_MS, DATE_THIS_YEAR_2_1_MS, useShortFormat, - DateUtils.FORMAT_24HOUR)); - } - } -} diff --git a/tests/unit/src/com/android/tv/util/UtilsTest_GetMultiAudioString.java b/tests/unit/src/com/android/tv/util/UtilsTest_GetMultiAudioString.java deleted file mode 100644 index 1e75342b..00000000 --- a/tests/unit/src/com/android/tv/util/UtilsTest_GetMultiAudioString.java +++ /dev/null @@ -1,94 +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.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 org.junit.Test; - -/** - * Tests for {@link com.android.tv.util.Utils#getMultiAudioString}. - */ -@SmallTest -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 = getTargetContext(); - assertEquals("Korean", - Utils.getMultiAudioString(context, createAudioTrackInfo("kor"), false)); - assertEquals("English", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng"), false)); - assertEquals("Unknown language", - Utils.getMultiAudioString(context, createAudioTrackInfo(null), false)); - assertEquals("Unknown language", - Utils.getMultiAudioString(context, createAudioTrackInfo(""), false)); - assertEquals("abc", Utils.getMultiAudioString(context, createAudioTrackInfo("abc"), false)); - } - - @Test - public void testAudioTrackCount() { - Context context = getTargetContext(); - assertEquals("English", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng", -1), false)); - assertEquals("English", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng", 0), false)); - assertEquals("English (mono)", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng", 1), false)); - assertEquals("English (stereo)", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng", 2), false)); - assertEquals("English (3 channels)", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng", 3), false)); - assertEquals("English (4 channels)", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng", 4), false)); - assertEquals("English (5 channels)", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng", 5), false)); - assertEquals("English (5.1 surround)", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng", 6), false)); - assertEquals("English (7 channels)", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng", 7), false)); - assertEquals("English (7.1 surround)", - Utils.getMultiAudioString(context, createAudioTrackInfo("eng", 8), false)); - } - - @Test - public void testShowSampleRate() { - assertEquals("Korean (48kHz)", - Utils.getMultiAudioString(getTargetContext(), - createAudioTrackInfo("kor", 0), true)); - assertEquals("Korean (7.1 surround, 48kHz)", - Utils.getMultiAudioString(getTargetContext(), - createAudioTrackInfo("kor", 8), true)); - } - - private static TvTrackInfo createAudioTrackInfo(String language) { - return createAudioTrackInfo(language, 0); - } - - private static TvTrackInfo createAudioTrackInfo(String language, int channelCount) { - return new TvTrackInfo.Builder(TvTrackInfo.TYPE_AUDIO, TRACK_ID) - .setLanguage(language).setAudioChannelCount(channelCount) - .setAudioSampleRate(AUDIO_SAMPLE_RATE).build(); - } -} diff --git a/tests/unit/src/com/android/tv/util/UtilsTest_IsInGivenDay.java b/tests/unit/src/com/android/tv/util/UtilsTest_IsInGivenDay.java deleted file mode 100644 index 2b43abc1..00000000 --- a/tests/unit/src/com/android/tv/util/UtilsTest_IsInGivenDay.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.util; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import android.support.test.filters.SmallTest; - -import org.junit.Test; - -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -/** - * Tests for {@link com.android.tv.util.Utils#isInGivenDay}. - */ -@SmallTest -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(); - - TimeZone.setDefault(TimeZone.getTimeZone("Asia/Seoul")); - - // 2015.01.01 00:00 in KST = 2014.12.31 15:00 in UTC - long date2015StartMs = - new GregorianCalendar(2015, Calendar.JANUARY, 1).getTimeInMillis(); - - // 2015.01.01 10:00 in KST = 2015.01.01 01:00 in UTC - long date2015Start10AMMs = - new GregorianCalendar(2015, Calendar.JANUARY, 1, 10, 0).getTimeInMillis(); - - // Those two times aren't in the same day in UTC, but they are in KST. - assertTrue(Utils.isInGivenDay(date2015StartMs, date2015Start10AMMs)); - - TimeZone.setDefault(timeZone); - } -} diff --git a/tests/unit/src/com/android/tv/util/ImageCacheTest.java b/tests/unit/src/com/android/tv/util/images/ImageCacheTest.java index a76194b8..b7715c4a 100644 --- a/tests/unit/src/com/android/tv/util/ImageCacheTest.java +++ b/tests/unit/src/com/android/tv/util/images/ImageCacheTest.java @@ -14,23 +14,22 @@ * limitations under the License. */ -package com.android.tv.util; +package com.android.tv.util.images; -import static com.android.tv.util.BitmapUtils.createScaledBitmapInfo; -import static org.junit.Assert.assertSame; +import static com.android.tv.util.images.BitmapUtils.createScaledBitmapInfo; +import static com.google.common.truth.Truth.assertWithMessage; import android.graphics.Bitmap; import android.support.test.filters.MediumTest; - -import com.android.tv.util.BitmapUtils.ScaledBitmapInfo; - +import android.support.test.runner.AndroidJUnit4; +import com.android.tv.util.images.BitmapUtils.ScaledBitmapInfo; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; -/** - * Tests for {@link ImageCache}. - */ +/** Tests for {@link ImageCache}. */ @MediumTest +@RunWith(AndroidJUnit4.class) public class ImageCacheTest { private static final Bitmap ORIG = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); @@ -47,34 +46,34 @@ public class ImageCacheTest { mImageCache = ImageCache.newInstance(0.1f); } - //TODO: Empty the cache in the setup. Try using @VisibleForTesting + // TODO: Empty the cache in the setup. Try using @VisibleForTesting @Test public void testPutIfLarger_smaller() throws Exception { - mImageCache.putIfNeeded( INFO_50); - assertSame("before", INFO_50, mImageCache.get(KEY)); + mImageCache.putIfNeeded(INFO_50); + assertWithMessage("before").that(mImageCache.get(KEY)).isSameAs(INFO_50); - mImageCache.putIfNeeded( INFO_25); - assertSame("after", INFO_50, mImageCache.get(KEY)); + mImageCache.putIfNeeded(INFO_25); + assertWithMessage("after").that(mImageCache.get(KEY)).isSameAs(INFO_50); } @Test public void testPutIfLarger_larger() throws Exception { - mImageCache.putIfNeeded( INFO_50); - assertSame("before", INFO_50, mImageCache.get(KEY)); + mImageCache.putIfNeeded(INFO_50); + assertWithMessage("before").that(mImageCache.get(KEY)).isSameAs(INFO_50); mImageCache.putIfNeeded(INFO_100); - assertSame("after", INFO_100, mImageCache.get(KEY)); + assertWithMessage("after").that(mImageCache.get(KEY)).isSameAs(INFO_100); } @Test public void testPutIfLarger_alreadyMax() throws Exception { - mImageCache.putIfNeeded( INFO_100); - assertSame("before", INFO_100, mImageCache.get(KEY)); + mImageCache.putIfNeeded(INFO_100); + assertWithMessage("before").that(mImageCache.get(KEY)).isSameAs(INFO_100); - mImageCache.putIfNeeded( INFO_200); - assertSame("after", INFO_100, mImageCache.get(KEY)); + mImageCache.putIfNeeded(INFO_200); + assertWithMessage("after").that(mImageCache.get(KEY)).isSameAs(INFO_100); } -}
\ No newline at end of file +} diff --git a/tests/unit/src/com/android/tv/util/images/ScaledBitmapInfoTest.java b/tests/unit/src/com/android/tv/util/images/ScaledBitmapInfoTest.java new file mode 100644 index 00000000..005775b6 --- /dev/null +++ b/tests/unit/src/com/android/tv/util/images/ScaledBitmapInfoTest.java @@ -0,0 +1,79 @@ +/* + * 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.images; + +import static com.google.common.truth.Truth.assertWithMessage; + +import android.graphics.Bitmap; +import android.support.test.filters.SmallTest; +import android.support.test.runner.AndroidJUnit4; +import com.android.tv.util.images.BitmapUtils.ScaledBitmapInfo; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** Tests for {@link ScaledBitmapInfo}. */ +@SmallTest +@RunWith(AndroidJUnit4.class) +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); + assertNeedsToReload(false, actual, 50, 50); + assertNeedsToReload(false, actual, 99, 99); + assertNeedsToReload(true, actual, 100, 100); + assertNeedsToReload(true, actual, 101, 101); + } + + /** Reproduces <a href="http://b/20488453">b/20488453</a>. */ + @Test + public void testBug20488453() { + ScaledBitmapInfo actual = + BitmapUtils.createScaledBitmapInfo("B960x1440", B960x1440, 284, 160); + assertScaledBitmapSize(8, 107, 160, actual); + assertNeedsToReload(false, actual, 284, 160); + } + + private static void assertNeedsToReload( + boolean expected, ScaledBitmapInfo scaledBitmap, int reqWidth, int reqHeight) { + assertWithMessage(scaledBitmap.id + " needToReload(" + reqWidth + "," + reqHeight + ")") + .that(scaledBitmap.needToReload(reqWidth, reqHeight)) + .isEqualTo(expected); + } + + private static void assertScaledBitmapSize( + int expectedInSampleSize, + int expectedWidth, + int expectedHeight, + ScaledBitmapInfo actual) { + assertWithMessage(actual.id + " inSampleSize") + .that(actual.inSampleSize) + .isEqualTo(expectedInSampleSize); + assertWithMessage(actual.id + " width").that(actual.bitmap.getWidth()).isEqualTo(expectedWidth); + assertWithMessage(actual.id + " height") + .that(actual.bitmap.getHeight()) + .isEqualTo(expectedHeight); + } +} |