blob: ce7adfa7087863f49d3178fdbe03cabc1dd08f0d [file] [log] [blame]
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.server.pm.shortcutmanagertest;
17
18import static junit.framework.Assert.assertEquals;
19import static junit.framework.Assert.assertFalse;
20import static junit.framework.Assert.assertNotNull;
21import static junit.framework.Assert.assertNull;
22import static junit.framework.Assert.assertTrue;
23import static junit.framework.Assert.fail;
24
25import static org.mockito.Matchers.any;
26import static org.mockito.Matchers.anyList;
27import static org.mockito.Matchers.anyString;
28import static org.mockito.Matchers.eq;
Makoto Onukib08790c2016-06-23 14:05:46 -070029import static org.mockito.Mockito.mock;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070030import static org.mockito.Mockito.reset;
31import static org.mockito.Mockito.times;
32import static org.mockito.Mockito.verify;
33
34import android.app.Instrumentation;
Makoto Onuki7001a612016-05-27 13:24:28 -070035import android.content.ComponentName;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070036import android.content.Context;
37import android.content.pm.LauncherApps;
Makoto Onukib08790c2016-06-23 14:05:46 -070038import android.content.pm.LauncherApps.Callback;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070039import android.content.pm.ShortcutInfo;
40import android.graphics.Bitmap;
41import android.graphics.BitmapFactory;
42import android.os.BaseBundle;
43import android.os.Bundle;
Makoto Onukib08790c2016-06-23 14:05:46 -070044import android.os.Handler;
45import android.os.Looper;
Makoto Onuki7001a612016-05-27 13:24:28 -070046import android.os.Parcel;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070047import android.os.ParcelFileDescriptor;
Makoto Onukib5a012f2016-06-21 11:13:53 -070048import android.os.PersistableBundle;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070049import android.os.UserHandle;
50import android.test.MoreAsserts;
51import android.util.Log;
52
53import junit.framework.Assert;
54
55import org.hamcrest.BaseMatcher;
56import org.hamcrest.Description;
57import org.hamcrest.Matcher;
Makoto Onukib08790c2016-06-23 14:05:46 -070058import org.mockito.ArgumentCaptor;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070059import org.mockito.Mockito;
60
61import java.io.BufferedReader;
62import java.io.FileReader;
63import java.io.IOException;
64import java.util.ArrayList;
65import java.util.Arrays;
66import java.util.Collection;
Makoto Onuki9e1f5592016-06-08 12:30:23 -070067import java.util.Collections;
68import java.util.Comparator;
69import java.util.LinkedHashSet;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070070import java.util.List;
71import java.util.Set;
Makoto Onuki9e1f5592016-06-08 12:30:23 -070072import java.util.SortedSet;
73import java.util.TreeSet;
Makoto Onukib08790c2016-06-23 14:05:46 -070074import java.util.concurrent.CountDownLatch;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070075import java.util.function.BooleanSupplier;
Makoto Onukidf6da042016-06-16 09:51:40 -070076import java.util.function.Consumer;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070077import java.util.function.Function;
78import java.util.function.Predicate;
79
Makoto Onuki51ab2b32016-06-02 11:03:51 -070080/**
81 * Common utility methods for ShortcutManager tests. This is used by both CTS and the unit tests.
82 * Because it's used by CTS too, it can only access the public APIs.
83 */
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070084public class ShortcutManagerTestUtils {
85 private static final String TAG = "ShortcutManagerUtils";
86
Makoto Onuki9e1f5592016-06-08 12:30:23 -070087 private static final boolean ENABLE_DUMPSYS = false; // DO NOT SUBMIT WITH true
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070088
89 private static final int STANDARD_TIMEOUT_SEC = 5;
90
Makoto Onuki9e1f5592016-06-08 12:30:23 -070091 private static final String[] EMPTY_STRINGS = new String[0];
92
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070093 private ShortcutManagerTestUtils() {
94 }
95
96 private static List<String> readAll(ParcelFileDescriptor pfd) {
97 try {
98 try {
99 final ArrayList<String> ret = new ArrayList<>();
100 try (BufferedReader r = new BufferedReader(
101 new FileReader(pfd.getFileDescriptor()))) {
102 String line;
103 while ((line = r.readLine()) != null) {
104 ret.add(line);
105 }
106 r.readLine();
107 }
108 return ret;
109 } finally {
110 pfd.close();
111 }
112 } catch (IOException e) {
113 throw new RuntimeException(e);
114 }
115 }
116
117 private static String concatResult(List<String> result) {
118 final StringBuilder sb = new StringBuilder();
119 for (String s : result) {
120 sb.append(s);
121 sb.append("\n");
122 }
123 return sb.toString();
124 }
125
126 private static List<String> runCommand(Instrumentation instrumentation, String command) {
127 return runCommand(instrumentation, command, null);
128 }
129 private static List<String> runCommand(Instrumentation instrumentation, String command,
130 Predicate<List<String>> resultAsserter) {
131 Log.d(TAG, "Running command: " + command);
132 final List<String> result;
133 try {
134 result = readAll(
135 instrumentation.getUiAutomation().executeShellCommand(command));
136 } catch (Exception e) {
137 throw new RuntimeException(e);
138 }
139 if (resultAsserter != null && !resultAsserter.test(result)) {
140 fail("Command '" + command + "' failed, output was:\n" + concatResult(result));
141 }
142 return result;
143 }
144
145 private static void runCommandForNoOutput(Instrumentation instrumentation, String command) {
146 runCommand(instrumentation, command, result -> result.size() == 0);
147 }
148
149 private static List<String> runShortcutCommand(Instrumentation instrumentation, String command,
150 Predicate<List<String>> resultAsserter) {
151 return runCommand(instrumentation, "cmd shortcut " + command, resultAsserter);
152 }
153
154 public static List<String> runShortcutCommandForSuccess(Instrumentation instrumentation,
155 String command) {
156 return runShortcutCommand(instrumentation, command, result -> result.contains("Success"));
157 }
158
159 public static String getDefaultLauncher(Instrumentation instrumentation) {
160 final String PREFIX = "Launcher: ComponentInfo{";
161 final String POSTFIX = "}";
162 final List<String> result = runShortcutCommandForSuccess(
163 instrumentation, "get-default-launcher");
164 for (String s : result) {
165 if (s.startsWith(PREFIX) && s.endsWith(POSTFIX)) {
166 return s.substring(PREFIX.length(), s.length() - POSTFIX.length());
167 }
168 }
169 fail("Default launcher not found");
170 return null;
171 }
172
173 public static void setDefaultLauncher(Instrumentation instrumentation, String component) {
Makoto Onuki3bdbf982016-06-23 16:56:35 -0700174 runCommand(instrumentation, "cmd package set-home-activity " + component,
175 result -> result.contains("Success"));
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700176 }
177
178 public static void setDefaultLauncher(Instrumentation instrumentation, Context packageContext) {
179 setDefaultLauncher(instrumentation, packageContext.getPackageName()
180 + "/android.content.pm.cts.shortcutmanager.packages.Launcher");
181 }
182
183 public static void overrideConfig(Instrumentation instrumentation, String config) {
184 runShortcutCommandForSuccess(instrumentation, "override-config " + config);
185 }
186
187 public static void resetConfig(Instrumentation instrumentation) {
188 runShortcutCommandForSuccess(instrumentation, "reset-config");
189 }
190
191 public static void resetThrottling(Instrumentation instrumentation) {
192 runShortcutCommandForSuccess(instrumentation, "reset-throttling");
193 }
194
195 public static void resetAllThrottling(Instrumentation instrumentation) {
196 runShortcutCommandForSuccess(instrumentation, "reset-all-throttling");
197 }
198
199 public static void clearShortcuts(Instrumentation instrumentation, int userId,
200 String packageName) {
201 runShortcutCommandForSuccess(instrumentation, "clear-shortcuts "
202 + " --user " + userId + " " + packageName);
203 }
204
205 public static void dumpsysShortcut(Instrumentation instrumentation) {
206 if (!ENABLE_DUMPSYS) {
207 return;
208 }
Makoto Onuki3bdbf982016-06-23 16:56:35 -0700209 Log.e(TAG, "Dumpsys shortcut");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700210 for (String s : runCommand(instrumentation, "dumpsys shortcut")) {
211 Log.e(TAG, s);
212 }
213 }
214
215 public static Bundle makeBundle(Object... keysAndValues) {
216 assertTrue((keysAndValues.length % 2) == 0);
217
218 if (keysAndValues.length == 0) {
219 return null;
220 }
221 final Bundle ret = new Bundle();
222
223 for (int i = keysAndValues.length - 2; i >= 0; i -= 2) {
224 final String key = keysAndValues[i].toString();
225 final Object value = keysAndValues[i + 1];
226
227 if (value == null) {
228 ret.putString(key, null);
229 } else if (value instanceof Integer) {
230 ret.putInt(key, (Integer) value);
231 } else if (value instanceof String) {
232 ret.putString(key, (String) value);
233 } else if (value instanceof Bundle) {
234 ret.putBundle(key, (Bundle) value);
235 } else {
236 fail("Type not supported yet: " + value.getClass().getName());
237 }
238 }
239 return ret;
240 }
241
Makoto Onukib5a012f2016-06-21 11:13:53 -0700242 public static PersistableBundle makePersistableBundle(Object... keysAndValues) {
243 assertTrue((keysAndValues.length % 2) == 0);
244
245 if (keysAndValues.length == 0) {
246 return null;
247 }
248 final PersistableBundle ret = new PersistableBundle();
249
250 for (int i = keysAndValues.length - 2; i >= 0; i -= 2) {
251 final String key = keysAndValues[i].toString();
252 final Object value = keysAndValues[i + 1];
253
254 if (value == null) {
255 ret.putString(key, null);
256 } else if (value instanceof Integer) {
257 ret.putInt(key, (Integer) value);
258 } else if (value instanceof String) {
259 ret.putString(key, (String) value);
260 } else if (value instanceof PersistableBundle) {
261 ret.putPersistableBundle(key, (PersistableBundle) value);
262 } else {
263 fail("Type not supported yet: " + value.getClass().getName());
264 }
265 }
266 return ret;
267 }
268
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700269 public static <T> List<T> list(T... array) {
270 return Arrays.asList(array);
271 }
272
273 public static <T> Set<T> hashSet(Set<T> in) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700274 return new LinkedHashSet<>(in);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700275 }
276
277 public static <T> Set<T> set(T... values) {
278 return set(v -> v, values);
279 }
280
281 public static <T, V> Set<T> set(Function<V, T> converter, V... values) {
282 return set(converter, Arrays.asList(values));
283 }
284
285 public static <T, V> Set<T> set(Function<V, T> converter, List<V> values) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700286 final LinkedHashSet<T> ret = new LinkedHashSet<>();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700287 for (V v : values) {
288 ret.add(converter.apply(v));
289 }
290 return ret;
291 }
292
293 public static void resetAll(Collection<?> mocks) {
294 for (Object o : mocks) {
295 reset(o);
296 }
297 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700298
Makoto Onukidf6da042016-06-16 09:51:40 -0700299 public static <T extends Collection<?>> T assertEmpty(T collection) {
300 if (collection == null) {
301 return collection; // okay.
302 }
303 assertEquals(0, collection.size());
304 return collection;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700305 }
306
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700307 public static List<ShortcutInfo> filter(List<ShortcutInfo> list, Predicate<ShortcutInfo> p) {
308 final ArrayList<ShortcutInfo> ret = new ArrayList<>(list);
309 ret.removeIf(si -> !p.test(si));
310 return ret;
311 }
312
Makoto Onuki7001a612016-05-27 13:24:28 -0700313 public static List<ShortcutInfo> filterByActivity(List<ShortcutInfo> list,
314 ComponentName activity) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700315 return filter(list, si ->
316 (si.getActivity().equals(activity)
Makoto Onukib5a012f2016-06-21 11:13:53 -0700317 && (si.isDeclaredInManifest() || si.isDynamic())));
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700318 }
319
320 public static List<ShortcutInfo> changedSince(List<ShortcutInfo> list, long time) {
321 return filter(list, si -> si.getLastChangedTimestamp() >= time);
Makoto Onuki7001a612016-05-27 13:24:28 -0700322 }
323
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700324 public static void assertExpectException(Class<? extends Throwable> expectedExceptionType,
325 String expectedExceptionMessageRegex, Runnable r) {
326 assertExpectException("", expectedExceptionType, expectedExceptionMessageRegex, r);
327 }
328
Makoto Onuki22fcc682016-05-17 14:52:19 -0700329 public static void assertCannotUpdateImmutable(Runnable r) {
330 assertExpectException(
331 IllegalArgumentException.class, "may not be manipulated via APIs", r);
332 }
333
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700334 public static void assertDynamicShortcutCountExceeded(Runnable r) {
335 assertExpectException(IllegalArgumentException.class,
336 "Max number of dynamic shortcuts exceeded", r);
337 }
338
339 public static void assertExpectException(String message,
340 Class<? extends Throwable> expectedExceptionType,
341 String expectedExceptionMessageRegex, Runnable r) {
342 try {
343 r.run();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700344 } catch (Throwable e) {
345 Assert.assertTrue(
346 "Expected exception type was " + expectedExceptionType.getName()
347 + " but caught " + e + " (message=" + message + ")",
348 expectedExceptionType.isAssignableFrom(e.getClass()));
349 if (expectedExceptionMessageRegex != null) {
350 MoreAsserts.assertContainsRegex(expectedExceptionMessageRegex, e.getMessage());
351 }
Makoto Onukia1d38b32016-06-10 15:32:26 -0700352 return; // Pass
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700353 }
Makoto Onukia1d38b32016-06-10 15:32:26 -0700354 Assert.fail("Expected exception type " + expectedExceptionType.getName()
355 + " was not thrown");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700356 }
357
358 public static List<ShortcutInfo> assertShortcutIds(List<ShortcutInfo> actualShortcuts,
359 String... expectedIds) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700360 final SortedSet<String> expected = new TreeSet<>(list(expectedIds));
361 final SortedSet<String> actual = new TreeSet<>();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700362 for (ShortcutInfo s : actualShortcuts) {
363 actual.add(s.getId());
364 }
365
366 // Compare the sets.
367 assertEquals(expected, actual);
368 return actualShortcuts;
369 }
370
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700371 public static List<ShortcutInfo> assertShortcutIdsOrdered(List<ShortcutInfo> actualShortcuts,
372 String... expectedIds) {
373 final ArrayList<String> expected = new ArrayList<>(list(expectedIds));
374 final ArrayList<String> actual = new ArrayList<>();
375 for (ShortcutInfo s : actualShortcuts) {
376 actual.add(s.getId());
377 }
378 assertEquals(expected, actual);
379 return actualShortcuts;
380 }
381
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700382 public static List<ShortcutInfo> assertAllHaveIntents(
383 List<ShortcutInfo> actualShortcuts) {
384 for (ShortcutInfo s : actualShortcuts) {
385 assertNotNull("ID " + s.getId(), s.getIntent());
386 }
387 return actualShortcuts;
388 }
389
390 public static List<ShortcutInfo> assertAllNotHaveIntents(
391 List<ShortcutInfo> actualShortcuts) {
392 for (ShortcutInfo s : actualShortcuts) {
393 assertNull("ID " + s.getId(), s.getIntent());
394 }
395 return actualShortcuts;
396 }
397
398 public static List<ShortcutInfo> assertAllHaveTitle(
399 List<ShortcutInfo> actualShortcuts) {
400 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukieddbfec2016-05-31 17:04:34 -0700401 assertNotNull("ID " + s.getId(), s.getShortLabel());
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700402 }
403 return actualShortcuts;
404 }
405
406 public static List<ShortcutInfo> assertAllNotHaveTitle(
407 List<ShortcutInfo> actualShortcuts) {
408 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukieddbfec2016-05-31 17:04:34 -0700409 assertNull("ID " + s.getId(), s.getShortLabel());
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700410 }
411 return actualShortcuts;
412 }
413
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700414 public static List<ShortcutInfo> assertAllKeyFieldsOnly(
415 List<ShortcutInfo> actualShortcuts) {
416 for (ShortcutInfo s : actualShortcuts) {
417 assertTrue("ID " + s.getId(), s.hasKeyFieldsOnly());
418 }
419 return actualShortcuts;
420 }
421
422 public static List<ShortcutInfo> assertAllNotKeyFieldsOnly(
423 List<ShortcutInfo> actualShortcuts) {
424 for (ShortcutInfo s : actualShortcuts) {
425 assertFalse("ID " + s.getId(), s.hasKeyFieldsOnly());
426 }
427 return actualShortcuts;
428 }
429
430 public static List<ShortcutInfo> assertAllDynamic(List<ShortcutInfo> actualShortcuts) {
431 for (ShortcutInfo s : actualShortcuts) {
432 assertTrue("ID " + s.getId(), s.isDynamic());
433 }
434 return actualShortcuts;
435 }
436
437 public static List<ShortcutInfo> assertAllPinned(List<ShortcutInfo> actualShortcuts) {
438 for (ShortcutInfo s : actualShortcuts) {
439 assertTrue("ID " + s.getId(), s.isPinned());
440 }
441 return actualShortcuts;
442 }
443
444 public static List<ShortcutInfo> assertAllDynamicOrPinned(
445 List<ShortcutInfo> actualShortcuts) {
446 for (ShortcutInfo s : actualShortcuts) {
447 assertTrue("ID " + s.getId(), s.isDynamic() || s.isPinned());
448 }
449 return actualShortcuts;
450 }
451
Makoto Onuki22fcc682016-05-17 14:52:19 -0700452 public static List<ShortcutInfo> assertAllManifest(
453 List<ShortcutInfo> actualShortcuts) {
454 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700455 assertTrue("ID " + s.getId(), s.isDeclaredInManifest());
Makoto Onuki22fcc682016-05-17 14:52:19 -0700456 }
457 return actualShortcuts;
458 }
459
460 public static List<ShortcutInfo> assertAllNotManifest(
461 List<ShortcutInfo> actualShortcuts) {
462 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700463 assertFalse("ID " + s.getId(), s.isDeclaredInManifest());
Makoto Onuki22fcc682016-05-17 14:52:19 -0700464 }
465 return actualShortcuts;
466 }
467
468 public static List<ShortcutInfo> assertAllDisabled(
469 List<ShortcutInfo> actualShortcuts) {
470 for (ShortcutInfo s : actualShortcuts) {
471 assertTrue("ID " + s.getId(), !s.isEnabled());
472 }
473 return actualShortcuts;
474 }
475
476 public static List<ShortcutInfo> assertAllEnabled(
477 List<ShortcutInfo> actualShortcuts) {
478 for (ShortcutInfo s : actualShortcuts) {
479 assertTrue("ID " + s.getId(), s.isEnabled());
480 }
481 return actualShortcuts;
482 }
483
484 public static List<ShortcutInfo> assertAllImmutable(
485 List<ShortcutInfo> actualShortcuts) {
486 for (ShortcutInfo s : actualShortcuts) {
487 assertTrue("ID " + s.getId(), s.isImmutable());
488 }
489 return actualShortcuts;
490 }
491
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700492 public static void assertDynamicOnly(ShortcutInfo si) {
493 assertTrue(si.isDynamic());
494 assertFalse(si.isPinned());
495 }
496
497 public static void assertPinnedOnly(ShortcutInfo si) {
498 assertFalse(si.isDynamic());
Makoto Onukib5a012f2016-06-21 11:13:53 -0700499 assertFalse(si.isDeclaredInManifest());
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700500 assertTrue(si.isPinned());
501 }
502
503 public static void assertDynamicAndPinned(ShortcutInfo si) {
504 assertTrue(si.isDynamic());
505 assertTrue(si.isPinned());
506 }
507
508 public static void assertBitmapSize(int expectedWidth, int expectedHeight, Bitmap bitmap) {
509 assertEquals("width", expectedWidth, bitmap.getWidth());
510 assertEquals("height", expectedHeight, bitmap.getHeight());
511 }
512
513 public static <T> void assertAllUnique(Collection<T> list) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700514 final Set<Object> set = new LinkedHashSet<>();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700515 for (T item : list) {
516 if (set.contains(item)) {
517 fail("Duplicate item found: " + item + " (in the list: " + list + ")");
518 }
519 set.add(item);
520 }
521 }
522
Makoto Onuki39686e82016-04-13 18:03:00 -0700523 public static ShortcutInfo findShortcut(List<ShortcutInfo> list, String id) {
524 for (ShortcutInfo si : list) {
525 if (si.getId().equals(id)) {
526 return si;
527 }
528 }
529 fail("Shortcut " + id + " not found in the list");
530 return null;
531 }
532
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700533 public static Bitmap pfdToBitmap(ParcelFileDescriptor pfd) {
534 assertNotNull(pfd);
535 try {
536 try {
537 return BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
538 } finally {
539 pfd.close();
540 }
541 } catch (IOException e) {
542 throw new RuntimeException(e);
543 }
544 }
545
546 public static void assertBundleEmpty(BaseBundle b) {
547 assertTrue(b == null || b.size() == 0);
548 }
549
550 public static void assertCallbackNotReceived(LauncherApps.Callback mock) {
551 verify(mock, times(0)).onShortcutsChanged(anyString(), anyList(),
552 any(UserHandle.class));
553 }
554
555 public static void assertCallbackReceived(LauncherApps.Callback mock,
556 UserHandle user, String packageName, String... ids) {
557 verify(mock).onShortcutsChanged(eq(packageName), checkShortcutIds(ids),
558 eq(user));
559 }
560
561 public static boolean checkAssertSuccess(Runnable r) {
562 try {
563 r.run();
564 return true;
565 } catch (AssertionError e) {
566 return false;
567 }
568 }
569
570 public static <T> T checkArgument(Predicate<T> checker, String description,
571 List<T> matchedCaptor) {
572 final Matcher<T> m = new BaseMatcher<T>() {
573 @Override
574 public boolean matches(Object item) {
575 if (item == null) {
576 return false;
577 }
578 final T value = (T) item;
579 if (!checker.test(value)) {
580 return false;
581 }
582
583 if (matchedCaptor != null) {
584 matchedCaptor.add(value);
585 }
586 return true;
587 }
588
589 @Override
590 public void describeTo(Description d) {
591 d.appendText(description);
592 }
593 };
594 return Mockito.argThat(m);
595 }
596
597 public static List<ShortcutInfo> checkShortcutIds(String... ids) {
598 return checkArgument((List<ShortcutInfo> list) -> {
599 final Set<String> actualSet = set(si -> si.getId(), list);
600 return actualSet.equals(set(ids));
601
602 }, "Shortcut IDs=[" + Arrays.toString(ids) + "]", null);
603 }
604
Makoto Onuki7001a612016-05-27 13:24:28 -0700605 public static ShortcutInfo parceled(ShortcutInfo si) {
606 Parcel p = Parcel.obtain();
607 p.writeParcelable(si, 0);
608 p.setDataPosition(0);
609 ShortcutInfo si2 = p.readParcelable(ShortcutManagerTestUtils.class.getClassLoader());
610 p.recycle();
611 return si2;
612 }
613
614 public static List<ShortcutInfo> cloneShortcutList(List<ShortcutInfo> list) {
615 if (list == null) {
616 return null;
617 }
618 final List<ShortcutInfo> ret = new ArrayList<>(list.size());
619 for (ShortcutInfo si : list) {
620 ret.add(parceled(si));
621 }
622
623 return ret;
624 }
625
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700626 private static final Comparator<ShortcutInfo> sRankComparator =
627 (ShortcutInfo a, ShortcutInfo b) -> Integer.compare(a.getRank(), b.getRank());
628
629 public static List<ShortcutInfo> sortedByRank(List<ShortcutInfo> shortcuts) {
630 final ArrayList<ShortcutInfo> ret = new ArrayList<>(shortcuts);
631 Collections.sort(ret, sRankComparator);
632 return ret;
633 }
634
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700635 public static void waitUntil(String message, BooleanSupplier condition) {
636 waitUntil(message, condition, STANDARD_TIMEOUT_SEC);
637 }
638
639 public static void waitUntil(String message, BooleanSupplier condition, int timeoutSeconds) {
640 final long timeout = System.currentTimeMillis() + (timeoutSeconds * 1000L);
641 while (System.currentTimeMillis() < timeout) {
642 if (condition.getAsBoolean()) {
643 return;
644 }
645 try {
646 Thread.sleep(100);
647 } catch (InterruptedException e) {
648 throw new RuntimeException(e);
649 }
650 }
651 fail("Timed out for: " + message);
652 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700653
654 public static ShortcutListAsserter assertWith(List<ShortcutInfo> list) {
655 return new ShortcutListAsserter(list);
656 }
657
658 /**
659 * New style assertion that allows chained calls.
660 */
661 public static class ShortcutListAsserter {
Makoto Onukidf6da042016-06-16 09:51:40 -0700662 private final ShortcutListAsserter mOriginal;
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700663 private final List<ShortcutInfo> mList;
664
665 ShortcutListAsserter(List<ShortcutInfo> list) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700666 this(null, list);
667 }
668
669 private ShortcutListAsserter(ShortcutListAsserter original, List<ShortcutInfo> list) {
Makoto Onukib08790c2016-06-23 14:05:46 -0700670 mOriginal = (original == null) ? this : original;
671 mList = (list == null) ? new ArrayList<>(0) : new ArrayList<>(list);
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700672 }
673
Makoto Onukidf6da042016-06-16 09:51:40 -0700674 public ShortcutListAsserter revertToOriginalList() {
675 return mOriginal;
676 }
677
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700678 public ShortcutListAsserter selectDynamic() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700679 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700680 filter(mList, ShortcutInfo::isDynamic));
681 }
682
683 public ShortcutListAsserter selectManifest() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700684 return new ShortcutListAsserter(this,
Makoto Onukib5a012f2016-06-21 11:13:53 -0700685 filter(mList, ShortcutInfo::isDeclaredInManifest));
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700686 }
687
688 public ShortcutListAsserter selectPinned() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700689 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700690 filter(mList, ShortcutInfo::isPinned));
691 }
692
693 public ShortcutListAsserter selectByActivity(ComponentName activity) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700694 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700695 ShortcutManagerTestUtils.filterByActivity(mList, activity));
696 }
697
698 public ShortcutListAsserter selectByChangedSince(long time) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700699 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700700 ShortcutManagerTestUtils.changedSince(mList, time));
701 }
702
Makoto Onukidf6da042016-06-16 09:51:40 -0700703 public ShortcutListAsserter selectByIds(String... ids) {
704 final Set<String> idSet = set(ids);
705 final ArrayList<ShortcutInfo> selected = new ArrayList<>();
706 for (ShortcutInfo si : mList) {
707 if (idSet.contains(si.getId())) {
708 selected.add(si);
709 idSet.remove(si.getId());
710 }
711 }
712 if (idSet.size() > 0) {
713 fail("Shortcuts not found for IDs=" + idSet);
714 }
715
716 return new ShortcutListAsserter(this, selected);
717 }
718
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700719 public ShortcutListAsserter toSortByRank() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700720 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700721 ShortcutManagerTestUtils.sortedByRank(mList));
722 }
723
Makoto Onukidf6da042016-06-16 09:51:40 -0700724 public ShortcutListAsserter call(Consumer<List<ShortcutInfo>> c) {
725 c.accept(mList);
726 return this;
727 }
728
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700729 public ShortcutListAsserter haveIds(String... expectedIds) {
730 assertShortcutIds(mList, expectedIds);
731 return this;
732 }
733
734 public ShortcutListAsserter haveIdsOrdered(String... expectedIds) {
735 assertShortcutIdsOrdered(mList, expectedIds);
736 return this;
737 }
738
739 private ShortcutListAsserter haveSequentialRanks() {
740 for (int i = 0; i < mList.size(); i++) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700741 final ShortcutInfo si = mList.get(i);
742 assertEquals("Rank not sequential: id=" + si.getId(), i, si.getRank());
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700743 }
744 return this;
745 }
746
747 public ShortcutListAsserter haveRanksInOrder(String... expectedIds) {
748 toSortByRank()
749 .haveSequentialRanks()
750 .haveIdsOrdered(expectedIds);
751 return this;
752 }
753
754 public ShortcutListAsserter isEmpty() {
755 assertEquals(0, mList.size());
756 return this;
757 }
Makoto Onukidf6da042016-06-16 09:51:40 -0700758
759 public ShortcutListAsserter areAllDynamic() {
760 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isDynamic()));
761 return this;
762 }
763
764 public ShortcutListAsserter areAllNotDynamic() {
765 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isDynamic()));
766 return this;
767 }
768
769 public ShortcutListAsserter areAllPinned() {
770 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isPinned()));
771 return this;
772 }
773
774 public ShortcutListAsserter areAllNotPinned() {
775 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isPinned()));
776 return this;
777 }
778
779 public ShortcutListAsserter areAllManifest() {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700780 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isDeclaredInManifest()));
Makoto Onukidf6da042016-06-16 09:51:40 -0700781 return this;
782 }
783
784 public ShortcutListAsserter areAllNotManifest() {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700785 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isDeclaredInManifest()));
Makoto Onukidf6da042016-06-16 09:51:40 -0700786 return this;
787 }
788
789 public ShortcutListAsserter areAllImmutable() {
790 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isImmutable()));
791 return this;
792 }
793
794 public ShortcutListAsserter areAllMutable() {
795 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isImmutable()));
796 return this;
797 }
798
799 public ShortcutListAsserter areAllEnabled() {
800 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isEnabled()));
801 return this;
802 }
803
804 public ShortcutListAsserter areAllDisabled() {
805 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isEnabled()));
806 return this;
807 }
808
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700809 public ShortcutListAsserter areAllWithKeyFieldsOnly() {
810 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.hasKeyFieldsOnly()));
811 return this;
812 }
813
814 public ShortcutListAsserter areAllNotWithKeyFieldsOnly() {
815 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.hasKeyFieldsOnly()));
816 return this;
817 }
818
Makoto Onukib08790c2016-06-23 14:05:46 -0700819 public ShortcutListAsserter areAllWithActivity(ComponentName activity) {
820 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.getActivity().equals(activity)));
821 return this;
822 }
823
Makoto Onukidf6da042016-06-16 09:51:40 -0700824 public ShortcutListAsserter forAllShortcuts(Consumer<ShortcutInfo> sa) {
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700825 boolean found = false;
Makoto Onukidf6da042016-06-16 09:51:40 -0700826 for (int i = 0; i < mList.size(); i++) {
827 final ShortcutInfo si = mList.get(i);
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700828 found = true;
Makoto Onukidf6da042016-06-16 09:51:40 -0700829 sa.accept(si);
830 }
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700831 assertTrue("No shortcuts found.", found);
Makoto Onukidf6da042016-06-16 09:51:40 -0700832 return this;
833 }
834
835 public ShortcutListAsserter forShortcut(Predicate<ShortcutInfo> p,
836 Consumer<ShortcutInfo> sa) {
837 boolean found = false;
838 for (int i = 0; i < mList.size(); i++) {
839 final ShortcutInfo si = mList.get(i);
840 if (p.test(si)) {
841 found = true;
842 try {
843 sa.accept(si);
844 } catch (Throwable e) {
845 throw new AssertionError("Assertion failed for shortcut " + si.getId(), e);
846 }
847 }
848 }
849 assertTrue("Shortcut with the given condition not found.", found);
850 return this;
851 }
852
853 public ShortcutListAsserter forShortcutWithId(String id, Consumer<ShortcutInfo> sa) {
854 forShortcut(si -> si.getId().equals(id), sa);
855
856 return this;
857 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700858 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700859
860 public static void assertBundlesEqual(BaseBundle b1, BaseBundle b2) {
861 if (b1 == null && b2 == null) {
862 return; // pass
863 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700864 assertNotNull("b1 is null but b2 is not", b1);
865 assertNotNull("b2 is null but b1 is not", b2);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700866
867 // HashSet makes the error message readable.
868 assertEquals(set(b1.keySet()), set(b2.keySet()));
869
870 for (String key : b1.keySet()) {
871 final Object v1 = b1.get(key);
872 final Object v2 = b2.get(key);
873 if (v1 == null) {
874 if (v2 == null) {
875 return;
876 }
877 }
878 if (v1.equals(v2)) {
879 return;
880 }
881
882 assertTrue("Only either value is null: key=" + key
883 + " b1=" + b1 + " b2=" + b2, v1 != null && v2 != null);
884 assertEquals("Class mismatch: key=" + key, v1.getClass(), v2.getClass());
885
886 if (v1 instanceof BaseBundle) {
887 assertBundlesEqual((BaseBundle) v1, (BaseBundle) v2);
888
889 } else if (v1 instanceof boolean[]) {
890 assertTrue(Arrays.equals((boolean[]) v1, (boolean[]) v2));
891
892 } else if (v1 instanceof int[]) {
893 MoreAsserts.assertEquals((int[]) v1, (int[]) v2);
894
895 } else if (v1 instanceof double[]) {
896 MoreAsserts.assertEquals((double[]) v1, (double[]) v2);
897
898 } else if (v1 instanceof String[]) {
899 MoreAsserts.assertEquals((String[]) v1, (String[]) v2);
900
901 } else if (v1 instanceof Double) {
902 if (((Double) v1).isNaN()) {
903 assertTrue(((Double) v2).isNaN());
904 } else {
905 assertEquals(v1, v2);
906 }
907
908 } else {
909 assertEquals(v1, v2);
910 }
911 }
912 }
Makoto Onukib08790c2016-06-23 14:05:46 -0700913
914 public static void waitOnMainThread() throws InterruptedException {
915 final CountDownLatch latch = new CountDownLatch(1);
916
917 new Handler(Looper.getMainLooper()).post(() -> latch.countDown());
918
919 latch.await();
920 }
921
922 public static class LauncherCallbackAsserter {
923 private final LauncherApps.Callback mCallback = mock(LauncherApps.Callback.class);
924
925 private Callback getMockCallback() {
926 return mCallback;
927 }
928
929 public LauncherCallbackAsserter assertNoCallbackCalled() {
930 verify(mCallback, times(0)).onShortcutsChanged(
931 anyString(),
932 any(List.class),
933 any(UserHandle.class));
934 return this;
935 }
936
937 public LauncherCallbackAsserter assertNoCallbackCalledForPackage(
938 String publisherPackageName) {
939 verify(mCallback, times(0)).onShortcutsChanged(
940 eq(publisherPackageName),
941 any(List.class),
942 any(UserHandle.class));
943 return this;
944 }
945
946 public LauncherCallbackAsserter assertNoCallbackCalledForPackageAndUser(
947 String publisherPackageName, UserHandle publisherUserHandle) {
948 verify(mCallback, times(0)).onShortcutsChanged(
949 eq(publisherPackageName),
950 any(List.class),
951 eq(publisherUserHandle));
952 return this;
953 }
954
955 public ShortcutListAsserter assertCallbackCalledForPackageAndUser(
956 String publisherPackageName, UserHandle publisherUserHandle) {
957 final ArgumentCaptor<List> shortcuts = ArgumentCaptor.forClass(List.class);
958 verify(mCallback, times(1)).onShortcutsChanged(
959 eq(publisherPackageName),
960 shortcuts.capture(),
961 eq(publisherUserHandle));
962 return new ShortcutListAsserter(shortcuts.getValue());
963 }
964 }
965
966 public static LauncherCallbackAsserter assertForLauncherCallback(
967 LauncherApps launcherApps, Runnable body) throws InterruptedException {
968 final LauncherCallbackAsserter asserter = new LauncherCallbackAsserter();
969 launcherApps.registerCallback(asserter.getMockCallback(),
970 new Handler(Looper.getMainLooper()));
971
972 body.run();
973
974 waitOnMainThread();
975
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700976 // TODO unregister doesn't work well during unit tests. Figure out and fix it.
977 // launcherApps.unregisterCallback(asserter.getMockCallback());
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700978
Makoto Onukib08790c2016-06-23 14:05:46 -0700979 return asserter;
980 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700981}