// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import java.io.File import java.io.FileOutputStream data class DiscoveredTest( val testName: String, val fileName: String ) tasks.register("embedTestResultImages") { group = "verification" description = "Dynamically discovers, pulls, and embeds all on-device test result images into the AGP HTML report." doLast { val buildDir = layout.buildDirectory.get().asFile val reportsDir = File(buildDir, "reports/androidTests/connected") // Dynamically find the active variant directory (e.g. "debug") where HTML files exist var targetVariantDir = File(reportsDir, "debug") if (!targetVariantDir.exists()) { val firstHtmlParent = reportsDir.walk().firstOrNull { it.name.endsWith(".html") && it.parentFile != reportsDir }?.parentFile if (firstHtmlParent != null) { targetVariantDir = firstHtmlParent } } val imagesDir = File(targetVariantDir, "test_result_images") imagesDir.mkdirs() val packageId = "com.example.android_hardware_smoke_test" val discoveredTests = mutableListOf() // Resolve binary safe adb executable from Android Gradle Plugin BaseExtension val android = project.extensions.getByType(com.android.build.gradle.BaseExtension::class.java) val adbPath = android.adbExecutable.absolutePath println("Resolved binary-safe adb executable from AGP: $adbPath") // 1. Query the device sandbox to list all files in cache/results/ using ProcessBuilder var files = listOf() try { val process = ProcessBuilder(adbPath, "shell", "run-as", packageId, "ls", "cache/results") .redirectErrorStream(true) // Safely merge stdout and stderr to prevent thread deadlocks! .start() val outputBytes = process.inputStream.readBytes() val exitCode = process.waitFor() val output = String(outputBytes).trim() if (exitCode == 0) { if (output.isNotEmpty()) { files = output.split(Regex("\\r?\\n")) } } else { if (output.contains("No such file or directory")) { println( "ℹ️ No test result images sandbox directory exists on-device (this is normal if no on-device screenshots were generated)." ) } else { println("❌ Failed to list sandbox directory cache/results (exit code $exitCode): $output") } } } catch (e: Exception) { println("Failed to query sandbox files from device: ${e.message}") } // 2. Iterate through all discovered files and pull PNGs for (rawFileName in files) { val file = File(rawFileName.trim()) if (file.extension.equals("png", ignoreCase = true)) { // Extract the clean test case name (e.g. "blueRectangleTest") before any dot-separators val testName = file.nameWithoutExtension.substringBefore(".") val fileName = file.name val destinationFile = File(imagesDir, fileName) try { // Copy the file from the device's temp folder. // Because we write the result images to a temp folder on the device, `adb pull` won't have access. // `run-as` resolves the temp folder permissions, but this means we have to use `cat` with `adb exec-out` to read the file contents and write them locally. val process = ProcessBuilder(adbPath, "exec-out", "run-as", packageId, "cat", "cache/results/$fileName") .start() FileOutputStream(destinationFile).use { os -> process.inputStream.copyTo(os) } val exitCode = process.waitFor() if (exitCode == 0) { discoveredTests.add(DiscoveredTest(testName, fileName)) println("Successfully pulled test result image: ${destinationFile.absolutePath}") } else { destinationFile.delete() val errorMsg = String(process.errorStream.readBytes()).trim() println("❌ Failed to pull $fileName (exit code $exitCode): $errorMsg") } } catch (e: Exception) { if (destinationFile.exists()) { destinationFile.delete() } println("Failed to pull test result image $fileName from device: ${e.message}") } } } // 3. Dynamically parse and inject tags for all discovered tests if (discoveredTests.isNotEmpty()) { targetVariantDir.walk().forEach { file -> if (file.extension.equals("html", ignoreCase = true)) { var htmlContent = file.readText() var modified = false for (test in discoveredTests) { val testName = test.testName val fileName = test.fileName val targetCell = "$testName" if (htmlContent.contains(targetCell)) { htmlContent = htmlContent.replace( targetCell, "$testName

Result Image: $fileName" ) modified = true } } if (modified) { file.writeText(htmlContent) } } } println( "🎉 Successfully embedded ${discoveredTests.size} test result images in HTML report: ${File( targetVariantDir, "index.html" ).absolutePath}" ) } else { println("No test result images found on device to embed.") } // 4. Final Cleanup: Manually trigger auto-uninstall to leave the device clean. // // Since we set 'android.injected.androidTest.leaveApksInstalledAfterRun=true' in // gradle.properties to prevent the Android Gradle Plugin from immediately uninstalling // the app (which would wipe the sandbox cache before we could pull the result images), // we must manually run the adb uninstall commands here as the final task action. // This ensures the device is left completely clean, matching standard test runner behaviors. println("🧹 Performing automated post-test device cleanup...") try { val exitCodeMain = ProcessBuilder(adbPath, "uninstall", packageId).start().waitFor() if (exitCodeMain == 0) { println("Successfully uninstalled main APK ($packageId) from device.") } else { println("ℹ️ Main APK uninstallation returned exit code $exitCodeMain (this is normal if it wasn't installed).") } val exitCodeTest = ProcessBuilder(adbPath, "uninstall", "$packageId.test").start().waitFor() if (exitCodeTest == 0) { println("Successfully uninstalled test APK ($packageId.test) from device.") } else { println("ℹ️ Test APK uninstallation returned exit code $exitCodeTest (this is normal if it wasn't installed).") } } catch (e: Exception) { println("Failed to execute automated device cleanup: ${e.message}") } } } // Bind the hook to run automatically after tests complete tasks.configureEach { if (name == "connectedDebugAndroidTest") { finalizedBy("embedTestResultImages") } }