1 /* 2 * Copyright (C) 2015 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 */ 16 17 package androidx.appcompat.testutils; 18 19 import static org.junit.Assert.assertEquals; 20 import static org.junit.Assert.assertTrue; 21 import static org.junit.Assert.fail; 22 23 import android.app.Instrumentation; 24 import android.content.Context; 25 import android.graphics.Bitmap; 26 import android.graphics.Canvas; 27 import android.graphics.Color; 28 import android.graphics.drawable.Drawable; 29 import android.os.ParcelFileDescriptor; 30 import android.os.SystemClock; 31 import android.view.InputDevice; 32 import android.view.MotionEvent; 33 import android.view.View; 34 import android.view.ViewConfiguration; 35 import android.view.ViewParent; 36 import android.view.ViewTreeObserver.OnDrawListener; 37 38 import androidx.annotation.ColorInt; 39 import androidx.annotation.RequiresApi; 40 import androidx.appcompat.widget.TintTypedArray; 41 import androidx.core.util.Pair; 42 import androidx.test.platform.app.InstrumentationRegistry; 43 import androidx.test.rule.ActivityTestRule; 44 45 import org.jspecify.annotations.NonNull; 46 import org.jspecify.annotations.Nullable; 47 48 import java.io.BufferedReader; 49 import java.io.IOException; 50 import java.io.InputStream; 51 import java.io.InputStreamReader; 52 import java.util.ArrayList; 53 import java.util.List; 54 import java.util.concurrent.CountDownLatch; 55 import java.util.concurrent.TimeUnit; 56 57 public class TestUtils { 58 /** 59 * This method takes a view and returns a single bitmap that is the layered combination 60 * of background drawables of this view and all its ancestors. It can be used to abstract 61 * away the specific implementation of a view hierarchy that is not exposed via class APIs 62 * or a view hierarchy that depends on the platform version. Instead of hard-coded lookups 63 * of particular inner implementations of such a view hierarchy that can break during 64 * refactoring or on newer platform versions, calling this API returns a "combined" background 65 * of the view. 66 * 67 * For example, it is useful to get the combined background of a popup / dropdown without 68 * delving into the inner implementation details of how that popup is implemented on a 69 * particular platform version. 70 */ getCombinedBackgroundBitmap(View view)71 public static Bitmap getCombinedBackgroundBitmap(View view) { 72 final int bitmapWidth = view.getWidth(); 73 final int bitmapHeight = view.getHeight(); 74 75 // Create a bitmap 76 final Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, 77 Bitmap.Config.ARGB_8888); 78 // Create a canvas that wraps the bitmap 79 final Canvas canvas = new Canvas(bitmap); 80 81 // As the draw pass starts at the top of view hierarchy, our first step is to traverse 82 // the ancestor hierarchy of our view and collect a list of all ancestors with non-null 83 // and visible backgrounds. At each step we're keeping track of the combined offsets 84 // so that we can properly combine all of the visuals together in the next pass. 85 List<View> ancestorsWithBackgrounds = new ArrayList<>(); 86 List<Pair<Integer, Integer>> ancestorOffsets = new ArrayList<>(); 87 int offsetX = 0; 88 int offsetY = 0; 89 while (true) { 90 final Drawable backgroundDrawable = view.getBackground(); 91 if ((backgroundDrawable != null) && backgroundDrawable.isVisible()) { 92 ancestorsWithBackgrounds.add(view); 93 ancestorOffsets.add(Pair.create(offsetX, offsetY)); 94 } 95 // Go to the parent 96 ViewParent parent = view.getParent(); 97 if (!(parent instanceof View)) { 98 // We're done traversing the ancestor chain 99 break; 100 } 101 102 // Update the offsets based on the location of current view in its parent's bounds 103 offsetX += view.getLeft(); 104 offsetY += view.getTop(); 105 106 view = (View) parent; 107 } 108 109 // Now we're going to iterate over the collected ancestors in reverse order (starting from 110 // the topmost ancestor) and draw their backgrounds into our combined bitmap. At each step 111 // we are respecting the offsets of our original view in the coordinate system of the 112 // currently drawn ancestor. 113 final int layerCount = ancestorsWithBackgrounds.size(); 114 for (int i = layerCount - 1; i >= 0; i--) { 115 View ancestor = ancestorsWithBackgrounds.get(i); 116 Pair<Integer, Integer> offsets = ancestorOffsets.get(i); 117 118 canvas.translate(offsets.first, offsets.second); 119 ancestor.getBackground().draw(canvas); 120 canvas.translate(-offsets.first, -offsets.second); 121 } 122 123 return bitmap; 124 } 125 126 /** 127 * Checks whether all the pixels in the specified drawable are of the same specified color. 128 * 129 * In case there is a color mismatch, the behavior of this method depends on the 130 * <code>throwExceptionIfFails</code> parameter. If it is <code>true</code>, this method will 131 * throw an <code>Exception</code> describing the mismatch. Otherwise this method will call 132 * <code>Assert.fail</code> with detailed description of the mismatch. 133 */ assertAllPixelsOfColor(String failMessagePrefix, @NonNull Drawable drawable, int drawableWidth, int drawableHeight, boolean callSetBounds, @ColorInt int color, int allowedComponentVariance, boolean throwExceptionIfFails)134 public static void assertAllPixelsOfColor(String failMessagePrefix, @NonNull Drawable drawable, 135 int drawableWidth, int drawableHeight, boolean callSetBounds, @ColorInt int color, 136 int allowedComponentVariance, boolean throwExceptionIfFails) { 137 // Create a bitmap 138 Bitmap bitmap = Bitmap.createBitmap(drawableWidth, drawableHeight, 139 Bitmap.Config.ARGB_8888); 140 // Create a canvas that wraps the bitmap 141 Canvas canvas = new Canvas(bitmap); 142 if (callSetBounds) { 143 // Configure the drawable to have bounds that match the passed size 144 drawable.setBounds(0, 0, drawableWidth, drawableHeight); 145 } 146 // And ask the drawable to draw itself to the canvas / bitmap 147 drawable.draw(canvas); 148 149 try { 150 assertAllPixelsOfColor(failMessagePrefix, bitmap, drawableWidth, drawableHeight, color, 151 allowedComponentVariance, throwExceptionIfFails); 152 } finally { 153 bitmap.recycle(); 154 } 155 } 156 157 /** 158 * Checks whether all the pixels in the specified bitmap are of the same specified color. 159 * 160 * In case there is a color mismatch, the behavior of this method depends on the 161 * <code>throwExceptionIfFails</code> parameter. If it is <code>true</code>, this method will 162 * throw an <code>Exception</code> describing the mismatch. Otherwise this method will call 163 * <code>Assert.fail</code> with detailed description of the mismatch. 164 */ assertAllPixelsOfColor(String failMessagePrefix, @NonNull Bitmap bitmap, int bitmapWidth, int bitmapHeight, @ColorInt int color, int allowedComponentVariance, boolean throwExceptionIfFails)165 public static void assertAllPixelsOfColor(String failMessagePrefix, @NonNull Bitmap bitmap, 166 int bitmapWidth, int bitmapHeight, @ColorInt int color, 167 int allowedComponentVariance, boolean throwExceptionIfFails) { 168 int[] rowPixels = new int[bitmapWidth]; 169 for (int row = 0; row < bitmapHeight; row++) { 170 bitmap.getPixels(rowPixels, 0, bitmapWidth, 0, row, bitmapWidth, 1); 171 for (int column = 0; column < bitmapWidth; column++) { 172 @ColorInt int colorAtCurrPixel = rowPixels[column]; 173 if (!areColorsTheSameWithTolerance(color, colorAtCurrPixel, 174 allowedComponentVariance)) { 175 String mismatchDescription = failMessagePrefix 176 + ": expected all drawable colors to be " 177 + formatColorToHex(color) 178 + " but at position (" + row + "," + column + ") out of (" 179 + bitmapWidth + "," + bitmapHeight + ") found " 180 + formatColorToHex(colorAtCurrPixel); 181 if (throwExceptionIfFails) { 182 throw new RuntimeException(mismatchDescription); 183 } else { 184 fail(mismatchDescription); 185 } 186 } 187 } 188 } 189 } 190 191 /** 192 * Checks whether the center pixel in the specified drawable is of the same specified color. 193 * 194 * In case there is a color mismatch, the behavior of this method depends on the 195 * <code>throwExceptionIfFails</code> parameter. If it is <code>true</code>, this method will 196 * throw an <code>Exception</code> describing the mismatch. Otherwise this method will call 197 * <code>Assert.fail</code> with detailed description of the mismatch. 198 */ assertCenterPixelOfColor(String failMessagePrefix, @NonNull Drawable drawable, int drawableWidth, int drawableHeight, boolean callSetBounds, @ColorInt int color, int allowedComponentVariance, boolean throwExceptionIfFails)199 public static void assertCenterPixelOfColor(String failMessagePrefix, @NonNull Drawable drawable, 200 int drawableWidth, int drawableHeight, boolean callSetBounds, @ColorInt int color, 201 int allowedComponentVariance, boolean throwExceptionIfFails) { 202 // Create a bitmap 203 Bitmap bitmap = Bitmap.createBitmap(drawableWidth, drawableHeight, Bitmap.Config.ARGB_8888); 204 // Create a canvas that wraps the bitmap 205 Canvas canvas = new Canvas(bitmap); 206 if (callSetBounds) { 207 // Configure the drawable to have bounds that match the passed size 208 drawable.setBounds(0, 0, drawableWidth, drawableHeight); 209 } 210 // And ask the drawable to draw itself to the canvas / bitmap 211 drawable.draw(canvas); 212 213 try { 214 assertCenterPixelOfColor(failMessagePrefix, bitmap, color, allowedComponentVariance, 215 throwExceptionIfFails); 216 } finally { 217 bitmap.recycle(); 218 } 219 } 220 221 /** 222 * Checks whether the center pixel in the specified bitmap is of the same specified color. 223 * 224 * In case there is a color mismatch, the behavior of this method depends on the 225 * <code>throwExceptionIfFails</code> parameter. If it is <code>true</code>, this method will 226 * throw an <code>Exception</code> describing the mismatch. Otherwise this method will call 227 * <code>Assert.fail</code> with detailed description of the mismatch. 228 */ assertCenterPixelOfColor(String failMessagePrefix, @NonNull Bitmap bitmap, @ColorInt int color, int allowedComponentVariance, boolean throwExceptionIfFails)229 public static void assertCenterPixelOfColor(String failMessagePrefix, @NonNull Bitmap bitmap, 230 @ColorInt int color, int allowedComponentVariance, boolean throwExceptionIfFails) { 231 final int centerX = bitmap.getWidth() / 2; 232 final int centerY = bitmap.getHeight() / 2; 233 final @ColorInt int colorAtCenterPixel = bitmap.getPixel(centerX, centerY); 234 if (!areColorsTheSameWithTolerance(color, colorAtCenterPixel, 235 allowedComponentVariance)) { 236 String mismatchDescription = failMessagePrefix 237 + ": expected all drawable colors to be " 238 + formatColorToHex(color) 239 + " but at position (" + centerX + "," + centerY + ") out of (" 240 + bitmap.getWidth() + "," + bitmap.getHeight() + ") found " 241 + formatColorToHex(colorAtCenterPixel); 242 if (throwExceptionIfFails) { 243 throw new RuntimeException(mismatchDescription); 244 } else { 245 fail(mismatchDescription); 246 } 247 } 248 } 249 250 /** 251 * Formats the passed integer-packed color into the #AARRGGBB format. 252 */ formatColorToHex(@olorInt int color)253 private static String formatColorToHex(@ColorInt int color) { 254 return String.format("#%08X", (0xFFFFFFFF & color)); 255 } 256 257 /** 258 * Compares two integer-packed colors to be equal, each component within the specified 259 * allowed variance. Returns <code>true</code> if the two colors are sufficiently equal 260 * and <code>false</code> otherwise. 261 */ areColorsTheSameWithTolerance(@olorInt int expectedColor, @ColorInt int actualColor, int allowedComponentVariance)262 private static boolean areColorsTheSameWithTolerance(@ColorInt int expectedColor, 263 @ColorInt int actualColor, int allowedComponentVariance) { 264 int sourceAlpha = Color.alpha(actualColor); 265 int sourceRed = Color.red(actualColor); 266 int sourceGreen = Color.green(actualColor); 267 int sourceBlue = Color.blue(actualColor); 268 269 int expectedAlpha = Color.alpha(expectedColor); 270 int expectedRed = Color.red(expectedColor); 271 int expectedGreen = Color.green(expectedColor); 272 int expectedBlue = Color.blue(expectedColor); 273 274 int varianceAlpha = Math.abs(sourceAlpha - expectedAlpha); 275 int varianceRed = Math.abs(sourceRed - expectedRed); 276 int varianceGreen = Math.abs(sourceGreen - expectedGreen); 277 int varianceBlue = Math.abs(sourceBlue - expectedBlue); 278 279 boolean isColorMatch = (varianceAlpha <= allowedComponentVariance) 280 && (varianceRed <= allowedComponentVariance) 281 && (varianceGreen <= allowedComponentVariance) 282 && (varianceBlue <= allowedComponentVariance); 283 284 return isColorMatch; 285 } 286 waitForActivityDestroyed(BaseTestActivity activity)287 public static void waitForActivityDestroyed(BaseTestActivity activity) { 288 while (!activity.isDestroyed()) { 289 SystemClock.sleep(30); 290 } 291 } 292 getThemeAttrColor(Context context, int attr)293 public static int getThemeAttrColor(Context context, int attr) { 294 final int[] attrs = { attr }; 295 TintTypedArray a = TintTypedArray.obtainStyledAttributes(context, null, attrs); 296 try { 297 return a.getColor(0, 0); 298 } finally { 299 a.recycle(); 300 } 301 } 302 303 /** 304 * Emulates a tap on a point relative to the top-left corner of the passed {@link View}. Offset 305 * parameters are used to compute the final screen coordinates of the tap point. 306 * 307 * @param instrumentation the instrumentation used to run the test 308 * @param anchorView the anchor view to determine the tap location on the screen 309 * @param offsetX extra X offset for the tap 310 * @param offsetY extra Y offset for the tap 311 */ emulateTapOnView(Instrumentation instrumentation, ActivityTestRule<?> activityTestRule, View anchorView, int offsetX, int offsetY)312 public static void emulateTapOnView(Instrumentation instrumentation, 313 ActivityTestRule<?> activityTestRule, View anchorView, 314 int offsetX, int offsetY) { 315 final int touchSlop = ViewConfiguration.get(anchorView.getContext()).getScaledTouchSlop(); 316 // Get anchor coordinates on the screen 317 final int[] viewOnScreenXY = new int[2]; 318 anchorView.getLocationOnScreen(viewOnScreenXY); 319 int xOnScreen = viewOnScreenXY[0] + offsetX; 320 int yOnScreen = viewOnScreenXY[1] + offsetY; 321 final long downTime = SystemClock.uptimeMillis(); 322 323 injectDownEvent(instrumentation, downTime, xOnScreen, yOnScreen); 324 injectMoveEventForTap(instrumentation, downTime, touchSlop, xOnScreen, yOnScreen); 325 injectUpEvent(instrumentation, downTime, false, xOnScreen, yOnScreen); 326 327 // Wait for the system to process all events in the queue 328 if (activityTestRule != null) { 329 runOnMainAndDrawSync(activityTestRule, 330 activityTestRule.getActivity().getWindow().getDecorView(), null); 331 } else { 332 instrumentation.waitForIdleSync(); 333 } 334 } 335 injectDownEvent(Instrumentation instrumentation, long downTime, int xOnScreen, int yOnScreen)336 private static long injectDownEvent(Instrumentation instrumentation, long downTime, 337 int xOnScreen, int yOnScreen) { 338 MotionEvent eventDown = MotionEvent.obtain( 339 downTime, downTime, MotionEvent.ACTION_DOWN, xOnScreen, yOnScreen, 1); 340 eventDown.setSource(InputDevice.SOURCE_TOUCHSCREEN); 341 instrumentation.sendPointerSync(eventDown); 342 eventDown.recycle(); 343 return downTime; 344 } 345 injectMoveEventForTap(Instrumentation instrumentation, long downTime, int touchSlop, int xOnScreen, int yOnScreen)346 private static void injectMoveEventForTap(Instrumentation instrumentation, long downTime, 347 int touchSlop, int xOnScreen, int yOnScreen) { 348 MotionEvent eventMove = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_MOVE, 349 xOnScreen + (touchSlop / 2.0f), yOnScreen + (touchSlop / 2.0f), 1); 350 eventMove.setSource(InputDevice.SOURCE_TOUCHSCREEN); 351 instrumentation.sendPointerSync(eventMove); 352 eventMove.recycle(); 353 } 354 355 injectUpEvent(Instrumentation instrumentation, long downTime, boolean useCurrentEventTime, int xOnScreen, int yOnScreen)356 private static void injectUpEvent(Instrumentation instrumentation, long downTime, 357 boolean useCurrentEventTime, int xOnScreen, int yOnScreen) { 358 long eventTime = useCurrentEventTime ? SystemClock.uptimeMillis() : downTime; 359 MotionEvent eventUp = MotionEvent.obtain( 360 downTime, eventTime, MotionEvent.ACTION_UP, xOnScreen, yOnScreen, 1); 361 eventUp.setSource(InputDevice.SOURCE_TOUCHSCREEN); 362 instrumentation.sendPointerSync(eventUp); 363 eventUp.recycle(); 364 } 365 366 /** 367 * Runs the specified {@link Runnable} on the main thread and ensures that the specified 368 * {@link View}'s tree is drawn before returning. 369 * 370 * @param activityTestRule the activity test rule used to run the test 371 * @param view the view whose tree should be drawn before returning 372 * @param runner the runnable to run on the main thread, or {@code null} to 373 * simply force invalidation and a draw pass 374 */ runOnMainAndDrawSync(final @NonNull ActivityTestRule activityTestRule, final @NonNull View view, final @Nullable Runnable runner)375 public static void runOnMainAndDrawSync(final @NonNull ActivityTestRule activityTestRule, 376 final @NonNull View view, final @Nullable Runnable runner) { 377 final CountDownLatch latch = new CountDownLatch(1); 378 379 try { 380 activityTestRule.runOnUiThread(new Runnable() { 381 @Override 382 public void run() { 383 // "Wrap" the OnDrawListener in a 1-element array so that we can access 384 // it for subsequent removal in the first onDraw pass 385 final OnDrawListener[] listener = new OnDrawListener[1]; 386 listener[0] = new OnDrawListener() { 387 @Override 388 public void onDraw() { 389 // posting so that the sync happens after the draw that's about to 390 // happen 391 view.post(new Runnable() { 392 @Override 393 public void run() { 394 activityTestRule.getActivity().getWindow().getDecorView() 395 .getViewTreeObserver().removeOnDrawListener( 396 listener[0]); 397 latch.countDown(); 398 } 399 }); 400 } 401 }; 402 403 activityTestRule.getActivity().getWindow().getDecorView() 404 .getViewTreeObserver().addOnDrawListener(listener[0]); 405 406 if (runner != null) { 407 runner.run(); 408 } 409 view.invalidate(); 410 } 411 }); 412 413 assertTrue("Expected draw pass occurred within 5 seconds", 414 latch.await(5, TimeUnit.SECONDS)); 415 } catch (Throwable t) { 416 throw new RuntimeException(t); 417 } 418 } 419 420 /** 421 * Executes the given shell command and returns true if any line matches the find predicate, or 422 * false otherwise. 423 * <p> 424 * Requires API 21+ due to UiAutomation.executeShellCommand() dependency. 425 */ 426 @RequiresApi(21) executeShellCommandAndFind(@onNull String cmd, @NonNull Predicate<String> find)427 public static boolean executeShellCommandAndFind(@NonNull String cmd, 428 @NonNull Predicate<String> find) throws IOException { 429 InputStream stdout = new ParcelFileDescriptor.AutoCloseInputStream( 430 InstrumentationRegistry.getInstrumentation() 431 .getUiAutomation().executeShellCommand(cmd)); 432 try (BufferedReader reader = new BufferedReader(new InputStreamReader(stdout))) { 433 String line; 434 while ((line = reader.readLine()) != null) { 435 if (find.test(line)) { 436 return true; 437 } 438 } 439 } 440 return false; 441 } 442 443 /** 444 * Substitute for Java 8 predicate until everyone moves to Java 8. 445 */ 446 public interface Predicate<T> { test(T t)447 boolean test(T t); 448 } 449 450 /** 451 * Asserts that the contents of two character sequences are equal, but does not consider their 452 * types. This is useful for comparing a String expected to a CharSequence actual. 453 * 454 * @param expected expected value 455 * @param actual actual value 456 */ assertContentEquals(@ullable CharSequence expected, @Nullable CharSequence actual)457 public static void assertContentEquals(@Nullable CharSequence expected, 458 @Nullable CharSequence actual) { 459 assertEquals( 460 expected != null ? expected.toString() : null, 461 actual != null ? actual.toString() : null 462 ); 463 } 464 } 465