blob: 78f95c4d217e8c2efc96244326462b6723570361 [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 Onuki9c850012016-07-26 15:50:50 -070058import org.json.JSONException;
59import org.json.JSONObject;
Makoto Onukib08790c2016-06-23 14:05:46 -070060import org.mockito.ArgumentCaptor;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070061import org.mockito.Mockito;
62
63import java.io.BufferedReader;
Makoto Onuki0b9d1db2016-07-18 14:16:41 -070064import java.io.File;
65import java.io.FileNotFoundException;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -070066import 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 Onuki9c850012016-07-26 15:50:50 -070091 private static final boolean ENABLE_DUMPSYS = true; // 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
Makoto Onuki0b9d1db2016-07-18 14:16:41 -0700100 public static List<String> readAll(File file) throws FileNotFoundException {
101 return readAll(ParcelFileDescriptor.open(
102 file.getAbsoluteFile(), ParcelFileDescriptor.MODE_READ_ONLY));
103 }
104
105 public static List<String> readAll(ParcelFileDescriptor pfd) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700106 try {
107 try {
108 final ArrayList<String> ret = new ArrayList<>();
109 try (BufferedReader r = new BufferedReader(
110 new FileReader(pfd.getFileDescriptor()))) {
111 String line;
112 while ((line = r.readLine()) != null) {
113 ret.add(line);
114 }
115 r.readLine();
116 }
117 return ret;
118 } finally {
119 pfd.close();
120 }
121 } catch (IOException e) {
122 throw new RuntimeException(e);
123 }
124 }
125
Makoto Onuki0b9d1db2016-07-18 14:16:41 -0700126 public static String concatResult(List<String> result) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700127 final StringBuilder sb = new StringBuilder();
128 for (String s : result) {
129 sb.append(s);
130 sb.append("\n");
131 }
132 return sb.toString();
133 }
134
Makoto Onuki0b9d1db2016-07-18 14:16:41 -0700135 public static boolean resultContains(List<String> result, String expected) {
136 for (String line : result) {
137 if (line.contains(expected)) {
138 return true;
139 }
140 }
141 return false;
142 }
143
144 public static List<String> assertSuccess(List<String> result) {
145 if (!resultContains(result, "Success")) {
146 fail("Command failed. Result was:\n" + concatResult(result));
147 }
148 return result;
149 }
150
151 public static List<String> assertContains(List<String> result, String expected) {
152 if (!resultContains(result, expected)) {
153 fail("Didn't contain expected string=" + expected
154 + "\nActual:\n" + concatResult(result));
155 }
156 return result;
157 }
158
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700159 private static List<String> runCommand(Instrumentation instrumentation, String command) {
160 return runCommand(instrumentation, command, null);
161 }
162 private static List<String> runCommand(Instrumentation instrumentation, String command,
163 Predicate<List<String>> resultAsserter) {
164 Log.d(TAG, "Running command: " + command);
165 final List<String> result;
166 try {
167 result = readAll(
168 instrumentation.getUiAutomation().executeShellCommand(command));
169 } catch (Exception e) {
170 throw new RuntimeException(e);
171 }
172 if (resultAsserter != null && !resultAsserter.test(result)) {
173 fail("Command '" + command + "' failed, output was:\n" + concatResult(result));
174 }
175 return result;
176 }
177
178 private static void runCommandForNoOutput(Instrumentation instrumentation, String command) {
179 runCommand(instrumentation, command, result -> result.size() == 0);
180 }
181
182 private static List<String> runShortcutCommand(Instrumentation instrumentation, String command,
183 Predicate<List<String>> resultAsserter) {
184 return runCommand(instrumentation, "cmd shortcut " + command, resultAsserter);
185 }
186
187 public static List<String> runShortcutCommandForSuccess(Instrumentation instrumentation,
188 String command) {
189 return runShortcutCommand(instrumentation, command, result -> result.contains("Success"));
190 }
191
192 public static String getDefaultLauncher(Instrumentation instrumentation) {
193 final String PREFIX = "Launcher: ComponentInfo{";
194 final String POSTFIX = "}";
195 final List<String> result = runShortcutCommandForSuccess(
196 instrumentation, "get-default-launcher");
197 for (String s : result) {
198 if (s.startsWith(PREFIX) && s.endsWith(POSTFIX)) {
199 return s.substring(PREFIX.length(), s.length() - POSTFIX.length());
200 }
201 }
202 fail("Default launcher not found");
203 return null;
204 }
205
206 public static void setDefaultLauncher(Instrumentation instrumentation, String component) {
Makoto Onuki3bdbf982016-06-23 16:56:35 -0700207 runCommand(instrumentation, "cmd package set-home-activity " + component,
208 result -> result.contains("Success"));
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700209 }
210
211 public static void setDefaultLauncher(Instrumentation instrumentation, Context packageContext) {
212 setDefaultLauncher(instrumentation, packageContext.getPackageName()
213 + "/android.content.pm.cts.shortcutmanager.packages.Launcher");
214 }
215
216 public static void overrideConfig(Instrumentation instrumentation, String config) {
217 runShortcutCommandForSuccess(instrumentation, "override-config " + config);
218 }
219
220 public static void resetConfig(Instrumentation instrumentation) {
221 runShortcutCommandForSuccess(instrumentation, "reset-config");
222 }
223
224 public static void resetThrottling(Instrumentation instrumentation) {
225 runShortcutCommandForSuccess(instrumentation, "reset-throttling");
226 }
227
228 public static void resetAllThrottling(Instrumentation instrumentation) {
229 runShortcutCommandForSuccess(instrumentation, "reset-all-throttling");
230 }
231
232 public static void clearShortcuts(Instrumentation instrumentation, int userId,
233 String packageName) {
234 runShortcutCommandForSuccess(instrumentation, "clear-shortcuts "
235 + " --user " + userId + " " + packageName);
236 }
237
Makoto Onuki9c850012016-07-26 15:50:50 -0700238 public static void anyContains(List<String> result, String expected) {
239 for (String l : result) {
240 if (l.contains(expected)) {
241 return;
242 }
243 }
244 fail("Result didn't contain '" + expected + "': was\n" + result);
245 }
246
247 public static void enableComponent(Instrumentation instrumentation, ComponentName cn,
248 boolean enable) {
249
250 final String word = (enable ? "enable" : "disable");
251 runCommand(instrumentation,
252 "pm " + word + " " + cn.flattenToString()
253 , result ->concatResult(result).contains(word));
254 }
255
256 public static void appOps(Instrumentation instrumentation, String packageName,
257 String op, String mode) {
258 runCommand(instrumentation, "appops set " + packageName + " " + op + " " + mode);
259 }
260
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700261 public static void dumpsysShortcut(Instrumentation instrumentation) {
262 if (!ENABLE_DUMPSYS) {
263 return;
264 }
Makoto Onuki3bdbf982016-06-23 16:56:35 -0700265 Log.e(TAG, "Dumpsys shortcut");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700266 for (String s : runCommand(instrumentation, "dumpsys shortcut")) {
267 Log.e(TAG, s);
268 }
269 }
270
Makoto Onuki9c850012016-07-26 15:50:50 -0700271 public static JSONObject getCheckinDump(Instrumentation instrumentation) throws JSONException {
272 return new JSONObject(concatResult(runCommand(instrumentation, "dumpsys shortcut -c")));
273 }
274
275 public static boolean isLowRamDevice(Instrumentation instrumentation) throws JSONException {
276 return getCheckinDump(instrumentation).getBoolean("lowRam");
277 }
278
279 public static int getIconSize(Instrumentation instrumentation) throws JSONException {
280 return getCheckinDump(instrumentation).getInt("iconSize");
281 }
282
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700283 public static Bundle makeBundle(Object... keysAndValues) {
284 assertTrue((keysAndValues.length % 2) == 0);
285
286 if (keysAndValues.length == 0) {
287 return null;
288 }
289 final Bundle ret = new Bundle();
290
291 for (int i = keysAndValues.length - 2; i >= 0; i -= 2) {
292 final String key = keysAndValues[i].toString();
293 final Object value = keysAndValues[i + 1];
294
295 if (value == null) {
296 ret.putString(key, null);
297 } else if (value instanceof Integer) {
298 ret.putInt(key, (Integer) value);
299 } else if (value instanceof String) {
300 ret.putString(key, (String) value);
301 } else if (value instanceof Bundle) {
302 ret.putBundle(key, (Bundle) value);
303 } else {
304 fail("Type not supported yet: " + value.getClass().getName());
305 }
306 }
307 return ret;
308 }
309
Makoto Onukib5a012f2016-06-21 11:13:53 -0700310 public static PersistableBundle makePersistableBundle(Object... keysAndValues) {
311 assertTrue((keysAndValues.length % 2) == 0);
312
313 if (keysAndValues.length == 0) {
314 return null;
315 }
316 final PersistableBundle ret = new PersistableBundle();
317
318 for (int i = keysAndValues.length - 2; i >= 0; i -= 2) {
319 final String key = keysAndValues[i].toString();
320 final Object value = keysAndValues[i + 1];
321
322 if (value == null) {
323 ret.putString(key, null);
324 } else if (value instanceof Integer) {
325 ret.putInt(key, (Integer) value);
326 } else if (value instanceof String) {
327 ret.putString(key, (String) value);
328 } else if (value instanceof PersistableBundle) {
329 ret.putPersistableBundle(key, (PersistableBundle) value);
330 } else {
331 fail("Type not supported yet: " + value.getClass().getName());
332 }
333 }
334 return ret;
335 }
336
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700337 public static <T> List<T> list(T... array) {
338 return Arrays.asList(array);
339 }
340
341 public static <T> Set<T> hashSet(Set<T> in) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700342 return new LinkedHashSet<>(in);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700343 }
344
345 public static <T> Set<T> set(T... values) {
346 return set(v -> v, values);
347 }
348
349 public static <T, V> Set<T> set(Function<V, T> converter, V... values) {
350 return set(converter, Arrays.asList(values));
351 }
352
353 public static <T, V> Set<T> set(Function<V, T> converter, List<V> values) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700354 final LinkedHashSet<T> ret = new LinkedHashSet<>();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700355 for (V v : values) {
356 ret.add(converter.apply(v));
357 }
358 return ret;
359 }
360
361 public static void resetAll(Collection<?> mocks) {
362 for (Object o : mocks) {
363 reset(o);
364 }
365 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700366
Makoto Onukidf6da042016-06-16 09:51:40 -0700367 public static <T extends Collection<?>> T assertEmpty(T collection) {
368 if (collection == null) {
369 return collection; // okay.
370 }
371 assertEquals(0, collection.size());
372 return collection;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700373 }
374
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700375 public static List<ShortcutInfo> filter(List<ShortcutInfo> list, Predicate<ShortcutInfo> p) {
376 final ArrayList<ShortcutInfo> ret = new ArrayList<>(list);
377 ret.removeIf(si -> !p.test(si));
378 return ret;
379 }
380
Makoto Onuki7001a612016-05-27 13:24:28 -0700381 public static List<ShortcutInfo> filterByActivity(List<ShortcutInfo> list,
382 ComponentName activity) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700383 return filter(list, si ->
384 (si.getActivity().equals(activity)
Makoto Onukib5a012f2016-06-21 11:13:53 -0700385 && (si.isDeclaredInManifest() || si.isDynamic())));
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700386 }
387
388 public static List<ShortcutInfo> changedSince(List<ShortcutInfo> list, long time) {
389 return filter(list, si -> si.getLastChangedTimestamp() >= time);
Makoto Onuki7001a612016-05-27 13:24:28 -0700390 }
391
Makoto Onuki0b9d1db2016-07-18 14:16:41 -0700392 @FunctionalInterface
393 public interface ExceptionRunnable {
394 void run() throws Exception;
395 }
396
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700397 public static void assertExpectException(Class<? extends Throwable> expectedExceptionType,
Makoto Onuki0b9d1db2016-07-18 14:16:41 -0700398 String expectedExceptionMessageRegex, ExceptionRunnable r) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700399 assertExpectException("", expectedExceptionType, expectedExceptionMessageRegex, r);
400 }
401
Makoto Onuki22fcc682016-05-17 14:52:19 -0700402 public static void assertCannotUpdateImmutable(Runnable r) {
403 assertExpectException(
Makoto Onuki0b9d1db2016-07-18 14:16:41 -0700404 IllegalArgumentException.class, "may not be manipulated via APIs", r::run);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700405 }
406
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700407 public static void assertDynamicShortcutCountExceeded(Runnable r) {
408 assertExpectException(IllegalArgumentException.class,
Makoto Onuki0b9d1db2016-07-18 14:16:41 -0700409 "Max number of dynamic shortcuts exceeded", r::run);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700410 }
411
412 public static void assertExpectException(String message,
413 Class<? extends Throwable> expectedExceptionType,
Makoto Onuki0b9d1db2016-07-18 14:16:41 -0700414 String expectedExceptionMessageRegex, ExceptionRunnable r) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700415 try {
416 r.run();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700417 } catch (Throwable e) {
418 Assert.assertTrue(
419 "Expected exception type was " + expectedExceptionType.getName()
420 + " but caught " + e + " (message=" + message + ")",
421 expectedExceptionType.isAssignableFrom(e.getClass()));
422 if (expectedExceptionMessageRegex != null) {
423 MoreAsserts.assertContainsRegex(expectedExceptionMessageRegex, e.getMessage());
424 }
Makoto Onukia1d38b32016-06-10 15:32:26 -0700425 return; // Pass
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700426 }
Makoto Onukia1d38b32016-06-10 15:32:26 -0700427 Assert.fail("Expected exception type " + expectedExceptionType.getName()
428 + " was not thrown");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700429 }
430
431 public static List<ShortcutInfo> assertShortcutIds(List<ShortcutInfo> actualShortcuts,
432 String... expectedIds) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700433 final SortedSet<String> expected = new TreeSet<>(list(expectedIds));
434 final SortedSet<String> actual = new TreeSet<>();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700435 for (ShortcutInfo s : actualShortcuts) {
436 actual.add(s.getId());
437 }
438
439 // Compare the sets.
440 assertEquals(expected, actual);
441 return actualShortcuts;
442 }
443
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700444 public static List<ShortcutInfo> assertShortcutIdsOrdered(List<ShortcutInfo> actualShortcuts,
445 String... expectedIds) {
446 final ArrayList<String> expected = new ArrayList<>(list(expectedIds));
447 final ArrayList<String> actual = new ArrayList<>();
448 for (ShortcutInfo s : actualShortcuts) {
449 actual.add(s.getId());
450 }
451 assertEquals(expected, actual);
452 return actualShortcuts;
453 }
454
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700455 public static List<ShortcutInfo> assertAllHaveIntents(
456 List<ShortcutInfo> actualShortcuts) {
457 for (ShortcutInfo s : actualShortcuts) {
458 assertNotNull("ID " + s.getId(), s.getIntent());
459 }
460 return actualShortcuts;
461 }
462
463 public static List<ShortcutInfo> assertAllNotHaveIntents(
464 List<ShortcutInfo> actualShortcuts) {
465 for (ShortcutInfo s : actualShortcuts) {
466 assertNull("ID " + s.getId(), s.getIntent());
467 }
468 return actualShortcuts;
469 }
470
471 public static List<ShortcutInfo> assertAllHaveTitle(
472 List<ShortcutInfo> actualShortcuts) {
473 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukieddbfec2016-05-31 17:04:34 -0700474 assertNotNull("ID " + s.getId(), s.getShortLabel());
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700475 }
476 return actualShortcuts;
477 }
478
479 public static List<ShortcutInfo> assertAllNotHaveTitle(
480 List<ShortcutInfo> actualShortcuts) {
481 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukieddbfec2016-05-31 17:04:34 -0700482 assertNull("ID " + s.getId(), s.getShortLabel());
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700483 }
484 return actualShortcuts;
485 }
486
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700487 public static List<ShortcutInfo> assertAllKeyFieldsOnly(
488 List<ShortcutInfo> actualShortcuts) {
489 for (ShortcutInfo s : actualShortcuts) {
490 assertTrue("ID " + s.getId(), s.hasKeyFieldsOnly());
491 }
492 return actualShortcuts;
493 }
494
495 public static List<ShortcutInfo> assertAllNotKeyFieldsOnly(
496 List<ShortcutInfo> actualShortcuts) {
497 for (ShortcutInfo s : actualShortcuts) {
498 assertFalse("ID " + s.getId(), s.hasKeyFieldsOnly());
499 }
500 return actualShortcuts;
501 }
502
503 public static List<ShortcutInfo> assertAllDynamic(List<ShortcutInfo> actualShortcuts) {
504 for (ShortcutInfo s : actualShortcuts) {
505 assertTrue("ID " + s.getId(), s.isDynamic());
506 }
507 return actualShortcuts;
508 }
509
510 public static List<ShortcutInfo> assertAllPinned(List<ShortcutInfo> actualShortcuts) {
511 for (ShortcutInfo s : actualShortcuts) {
512 assertTrue("ID " + s.getId(), s.isPinned());
513 }
514 return actualShortcuts;
515 }
516
517 public static List<ShortcutInfo> assertAllDynamicOrPinned(
518 List<ShortcutInfo> actualShortcuts) {
519 for (ShortcutInfo s : actualShortcuts) {
520 assertTrue("ID " + s.getId(), s.isDynamic() || s.isPinned());
521 }
522 return actualShortcuts;
523 }
524
Makoto Onuki22fcc682016-05-17 14:52:19 -0700525 public static List<ShortcutInfo> assertAllManifest(
526 List<ShortcutInfo> actualShortcuts) {
527 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700528 assertTrue("ID " + s.getId(), s.isDeclaredInManifest());
Makoto Onuki22fcc682016-05-17 14:52:19 -0700529 }
530 return actualShortcuts;
531 }
532
533 public static List<ShortcutInfo> assertAllNotManifest(
534 List<ShortcutInfo> actualShortcuts) {
535 for (ShortcutInfo s : actualShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700536 assertFalse("ID " + s.getId(), s.isDeclaredInManifest());
Makoto Onuki22fcc682016-05-17 14:52:19 -0700537 }
538 return actualShortcuts;
539 }
540
541 public static List<ShortcutInfo> assertAllDisabled(
542 List<ShortcutInfo> actualShortcuts) {
543 for (ShortcutInfo s : actualShortcuts) {
544 assertTrue("ID " + s.getId(), !s.isEnabled());
545 }
546 return actualShortcuts;
547 }
548
549 public static List<ShortcutInfo> assertAllEnabled(
550 List<ShortcutInfo> actualShortcuts) {
551 for (ShortcutInfo s : actualShortcuts) {
552 assertTrue("ID " + s.getId(), s.isEnabled());
553 }
554 return actualShortcuts;
555 }
556
557 public static List<ShortcutInfo> assertAllImmutable(
558 List<ShortcutInfo> actualShortcuts) {
559 for (ShortcutInfo s : actualShortcuts) {
560 assertTrue("ID " + s.getId(), s.isImmutable());
561 }
562 return actualShortcuts;
563 }
564
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700565 public static void assertDynamicOnly(ShortcutInfo si) {
566 assertTrue(si.isDynamic());
567 assertFalse(si.isPinned());
568 }
569
570 public static void assertPinnedOnly(ShortcutInfo si) {
571 assertFalse(si.isDynamic());
Makoto Onukib5a012f2016-06-21 11:13:53 -0700572 assertFalse(si.isDeclaredInManifest());
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700573 assertTrue(si.isPinned());
574 }
575
576 public static void assertDynamicAndPinned(ShortcutInfo si) {
577 assertTrue(si.isDynamic());
578 assertTrue(si.isPinned());
579 }
580
581 public static void assertBitmapSize(int expectedWidth, int expectedHeight, Bitmap bitmap) {
582 assertEquals("width", expectedWidth, bitmap.getWidth());
583 assertEquals("height", expectedHeight, bitmap.getHeight());
584 }
585
586 public static <T> void assertAllUnique(Collection<T> list) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700587 final Set<Object> set = new LinkedHashSet<>();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700588 for (T item : list) {
589 if (set.contains(item)) {
590 fail("Duplicate item found: " + item + " (in the list: " + list + ")");
591 }
592 set.add(item);
593 }
594 }
595
Makoto Onuki39686e82016-04-13 18:03:00 -0700596 public static ShortcutInfo findShortcut(List<ShortcutInfo> list, String id) {
597 for (ShortcutInfo si : list) {
598 if (si.getId().equals(id)) {
599 return si;
600 }
601 }
602 fail("Shortcut " + id + " not found in the list");
603 return null;
604 }
605
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700606 public static Bitmap pfdToBitmap(ParcelFileDescriptor pfd) {
607 assertNotNull(pfd);
608 try {
609 try {
610 return BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
611 } finally {
612 pfd.close();
613 }
614 } catch (IOException e) {
615 throw new RuntimeException(e);
616 }
617 }
618
619 public static void assertBundleEmpty(BaseBundle b) {
620 assertTrue(b == null || b.size() == 0);
621 }
622
623 public static void assertCallbackNotReceived(LauncherApps.Callback mock) {
624 verify(mock, times(0)).onShortcutsChanged(anyString(), anyList(),
625 any(UserHandle.class));
626 }
627
628 public static void assertCallbackReceived(LauncherApps.Callback mock,
629 UserHandle user, String packageName, String... ids) {
630 verify(mock).onShortcutsChanged(eq(packageName), checkShortcutIds(ids),
631 eq(user));
632 }
633
634 public static boolean checkAssertSuccess(Runnable r) {
635 try {
636 r.run();
637 return true;
638 } catch (AssertionError e) {
639 return false;
640 }
641 }
642
643 public static <T> T checkArgument(Predicate<T> checker, String description,
644 List<T> matchedCaptor) {
645 final Matcher<T> m = new BaseMatcher<T>() {
646 @Override
647 public boolean matches(Object item) {
648 if (item == null) {
649 return false;
650 }
651 final T value = (T) item;
652 if (!checker.test(value)) {
653 return false;
654 }
655
656 if (matchedCaptor != null) {
657 matchedCaptor.add(value);
658 }
659 return true;
660 }
661
662 @Override
663 public void describeTo(Description d) {
664 d.appendText(description);
665 }
666 };
667 return Mockito.argThat(m);
668 }
669
670 public static List<ShortcutInfo> checkShortcutIds(String... ids) {
671 return checkArgument((List<ShortcutInfo> list) -> {
672 final Set<String> actualSet = set(si -> si.getId(), list);
673 return actualSet.equals(set(ids));
674
675 }, "Shortcut IDs=[" + Arrays.toString(ids) + "]", null);
676 }
677
Makoto Onuki7001a612016-05-27 13:24:28 -0700678 public static ShortcutInfo parceled(ShortcutInfo si) {
679 Parcel p = Parcel.obtain();
680 p.writeParcelable(si, 0);
681 p.setDataPosition(0);
682 ShortcutInfo si2 = p.readParcelable(ShortcutManagerTestUtils.class.getClassLoader());
683 p.recycle();
684 return si2;
685 }
686
687 public static List<ShortcutInfo> cloneShortcutList(List<ShortcutInfo> list) {
688 if (list == null) {
689 return null;
690 }
691 final List<ShortcutInfo> ret = new ArrayList<>(list.size());
692 for (ShortcutInfo si : list) {
693 ret.add(parceled(si));
694 }
695
696 return ret;
697 }
698
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700699 private static final Comparator<ShortcutInfo> sRankComparator =
700 (ShortcutInfo a, ShortcutInfo b) -> Integer.compare(a.getRank(), b.getRank());
701
702 public static List<ShortcutInfo> sortedByRank(List<ShortcutInfo> shortcuts) {
703 final ArrayList<ShortcutInfo> ret = new ArrayList<>(shortcuts);
704 Collections.sort(ret, sRankComparator);
705 return ret;
706 }
707
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700708 public static void waitUntil(String message, BooleanSupplier condition) {
709 waitUntil(message, condition, STANDARD_TIMEOUT_SEC);
710 }
711
712 public static void waitUntil(String message, BooleanSupplier condition, int timeoutSeconds) {
713 final long timeout = System.currentTimeMillis() + (timeoutSeconds * 1000L);
714 while (System.currentTimeMillis() < timeout) {
715 if (condition.getAsBoolean()) {
716 return;
717 }
718 try {
719 Thread.sleep(100);
720 } catch (InterruptedException e) {
721 throw new RuntimeException(e);
722 }
723 }
724 fail("Timed out for: " + message);
725 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700726
727 public static ShortcutListAsserter assertWith(List<ShortcutInfo> list) {
728 return new ShortcutListAsserter(list);
729 }
730
731 /**
732 * New style assertion that allows chained calls.
733 */
734 public static class ShortcutListAsserter {
Makoto Onukidf6da042016-06-16 09:51:40 -0700735 private final ShortcutListAsserter mOriginal;
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700736 private final List<ShortcutInfo> mList;
737
738 ShortcutListAsserter(List<ShortcutInfo> list) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700739 this(null, list);
740 }
741
742 private ShortcutListAsserter(ShortcutListAsserter original, List<ShortcutInfo> list) {
Makoto Onukib08790c2016-06-23 14:05:46 -0700743 mOriginal = (original == null) ? this : original;
744 mList = (list == null) ? new ArrayList<>(0) : new ArrayList<>(list);
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700745 }
746
Makoto Onukidf6da042016-06-16 09:51:40 -0700747 public ShortcutListAsserter revertToOriginalList() {
748 return mOriginal;
749 }
750
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700751 public ShortcutListAsserter selectDynamic() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700752 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700753 filter(mList, ShortcutInfo::isDynamic));
754 }
755
756 public ShortcutListAsserter selectManifest() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700757 return new ShortcutListAsserter(this,
Makoto Onukib5a012f2016-06-21 11:13:53 -0700758 filter(mList, ShortcutInfo::isDeclaredInManifest));
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700759 }
760
761 public ShortcutListAsserter selectPinned() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700762 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700763 filter(mList, ShortcutInfo::isPinned));
764 }
765
766 public ShortcutListAsserter selectByActivity(ComponentName activity) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700767 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700768 ShortcutManagerTestUtils.filterByActivity(mList, activity));
769 }
770
771 public ShortcutListAsserter selectByChangedSince(long time) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700772 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700773 ShortcutManagerTestUtils.changedSince(mList, time));
774 }
775
Makoto Onukidf6da042016-06-16 09:51:40 -0700776 public ShortcutListAsserter selectByIds(String... ids) {
777 final Set<String> idSet = set(ids);
778 final ArrayList<ShortcutInfo> selected = new ArrayList<>();
779 for (ShortcutInfo si : mList) {
780 if (idSet.contains(si.getId())) {
781 selected.add(si);
782 idSet.remove(si.getId());
783 }
784 }
785 if (idSet.size() > 0) {
786 fail("Shortcuts not found for IDs=" + idSet);
787 }
788
789 return new ShortcutListAsserter(this, selected);
790 }
791
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700792 public ShortcutListAsserter toSortByRank() {
Makoto Onukidf6da042016-06-16 09:51:40 -0700793 return new ShortcutListAsserter(this,
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700794 ShortcutManagerTestUtils.sortedByRank(mList));
795 }
796
Makoto Onukidf6da042016-06-16 09:51:40 -0700797 public ShortcutListAsserter call(Consumer<List<ShortcutInfo>> c) {
798 c.accept(mList);
799 return this;
800 }
801
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700802 public ShortcutListAsserter haveIds(String... expectedIds) {
803 assertShortcutIds(mList, expectedIds);
804 return this;
805 }
806
807 public ShortcutListAsserter haveIdsOrdered(String... expectedIds) {
808 assertShortcutIdsOrdered(mList, expectedIds);
809 return this;
810 }
811
812 private ShortcutListAsserter haveSequentialRanks() {
813 for (int i = 0; i < mList.size(); i++) {
Makoto Onukidf6da042016-06-16 09:51:40 -0700814 final ShortcutInfo si = mList.get(i);
815 assertEquals("Rank not sequential: id=" + si.getId(), i, si.getRank());
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700816 }
817 return this;
818 }
819
820 public ShortcutListAsserter haveRanksInOrder(String... expectedIds) {
821 toSortByRank()
822 .haveSequentialRanks()
823 .haveIdsOrdered(expectedIds);
824 return this;
825 }
826
827 public ShortcutListAsserter isEmpty() {
828 assertEquals(0, mList.size());
829 return this;
830 }
Makoto Onukidf6da042016-06-16 09:51:40 -0700831
832 public ShortcutListAsserter areAllDynamic() {
833 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isDynamic()));
834 return this;
835 }
836
837 public ShortcutListAsserter areAllNotDynamic() {
838 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isDynamic()));
839 return this;
840 }
841
842 public ShortcutListAsserter areAllPinned() {
843 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isPinned()));
844 return this;
845 }
846
847 public ShortcutListAsserter areAllNotPinned() {
848 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isPinned()));
849 return this;
850 }
851
852 public ShortcutListAsserter areAllManifest() {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700853 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isDeclaredInManifest()));
Makoto Onukidf6da042016-06-16 09:51:40 -0700854 return this;
855 }
856
857 public ShortcutListAsserter areAllNotManifest() {
Makoto Onukib5a012f2016-06-21 11:13:53 -0700858 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isDeclaredInManifest()));
Makoto Onukidf6da042016-06-16 09:51:40 -0700859 return this;
860 }
861
862 public ShortcutListAsserter areAllImmutable() {
863 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isImmutable()));
864 return this;
865 }
866
867 public ShortcutListAsserter areAllMutable() {
868 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isImmutable()));
869 return this;
870 }
871
872 public ShortcutListAsserter areAllEnabled() {
873 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.isEnabled()));
874 return this;
875 }
876
877 public ShortcutListAsserter areAllDisabled() {
878 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.isEnabled()));
879 return this;
880 }
881
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700882 public ShortcutListAsserter areAllWithKeyFieldsOnly() {
883 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.hasKeyFieldsOnly()));
884 return this;
885 }
886
887 public ShortcutListAsserter areAllNotWithKeyFieldsOnly() {
888 forAllShortcuts(s -> assertFalse("id=" + s.getId(), s.hasKeyFieldsOnly()));
889 return this;
890 }
891
Makoto Onukib08790c2016-06-23 14:05:46 -0700892 public ShortcutListAsserter areAllWithActivity(ComponentName activity) {
893 forAllShortcuts(s -> assertTrue("id=" + s.getId(), s.getActivity().equals(activity)));
894 return this;
895 }
896
Makoto Onukidf6da042016-06-16 09:51:40 -0700897 public ShortcutListAsserter forAllShortcuts(Consumer<ShortcutInfo> sa) {
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700898 boolean found = false;
Makoto Onukidf6da042016-06-16 09:51:40 -0700899 for (int i = 0; i < mList.size(); i++) {
900 final ShortcutInfo si = mList.get(i);
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700901 found = true;
Makoto Onukidf6da042016-06-16 09:51:40 -0700902 sa.accept(si);
903 }
Makoto Onuki4d6b87f2016-06-17 13:47:40 -0700904 assertTrue("No shortcuts found.", found);
Makoto Onukidf6da042016-06-16 09:51:40 -0700905 return this;
906 }
907
908 public ShortcutListAsserter forShortcut(Predicate<ShortcutInfo> p,
909 Consumer<ShortcutInfo> sa) {
910 boolean found = false;
911 for (int i = 0; i < mList.size(); i++) {
912 final ShortcutInfo si = mList.get(i);
913 if (p.test(si)) {
914 found = true;
915 try {
916 sa.accept(si);
917 } catch (Throwable e) {
918 throw new AssertionError("Assertion failed for shortcut " + si.getId(), e);
919 }
920 }
921 }
922 assertTrue("Shortcut with the given condition not found.", found);
923 return this;
924 }
925
926 public ShortcutListAsserter forShortcutWithId(String id, Consumer<ShortcutInfo> sa) {
927 forShortcut(si -> si.getId().equals(id), sa);
928
929 return this;
930 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700931 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700932
933 public static void assertBundlesEqual(BaseBundle b1, BaseBundle b2) {
934 if (b1 == null && b2 == null) {
935 return; // pass
936 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700937 assertNotNull("b1 is null but b2 is not", b1);
938 assertNotNull("b2 is null but b1 is not", b2);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700939
940 // HashSet makes the error message readable.
941 assertEquals(set(b1.keySet()), set(b2.keySet()));
942
943 for (String key : b1.keySet()) {
944 final Object v1 = b1.get(key);
945 final Object v2 = b2.get(key);
946 if (v1 == null) {
947 if (v2 == null) {
948 return;
949 }
950 }
951 if (v1.equals(v2)) {
952 return;
953 }
954
955 assertTrue("Only either value is null: key=" + key
956 + " b1=" + b1 + " b2=" + b2, v1 != null && v2 != null);
957 assertEquals("Class mismatch: key=" + key, v1.getClass(), v2.getClass());
958
959 if (v1 instanceof BaseBundle) {
960 assertBundlesEqual((BaseBundle) v1, (BaseBundle) v2);
961
962 } else if (v1 instanceof boolean[]) {
963 assertTrue(Arrays.equals((boolean[]) v1, (boolean[]) v2));
964
965 } else if (v1 instanceof int[]) {
966 MoreAsserts.assertEquals((int[]) v1, (int[]) v2);
967
968 } else if (v1 instanceof double[]) {
969 MoreAsserts.assertEquals((double[]) v1, (double[]) v2);
970
971 } else if (v1 instanceof String[]) {
972 MoreAsserts.assertEquals((String[]) v1, (String[]) v2);
973
974 } else if (v1 instanceof Double) {
975 if (((Double) v1).isNaN()) {
976 assertTrue(((Double) v2).isNaN());
977 } else {
978 assertEquals(v1, v2);
979 }
980
981 } else {
982 assertEquals(v1, v2);
983 }
984 }
985 }
Makoto Onukib08790c2016-06-23 14:05:46 -0700986
987 public static void waitOnMainThread() throws InterruptedException {
988 final CountDownLatch latch = new CountDownLatch(1);
989
990 new Handler(Looper.getMainLooper()).post(() -> latch.countDown());
991
992 latch.await();
993 }
994
995 public static class LauncherCallbackAsserter {
996 private final LauncherApps.Callback mCallback = mock(LauncherApps.Callback.class);
997
998 private Callback getMockCallback() {
999 return mCallback;
1000 }
1001
1002 public LauncherCallbackAsserter assertNoCallbackCalled() {
1003 verify(mCallback, times(0)).onShortcutsChanged(
1004 anyString(),
1005 any(List.class),
1006 any(UserHandle.class));
1007 return this;
1008 }
1009
1010 public LauncherCallbackAsserter assertNoCallbackCalledForPackage(
1011 String publisherPackageName) {
1012 verify(mCallback, times(0)).onShortcutsChanged(
1013 eq(publisherPackageName),
1014 any(List.class),
1015 any(UserHandle.class));
1016 return this;
1017 }
1018
1019 public LauncherCallbackAsserter assertNoCallbackCalledForPackageAndUser(
1020 String publisherPackageName, UserHandle publisherUserHandle) {
1021 verify(mCallback, times(0)).onShortcutsChanged(
1022 eq(publisherPackageName),
1023 any(List.class),
1024 eq(publisherUserHandle));
1025 return this;
1026 }
1027
1028 public ShortcutListAsserter assertCallbackCalledForPackageAndUser(
1029 String publisherPackageName, UserHandle publisherUserHandle) {
1030 final ArgumentCaptor<List> shortcuts = ArgumentCaptor.forClass(List.class);
1031 verify(mCallback, times(1)).onShortcutsChanged(
1032 eq(publisherPackageName),
1033 shortcuts.capture(),
1034 eq(publisherUserHandle));
1035 return new ShortcutListAsserter(shortcuts.getValue());
1036 }
1037 }
1038
1039 public static LauncherCallbackAsserter assertForLauncherCallback(
1040 LauncherApps launcherApps, Runnable body) throws InterruptedException {
1041 final LauncherCallbackAsserter asserter = new LauncherCallbackAsserter();
1042 launcherApps.registerCallback(asserter.getMockCallback(),
1043 new Handler(Looper.getMainLooper()));
1044
1045 body.run();
1046
1047 waitOnMainThread();
1048
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001049 // TODO unregister doesn't work well during unit tests. Figure out and fix it.
1050 // launcherApps.unregisterCallback(asserter.getMockCallback());
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001051
Makoto Onukib08790c2016-06-23 14:05:46 -07001052 return asserter;
1053 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001054
1055 public static void retryUntil(BooleanSupplier checker, String message) {
1056 final long timeOut = System.currentTimeMillis() + 30 * 1000; // wait for 30 seconds.
1057 while (!checker.getAsBoolean()) {
Makoto Onukia210ccf2016-07-27 14:08:48 -07001058 if (System.currentTimeMillis() > timeOut) {
1059 break;
1060 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001061 try {
1062 Thread.sleep(200);
1063 } catch (InterruptedException ignore) {
1064 }
1065 }
1066 assertTrue(message, checker.getAsBoolean());
1067 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07001068}