diff --git a/.github/workflows/instrumentation-test.yml b/.github/workflows/instrumentation-test.yml index 2ad3784..54f954f 100644 --- a/.github/workflows/instrumentation-test.yml +++ b/.github/workflows/instrumentation-test.yml @@ -80,7 +80,14 @@ jobs: arch: x86_64 disable-animations: true emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none - script: ./gradlew connectedAndroidTest --stacktrace + # android-emulator-runner runs every script line as a separate `sh -c`, so multi-line + # shell constructs (if/fi, variables carried across lines) do not work here. Keep the + # logcat diagnostics on a single line, preserving the Gradle exit status. The filtered + # logcat is always printed; the full logcat is only saved for upload on failure. Google API + # keys are redacted first: the Maps SDK logs the key on authorization failures, and secret + # masking does not apply to uploaded artifacts. + script: | + ./gradlew connectedAndroidTest --stacktrace; status=$?; echo "=== Filtered logcat (BaseVisualTest / Maps SDK) ==="; adb logcat -d | sed -E 's/AIza[0-9A-Za-z_-]{35}/[REDACTED]/g' | grep -iE "BaseVisualTest|Google Maps Android API|MapsInitializer|Authorization|API_KEY|VisualMapSampleTest|StoreLocator|GoogleApi|MapsDynamite" | tail -n 120; [ $status -eq 0 ] || adb logcat -d | sed -E 's/AIza[0-9A-Za-z_-]{35}/[REDACTED]/g' > emulator-logcat.txt; exit $status # Stage coverage reports flat, named after their module, for coverage-history.yml post-merge reuse - name: Stage coverage reports @@ -110,3 +117,4 @@ jobs: path: | */build/reports/androidTests/ */build/reports/coverage/ + emulator-logcat.txt diff --git a/app/src/androidTest/java/com/google/maps/android/testing/sample/VisualMapSampleTest.kt b/app/src/androidTest/java/com/google/maps/android/testing/sample/VisualMapSampleTest.kt index af4e4d4..175eb4e 100644 --- a/app/src/androidTest/java/com/google/maps/android/testing/sample/VisualMapSampleTest.kt +++ b/app/src/androidTest/java/com/google/maps/android/testing/sample/VisualMapSampleTest.kt @@ -41,9 +41,9 @@ class VisualMapSampleTest : BaseVisualTest() { } context.startActivity(intent) - // 2. Wait for application window to settle + // 2. Wait for application window and map tiles to finish rendering uiDevice.wait(Until.hasObject(By.pkg(context.packageName).depth(0)), 10000) - waitForMapRendering(timeoutSeconds = 5) + waitForMapRendering() // 3. Capture screenshot of current map state val screenshotBitmap = captureScreenshot("store_locator_screenshot.png") diff --git a/visual-testing/src/main/java/com/google/maps/android/testing/visual/BaseVisualTest.kt b/visual-testing/src/main/java/com/google/maps/android/testing/visual/BaseVisualTest.kt index 902e230..c8b2217 100644 --- a/visual-testing/src/main/java/com/google/maps/android/testing/visual/BaseVisualTest.kt +++ b/visual-testing/src/main/java/com/google/maps/android/testing/visual/BaseVisualTest.kt @@ -20,6 +20,7 @@ import android.app.Instrumentation import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory +import android.os.SystemClock import android.util.Log import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By @@ -119,16 +120,60 @@ abstract class BaseVisualTest { /** * Waits for MapView rendering to settle before taking a screenshot. + * + * Uses the full [timeoutSeconds] budget to wait for the map view to appear in the UI hierarchy + * and then polls screenshots of the map region until map tiles/overlays have rendered and + * stabilized across consecutive frames. */ protected fun waitForMapRendering(timeoutSeconds: Long = 30) { - // First check for accessibility presence - uiDevice.wait(Until.hasObject(By.descContains("Google Map")), 3000) + if (timeoutSeconds <= 0L) return + + val totalTimeoutMillis = TimeUnit.SECONDS.toMillis(timeoutSeconds) + val startMillis = SystemClock.elapsedRealtime() + val deadlineMillis = startMillis + totalTimeoutMillis + + // Wait for the Google Map accessibility node to appear within the full timeout budget + uiDevice.wait(Until.hasObject(By.descContains("Google Map")), totalTimeoutMillis) + + val remainingMillis = (deadlineMillis - SystemClock.elapsedRealtime()).coerceAtLeast(0L) + if (remainingMillis == 0L) { + Log.w("BaseVisualTest", "Timed out after ${timeoutSeconds}s waiting for Google Map view to appear.") + return + } - // Allow OpenGL / Vulkan tile drawing and vector overlay shaders to settle + val probeFile = File(context.cacheDir, "_map_readiness_probe.png") try { - TimeUnit.SECONDS.sleep(timeoutSeconds.coerceAtMost(5)) - } catch (e: InterruptedException) { - Thread.currentThread().interrupt() + val settled = MapRenderingReadiness.waitUntilSettled( + timeoutMillis = remainingMillis, + nowMillis = { SystemClock.elapsedRealtime() }, + sleepMillis = { millis -> + try { + Thread.sleep(millis) + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + } + }, + boundsProvider = { uiDevice.findObject(By.descContains("Google Map"))?.visibleBounds }, + captureFrame = { + probeFile.parentFile?.mkdirs() + if (uiDevice.takeScreenshot(probeFile)) { + BitmapFactory.decodeFile(probeFile.absolutePath) + } else { + null + } + }, + ) + val elapsedMillis = SystemClock.elapsedRealtime() - startMillis + if (settled) { + Log.i("BaseVisualTest", "Map rendering settled in ${elapsedMillis}ms.") + } else { + Log.w( + "BaseVisualTest", + "Map rendering did not settle within ${timeoutSeconds}s (${elapsedMillis}ms elapsed); proceeding with capture.", + ) + } + } finally { + probeFile.delete() } } diff --git a/visual-testing/src/main/java/com/google/maps/android/testing/visual/MapRenderingReadiness.kt b/visual-testing/src/main/java/com/google/maps/android/testing/visual/MapRenderingReadiness.kt new file mode 100644 index 0000000..5af3df1 --- /dev/null +++ b/visual-testing/src/main/java/com/google/maps/android/testing/visual/MapRenderingReadiness.kt @@ -0,0 +1,171 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.maps.android.testing.visual + +import android.graphics.Bitmap +import android.graphics.Rect + +/** + * Pure pixel-sampling heuristics for detecting when a Google Map surface has finished + * rendering tiles/overlays and settled between consecutive frames. + */ +internal object MapRenderingReadiness { + private const val GRID_STEPS = 16 + private const val EDGE_INSET_FRACTION = 0.15f + private const val MIN_INSET_DIMENSION_PX = 20 + private const val CHANNEL_QUANTIZATION_MASK = 0xF8 + private const val MIN_DISTINCT_COLOR_BUCKETS = 6 + private const val MIN_NON_DOMINANT_RATIO = 0.05 + private const val MIN_STABLE_SAMPLE_RATIO = 0.98 + + /** + * Returns `true` when the interior of [bounds] (or the full [bitmap] when [bounds] is null/empty) + * contains enough color diversity and non-background coverage to indicate rendered map tiles + * rather than a blank or grid-only loading surface. + */ + fun hasRenderedMapContent(bitmap: Bitmap, bounds: Rect? = null): Boolean { + val samples = sampleInteriorColors(bitmap, bounds) + if (samples.isEmpty()) return false + + val counts = HashMap() + var maxCount = 0 + for (color in samples) { + val updated = (counts[color] ?: 0) + 1 + counts[color] = updated + if (updated > maxCount) { + maxCount = updated + } + } + + val nonDominantRatio = (samples.size - maxCount).toDouble() / samples.size.toDouble() + return counts.size >= MIN_DISTINCT_COLOR_BUCKETS && nonDominantRatio >= MIN_NON_DOMINANT_RATIO + } + + /** + * Returns `true` when [previous] and [current] agree on at least 98% of sampled interior pixels, + * indicating that tile fade-ins and camera animations have settled. + */ + fun areFramesSettled(previous: Bitmap, current: Bitmap, bounds: Rect? = null): Boolean { + if (previous.width != current.width || previous.height != current.height) return false + val prevSamples = sampleInteriorColors(previous, bounds) + val currSamples = sampleInteriorColors(current, bounds) + if (prevSamples.isEmpty() || prevSamples.size != currSamples.size) return false + + var matching = 0 + for (i in prevSamples.indices) { + if (prevSamples[i] == currSamples[i]) { + matching++ + } + } + return matching.toDouble() / prevSamples.size.toDouble() >= MIN_STABLE_SAMPLE_RATIO + } + + /** + * Polls [captureFrame] until [hasRenderedMapContent] is true and two consecutive rendered frames + * satisfy [areFramesSettled], or until [timeoutMillis] elapses. + * + * Returns `true` if the map rendered and settled before the deadline, or `false` on timeout. + */ + fun waitUntilSettled( + timeoutMillis: Long, + pollIntervalMillis: Long = 500L, + nowMillis: () -> Long, + sleepMillis: (Long) -> Unit, + boundsProvider: () -> Rect?, + captureFrame: () -> Bitmap?, + ): Boolean { + if (timeoutMillis <= 0L) return false + + val deadline = nowMillis() + timeoutMillis + var previousRendered: Bitmap? = null + + try { + while (true) { + val current = captureFrame() + if (current != null) { + val bounds = boundsProvider() + if (hasRenderedMapContent(current, bounds)) { + val prev = previousRendered + if (prev != null && areFramesSettled(prev, current, bounds)) { + current.recycle() + return true + } + prev?.recycle() + previousRendered = current + } else { + previousRendered?.recycle() + previousRendered = null + current.recycle() + } + } + + val remaining = deadline - nowMillis() + if (remaining <= 0L) { + return false + } + sleepMillis(minOf(pollIntervalMillis, remaining)) + } + } finally { + previousRendered?.recycle() + } + } + + private fun sampleInteriorColors(bitmap: Bitmap, bounds: Rect?): IntArray { + val region = resolveInteriorRect(bitmap.width, bitmap.height, bounds) + val regionWidth = region.width() + val regionHeight = region.height() + if (regionWidth <= 0 || regionHeight <= 0) return IntArray(0) + + val stepsX = minOf(GRID_STEPS, regionWidth) + val stepsY = minOf(GRID_STEPS, regionHeight) + val samples = IntArray(stepsX * stepsY) + var index = 0 + + for (gy in 0 until stepsY) { + val y = region.top + ((gy + 0.5) * regionHeight / stepsY).toInt().coerceIn(0, regionHeight - 1) + for (gx in 0 until stepsX) { + val x = region.left + ((gx + 0.5) * regionWidth / stepsX).toInt().coerceIn(0, regionWidth - 1) + samples[index++] = quantizeRgb(bitmap.getPixel(x, y)) + } + } + return samples + } + + private fun resolveInteriorRect(width: Int, height: Int, bounds: Rect?): Rect { + val left = (bounds?.left ?: 0).coerceIn(0, width) + val top = (bounds?.top ?: 0).coerceIn(0, height) + val right = (bounds?.right ?: width).coerceIn(left, width) + val bottom = (bounds?.bottom ?: height).coerceIn(top, height) + + val regionWidth = right - left + val regionHeight = bottom - top + if (regionWidth < MIN_INSET_DIMENSION_PX || regionHeight < MIN_INSET_DIMENSION_PX) { + return Rect(left, top, right, bottom) + } + + val insetX = (regionWidth * EDGE_INSET_FRACTION).toInt() + val insetY = (regionHeight * EDGE_INSET_FRACTION).toInt() + return Rect(left + insetX, top + insetY, right - insetX, bottom - insetY) + } + + private fun quantizeRgb(argb: Int): Int { + val r = (argb ushr 16) and CHANNEL_QUANTIZATION_MASK + val g = (argb ushr 8) and CHANNEL_QUANTIZATION_MASK + val b = argb and CHANNEL_QUANTIZATION_MASK + return (r shl 16) or (g shl 8) or b + } +} diff --git a/visual-testing/src/test/java/com/google/maps/android/testing/visual/MapRenderingReadinessTest.kt b/visual-testing/src/test/java/com/google/maps/android/testing/visual/MapRenderingReadinessTest.kt new file mode 100644 index 0000000..9d657ba --- /dev/null +++ b/visual-testing/src/test/java/com/google/maps/android/testing/visual/MapRenderingReadinessTest.kt @@ -0,0 +1,193 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.maps.android.testing.visual + +import android.graphics.Bitmap +import android.graphics.Color +import android.graphics.Rect +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class MapRenderingReadinessTest { + + @Test + fun hasRenderedMapContent_blankSurface_returnsFalse() { + val blank = createSolidBitmap(Color.rgb(239, 236, 230)) + assertThat(MapRenderingReadiness.hasRenderedMapContent(blank)).isFalse() + blank.recycle() + } + + @Test + fun hasRenderedMapContent_watermarkOnlyInCorner_returnsFalse() { + val blankWithWatermark = createSolidBitmap(Color.rgb(239, 236, 230)) + // Draw multicolored Google logo / controls only inside the bottom-left 10% corner + val colors = listOf(Color.BLUE, Color.RED, Color.YELLOW, Color.GREEN, Color.BLACK, Color.CYAN) + colors.forEachIndexed { idx, color -> + fillRect(blankWithWatermark, idx * 2, 185, idx * 2 + 2, 198, color) + } + + assertThat(MapRenderingReadiness.hasRenderedMapContent(blankWithWatermark)).isFalse() + blankWithWatermark.recycle() + } + + @Test + fun hasRenderedMapContent_faintTwoColorLoadingGrid_returnsFalse() { + val grid = createSolidBitmap(Color.rgb(239, 236, 230)) + val gridColor = Color.rgb(220, 217, 211) + for (pos in 0 until 200 step 32) { + fillRect(grid, pos, 0, pos + 1, 200, gridColor) + fillRect(grid, 0, pos, 200, pos + 1, gridColor) + } + + assertThat(MapRenderingReadiness.hasRenderedMapContent(grid)).isFalse() + grid.recycle() + } + + @Test + fun hasRenderedMapContent_renderedMapWithTilesAndMarkers_returnsTrue() { + val rendered = createRenderedMapBitmap(offset = 0) + assertThat(MapRenderingReadiness.hasRenderedMapContent(rendered)).isTrue() + rendered.recycle() + } + + @Test + fun hasRenderedMapContent_respectsExplicitMapBounds() { + // Full screen has colorful header at top (y: 0..60), but map bounds (y: 60..200) are blank + val screen = createSolidBitmap(Color.rgb(239, 236, 230)) + val headerColors = listOf(Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW, Color.MAGENTA, Color.CYAN) + headerColors.forEachIndexed { idx, color -> + fillRect(screen, idx * 30, 0, (idx + 1) * 30, 50, color) + } + + val mapBounds = Rect(0, 60, 200, 200) + assertThat(MapRenderingReadiness.hasRenderedMapContent(screen, mapBounds)).isFalse() + screen.recycle() + } + + @Test + fun areFramesSettled_detectsChangingVsStableFrames() { + val frameA = createRenderedMapBitmap(offset = 0) + val frameB = createRenderedMapBitmap(offset = 25) + val frameC = createRenderedMapBitmap(offset = 25) + + assertThat(MapRenderingReadiness.areFramesSettled(frameA, frameB)).isFalse() + assertThat(MapRenderingReadiness.areFramesSettled(frameB, frameC)).isTrue() + + frameA.recycle() + frameB.recycle() + frameC.recycle() + } + + @Test + fun waitUntilSettled_waitsPastFiveSecondsUntilMapRendersAndSettles() { + var clock = 0L + // 14 blank frames (7 seconds at 500ms/poll), then 1 animating frame, then 2 settled frames + val frames = ArrayDeque().apply { + repeat(14) { add(createSolidBitmap(Color.rgb(239, 236, 230))) } + add(createRenderedMapBitmap(offset = 0)) + add(createRenderedMapBitmap(offset = 20)) + add(createRenderedMapBitmap(offset = 20)) + } + + val settled = MapRenderingReadiness.waitUntilSettled( + timeoutMillis = 30_000L, + pollIntervalMillis = 500L, + nowMillis = { clock }, + sleepMillis = { clock += it }, + boundsProvider = { Rect(0, 0, 200, 200) }, + captureFrame = { frames.removeFirstOrNull() }, + ) + + assertThat(settled).isTrue() + // Proves it waited beyond the old 5s cap and returned as soon as frame 16 matched frame 15 + assertThat(clock).isEqualTo(8_000L) + } + + @Test + fun waitUntilSettled_returnsFalseWhenBlankUntilTimeout() { + var clock = 0L + + val settled = MapRenderingReadiness.waitUntilSettled( + timeoutMillis = 10_000L, + pollIntervalMillis = 500L, + nowMillis = { clock }, + sleepMillis = { clock += it }, + boundsProvider = { null }, + captureFrame = { createSolidBitmap(Color.rgb(239, 236, 230)) }, + ) + + assertThat(settled).isFalse() + assertThat(clock).isEqualTo(10_000L) + } + + @Test + fun waitUntilSettled_nonPositiveTimeout_returnsFalseImmediately() { + var captures = 0 + val settled = MapRenderingReadiness.waitUntilSettled( + timeoutMillis = 0L, + nowMillis = { 0L }, + sleepMillis = {}, + boundsProvider = { null }, + captureFrame = { + captures++ + createRenderedMapBitmap(offset = 0) + }, + ) + + assertThat(settled).isFalse() + assertThat(captures).isEqualTo(0) + } + + private fun createSolidBitmap(color: Int, size: Int = 200): Bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply { + eraseColor(color) + } + + private fun createRenderedMapBitmap(offset: Int, size: Int = 200): Bitmap { + val bitmap = createSolidBitmap(Color.rgb(239, 236, 230), size) + val bands = listOf( + Color.rgb(170, 218, 255), // water + Color.rgb(203, 230, 163), // park + Color.rgb(255, 255, 255), // arterial road + Color.rgb(254, 224, 139), // highway + Color.rgb(234, 67, 53), // red marker pin + Color.rgb(66, 133, 244), // blue route/water label + Color.rgb(95, 99, 104), // street label + ) + bands.forEachIndexed { idx, color -> + val top = (idx * 24 + offset) % size + fillRect(bitmap, 0, top, size, (top + 20).coerceAtMost(size), color) + } + return bitmap + } + + private fun fillRect(bitmap: Bitmap, left: Int, top: Int, right: Int, bottom: Int, color: Int) { + val clampedLeft = left.coerceIn(0, bitmap.width) + val clampedRight = right.coerceIn(clampedLeft, bitmap.width) + val clampedTop = top.coerceIn(0, bitmap.height) + val clampedBottom = bottom.coerceIn(clampedTop, bitmap.height) + for (y in clampedTop until clampedBottom) { + for (x in clampedLeft until clampedRight) { + bitmap.setPixel(x, y, color) + } + } + } +}