Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support test resources in Compose UI tests. #5122

Merged
merged 8 commits into from
Aug 29, 2024
Merged
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
3 changes: 2 additions & 1 deletion components/gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ kotlinx-coroutines = "1.8.0"
androidx-appcompat = "1.6.1"
androidx-activity-compose = "1.8.2"
androidx-test = "1.5.0"
androidx-compose = "1.6.0"
androidx-compose = "1.6.1"

[libraries]
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }
androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "androidx-appcompat" }
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activity-compose" }
androidx-test-core = { module = "androidx.test:core", version.ref = "androidx-test" }
androidx-test-monitor = { module = "androidx.test:monitor", version.ref = "androidx-test" }
androidx-compose-ui-test = { module = "androidx.compose.ui:ui-test", version.ref = "androidx-compose" }
androidx-compose-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest", version.ref = "androidx-compose" }
androidx-compose-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "androidx-compose" }
Expand Down
4 changes: 4 additions & 0 deletions components/resources/library/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ kotlin {
}
val androidMain by getting {
dependsOn(jvmAndAndroidMain)
dependencies {
//it will be called only in android instrumented tests where the library should be available
compileOnly(libs.androidx.test.monitor)
}
}
val androidInstrumentedTest by getting {
dependsOn(jvmAndAndroidTest)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ import android.net.Uri
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.test.platform.app.InstrumentationRegistry

internal val androidContext get() = AndroidContextProvider.ANDROID_CONTEXT
internal val androidInstrumentedContext get() = InstrumentationRegistry.getInstrumentation().context

/**
* The function configures the android context
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package org.jetbrains.compose.resources

import android.content.res.AssetManager
import android.net.Uri
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ProvidableCompositionLocal
import java.io.FileNotFoundException
Expand All @@ -16,6 +17,14 @@ internal actual fun getPlatformResourceReader(): ResourceReader = object : Resou
context.assets
}

private val instrumentedAssets: AssetManager?
get() = try {
androidInstrumentedContext.assets
} catch (e: NoClassDefFoundError) {
Log.d("ResourceReader", "Android Instrumentation context is not available.")
null
}

override suspend fun read(path: String): ByteArray {
val resource = getResourceAsStream(path)
return resource.use { input -> input.readBytes() }
Expand Down Expand Up @@ -52,7 +61,7 @@ internal actual fun getPlatformResourceReader(): ResourceReader = object : Resou
}

override fun getUri(path: String): String {
val uri = if (assets.hasFile(path)) {
val uri = if (assets.hasFile(path) || instrumentedAssets.hasFile(path)) {
Uri.parse("file:///android_asset/$path")
} else {
val classLoader = getClassLoader()
Expand All @@ -66,16 +75,20 @@ internal actual fun getPlatformResourceReader(): ResourceReader = object : Resou
return try {
assets.open(path)
} catch (e: FileNotFoundException) {
val classLoader = getClassLoader()
classLoader.getResourceAsStream(path) ?: throw MissingResourceException(path)
try {
instrumentedAssets.open(path)
} catch (e: FileNotFoundException) {
val classLoader = getClassLoader()
classLoader.getResourceAsStream(path) ?: throw MissingResourceException(path)
}
}
}

private fun getClassLoader(): ClassLoader {
return this.javaClass.classLoader ?: error("Cannot find class loader")
}

private fun AssetManager.hasFile(path: String): Boolean {
private fun AssetManager?.hasFile(path: String): Boolean {
var inputStream: InputStream? = null
val result = try {
inputStream = open(path)
Expand All @@ -87,6 +100,9 @@ internal actual fun getPlatformResourceReader(): ResourceReader = object : Resou
}
return result
}

private fun AssetManager?.open(path: String): InputStream =
this?.open(path) ?: throw FileNotFoundException("Current AssetManager is null.")
}

internal actual val ProvidableCompositionLocal<ResourceReader>.currentOrPreview: ResourceReader
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package org.jetbrains.compose.resources

import com.android.build.api.variant.AndroidComponentsExtension
import com.android.build.api.variant.Variant
import com.android.build.api.variant.Component
import com.android.build.api.variant.HasAndroidTest
import com.android.build.gradle.internal.lint.AndroidLintAnalysisTask
import com.android.build.gradle.internal.lint.LintModelWriterTask
import org.gradle.api.DefaultTask
Expand All @@ -10,23 +11,73 @@ import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileCollection
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.IgnoreEmptyDirectories
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import org.jetbrains.compose.internal.utils.registerTask
import org.jetbrains.compose.internal.utils.uppercaseFirstChar
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinAndroidTarget
import java.io.File
import javax.inject.Inject

private fun Project.getAndroidVariantComposeResources(
internal fun Project.configureAndroidComposeResources(moduleResourceDir: Provider<File>? = null) {
//copy all compose resources to android assets
val androidComponents = project.extensions.findByType(AndroidComponentsExtension::class.java) ?: return
androidComponents.onVariants { variant ->
configureGeneratedAndroidComponentAssets(variant, moduleResourceDir)

if (variant is HasAndroidTest) {
variant.androidTest?.let { androidTest ->
configureGeneratedAndroidComponentAssets(androidTest, moduleResourceDir)
}
}
}
}

private fun Project.configureGeneratedAndroidComponentAssets(
component: Component,
moduleResourceDir: Provider<File>?
) {
val kotlinExtension = project.extensions.findByType(KotlinMultiplatformExtension::class.java) ?: return
val camelComponentName = component.name.uppercaseFirstChar()
val componentAssets = getAndroidComponentComposeResources(kotlinExtension, component.name)
logger.info("Configure ${component.name} resources for 'android' target")

val copyComponentAssets = registerTask<CopyResourcesToAndroidAssetsTask>(
"copy${camelComponentName}ComposeResourcesToAndroidAssets"
) {
from.set(componentAssets)
moduleResourceDir?.let { relativeResourcePlacement.set(it) }
}

component.sources.assets?.addGeneratedSourceDirectory(
copyComponentAssets,
CopyResourcesToAndroidAssetsTask::outputDirectory
)
tasks.configureEach { task ->
//fix agp task dependencies for AndroidStudio preview
if (task.name == "compile${camelComponentName}Sources") {
task.dependsOn(copyComponentAssets)
}
//fix linter task dependencies for `build` task
if (task is AndroidLintAnalysisTask || task is LintModelWriterTask) {
task.mustRunAfter(copyComponentAssets)
}
}
}

private fun Project.getAndroidComponentComposeResources(
kotlinExtension: KotlinMultiplatformExtension,
variant: Variant
componentName: String
): FileCollection = project.files({
kotlinExtension.targets.withType(KotlinAndroidTarget::class.java).flatMap { androidTarget ->
androidTarget.compilations.flatMap { compilation ->
if (compilation.androidVariant.name == variant.name) {
if (compilation.androidVariant.name == componentName) {
compilation.allKotlinSourceSets.map { kotlinSourceSet ->
getPreparedComposeResourcesDir(kotlinSourceSet)
}
Expand All @@ -35,37 +86,6 @@ private fun Project.getAndroidVariantComposeResources(
}
})

internal fun Project.configureAndroidComposeResources() {
//copy all compose resources to android assets
val androidComponents = project.extensions.findByType(AndroidComponentsExtension::class.java) ?: return
val kotlinExtension = project.extensions.findByType(KotlinMultiplatformExtension::class.java) ?: return
androidComponents.onVariants { variant ->
val camelVariantName = variant.name.uppercaseFirstChar()
val variantAssets = getAndroidVariantComposeResources(kotlinExtension, variant)

val copyVariantAssets = registerTask<CopyResourcesToAndroidAssetsTask>(
"copy${camelVariantName}ComposeResourcesToAndroidAssets"
) {
from.set(variantAssets)
}

variant.sources.assets?.addGeneratedSourceDirectory(
copyVariantAssets,
CopyResourcesToAndroidAssetsTask::outputDirectory
)
tasks.configureEach { task ->
//fix agp task dependencies for AndroidStudio preview
if (task.name == "compile${camelVariantName}Sources") {
task.dependsOn(copyVariantAssets)
}
//fix linter task dependencies for `build` task
if (task is AndroidLintAnalysisTask || task is LintModelWriterTask) {
task.mustRunAfter(copyVariantAssets)
}
}
}
}

//Copy task doesn't work with 'variant.sources?.assets?.addGeneratedSourceDirectory' API
internal abstract class CopyResourcesToAndroidAssetsTask : DefaultTask() {
@get:Inject
Expand All @@ -75,6 +95,10 @@ internal abstract class CopyResourcesToAndroidAssetsTask : DefaultTask() {
@get:IgnoreEmptyDirectories
abstract val from: Property<FileCollection>

@get:Input
@get:Optional
abstract val relativeResourcePlacement: Property<File>

@get:OutputDirectory
abstract val outputDirectory: DirectoryProperty

Expand All @@ -83,7 +107,11 @@ internal abstract class CopyResourcesToAndroidAssetsTask : DefaultTask() {
fileSystem.copy {
it.includeEmptyDirs = false
it.from(from)
it.into(outputDirectory)
if (relativeResourcePlacement.isPresent) {
it.into(outputDirectory.dir(relativeResourcePlacement.get().path))
} else {
it.into(outputDirectory)
}
}
}
}
Expand All @@ -105,14 +133,3 @@ internal fun Project.fixAndroidLintTaskDependencies() {
it.mustRunAfter(tasks.withType(GenerateResourceAccessorsTask::class.java))
}
}

internal fun Project.fixKgpAndroidPreviewTaskDependencies() {
val androidComponents = project.extensions.findByType(AndroidComponentsExtension::class.java) ?: return
androidComponents.onVariants { variant ->
tasks.configureEach { task ->
if (task.name == "compile${variant.name.uppercaseFirstChar()}Sources") {
task.dependsOn("${variant.name}AssetsCopyForAGP")
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package org.jetbrains.compose.resources

import org.gradle.api.DefaultTask
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.work.DisableCachingByDefault
import java.io.File
import javax.inject.Inject

@DisableCachingByDefault(because = "There is no logic, just copy files")
internal abstract class AssembleTargetResourcesTask : DefaultTask() {

@get:Inject
abstract val fileSystem: FileSystemOperations

@get:InputFiles
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val resourceDirectories: ConfigurableFileCollection

@get:Input
abstract val relativeResourcePlacement: Property<File>

@get:OutputDirectory
abstract val outputDirectory: DirectoryProperty

@TaskAction
fun action() {
val outputDirectoryFile = outputDirectory.get().asFile
if (outputDirectoryFile.exists()) {
outputDirectoryFile.deleteRecursively()
}
outputDirectoryFile.mkdirs()

fileSystem.copy { copy ->
resourceDirectories.files.forEach { dir ->
copy.from(dir)
}
copy.into(outputDirectoryFile.resolve(relativeResourcePlacement.get()))
copy.duplicatesStrategy = DuplicatesStrategy.INCLUDE
}

if (outputDirectoryFile.listFiles()?.isEmpty() != false) {
// Output an empty directory for the zip task
outputDirectoryFile.resolve(relativeResourcePlacement.get()).mkdirs()
}
}
}
Loading
Loading