blob: 7d7285a24a044a743e9faa5293e8a73f9149889b [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;
Makoto Onukib5a012f2016-06-21 11:13:53 -070021import static junit.framework.Assert.assertNotSame;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070022import static junit.framework.Assert.assertNull;
23import static junit.framework.Assert.assertTrue;
24import static junit.framework.Assert.fail;
25
26import static org.mockito.Matchers.any;
Makoto Onukib08790c2016-06-23 14:05:46 -070027import static org.mockito.Matchers.anyInt;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070028import static org.mockito.Matchers.anyList;
29import static org.mockito.Matchers.anyString;
30import static org.mockito.Matchers.eq;
Makoto Onukib08790c2016-06-23 14:05:46 -070031import static org.mockito.Mockito.mock;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070032import static org.mockito.Mockito.reset;
33import static org.mockito.Mockito.times;
34import static org.mockito.Mockito.verify;
35
36import android.app.Instrumentation;
Makoto Onuki7001a612016-05-27 13:24:28 -070037import android.content.ComponentName;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070038import android.content.Context;
39import android.content.pm.LauncherApps;
Makoto Onukib08790c2016-06-23 14:05:46 -070040import android.content.pm.LauncherApps.Callback;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070041import android.content.pm.ShortcutInfo;
42import android.graphics.Bitmap;
43import android.graphics.BitmapFactory;
44import android.os.BaseBundle;
45import android.os.Bundle;
Makoto Onukib08790c2016-06-23 14:05:46 -070046import android.os.Handler;
47import android.os.Looper;
Makoto Onuki7001a612016-05-27 13:24:28 -070048import android.os.Parcel;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070049import android.os.ParcelFileDescriptor;
Makoto Onukib5a012f2016-06-21 11:13:53 -070050import android.os.PersistableBundle;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070051import android.os.UserHandle;
52import android.test.MoreAsserts;
Makoto Onukidf6da042016-06-16 09:51:40 -070053import android.util.ArraySet;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070054import android.util.Log;
55
56import junit.framework.Assert;
Makoto Onukidf6da042016-06-16 09:51:40 -070057import junit.framework.AssertionFailedError;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070058
59import org.hamcrest.BaseMatcher;
60import org.hamcrest.Description;
61import org.hamcrest.Matcher;
Makoto Onukib08790c2016-06-23 14:05:46 -070062import org.mockito.ArgumentCaptor;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070063import org.mockito.Mockito;
64
65import java.io.BufferedReader;
66import java.io.FileReader;
67import java.io.IOException;
68import java.util.ArrayList;
69import java.util.Arrays;
70import java.util.Collection;
Makoto Onuki9e1f5592016-06-08 12:30:23 -070071import java.util.Collections;
72import java.util.Comparator;
73import java.util.LinkedHashSet;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070074import java.util.List;
75import java.util.Set;
Makoto Onuki9e1f5592016-06-08 12:30:23 -070076import java.util.SortedSet;
77import java.util.TreeSet;
Makoto Onukib08790c2016-06-23 14:05:46 -070078import java.util.concurrent.CountDownLatch;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070079import java.util.function.BooleanSupplier;
Makoto Onukidf6da042016-06-16 09:51:40 -070080import java.util.function.Consumer;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070081import java.util.function.Function;
82import java.util.function.Predicate;
83
Makoto Onuki51ab2b32016-06-02 11:03:51 -070084/**
85 * Common utility methods for ShortcutManager tests. This is used by both CTS and the unit tests.
86 * Because it's used by CTS too, it can only access the public APIs.
87 */
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070088public class ShortcutManagerTestUtils {
89 private static final String TAG = "ShortcutManagerUtils";
90
Makoto Onuki9e1f5592016-06-08 12:30:23 -070091 private static final boolean ENABLE_DUMPSYS = false; // DO NOT SUBMIT WITH true
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070092
93 private static final int STANDARD_TIMEOUT_SEC = 5;
94
Makoto Onuki9e1f5592016-06-08 12:30:23 -070095 private static final String[] EMPTY_STRINGS = new String[0];
96
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070097 private ShortcutManagerTestUtils() {
98 }
99
100 private static List<String> readAll(ParcelFileDescriptor pfd) {
101 try {
102 try {
103 final ArrayList<String> ret = new ArrayList<>();
104 try (BufferedReader r = new BufferedReader(
105 new FileReader(pfd.getFileDescriptor()))) {
106 String line;
107 while ((line = r.readLine()) != null) {
108 ret.add(line);
109 }
110 r.readLine();
111 }
112 return ret;
113 } finally {
114 pfd.close();
115 }
116 } catch (IOException e) {
117 throw new RuntimeException(e);
118 }
119 }
120
121 private static String concatResult(List<String> result) {
122 final StringBuilder sb = new StringBuilder();
123 for (String s : result) {
124 sb.append(s);
125 sb.append("\n");
126 }
127 return sb.toString();
128 }
129
130 private static List<String> runCommand(Instrumentation instrumentation, String command) {
131 return runCommand(instrumentation, command, null);
132 }
133 private static List<String> runCommand(Instrumentation instrumentation, String command,
134 Predicate<List<String>> resultAsserter) {
135 Log.d(TAG, "Running command: " + command);
136 final List<String> result;
137 try {
138 result = readAll(
139 instrumentation.getUiAutomation().executeShellCommand(command));
140 } catch (Exception e) {
141 throw new RuntimeException(e);
142 }
143 if (resultAsserter != null && !resultAsserter.test(result)) {
144 fail("Command '" + command + "' failed, output was:\n" + concatResult(result));
145 }
146 return result;
147 }
148
149 private static void runCommandForNoOutput(Instrumentation instrumentation, String command) {
150 runCommand(instrumentation, command, result -> result.size() == 0);
151 }
152
153 private static List<String> runShortcutCommand(Instrumentation instrumentation, String command,
154 Predicate<List<String>> resultAsserter) {
155 return runCommand(instrumentation, "cmd shortcut " + command, resultAsserter);
156 }
157
158 public static List<String> runShortcutCommandForSuccess(Instrumentation instrumentation,
159 String command) {
160 return runShortcutCommand(instrumentation, command, result -> result.contains("Success"));
161 }
162
163 public static String getDefaultLauncher(Instrumentation instrumentation) {
164 final String PREFIX = "Launcher: ComponentInfo{";
165 final String POSTFIX = "}";
166 final List<String> result = runShortcutCommandForSuccess(
167 instrumentation, "get-default-launcher");
168 for (String s : result) {
169 if (s.startsWith(PREFIX) && s.endsWith(POSTFIX)) {
170 return s.substring(PREFIX.length(), s.length() - POSTFIX.length());
171 }
172 }
173 fail("Default launcher not found");
174 return null;
175 }
176
177 public static void setDefaultLauncher(Instrumentation instrumentation, String component) {
Makoto Onuki3bdbf982016-06-23 16:56:35 -0700178 runCommand(instrumentation, "cmd package set-home-activity " + component,
179 result -> result.contains("Success"));
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700180 }
181
182 public static void setDefaultLauncher(Instrumentation instrumentation, Context packageContext) {
183 setDefaultLauncher(instrumentation, packageContext.getPackageName()
184 + "/android.content.pm.cts.shortcutmanager.packages.Launcher");
185 }
186
187 public static void overrideConfig(Instrumentation instrumentation, String config) {
188 runShortcutCommandForSuccess(instrumentation, "override-config " + config);
189 }
190
191 public static void resetConfig(Instrumentation instrumentation) {
192 runShortcutCommandForSuccess(instrumentation, "reset-config");
193 }
194
195 public static void resetThrottling(Instrumentation instrumentation) {
196 runShortcutCommandForSuccess(instrumentation, "reset-throttling");
197 }
198
199 public static void resetAllThrottling(Instrumentation instrumentation) {
200 runShortcutCommandForSuccess(instrumentation, "reset-all-throttling");
201 }
202
203 public static void clearShortcuts(Instrumentation instrumentation, int userId,
204 String packageName) {
205 runShortcutCommandForSuccess(instrumentation, "clear-shortcuts "
206 + " --user " + userId + " " + packageName);
207 }
208
209 public static void dumpsysShortcut(Instrumentation instrumentation) {
210 if (!ENABLE_DUMPSYS) {
211 return;
212 }
Makoto Onuki3bdbf982016-06-23 16:56:35 -0700213 Log.e(TAG, "Dumpsys shortcut");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700214 for (String s : runCommand(instrumentation, "dumpsys shortcut")) {
215 Log.e(TAG, s);
216 }
217 }
218
219 public static Bundle makeBundle(Object... keysAndValues) {
220 assertTrue((keysAndValues.length % 2) == 0);
221
222 if (keysAndValues.length == 0) {
223 return null;
224 }
225 final Bundle ret = new Bundle();
226
227 for (int i = keysAndValues.length - 2; i >= 0; i -= 2) {
228 final String key = keysAndValues[i].toString();
229 final Object value = keysAndValues[i + 1];
230
231 if (value == null) {
232 ret.putString(key, null);
233 } else if (value instanceof Integer) {
234 ret.putInt(key, (Integer) value);
235 } else if (value instanceof String) {
236 ret.putString(key, (String) value);
237 } else if (value instanceof Bundle) {
238 ret.putBundle(key, (Bundle) value);
239 } else {
240 fail("Type not supported yet: " + value.getClass().getName());
241 }
242 }
243 return ret;
244 }
245
Makoto Onukib5a012f2016-06-21 11:13:53 -0700246 public static PersistableBundle makePersistableBundle(Object... keysAndValues) {
247 assertTrue((keysAndValues.length % 2) == 0);
248
249 if (keysAndValues.length == 0) {
250 return null;
251 }
252 final PersistableBundle ret = new PersistableBundle();
253
254 for (int i = keysAndValues.length - 2; i >= 0; i -= 2) {
255 final String key = keysAndValues[i].toString();
256 final Object value = keysAndValues[i + 1];
257
258 if (value == null) {
259 ret.putString(key, null);
260 } else if (value instanceof Integer) {
261 ret.putInt(key, (Integer) value);
262 } else if (value instanceof String) {
263 ret.putString(key, (String) value);
264 } else if (value instanceof PersistableBundle) {
265 ret.putPersistableBundle(key, (PersistableBundle) value);
266 } else {
267 fail("Type not supported yet: " + value.getClass().getName());
268 }
269 }
270 return ret;
271 }
272
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700273 public static <T> List<T> list(T... array) {
274 return Arrays.asList(array);
275 }
276
277 public static <T> Set<T> hashSet(Set<T> in) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700278 return new LinkedHashSet<>(in);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700279 }
280
281 public static <T> Set<T> set(T... values) {
282 return set(v -> v, values);
283 }
284
285 public static <T, V> Set<T> set(Function<V, T> converter, V... values) {
286 return set(converter, Arrays.asList(values));
287 }
288
289 public static <T, V> Set<T> set(Function<V, T> converter, List<V> values) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700290 final LinkedHashSet<T> ret = new LinkedHashSet<>();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700291 for (V v : values) {
292 ret.add(converter.apply(v));
293 }
294 return ret;
295 }
296
297 public static void resetAll(Collection<?> mocks) {
298 for (Object o : mocks) {
299 reset(o);
300 }
301 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700302
Makoto Onukidf6da042016-06-16 09:51:40 -0700303 public static <T extends Collection<?>> T assertEmpty(T collection) {
304 if (collection == null) {
305 return collection; // okay.
306 }
307 assertEquals(0, collection.size());
308 return collection;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700309 }
310
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700311 public static List<ShortcutInfo> filter(List<ShortcutInfo> list, Predicate<ShortcutInfo> p) {
312 final ArrayList<ShortcutInfo> ret = new ArrayList<>(list);
313 ret.removeIf(si -> !p.test(si));
314 return ret;
315 }
316
Makoto Onuki7001a612016-05-27 13:24:28 -0700317 public static List<ShortcutInfo> filterByActivity(List<ShortcutInfo> list,
318 ComponentName activity) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700319 return filter(list, si ->
320 (si.getActivity().equals(activity)
Makoto Onukib5a012f2016-06-21 11:13:53 -0700321 && (si.isDeclaredInManifest() || si.isDynamic())));
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700322 }
323
324 public static List<ShortcutInfo> changedSince(List<ShortcutInfo> list, long time) {
325 return filter(list, si -> si.getLastChangedTimestamp() >= time);
Makoto Onuki7001a612016-05-27 13:24:28 -0700326 }
327
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700328 public static void assertExpectException(Class<? extends Throwable> expectedExceptionType,
329 String expectedExceptionMessageRegex, Runnable r) {
330 assertExpectException("", expectedExceptionType, expectedExceptionMessageRegex, r);
331 }
332
Makoto Onuki22fcc682016-05-17 14:52:19 -0700333 public static void assertCannotUpdateImmutable(Runnable r) {
334 assertExpectException(
335 IllegalArgumentException.class, "may not be manipulated via APIs", r);
336 }
337
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700338 public static void assertDynamicShortcutCountExceeded(Runnable r) {
339 assertExpectException(IllegalArgumentException.class,
340 "Max number of dynamic shortcuts exceeded", r);
341 }
342
343 public static void assertExpectException(String message,
344 Class<? extends Throwable> expectedExceptionType,
345 String expectedExceptionMessageRegex, Runnable r) {
346 try {
347 r.run();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700348 } catch (Throwable e) {
349 Assert.assertTrue(
350 "Expected exception type was " + expectedExceptionType.getName()
351 + " but caught " + e + " (message=" + message + ")",
352 expectedExceptionType.isAssignableFrom(e.getClass()));
353 if (expectedExceptionMessageRegex != null) {
354 MoreAsserts.assertContainsRegex(expectedExceptionMessageRegex, e.getMessage());
355 }
Makoto Onukia1d38b32016-06-10 15:32:26 -0700356 return; // Pass
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700357 }
Makoto Onukia1d38b32016-06-10 15:32:26 -0700358 Assert.fail("Expected exception type " + expectedExceptionType.getName()
359 + " was not thrown");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700360 }
361
362 public static List<ShortcutInfo> assertShortcutIds(List<ShortcutInfo> actualShortcuts,
363 String... expectedIds) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700364 final SortedSet<String> expected = new TreeSet<>(list(expectedIds));
365 final SortedSet<String> actual = new TreeSet<>();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700366 for (ShortcutInfo s : actualShortcuts) {
367 actual.add(s.getId());
368 }
369
370 // Compare the sets.
371 assertEquals(expected, actual);
372 return actualShortcuts;
373 }
374
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700375 public static List<ShortcutInfo> assertShortcutIdsOrdered(List<ShortcutInfo> actualShortcuts,
376 String... expectedIds) {
377 final ArrayList<String> expected = new ArrayList<>(list(expectedIds));
378 final ArrayList<String> actual = new ArrayList<>();
379 for (ShortcutInfo s : actualShortcuts) {
380 actual.add(s.getId());
381 }
382 assertEquals(expected, actual);
383 return actualShortcuts;
384 }
385
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700386 public static List<ShortcutInfo> assertAllHaveIntents(
387 List<ShortcutInfo> actualShortcuts) {
388 for (ShortcutInfo s : actualShortcuts) {
389 assertNotNull("ID " + s.getId(), s.getIntent());
390 }
391 return actualShortcuts;
392 }
393
394 public static List<ShortcutInfo> assertAllNotHaveIntents(
395 List<ShortcutInfo> actualShortcuts) {
396 for (ShortcutInfo s : actualShortcuts) {
397 assertNull("ID " + s.getId(), s.getIntent());
398 }
399 return actualShortcuts;
400 }
401
402 public static List<ShortcutInfo> assertAllHaveTitle(
403 List<ShortcutInfo> actualShortcuts) {
404 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukieddbfec2016-05-31 17:04:34 -0700405 assertNotNull("ID " + s.getId(), s.getShortLabel());
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700406 }
407 return actualShortcuts;
408 }
409
410 public static List<ShortcutInfo> assertAllNotHaveTitle(
411 List<ShortcutInfo> actualShortcuts) {
412 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukieddbfec2016-05-31 17:04:34 -0700413 assertNull("ID " + s.getId(), s.getShortLabel());
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700414 }
415 return actualShortcuts;
416 }
417
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700418 public static List<ShortcutInfo> assertAllKeyFieldsOnly(
419 List<ShortcutInfo> actualShortcuts) {
420 for (ShortcutInfo s : actualShortcuts) {
421 assertTrue("ID " + s.getId(), s.hasKeyFieldsOnly());
422 }
423 return actualShortcuts;
424 }
425
426 public static List<ShortcutInfo> assertAllNotKeyFieldsOnly(
427 List<ShortcutInfo> actualShortcuts) {
428 for (ShortcutInfo s : actualShortcuts) {
429 assertFalse("ID " + s.getId(), s.hasKeyFieldsOnly());
430 }
431 return actualShortcuts;
432 }
433
434 public static List<ShortcutInfo> assertAllDynamic(List<ShortcutInfo> actualShortcuts) {
435 for (ShortcutInfo s : actualShortcuts) {
436 assertTrue("ID " + s.getId(), s.isDynamic());
437 }
438 return actualShortcuts;
439 }
440
441 public static List<ShortcutInfo> assertAllPinned(List<ShortcutInfo> actualShortcuts) {
442 for (ShortcutInfo s : actualShortcuts) {
443 assertTrue("ID " + s.getId(), s.isPinned());
444 }
445 return actualShortcuts;
446 }
447
448 public static List<ShortcutInfo> assertAllDynamicOrPinned(
449 List<ShortcutInfo> actualShortcuts) {
450 for (ShortcutInfo s : actualShortcuts) {
451 assertTrue("ID " + s.getId(), s.isDynamic() || s.isPinned());
452 }
453 return actualShortcuts;
454 }
455
Makoto Onuki22fcc682016-05-17 14:52:19 -0700456 public static List<ShortcutInfo> assertAllManifest(
457 List<ShortcutInfo> actualShortcuts) {
458 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700459 assertTrue("ID " + s.getId(), s.isDeclaredInManifest());
Makoto Onuki22fcc682016-05-17 14:52:19 -0700460 }
461 return actualShortcuts;
462 }
463
464 public static List<ShortcutInfo> assertAllNotManifest(
465 List<ShortcutInfo> actualShortcuts) {
466 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700467 assertFalse("ID " + s.getId(), s.isDeclaredInManifest());
Makoto Onuki22fcc682016-05-17 14:52:19 -0700468 }
469 return actualShortcuts;
470 }
471
472 public static List<ShortcutInfo> assertAllDisabled(
473 List<ShortcutInfo> actualShortcuts) {
474 for (ShortcutInfo s : actualShortcuts) {
475 assertTrue("ID " + s.getId(), !s.isEnabled());
476 }
477 return actualShortcuts;
478 }
479
480 public static List<ShortcutInfo> assertAllEnabled(
481 List<ShortcutInfo> actualShortcuts) {
482 for (ShortcutInfo s : actualShortcuts) {
483 assertTrue("ID " + s.getId(), s.isEnabled());
484 }
485 return actualShortcuts;
486 }
487
488 public static List<ShortcutInfo> assertAllImmutable(
489 List<ShortcutInfo> actualShortcuts) {
490 for (ShortcutInfo s : actualShortcuts) {
491 assertTrue("ID " + s.getId(), s.isImmutable());
492 }
493 return actualShortcuts;
494 }
495
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700496 public static void assertDynamicOnly(ShortcutInfo si) {
497 assertTrue(si.isDynamic());
498 assertFalse(si.isPinned());
499 }
500
501 public static void assertPinnedOnly(ShortcutInfo si) {
502 assertFalse(si.isDynamic());
Makoto Onukib5a012f2016-06-21 11:13:53 -0700503 assertFalse(si.isDeclaredInManifest());
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700504 assertTrue(si.isPinned());
505 }
506
507 public static void assertDynamicAndPinned(ShortcutInfo si) {
508 assertTrue(si.isDynamic());
509 assertTrue(si.isPinned());
510 }
511
512 public static void assertBitmapSize(int expectedWidth, int expectedHeight, Bitmap bitmap) {
513 assertEquals("width", expectedWidth, bitmap.getWidth());
514 assertEquals("height", expectedHeight, bitmap.getHeight());
515 }
516
517 public static <T> void assertAllUnique(Collection<T> list) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700518 final Set<Object> set = new LinkedHashSet<>();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700519 for (T item : list) {
520 if (set.contains(item)) {
521 fail("Duplicate item found: " + item + " (in the list: " + list + ")");
522 }
523 set.add(item);
524 }
525 }
526
Makoto Onuki39686e82016-04-13 18:03:00 -0700527 public static ShortcutInfo findShortcut(List<ShortcutInfo> list, String id) {
528 for (ShortcutInfo si : list) {
529 if (si.getId().equals(id)) {
530 return si;
531 }
532 }
533 fail("Shortcut " + id + " not found in the list");
534 return null;
535 }
536
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700537 public static Bitmap pfdToBitmap(ParcelFileDescriptor pfd) {
538 assertNotNull(pfd);
539 try {
540 try {
541 return BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
542 } finally {
543 pfd.close();
544 }
545 } catch (IOException e) {
546 throw new RuntimeException(e);
547 }
548 }
549
550 public static void assertBundleEmpty(BaseBundle b) {
551 assertTrue(b == null || b.size() == 0);
552 }
553
554 public static void assertCallbackNotReceived(LauncherApps.Callback mock) {
555 verify(mock, times(0)).onShortcutsChanged(anyString(), anyList(),
556 any(UserHandle.class));
557 }
558
559 public static void assertCallbackReceived(LauncherApps.Callback mock,
560 UserHandle user, String packageName, String... ids) {
561 verify(mock).onShortcutsChanged(eq(packageName), checkShortcutIds(ids),
562 eq(user));
563 }
564
565 public static boolean checkAssertSuccess(Runnable r) {
566 try {
567 r.run();
568 return true;
569 } catch (AssertionError e) {
570 return false;
571 }
572 }
573
574 public static <T> T checkArgument(Predicate<T> checker, String description,
575 List<T> matchedCaptor) {
576 final Matcher<T> m = new BaseMatcher<T>() {
577 @Override
578 public boolean matches(Object item) {
579 if (item == null) {
580 return false;
581 }
582 final T value = (T) item;
583 if (!checker.test(value)) {
584 return false;
585 }
586
587 if (matchedCaptor != null) {
588 matchedCaptor.add(value);
589 }
590 return true;
591 }
592
593 @Override
594 public void describeTo(Description d) {
595 d.appendText(description);
596 }
597 };
598 return Mockito.argThat(m);
599 }
600
601 public static List<ShortcutInfo> checkShortcutIds(String... ids) {
602 return checkArgument((List<ShortcutInfo> list) -> {
603 final Set<String> actualSet = set(si -> si.getId(), list);
604 return actualSet.equals(set(ids));
605
606 }, "Shortcut IDs=[" + Arrays.toString(ids) + "]", null);
607 }
608
Makoto Onuki7001a612016-05-27 13:24:28 -0700609 public static ShortcutInfo parceled(ShortcutInfo si) {
610 Parcel p = Parcel.obtain();
611 p.writeParcelable(si, 0);
612 p.setDataPosition(0);
613 ShortcutInfo si2 = p.readParcelable(ShortcutManagerTestUtils.class.getClassLoader());
614 p.recycle();
615 return si2;
616 }
617
618 public static List<ShortcutInfo> cloneShortcutList(List<ShortcutInfo> list) {
619 if (list == null) {
620 return null;
621 }
622 final List<ShortcutInfo> ret = new ArrayList<>(list.size());
623 for (ShortcutInfo si : list) {
624 ret.add(parceled(si));
625 }
626
627 return ret;
628 }
629
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700630 private static final Comparator<ShortcutInfo> sRankComparator =
631 (ShortcutInfo a, ShortcutInfo b) -> Integer.compare(a.getRank(), b.getRank());
632
633 public static List<ShortcutInfo> sortedByRank(List<ShortcutInfo> shortcuts) {
634 final ArrayList<ShortcutInfo> ret = new ArrayList<>(shortcuts);
635 Collections.sort(ret, sRankComparator);
636 return ret;
637 }
638
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700639 public static void waitUntil(String message, BooleanSupplier condition) {
640 waitUntil(message, condition, STANDARD_TIMEOUT_SEC);
641 }
642
643 public static void waitUntil(String message, BooleanSupplier condition, int timeoutSeconds) {
644 final long timeout = System.currentTimeMillis() + (timeoutSeconds * 1000L);
645 while (System.currentTimeMillis() < timeout) {
646 if (condition.getAsBoolean()) {
647 return;
648 }
649 try {
650 Thread.sleep(100);
651 } catch (InterruptedException e) {
652 throw new RuntimeException(e);
653 }
654 }
655 fail("Timed out for: " + message);
656 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700657
658 public static ShortcutListAsserter assertWith(List<ShortcutInfo> list) {
659 return new ShortcutListAsserter(list);
660 }
661
662 /**
663 * New style assertion that allows chained calls.
664 */
665 public static class ShortcutListAsserter {
Makoto Onukidf6da042016-06-16 09:51:40 -0700666 private final ShortcutListAsserter mOriginal;
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700667 private final List<ShortcutInfo> mList;
668
669 ShortcutListAsserter(List<ShortcutInfo> list) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700670 this(null, list);
671 }
672
673 private ShortcutListAsserter(ShortcutListAsserter original, List<ShortcutInfo> list) {
Makoto Onukib08790c2016-06-23 14:05:46 -0700674 mOriginal = (original == null) ? this : original;
675 mList = (list == null) ? new ArrayList<>(0) : new ArrayList<>(list);
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700676 }
677
Makoto Onukidf6da042016-06-16 09:51:40 -0700678 public ShortcutListAsserter revertToOriginalList() {
679 return mOriginal;
680 }
681
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700682 public ShortcutListAsserter selectDynamic() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700683 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700684 filter(mList, ShortcutInfo::isDynamic));
685 }
686
687 public ShortcutListAsserter selectManifest() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700688 return new ShortcutListAsserter(this,
Makoto Onukib5a012f2016-06-21 11:13:53 -0700689 filter(mList, ShortcutInfo::isDeclaredInManifest));
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700690 }
691
692 public ShortcutListAsserter selectPinned() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700693 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700694 filter(mList, ShortcutInfo::isPinned));
695 }
696
697 public ShortcutListAsserter selectByActivity(ComponentName activity) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700698 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700699 ShortcutManagerTestUtils.filterByActivity(mList, activity));
700 }
701
702 public ShortcutListAsserter selectByChangedSince(long time) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700703 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700704 ShortcutManagerTestUtils.changedSince(mList, time));
705 }
706
Makoto Onukidf6da042016-06-16 09:51:40 -0700707 public ShortcutListAsserter selectByIds(String... ids) {
708 final Set<String> idSet = set(ids);
709 final ArrayList<ShortcutInfo> selected = new ArrayList<>();
710 for (ShortcutInfo si : mList) {
711 if (idSet.contains(si.getId())) {
712 selected.add(si);
713 idSet.remove(si.getId());
714 }
715 }
716 if (idSet.size() > 0) {
717 fail("Shortcuts not found for IDs=" + idSet);
718 }
719
720 return new ShortcutListAsserter(this, selected);
721 }
722
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700723 public ShortcutListAsserter toSortByRank() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700724 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700725 ShortcutManagerTestUtils.sortedByRank(mList));
726 }
727
Makoto Onukidf6da042016-06-16 09:51:40 -0700728 public ShortcutListAsserter call(Consumer<List<ShortcutInfo>> c) {
729 c.accept(mList);
730 return this;
731 }
732
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700733 public ShortcutListAsserter haveIds(String... expectedIds) {
734 assertShortcutIds(mList, expectedIds);
735 return this;
736 }
737
738 public ShortcutListAsserter haveIdsOrdered(String... expectedIds) {
739 assertShortcutIdsOrdered(mList, expectedIds);
740 return this;
741 }
742
743 private ShortcutListAsserter haveSequentialRanks() {
744 for (int i = 0; i < mList.size(); i++) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700745 final ShortcutInfo si = mList.get(i);
746 assertEquals("Rank not sequential: id=" + si.getId(), i, si.getRank());
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700747 }
748 return this;
749 }
750
751 public ShortcutListAsserter haveRanksInOrder(String... expectedIds) {
752 toSortByRank()
753 .haveSequentialRanks()
754 .haveIdsOrdered(expectedIds);
755 return this;
756 }
757
758 public ShortcutListAsserter isEmpty() {
759 assertEquals(0, mList.size());
760 return this;
761 }
Makoto Onukidf6da042016-06-16 09:51:40 -0700762
763 public ShortcutListAsserter areAllDynamic() {
764 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isDynamic()));
765 return this;
766 }
767
768 public ShortcutListAsserter areAllNotDynamic() {
769 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isDynamic()));
770 return this;
771 }
772
773 public ShortcutListAsserter areAllPinned() {
774 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isPinned()));
775 return this;
776 }
777
778 public ShortcutListAsserter areAllNotPinned() {
779 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isPinned()));
780 return this;
781 }
782
783 public ShortcutListAsserter areAllManifest() {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700784 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isDeclaredInManifest()));
Makoto Onukidf6da042016-06-16 09:51:40 -0700785 return this;
786 }
787
788 public ShortcutListAsserter areAllNotManifest() {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700789 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isDeclaredInManifest()));
Makoto Onukidf6da042016-06-16 09:51:40 -0700790 return this;
791 }
792
793 public ShortcutListAsserter areAllImmutable() {
794 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isImmutable()));
795 return this;
796 }
797
798 public ShortcutListAsserter areAllMutable() {
799 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isImmutable()));
800 return this;
801 }
802
803 public ShortcutListAsserter areAllEnabled() {
804 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isEnabled()));
805 return this;
806 }
807
808 public ShortcutListAsserter areAllDisabled() {
809 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isEnabled()));
810 return this;
811 }
812
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700813 public ShortcutListAsserter areAllWithKeyFieldsOnly() {
814 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.hasKeyFieldsOnly()));
815 return this;
816 }
817
818 public ShortcutListAsserter areAllNotWithKeyFieldsOnly() {
819 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.hasKeyFieldsOnly()));
820 return this;
821 }
822
Makoto Onukib08790c2016-06-23 14:05:46 -0700823 public ShortcutListAsserter areAllWithActivity(ComponentName activity) {
824 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.getActivity().equals(activity)));
825 return this;
826 }
827
Makoto Onukidf6da042016-06-16 09:51:40 -0700828 public ShortcutListAsserter forAllShortcuts(Consumer<ShortcutInfo> sa) {
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700829 boolean found = false;
Makoto Onukidf6da042016-06-16 09:51:40 -0700830 for (int i = 0; i < mList.size(); i++) {
831 final ShortcutInfo si = mList.get(i);
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700832 found = true;
Makoto Onukidf6da042016-06-16 09:51:40 -0700833 sa.accept(si);
834 }
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700835 assertTrue("No shortcuts found.", found);
Makoto Onukidf6da042016-06-16 09:51:40 -0700836 return this;
837 }
838
839 public ShortcutListAsserter forShortcut(Predicate<ShortcutInfo> p,
840 Consumer<ShortcutInfo> sa) {
841 boolean found = false;
842 for (int i = 0; i < mList.size(); i++) {
843 final ShortcutInfo si = mList.get(i);
844 if (p.test(si)) {
845 found = true;
846 try {
847 sa.accept(si);
848 } catch (Throwable e) {
849 throw new AssertionError("Assertion failed for shortcut " + si.getId(), e);
850 }
851 }
852 }
853 assertTrue("Shortcut with the given condition not found.", found);
854 return this;
855 }
856
857 public ShortcutListAsserter forShortcutWithId(String id, Consumer<ShortcutInfo> sa) {
858 forShortcut(si -> si.getId().equals(id), sa);
859
860 return this;
861 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700862 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700863
864 public static void assertBundlesEqual(BaseBundle b1, BaseBundle b2) {
865 if (b1 == null && b2 == null) {
866 return; // pass
867 }
868 assertNotNull(b1);
869 assertNotNull(b2);
870
871 // HashSet makes the error message readable.
872 assertEquals(set(b1.keySet()), set(b2.keySet()));
873
874 for (String key : b1.keySet()) {
875 final Object v1 = b1.get(key);
876 final Object v2 = b2.get(key);
877 if (v1 == null) {
878 if (v2 == null) {
879 return;
880 }
881 }
882 if (v1.equals(v2)) {
883 return;
884 }
885
886 assertTrue("Only either value is null: key=" + key
887 + " b1=" + b1 + " b2=" + b2, v1 != null && v2 != null);
888 assertEquals("Class mismatch: key=" + key, v1.getClass(), v2.getClass());
889
890 if (v1 instanceof BaseBundle) {
891 assertBundlesEqual((BaseBundle) v1, (BaseBundle) v2);
892
893 } else if (v1 instanceof boolean[]) {
894 assertTrue(Arrays.equals((boolean[]) v1, (boolean[]) v2));
895
896 } else if (v1 instanceof int[]) {
897 MoreAsserts.assertEquals((int[]) v1, (int[]) v2);
898
899 } else if (v1 instanceof double[]) {
900 MoreAsserts.assertEquals((double[]) v1, (double[]) v2);
901
902 } else if (v1 instanceof String[]) {
903 MoreAsserts.assertEquals((String[]) v1, (String[]) v2);
904
905 } else if (v1 instanceof Double) {
906 if (((Double) v1).isNaN()) {
907 assertTrue(((Double) v2).isNaN());
908 } else {
909 assertEquals(v1, v2);
910 }
911
912 } else {
913 assertEquals(v1, v2);
914 }
915 }
916 }
Makoto Onukib08790c2016-06-23 14:05:46 -0700917
918 public static void waitOnMainThread() throws InterruptedException {
919 final CountDownLatch latch = new CountDownLatch(1);
920
921 new Handler(Looper.getMainLooper()).post(() -> latch.countDown());
922
923 latch.await();
924 }
925
926 public static class LauncherCallbackAsserter {
927 private final LauncherApps.Callback mCallback = mock(LauncherApps.Callback.class);
928
929 private Callback getMockCallback() {
930 return mCallback;
931 }
932
933 public LauncherCallbackAsserter assertNoCallbackCalled() {
934 verify(mCallback, times(0)).onShortcutsChanged(
935 anyString(),
936 any(List.class),
937 any(UserHandle.class));
938 return this;
939 }
940
941 public LauncherCallbackAsserter assertNoCallbackCalledForPackage(
942 String publisherPackageName) {
943 verify(mCallback, times(0)).onShortcutsChanged(
944 eq(publisherPackageName),
945 any(List.class),
946 any(UserHandle.class));
947 return this;
948 }
949
950 public LauncherCallbackAsserter assertNoCallbackCalledForPackageAndUser(
951 String publisherPackageName, UserHandle publisherUserHandle) {
952 verify(mCallback, times(0)).onShortcutsChanged(
953 eq(publisherPackageName),
954 any(List.class),
955 eq(publisherUserHandle));
956 return this;
957 }
958
959 public ShortcutListAsserter assertCallbackCalledForPackageAndUser(
960 String publisherPackageName, UserHandle publisherUserHandle) {
961 final ArgumentCaptor<List> shortcuts = ArgumentCaptor.forClass(List.class);
962 verify(mCallback, times(1)).onShortcutsChanged(
963 eq(publisherPackageName),
964 shortcuts.capture(),
965 eq(publisherUserHandle));
966 return new ShortcutListAsserter(shortcuts.getValue());
967 }
968 }
969
970 public static LauncherCallbackAsserter assertForLauncherCallback(
971 LauncherApps launcherApps, Runnable body) throws InterruptedException {
972 final LauncherCallbackAsserter asserter = new LauncherCallbackAsserter();
973 launcherApps.registerCallback(asserter.getMockCallback(),
974 new Handler(Looper.getMainLooper()));
975
976 body.run();
977
978 waitOnMainThread();
979
980 return asserter;
981 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700982}