Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion .github/workflows/instrumentation-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -110,3 +117,4 @@ jobs:
path: |
*/build/reports/androidTests/
*/build/reports/coverage/
emulator-logcat.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Being the result of uiDevice.wait ignored, if the map has no "Google Map" description we now spend the whole 30s here and then return without any settle check (before it was 3s + 5s). Could we check the result and fall back to the full screen, or at least log which node we didn't find?


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()
}
Comment on lines +152 to +154

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: after restoring the flag, every following Thread.sleep throws directly, so the loop takes screenshots without pause until the deadline. What about stopping the wait here?

Suggested change
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
}
} catch (e: InterruptedException) {
Thread.currentThread().interrupt()
throw IllegalStateException("Interrupted while waiting for map rendering", e)
}

},
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()
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<Int, Int>()
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
}
}
Loading
Loading