summaryrefslogtreecommitdiff
path: root/android/media/MediaSession2Test.java
blob: 045dcd5ae6f9fe1801ffdc38c7f281c4ad1bbfab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*
 * Copyright 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.media;

import android.media.MediaPlayerBase.PlaybackListener;
import android.media.MediaSession2.Builder;
import android.media.MediaSession2.ControllerInfo;
import android.media.MediaSession2.SessionCallback;
import android.media.session.PlaybackState;
import android.os.Process;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;

import java.util.ArrayList;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static android.media.TestUtils.createPlaybackState;
import static org.junit.Assert.*;

/**
 * Tests {@link MediaSession2}.
 */
@RunWith(AndroidJUnit4.class)
@SmallTest
public class MediaSession2Test extends MediaSession2TestBase {
    private static final String TAG = "MediaSession2Test";

    private MediaSession2 mSession;
    private MockPlayer mPlayer;

    @Before
    @Override
    public void setUp() throws Exception {
        super.setUp();
        sHandler.postAndSync(() -> {
            mPlayer = new MockPlayer(0);
            mSession = new MediaSession2.Builder(mContext, mPlayer).build();
        });
    }

    @After
    @Override
    public void cleanUp() throws Exception {
        super.cleanUp();
        sHandler.postAndSync(() -> {
            mSession.close();
        });
    }

    @Test
    public void testBuilder() throws Exception {
        try {
            MediaSession2.Builder builder = new Builder(mContext, null);
            fail("null player shouldn't be allowed");
        } catch (IllegalArgumentException e) {
            // expected. pass-through
        }
        MediaSession2.Builder builder = new Builder(mContext, mPlayer);
        try {
            builder.setId(null);
            fail("null id shouldn't be allowed");
        } catch (IllegalArgumentException e) {
            // expected. pass-through
        }
    }

    @Test
    public void testSetPlayer() throws Exception {
        sHandler.postAndSync(() -> {
            MockPlayer player = new MockPlayer(0);
            // Test if setPlayer doesn't crash with various situations.
            mSession.setPlayer(mPlayer);
            mSession.setPlayer(player);
            mSession.close();
        });
    }

    @Test
    public void testPlay() throws Exception {
        sHandler.postAndSync(() -> {
            mSession.play();
            assertTrue(mPlayer.mPlayCalled);
        });
    }

    @Test
    public void testPause() throws Exception {
        sHandler.postAndSync(() -> {
            mSession.pause();
            assertTrue(mPlayer.mPauseCalled);
        });
    }

    @Test
    public void testStop() throws Exception {
        sHandler.postAndSync(() -> {
            mSession.stop();
            assertTrue(mPlayer.mStopCalled);
        });
    }

    @Test
    public void testSkipToNext() throws Exception {
        sHandler.postAndSync(() -> {
            mSession.skipToNext();
            assertTrue(mPlayer.mSkipToNextCalled);
        });
    }

    @Test
    public void testSkipToPrevious() throws Exception {
        sHandler.postAndSync(() -> {
            mSession.skipToPrevious();
            assertTrue(mPlayer.mSkipToPreviousCalled);
        });
    }

    @Test
    public void testPlaybackStateChangedListener() throws InterruptedException {
        // TODO(jaewan): Add equivalent tests again
        /*
        final CountDownLatch latch = new CountDownLatch(2);
        final MockPlayer player = new MockPlayer(0);
        final PlaybackListener listener = (state) -> {
            assertEquals(sHandler.getLooper(), Looper.myLooper());
            assertNotNull(state);
            switch ((int) latch.getCount()) {
                case 2:
                    assertEquals(PlaybackState.STATE_PLAYING, state.getState());
                    break;
                case 1:
                    assertEquals(PlaybackState.STATE_PAUSED, state.getState());
                    break;
                case 0:
                    fail();
            }
            latch.countDown();
        };
        player.notifyPlaybackState(createPlaybackState(PlaybackState.STATE_PLAYING));
        sHandler.postAndSync(() -> {
            mSession.addPlaybackListener(listener, sHandler);
            // When the player is set, listeners will be notified about the player's current state.
            mSession.setPlayer(player);
        });
        player.notifyPlaybackState(createPlaybackState(PlaybackState.STATE_PAUSED));
        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        */
    }

    @Test
    public void testBadPlayer() throws InterruptedException {
        // TODO(jaewan): Add equivalent tests again
        /*
        final CountDownLatch latch = new CountDownLatch(3); // expected call + 1
        final BadPlayer player = new BadPlayer(0);
        sHandler.postAndSync(() -> {
            mSession.addPlaybackListener((state) -> {
                // This will be called for every setPlayer() calls, but no more.
                assertNull(state);
                latch.countDown();
            }, sHandler);
            mSession.setPlayer(player);
            mSession.setPlayer(mPlayer);
        });
        player.notifyPlaybackState(createPlaybackState(PlaybackState.STATE_PAUSED));
        assertFalse(latch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS));
        */
    }

    private static class BadPlayer extends MockPlayer {
        public BadPlayer(int count) {
            super(count);
        }

        @Override
        public void removePlaybackListener(@NonNull PlaybackListener listener) {
            // No-op. This bad player will keep push notification to the listener that is previously
            // registered by session.setPlayer().
        }
    }

    @Test
    public void testOnCommandCallback() throws InterruptedException {
        final MockOnCommandCallback callback = new MockOnCommandCallback();
        sHandler.postAndSync(() -> {
            mSession.close();
            mPlayer = new MockPlayer(1);
            mSession = new MediaSession2.Builder(mContext, mPlayer)
                    .setSessionCallback(sHandlerExecutor, callback).build();
        });
        MediaController2 controller = createController(mSession.getToken());
        controller.pause();
        assertFalse(mPlayer.mCountDownLatch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS));
        assertFalse(mPlayer.mPauseCalled);
        assertEquals(1, callback.commands.size());
        assertEquals(MediaSession2.COMMAND_CODE_PLAYBACK_PAUSE,
                (long) callback.commands.get(0).getCommandCode());
        controller.skipToNext();
        assertTrue(mPlayer.mCountDownLatch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS));
        assertTrue(mPlayer.mSkipToNextCalled);
        assertFalse(mPlayer.mPauseCalled);
        assertEquals(2, callback.commands.size());
        assertEquals(MediaSession2.COMMAND_CODE_PLAYBACK_SKIP_NEXT_ITEM,
                (long) callback.commands.get(1).getCommandCode());
    }

    @Test
    public void testOnConnectCallback() throws InterruptedException {
        final MockOnConnectCallback sessionCallback = new MockOnConnectCallback();
        sHandler.postAndSync(() -> {
            mSession.close();
            mSession = new MediaSession2.Builder(mContext, mPlayer)
                    .setSessionCallback(sHandlerExecutor, sessionCallback).build();
        });
        MediaController2 controller =
                createController(mSession.getToken(), false, null);
        assertNotNull(controller);
        waitForConnect(controller, false);
        waitForDisconnect(controller, true);
    }

    public class MockOnConnectCallback extends SessionCallback {
        @Override
        public MediaSession2.CommandGroup onConnect(ControllerInfo controllerInfo) {
            if (Process.myUid() != controllerInfo.getUid()) {
                return null;
            }
            assertEquals(mContext.getPackageName(), controllerInfo.getPackageName());
            assertEquals(Process.myUid(), controllerInfo.getUid());
            assertFalse(controllerInfo.isTrusted());
            // Reject all
            return null;
        }
    }

    public class MockOnCommandCallback extends SessionCallback {
        public final ArrayList<MediaSession2.Command> commands = new ArrayList<>();

        @Override
        public boolean onCommandRequest(ControllerInfo controllerInfo, MediaSession2.Command command) {
            assertEquals(mContext.getPackageName(), controllerInfo.getPackageName());
            assertEquals(Process.myUid(), controllerInfo.getUid());
            assertFalse(controllerInfo.isTrusted());
            commands.add(command);
            if (command.getCommandCode() == MediaSession2.COMMAND_CODE_PLAYBACK_PAUSE) {
                return false;
            }
            return true;
        }
    }
}