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..eea5595 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 @@ -33,6 +33,10 @@ import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class VisualMapSampleTest : BaseVisualTest() { + // Report the test as skipped, not failed, when Gemini stays unavailable (e.g. 503 under high + // demand), so an outage on Gemini's side does not break CI. + override val skipWhenGeminiUnavailable = true + @Test fun verifyStoreLocatorMapRendering() = runBlocking { // 1. Launch MainActivity diff --git a/visual-testing/README.md b/visual-testing/README.md index 15c5995..adb5c76 100644 --- a/visual-testing/README.md +++ b/visual-testing/README.md @@ -117,6 +117,10 @@ export GEMINI_API_KEY="your-gemini-api-key" @RunWith(AndroidJUnit4::class) class VisualMapSampleTest : BaseVisualTest() { + // Report the test as skipped, not failed, when Gemini stays unavailable (e.g. 503 under high + // demand), so an outage on Gemini's side does not break CI. + override val skipWhenGeminiUnavailable = true + @Test fun verifyStoreLocatorMapRendering() = runBlocking { // 1. Launch MainActivity @@ -212,7 +216,13 @@ class VisualMapSampleTest : BaseVisualTest() { return } - val geminiResponse = helper.analyzeImage(screenshotBitmap, prompt, apiKey) + val geminiResponse = try { + helper.analyzeImage(screenshotBitmap, prompt, apiKey) + } catch (e: GeminiUnavailableException) { + if (!skipWhenGeminiUnavailable) throw e + Log.w("BaseVisualTest", "Gemini is unavailable, skipping the visual verification for '$testName'", e) + throw AssumptionViolatedException("Skipping Gemini visual verification for '$testName': Gemini is unavailable. ${e.message}", e) + } Log.i("BaseVisualTest", "Gemini response for '$testName':\n$geminiResponse") assertTrue("Gemini returned a null response for '$testName'", geminiResponse != null) @@ -270,7 +280,7 @@ val visualTestHelper = GeminiVisualTestHelper(preferredModel = "gemini-3.8-flash ## CI Emulator Setup & Troubleshooting -When running `:visual-testing` instrumented tests on CI emulators (such as GitHub Actions `google_apis` images), keep three common pitfalls in mind: +When running `:visual-testing` instrumented tests on CI emulators (such as GitHub Actions `google_apis` images), keep four common pitfalls in mind: 1. **Missing `org.apache.http.legacy` on older Play Services emulators**: Even with a recent `play-services-maps`, the map renderer runs inside Google Play Services and can crash with `NoClassDefFoundError: org/apache/http/ProtocolVersion` on API 28+ devices running older Play Services or the legacy renderer. Declare the optional library inside `` in your app's `AndroidManifest.xml` (see `app/src/main/AndroidManifest.xml`): ```xml @@ -280,6 +290,10 @@ When running `:visual-testing` instrumented tests on CI emulators (such as GitHu ``` 2. **Map tile authorization on ephemeral debug keystores**: CI runners generate a new debug signing key on each run, so a `MAPS_API_KEY` restricted to a local workstation's SHA-1 fingerprint will fail to load map tiles. Configure a CI Maps API key restricted by API targets (`Maps SDK for Android`) rather than a workstation SHA-1. 3. **Defer camera bounds fitting until `MapView` layout**: Calling `CameraUpdateFactory.newLatLngBounds(...)` before a `MapView` has non-zero dimensions (especially inside Jetpack Compose `AndroidView`) can leave the camera uncentered when the screenshot is captured. Wrap initial bounds fitting in `mapView.doOnLayout { ... }` so markers are framed reliably before capture (see `renderStoresOnMap` in `app/src/main/java/com/google/maps/android/testing/sample/ui/main/MainScreen.kt`). +4. **Gemini unavailable under high demand**: `GeminiVisualTestHelper` makes up to three attempts, with backoff, when a request times out or Gemini answers `429` or `5xx`. If Gemini is still unavailable after the last attempt, it throws `GeminiUnavailableException`, which fails the test by default. To report the test as skipped instead, so an outage on Gemini's side does not break CI, override `skipWhenGeminiUnavailable` in your `BaseVisualTest` subclass (as `VisualMapSampleTest` does). Gemini rejecting the screenshot, or any other error, still fails the test: + ```kotlin + override val skipWhenGeminiUnavailable = true + ``` --- diff --git a/visual-testing/api/visual-testing.api b/visual-testing/api/visual-testing.api index fc730a9..ef2492b 100644 --- a/visual-testing/api/visual-testing.api +++ b/visual-testing/api/visual-testing.api @@ -71,6 +71,7 @@ public abstract class com/google/maps/android/testing/visual/BaseVisualTest { protected final fun getGeminiApiKey ()Ljava/lang/String; protected fun getHelper ()Lcom/google/maps/android/testing/visual/GeminiVisualTestHelper; protected final fun getInstrumentation ()Landroid/app/Instrumentation; + protected fun getSkipWhenGeminiUnavailable ()Z protected final fun getUiDevice ()Landroidx/test/uiautomator/UiDevice; protected fun loadGoldenBaseline (Ljava/lang/String;Ljava/io/File;)Landroid/graphics/Bitmap; public final fun verifyScreenshotWithGoldenFallback (Ljava/lang/String;Landroid/graphics/Bitmap;Ljava/lang/String;Lkotlin/jvm/functions/Function1;Ljava/io/File;DZLkotlin/coroutines/Continuation;)Ljava/lang/Object; @@ -201,6 +202,11 @@ public final class com/google/maps/android/testing/visual/GeminiResponse$Compani public final fun serializer ()Lkotlinx/serialization/KSerializer; } +public final class com/google/maps/android/testing/visual/GeminiUnavailableException : java/lang/IllegalStateException { + public fun (Ljava/lang/String;Ljava/lang/Throwable;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/Throwable;ILkotlin/jvm/internal/DefaultConstructorMarker;)V +} + public final class com/google/maps/android/testing/visual/GeminiVisualTestHelper { public static final field Companion Lcom/google/maps/android/testing/visual/GeminiVisualTestHelper$Companion; public static final field DEFAULT_FALLBACK_MODEL Ljava/lang/String; 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..54f863f 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 @@ -30,6 +30,7 @@ import kotlinx.coroutines.runBlocking import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.Assume.assumeTrue +import org.junit.AssumptionViolatedException import java.io.File import java.io.FileOutputStream import java.util.concurrent.TimeUnit @@ -57,6 +58,17 @@ abstract class BaseVisualTest { */ protected open val helper: GeminiVisualTestHelper = GeminiVisualTestHelper() + /** + * When true, [verifyScreenshotWithGoldenFallback] skips the test (through JUnit's `Assume`) + * instead of failing it if Gemini is still unavailable after every retry, for example when the + * model keeps answering `503` under high demand (see [GeminiUnavailableException]). The test is + * reported as skipped, not passed. Any other failure, such as Gemini rejecting the screenshot or + * an invalid API key, still fails the test. + * + * Defaults to false, so an unavailable Gemini fails the test unless you opt in. + */ + protected open val skipWhenGeminiUnavailable: Boolean = false + /** * Resolves the Gemini API key from various configuration sources. * @@ -200,7 +212,13 @@ abstract class BaseVisualTest { return } - val geminiResponse = helper.analyzeImage(screenshotBitmap, prompt, apiKey) + val geminiResponse = try { + helper.analyzeImage(screenshotBitmap, prompt, apiKey) + } catch (e: GeminiUnavailableException) { + if (!skipWhenGeminiUnavailable) throw e + Log.w("BaseVisualTest", "Gemini is unavailable, skipping the visual verification for '$testName'", e) + throw AssumptionViolatedException("Skipping Gemini visual verification for '$testName': Gemini is unavailable. ${e.message}", e) + } Log.i("BaseVisualTest", "Gemini response for '$testName':\n$geminiResponse") assertTrue("Gemini returned a null response for '$testName'", geminiResponse != null) diff --git a/visual-testing/src/main/java/com/google/maps/android/testing/visual/GeminiUnavailableException.kt b/visual-testing/src/main/java/com/google/maps/android/testing/visual/GeminiUnavailableException.kt new file mode 100644 index 0000000..b0161e7 --- /dev/null +++ b/visual-testing/src/main/java/com/google/maps/android/testing/visual/GeminiUnavailableException.kt @@ -0,0 +1,28 @@ +/* + * 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 + +/** + * Thrown by [GeminiVisualTestHelper] when Gemini is still unavailable after every retry: the + * request timed out or failed with a network error, or the API kept answering + * `429 Too Many Requests` or a `5xx` status, such as `503` when the model is under high demand. + * + * It says nothing about the screenshot under test, so [BaseVisualTest] can skip the test instead + * of failing it, see [BaseVisualTest.skipWhenGeminiUnavailable]. It extends + * [IllegalStateException], so code that catches that keeps working. + */ +class GeminiUnavailableException(message: String, cause: Throwable? = null) : IllegalStateException(message, cause) diff --git a/visual-testing/src/main/java/com/google/maps/android/testing/visual/GeminiVisualTestHelper.kt b/visual-testing/src/main/java/com/google/maps/android/testing/visual/GeminiVisualTestHelper.kt index e60b8dd..b775dfb 100644 --- a/visual-testing/src/main/java/com/google/maps/android/testing/visual/GeminiVisualTestHelper.kt +++ b/visual-testing/src/main/java/com/google/maps/android/testing/visual/GeminiVisualTestHelper.kt @@ -213,6 +213,8 @@ class GeminiVisualTestHelper( * @param prompt The natural language specification and verification criteria. * @param apiKey The Gemini API key. * @return The text response generated by Gemini. + * @throws GeminiUnavailableException when Gemini still times out, rate limits or returns a + * server error after all retries. */ suspend fun analyzeImage( bitmap: Bitmap, @@ -264,6 +266,9 @@ class GeminiVisualTestHelper( /** * Blocking version of [analyzeImage] for Java test runners. + * + * @throws GeminiUnavailableException when Gemini still times out, rate limits or returns a + * server error after all retries. */ fun analyzeImageBlocking( bitmap: Bitmap, @@ -282,6 +287,8 @@ class GeminiVisualTestHelper( * @param prompt Natural language command (e.g. "Click the Sydney marker", "Set search text to Park"). * @param uiDevice The UiAutomator device instance. * @param apiKey The Gemini API key. + * @throws GeminiUnavailableException when Gemini still times out, rate limits or returns a + * server error after all retries. */ suspend fun performActionFromPrompt( prompt: String, @@ -367,6 +374,9 @@ class GeminiVisualTestHelper( /** * Blocking version of [performActionFromPrompt] for Java test runners. + * + * @throws GeminiUnavailableException when Gemini still times out, rate limits or returns a + * server error after all retries. */ fun performActionFromPromptBlocking( prompt: String, @@ -385,7 +395,10 @@ class GeminiVisualTestHelper( /** * Posts [request] to [url], retrying transient failures: request timeouts and other network * errors, `429 Too Many Requests`, and `5xx` server errors such as `503` when the model is - * under high demand. Any other status fails immediately. + * under high demand. Any other status fails immediately with an [IllegalStateException]. + * + * @throws GeminiUnavailableException when the last attempt still fails with one of those + * transient errors. */ private suspend fun executeWithRetry( url: String, @@ -405,7 +418,7 @@ class GeminiVisualTestHelper( // HttpRequestTimeoutException and the connect/socket timeouts are IOExceptions. if (isLastAttempt) { Log.e(TAG, "Gemini API request failed after $attempt attempts", e) - throw e + throw GeminiUnavailableException("Gemini API request failed after $attempt attempts: $e", e) } backOff(attempt, maxAttempts, "Gemini API request failed with ${e::class.simpleName}") continue @@ -415,10 +428,12 @@ class GeminiVisualTestHelper( return response } - if (isLastAttempt || !response.status.isTransient()) { + val isTransient = response.status.isTransient() + if (isLastAttempt || !isTransient) { val errorBody = response.bodyAsText() Log.e(TAG, "Gemini API failed with status ${response.status}: $errorBody") - throw IllegalStateException("Gemini API request failed with status ${response.status}:\n$errorBody") + val message = "Gemini API request failed with status ${response.status}:\n$errorBody" + throw if (isTransient) GeminiUnavailableException(message) else IllegalStateException(message) } backOff(attempt, maxAttempts, "Transient Gemini API status ${response.status}") } diff --git a/visual-testing/src/test/java/com/google/maps/android/testing/visual/GeminiRetryTest.kt b/visual-testing/src/test/java/com/google/maps/android/testing/visual/GeminiRetryTest.kt index 97c7ce2..65ea89b 100644 --- a/visual-testing/src/test/java/com/google/maps/android/testing/visual/GeminiRetryTest.kt +++ b/visual-testing/src/test/java/com/google/maps/android/testing/visual/GeminiRetryTest.kt @@ -85,9 +85,10 @@ class GeminiRetryTest { fun rethrowsTimeoutWhenEveryAttemptTimesOut() { val client = scriptedClient(Outcome.Timeout, Outcome.Timeout, Outcome.Timeout) - assertThrows(HttpRequestTimeoutException::class.java) { + val error = assertThrows(GeminiUnavailableException::class.java) { runBlocking { helper(client).analyzeImage(bitmap, "Verify the map", "key") } } + assertThat(error).hasCauseThat().isInstanceOf(HttpRequestTimeoutException::class.java) assertThat(client.calls).isEqualTo(GeminiVisualTestHelper.MAX_ATTEMPTS) } @@ -99,7 +100,7 @@ class GeminiRetryTest { Outcome.Respond(HttpStatusCode.ServiceUnavailable), ) - val error = assertThrows(IllegalStateException::class.java) { + val error = assertThrows(GeminiUnavailableException::class.java) { runBlocking { helper(client).analyzeImage(bitmap, "Verify the map", "key") } } assertThat(error).hasMessageThat().contains("503") @@ -114,6 +115,7 @@ class GeminiRetryTest { runBlocking { helper(client).analyzeImage(bitmap, "Verify the map", "key") } } assertThat(error).hasMessageThat().contains("400") + assertThat(error).isNotInstanceOf(GeminiUnavailableException::class.java) assertThat(client.calls).isEqualTo(1) } diff --git a/visual-testing/src/test/java/com/google/maps/android/testing/visual/GoldenFallbackLogicTest.kt b/visual-testing/src/test/java/com/google/maps/android/testing/visual/GoldenFallbackLogicTest.kt index 3ffeac0..378e7c1 100644 --- a/visual-testing/src/test/java/com/google/maps/android/testing/visual/GoldenFallbackLogicTest.kt +++ b/visual-testing/src/test/java/com/google/maps/android/testing/visual/GoldenFallbackLogicTest.kt @@ -19,9 +19,11 @@ package com.google.maps.android.testing.visual import android.graphics.Bitmap import android.graphics.Color import com.google.common.truth.Truth.assertThat +import io.ktor.http.HttpStatusCode import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Assert.assertThrows +import org.junit.AssumptionViolatedException import org.junit.Before import org.junit.Rule import org.junit.Test @@ -160,6 +162,82 @@ class GoldenFallbackLogicTest { assertThat(File(goldensDir, "negated.png").exists()).isFalse() } + @Test + fun skipsWhenGeminiStaysUnavailableAndSkippingIsEnabled() { + val goldensDir = tempFolder.newFolder("goldens") + + val error = assertThrows(AssumptionViolatedException::class.java) { + runBlocking { + skippingUnavailableGeminiHarness().verifyScreenshotWithGoldenFallback( + testName = "unavailable_skip", + screenshotBitmap = solidBitmap(Color.RED), + prompt = "Verify the map", + goldensDirectory = goldensDir, + ) + } + } + + assertThat(error).hasMessageThat().contains("Gemini is unavailable") + assertThat(error).hasCauseThat().isInstanceOf(GeminiUnavailableException::class.java) + assertThat(File(goldensDir, "unavailable_skip.png").exists()).isFalse() + } + + @Test + fun failsWhenGeminiStaysUnavailableByDefault() { + val goldensDir = tempFolder.newFolder("goldens") + + assertThrows(GeminiUnavailableException::class.java) { + runBlocking { + unavailableGeminiHarness().verifyScreenshotWithGoldenFallback( + testName = "unavailable_fail", + screenshotBitmap = solidBitmap(Color.RED), + prompt = "Verify the map", + goldensDirectory = goldensDir, + ) + } + } + } + + @Test + fun stillFailsOnRejectedScreenshotWhenSkippingIsEnabled() { + val goldensDir = tempFolder.newFolder("goldens") + val harness = object : BaseVisualTest() { + override val skipWhenGeminiUnavailable = true + override val helper = GeminiVisualTestHelper( + preferredModel = "test-model", + client = mockGeminiClient { generateContentResponse("FAILED: the map is blank") }, + ) + } + + val error = assertThrows(AssertionError::class.java) { + runBlocking { + harness.verifyScreenshotWithGoldenFallback( + testName = "rejected_with_skip", + screenshotBitmap = solidBitmap(Color.RED), + prompt = "Verify the map", + goldensDirectory = goldensDir, + ) + } + } + + assertThat(error).hasMessageThat().contains("Gemini visual verification failed") + } + + /** Leaves [BaseVisualTest.skipWhenGeminiUnavailable] at its default, so tests cover the default. */ + private fun unavailableGeminiHarness() = object : BaseVisualTest() { + override val helper = unavailableGeminiHelper() + } + + private fun skippingUnavailableGeminiHarness() = object : BaseVisualTest() { + override val skipWhenGeminiUnavailable = true + override val helper = unavailableGeminiHelper() + } + + private fun unavailableGeminiHelper() = GeminiVisualTestHelper( + preferredModel = "test-model", + client = mockGeminiClient(status = HttpStatusCode.ServiceUnavailable) { """{ "error": { "code": 503 } }""" }, + ).apply { retryBaseDelayMillis = 0L } + private fun geminiHarness(answer: String) = object : BaseVisualTest() { override val helper = GeminiVisualTestHelper( preferredModel = "test-model",