diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3412270 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.idea/ +.gradle/ +build/ +*.iml +local.properties +.DS_Store diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..7eb7ea2 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,39 @@ +plugins { + `kotlin-dsl` +} + +group = "flank" +version = "1.0-SNAPSHOT" + +repositories { + google() + mavenCentral() +} + +val fixtureClasspath: Configuration by configurations.creating +dependencies { + implementation(kotlin("stdlib")) + testImplementation("junit:junit:4.13.2") + testImplementation("io.strikt:strikt-gradle:0.31.0") + compileOnly("com.android.tools.build:gradle:7.1.2") + fixtureClasspath("com.android.tools.build:gradle:7.1.2") + fixtureClasspath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.20") +} + +// Inspired by: https://github.com/square/sqldelight/blob/83145b28cbdd949e98e87819299638074bd21147/sqldelight-gradle-plugin/build.gradle#L18 +// Append any extra dependencies to the test fixtures via a custom configuration classpath. This +// allows us to apply additional plugins in a fixture while still leveraging dependency resolution +// and de-duplication semantics. +tasks.named("pluginUnderTestMetadata", PluginUnderTestMetadata::class.java) { + pluginClasspath.from(fixtureClasspath) +} + +tasks.withType { + javaLauncher.set( + javaToolchains.launcherFor { languageVersion.set(JavaLanguageVersion.of(11)) } + ) + + if (!environment.containsKey("ANDROID_HOME")) { + environment("ANDROID_HOME", "${environment["HOME"]}/Library/Android/sdk") + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..2a74c6c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +kotlin.code.style=official + +org.gradle.caching=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..41d9927 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..aa991fc --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..418cdfc --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "simple-flank" + diff --git a/src/main/kotlin/AvailableVirtualDevice.kt b/src/main/kotlin/AvailableVirtualDevice.kt new file mode 100644 index 0000000..0bd2b64 --- /dev/null +++ b/src/main/kotlin/AvailableVirtualDevice.kt @@ -0,0 +1,79 @@ +import org.gradle.api.tasks.Input + +sealed class AvailableVirtualDevice( + @Input + val id: String, + @Input + private val make: String, + @Input + private val model: String, + @Input + val osVersion: Int +) { + fun toFladleDevice() = mapOf("model" to id, "version" to osVersion.toString()) + override fun toString(): String { + return "$make $model - $osVersion" + } +} + +class NexusLowRes(osVersion: Int) : + AvailableVirtualDevice("NexusLowRes", "Generic", "Low-resolution MDPI phone", osVersion) { + companion object { + fun minOsVersion() = 23 + fun maxOsVersion() = 30 + fun api23() = NexusLowRes(23) + fun api24() = NexusLowRes(24) + fun api25() = NexusLowRes(25) + fun api26() = NexusLowRes(26) + fun api27() = NexusLowRes(27) + fun api28() = NexusLowRes(28) + fun api29() = NexusLowRes(29) + fun api30() = NexusLowRes(30) + } +} + +class Nexus5(osVersion: Int) : AvailableVirtualDevice("Nexus5", "LG", "Nexus 5", osVersion) { + companion object { + fun api19() = Nexus5(19) + fun api21() = Nexus5(21) + fun api22() = Nexus5(22) + fun api23() = Nexus5(23) + } +} + +class Nexus5X(osVersion: Int) : AvailableVirtualDevice("Nexus5X", "LG", "Nexus 5X", osVersion) { + companion object { + fun api23() = Nexus5X(23) + fun api24() = Nexus5X(24) + fun api25() = Nexus5X(25) + fun api26() = Nexus5X(26) + } +} + +class Nexus7(osVersion: Int) : AvailableVirtualDevice("Nexus7", "Asus", "Nexus 7 (2012)", osVersion) { + companion object { + fun api19() = Nexus7(19) + fun api21() = Nexus7(21) + fun api22() = Nexus7(22) + } +} + +class Nexus7Clone169(osVersion: Int) : + AvailableVirtualDevice("Nexus7_clone_16_9", "Generic", "Nexus7 clone, DVD 16:9 aspect ratio ", osVersion) { + companion object { + fun api23() = Nexus7Clone169(23) + fun api24() = Nexus7Clone169(24) + fun api25() = Nexus7Clone169(25) + fun api26() = Nexus7Clone169(26) + } +} + +class Nexus9(osVersion: Int) : AvailableVirtualDevice("Nexus9", "HTC", "Nexus 9", osVersion) { + companion object { + fun api21() = Nexus9(21) + fun api22() = Nexus9(22) + fun api23() = Nexus9(23) + fun api24() = Nexus9(24) + fun api25() = Nexus9(25) + } +} diff --git a/src/main/kotlin/FlankExecutionTask.kt b/src/main/kotlin/FlankExecutionTask.kt new file mode 100644 index 0000000..20c2644 --- /dev/null +++ b/src/main/kotlin/FlankExecutionTask.kt @@ -0,0 +1,152 @@ +import org.gradle.api.DefaultTask +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.ProjectLayout +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.model.ObjectFactory +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Classpath +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.Nested +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.testing.Test +import org.gradle.process.ExecOperations +import javax.inject.Inject + +abstract class FlankExecutionTask : DefaultTask() { + @get:Inject + internal abstract val objectFactory: ObjectFactory + @get:Inject + internal abstract val projectLayout: ProjectLayout + @get:Inject + internal abstract val execOperations: ExecOperations + + @get:Input + val hermeticTests: Property = objectFactory.property(Boolean::class.java).convention(false) + + @get:Input + val dumpShards: Property = objectFactory.property(Boolean::class.java).convention(false) + + @get:InputFile + @get:PathSensitive(PathSensitivity.NONE) + abstract val serviceAccountCredentials: RegularFileProperty + + @get:Input + abstract val projectId: Property + + @get:Input + abstract val flankProject: Property + + @get:Input + abstract val variant: Property + + @get:InputFile + @Classpath + val appApk = objectFactory.fileProperty() + + @get:InputFile + @Classpath + val testApk = objectFactory.fileProperty() + + @get:Nested + abstract val device: Property + + @get:InputFiles + @get:Classpath + abstract val flankJarClasspath: ConfigurableFileCollection + + @get:Input + val localResultsDir = objectFactory.property(String::class.java).convention("results") + + @Input + fun getWorkingDirRelativePath(): String = workingDir.asFile.get().relativeTo(projectLayout.flankDir.get().asFile).path + + private val workingDir = objectFactory.directoryProperty().convention(projectLayout.flankDir) + fun setUpWorkingDir(configName: String) { + workingDir.set(projectLayout.buildDirectory.dir("flank/$configName")) + } + + @OutputDirectory + fun getOutputDir() = workingDir.dir(localResultsDir) + + @get:OutputFile + val flankYaml = workingDir.file("flank.yml") + + @get:OutputFile + val androidShardsOutput = workingDir.file("android_shards.json") + + @get:OutputFile + val flankLinksOutput = workingDir.file("flank-links.log") + + init { + group = Test.TASK_GROUP + description = "Runs instrumentation tests using flank on firebase test lab." + + outputs.cacheIf { + dumpShards.get() || hermeticTests.get() + } + outputs.upToDateWhen { + dumpShards.get() || hermeticTests.get() + } + } + + @TaskAction + fun run() { + check(serviceAccountCredentials.get().asFile.exists()) { "serviceAccountCredential file doesn't exist ${serviceAccountCredentials.get()}" } + + getOutputDir().get().asFile.deleteRecursively() + writeYaml(projectId.get(), flankProject.get(), variant.get(), device.get()) + + logger.debug(flankYaml.get().asFile.readText()) + + execOperations.javaexec { + classpath = flankJarClasspath + mainClass.set("ftl.Main") + environment(mapOf("GOOGLE_APPLICATION_CREDENTIALS" to serviceAccountCredentials.get().asFile)) + args = if (dumpShards.get()) { + listOf("firebase", "test", "android", "run", "--dump-shards") + } else { + listOf("firebase", "test", "android", "run") + } + workingDir(this@FlankExecutionTask.workingDir.asFile.get()) + }.assertNormalExitValue() + } + + private fun writeYaml(projectId: String, flankProject: String, variant: String, device: AvailableVirtualDevice) { + flankYaml.get().asFile.writeText(""" + gcloud: + app: ${appApk.get().asFile.relativeTo(workingDir.get().asFile)} + test: ${testApk.get().asFile.relativeTo(workingDir.get().asFile)} + device: + - model: ${device.id} + version: ${device.osVersion} + + use-orchestrator: false + auto-google-login: false + record-video: false + performance-metrics: false + timeout: 15m + results-history-name: $flankProject.$variant + num-flaky-test-attempts: 0 + + flank: + max-test-shards: 40 + shard-time: 120 + smart-flank-gcs-path: gs://$projectId/$flankProject.$variant/JUnitReport.xml + keep-file-path: false + ignore-failed-tests: false + disable-sharding: false + smart-flank-disable-upload: false + legacy-junit-result: false + full-junit-result: false + output-style: single + default-test-time: 1.0 + use-average-test-time-for-new-tests: true + """.trimIndent()) + } +} diff --git a/src/main/kotlin/GetFlankProject.kt b/src/main/kotlin/GetFlankProject.kt new file mode 100644 index 0000000..cc51706 --- /dev/null +++ b/src/main/kotlin/GetFlankProject.kt @@ -0,0 +1,14 @@ +import org.gradle.api.Project + +fun Project.getFlankProject(): String { + // Add the rootProject name in case the user changed the group + val projectPrefix: String = + if (rootProject == project || group.toString().contains(rootProject.name)) { + "" + } else { + rootProject.name + } + return listOf(projectPrefix, group.toString(), name) + .filter { it.isNotEmpty() } + .joinToString(".") +} \ No newline at end of file diff --git a/src/main/kotlin/SimpleFlankExtension.kt b/src/main/kotlin/SimpleFlankExtension.kt new file mode 100644 index 0000000..f97ca36 --- /dev/null +++ b/src/main/kotlin/SimpleFlankExtension.kt @@ -0,0 +1,21 @@ +import org.gradle.api.Project +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.kotlin.dsl.property +import java.io.File + +abstract class SimpleFlankExtension(private val project: Project) { + val credentialsFile: RegularFileProperty = project.objects.fileProperty() + .convention { project.rootProject.file("ftl-credentials.json") } + val projectId: Property = project.objects.property() + .convention( + credentialsFile.map { defaultProjectId(it.asFile) } + ) + + private fun defaultProjectId(file: File): String { + val projectIdRegex = "\"project_id\": \"(.*)\"".toRegex() + return if (file.exists()) + projectIdRegex.find(file.readText())?.groups?.get(1)?.value ?: throw RuntimeException(file.name + " doesn't contain a project_id") + else "" + } +} diff --git a/src/main/kotlin/flankDir.kt b/src/main/kotlin/flankDir.kt new file mode 100644 index 0000000..2800d89 --- /dev/null +++ b/src/main/kotlin/flankDir.kt @@ -0,0 +1,6 @@ +import org.gradle.api.file.Directory +import org.gradle.api.file.ProjectLayout +import org.gradle.api.provider.Provider + +internal val ProjectLayout.flankDir: Provider + get() = buildDirectory.dir("flank") diff --git a/src/main/kotlin/keystoreUtils.kt b/src/main/kotlin/keystoreUtils.kt new file mode 100644 index 0000000..91dbdd5 --- /dev/null +++ b/src/main/kotlin/keystoreUtils.kt @@ -0,0 +1,42 @@ +import com.android.build.api.dsl.ApplicationExtension +import com.android.build.gradle.LibraryExtension +import com.android.build.gradle.internal.tasks.ValidateSigningTask +import org.gradle.api.Project +import org.gradle.api.tasks.Copy +import org.gradle.kotlin.dsl.maybeCreate +import org.gradle.kotlin.dsl.withType +import java.io.File + +fun Project.verifyNotDefaultKeystore() { + val androidExtension = project.extensions.getByName("android") as ApplicationExtension + afterEvaluate { + androidExtension.signingConfigs { + named("debug") { + if (storeFile?.path?.contains("/.android/debug.keystore") == true) { + println("Warning: The debug keystore should be set, using the default means the cache won't work") + } + } + } + } +} +fun Project.useFixedKeystore() { + val copyDebugKeystore: Copy = rootProject.tasks.maybeCreate("copyDebugKeystore") + with(copyDebugKeystore) { + val pluginJar = zipTree( + SimpleFlankExtension::class.java.classLoader.getResource("debugKeystore")!!.path.split("!").first() + ) + from({ pluginJar.single { it.name == "debugKeystore" }.path }) + into("$buildDir/uitestKeystore") + } + + val androidExtension = extensions.getByName("android") as LibraryExtension + tasks.withType().configureEach { dependsOn(copyDebugKeystore) } + androidExtension.signingConfigs { + named("debug") { + storeFile = File(rootProject.buildDir, "uitestKeystore/debugKeystore") + keyAlias = "debugKey" + keyPassword = "debugKeystore" + storePassword = "debugKeystore" + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/simple-flank.gradle.kts b/src/main/kotlin/simple-flank.gradle.kts new file mode 100644 index 0000000..081452b --- /dev/null +++ b/src/main/kotlin/simple-flank.gradle.kts @@ -0,0 +1,91 @@ +import com.android.build.api.artifact.SingleArtifact +import com.android.build.api.variant.ApplicationAndroidComponentsExtension +import com.android.build.api.variant.BuiltArtifactsLoader +import com.android.build.api.variant.LibraryAndroidComponentsExtension +import com.android.build.api.variant.Variant +import com.android.build.gradle.AppPlugin +import com.android.build.gradle.LibraryPlugin +import java.lang.Integer.max +import java.lang.Integer.min + +val flankExecutable: Configuration by configurations.creating + +dependencies { + flankExecutable("com.github.flank:flank") { + version { + prefer("22.04.0") + } + } +} + +val simpleFlankExtension = extensions.create("simpleFlank") + +plugins.withType(AppPlugin::class.java) { + val appExtension = requireNotNull(extensions.findByType()) + appExtension.onVariants { + val debugApkDir: Provider = it.artifacts.get(SingleArtifact.APK) + val testApkDir: Provider? = it.androidTest?.artifacts?.get(SingleArtifact.APK) + + if (testApkDir != null) { + val builtArtifactsLoader = it.artifacts.getBuiltArtifactsLoader() + val apkProvider: Provider = debugApkDir.map { apk -> + file { builtArtifactsLoader.load(apk)?.elements?.single()?.outputFile } + } + registerFlankRun(it, testApkDir, builtArtifactsLoader).configure { + appApk.fileProvider( + apkProvider + ) + } + } + } + tasks.register("flankRun") { + dependsOn(tasks.withType()) + } + verifyNotDefaultKeystore() +} + +plugins.withType(LibraryPlugin::class.java) { + useFixedKeystore() + val libraryExtension = requireNotNull(extensions.findByType()) + libraryExtension.onVariants { + val testApkDir: Provider? = it.androidTest?.artifacts?.get(SingleArtifact.APK) + + if (testApkDir != null) { + val copySmallApp: Copy = getSmallAppTask() + val builtArtifactsLoader = it.artifacts.getBuiltArtifactsLoader() + registerFlankRun(it, testApkDir, builtArtifactsLoader).configure { + dependsOn(copySmallApp) + appApk.value { + files(copySmallApp).asFileTree.matching { include("*.apk") }.singleFile + } + } + } + } + tasks.register("flankRun") { + dependsOn(tasks.withType()) + } +} + +fun registerFlankRun( + variant: Variant, + testApkDir: Provider, + builtArtifactsLoader: BuiltArtifactsLoader +) = + tasks.register("flankRun${variant.name.capitalize()}") { + flankJarClasspath.from(flankExecutable) + + serviceAccountCredentials.set(simpleFlankExtension.credentialsFile) + projectId.set(simpleFlankExtension.projectId) + flankProject.set(getFlankProject()) + this@register.variant.set(variant.name) + + val minSdk = variant.minSdkVersion.apiLevel + val selectedSdk = min(max(NexusLowRes.minOsVersion(), minSdk), NexusLowRes.maxOsVersion()) + device.set(NexusLowRes(selectedSdk)) + testApk.fileProvider( + testApkDir.map { apk -> + file { builtArtifactsLoader.load(apk)?.elements?.single()?.outputFile } + } + ) + dumpShards.set(true) + } diff --git a/src/main/kotlin/smallAppUtils.kt b/src/main/kotlin/smallAppUtils.kt new file mode 100644 index 0000000..b4540d7 --- /dev/null +++ b/src/main/kotlin/smallAppUtils.kt @@ -0,0 +1,10 @@ +import org.gradle.api.Project +import org.gradle.api.tasks.Copy + +fun Project.getSmallAppTask(): Copy = rootProject.tasks.maybeCreate("copySmallApp", Copy::class.java).apply { + val pluginJar = zipTree( + SimpleFlankExtension::class.java.classLoader.getResource("small-app.apk")!!.path.split("!").first() + ) + from({ pluginJar.single { it.name == "small-app.apk" }.path }) + into("$buildDir/smallApp") +} \ No newline at end of file diff --git a/src/main/resources/debugKeystore b/src/main/resources/debugKeystore new file mode 100644 index 0000000..5c0df2d Binary files /dev/null and b/src/main/resources/debugKeystore differ diff --git a/src/main/resources/small-app.apk b/src/main/resources/small-app.apk new file mode 100644 index 0000000..1baeea1 Binary files /dev/null and b/src/main/resources/small-app.apk differ diff --git a/src/test/kotlin/BasicTest.kt b/src/test/kotlin/BasicTest.kt new file mode 100644 index 0000000..e88d479 --- /dev/null +++ b/src/test/kotlin/BasicTest.kt @@ -0,0 +1,44 @@ +import org.junit.Test +import strikt.api.expectThat +import strikt.assertions.isNotNull +import strikt.gradle.testkit.isFromCache +import strikt.gradle.testkit.task +import java.io.File + +internal class BasicTest: GradleTest() { + + @Test + internal fun libraryWorks() { + projectFromResources("library") + File(testProjectDir.root, "build.gradle").appendText( + """ + simpleFlank { + credentialsFile.set(project.rootProject.file("some-credentials.json")) + } + """.trimIndent() + ) + + gradleRunner("flankRun", "--stacktrace").forwardOutput().build() + gradleRunner("clean").build() + val build = gradleRunner("flankRun", "--stacktrace", "--info").forwardOutput().build() + + expectThat(build) { + task(":flankRunDebug").isNotNull().isFromCache() + task(":flankRun").isNotNull() + } + } + + @Test + internal fun appWorks() { + projectFromResources("app") + + gradleRunner("flankRun", "--stacktrace").forwardOutput().build() + gradleRunner("clean").build() + val build = gradleRunner("flankRun", "--stacktrace").forwardOutput().build() + + expectThat(build) { + task(":flankRunDebug").isNotNull().isFromCache() + task(":flankRun").isNotNull() + } + } +} \ No newline at end of file diff --git a/src/test/kotlin/GradleTest.kt b/src/test/kotlin/GradleTest.kt new file mode 100644 index 0000000..30162c6 --- /dev/null +++ b/src/test/kotlin/GradleTest.kt @@ -0,0 +1,21 @@ +import org.gradle.testkit.runner.GradleRunner +import org.junit.Rule +import org.junit.rules.TemporaryFolder +import java.io.File + +abstract class GradleTest { + @get:Rule + val testProjectDir = TemporaryFolder() + + fun projectFromResources(resourceFolder: String) { + File(javaClass.getResource(resourceFolder)!!.toURI()).copyRecursively(testProjectDir.root) + } + + fun gradleRunner(vararg arguments: String): GradleRunner { + return GradleRunner.create() + .withProjectDir(testProjectDir.root) + .withArguments(arguments.asList()) + .withPluginClasspath() + } + +} \ No newline at end of file diff --git a/src/test/kotlin/VariantsTest.kt b/src/test/kotlin/VariantsTest.kt new file mode 100644 index 0000000..1221a89 --- /dev/null +++ b/src/test/kotlin/VariantsTest.kt @@ -0,0 +1,76 @@ +import org.junit.Test +import strikt.api.expectThat +import strikt.assertions.isNotNull +import strikt.gradle.testkit.task +import java.io.File + +class VariantsTest: GradleTest() { + + @Test + fun useTheDefaultBuildType() { + projectFromResources("app") + + val build = gradleRunner("flankRun").forwardOutput().build() + + expectThat(build) { + task(":packageDebug").isNotNull() + task(":packageDebugAndroidTest").isNotNull() + task(":flankRun").isNotNull() + } + } + + @Test + fun allowToChangeTheBuildType() { + projectFromResources("app") + File(testProjectDir.root, "build.gradle.kts").appendText( + """ + android { + testBuildType = "beta" + + buildTypes { + create("beta") + } + } + """.trimIndent() + ) + + val build = gradleRunner("flankRun").forwardOutput().build() + + expectThat(build) { + task(":packageBeta").isNotNull() + task(":packageBetaAndroidTest").isNotNull() + task(":flankRun").isNotNull() + } + } + + @Test + fun allowFlavors() { + projectFromResources("app") + File(testProjectDir.root, "build.gradle.kts").appendText( + """ + android { + flavorDimensions += listOf("env") + + productFlavors { + create("pre") { + dimension = "env" + } + create("pro") { + dimension = "env" + } + } + } + """.trimIndent() + ) + + val build = gradleRunner("flankRun").forwardOutput().build() + + expectThat(build) { + task(":packagePreDebug").isNotNull() + task(":packagePreDebugAndroidTest").isNotNull() + task(":packageProDebug").isNotNull() + task(":packageProDebugAndroidTest").isNotNull() + task(":flankRun").isNotNull() + } + } +} \ No newline at end of file diff --git a/src/test/resources/app/build.gradle.kts b/src/test/resources/app/build.gradle.kts new file mode 100644 index 0000000..21d64ce --- /dev/null +++ b/src/test/resources/app/build.gradle.kts @@ -0,0 +1,26 @@ +plugins { + id("com.android.application") + id("kotlin-android") + id("simple-flank") +} + +repositories { + google() + mavenCentral() +} + +android { + compileSdkVersion(30) + defaultConfig { + applicationId = "flank.simpleflank.testApp" + versionCode = 1 + versionName = "1.0" + targetSdkVersion(30) + minSdkVersion(21) + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } +} diff --git a/src/test/resources/app/gradle.properties b/src/test/resources/app/gradle.properties new file mode 100644 index 0000000..1608900 --- /dev/null +++ b/src/test/resources/app/gradle.properties @@ -0,0 +1 @@ +org.gradle.caching=true diff --git a/src/test/resources/app/settings.gradle b/src/test/resources/app/settings.gradle new file mode 100644 index 0000000..6780415 --- /dev/null +++ b/src/test/resources/app/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'app' \ No newline at end of file diff --git a/src/test/resources/app/src/androidTest/SampleAppTest.kt b/src/test/resources/app/src/androidTest/SampleAppTest.kt new file mode 100644 index 0000000..44b3162 --- /dev/null +++ b/src/test/resources/app/src/androidTest/SampleAppTest.kt @@ -0,0 +1,2 @@ +class SampleAppTest { +} diff --git a/src/test/resources/app/src/main/AndroidManifest.xml b/src/test/resources/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..e399766 --- /dev/null +++ b/src/test/resources/app/src/main/AndroidManifest.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/app/src/main/java/flank/simpleflank/smallapp/MainActivity.java b/src/test/resources/app/src/main/java/flank/simpleflank/smallapp/MainActivity.java new file mode 100644 index 0000000..f1ce42c --- /dev/null +++ b/src/test/resources/app/src/main/java/flank/simpleflank/smallapp/MainActivity.java @@ -0,0 +1,12 @@ +package flank.simpleflank.smallapp; + +import android.app.Activity; +import android.os.Bundle; + +public class MainActivity extends Activity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } +} \ No newline at end of file diff --git a/src/test/resources/library/build.gradle b/src/test/resources/library/build.gradle new file mode 100644 index 0000000..6ac15f2 --- /dev/null +++ b/src/test/resources/library/build.gradle @@ -0,0 +1,26 @@ +plugins { + id("com.android.library") + id("kotlin-android") + id("simple-flank") +} + +repositories { + google() + mavenCentral() +} + +android { + useLibrary 'android.test.runner' + useLibrary 'android.test.base' + + compileSdkVersion = 30 + defaultConfig { + targetSdkVersion = 30 + minSdkVersion = 21 + } +} + +dependencies { + androidTestImplementation("junit:junit:4.13") + flankExecutable("com.github.flank:flank:22.04.0") +} diff --git a/src/test/resources/library/gradle.properties b/src/test/resources/library/gradle.properties new file mode 100644 index 0000000..514c7b7 --- /dev/null +++ b/src/test/resources/library/gradle.properties @@ -0,0 +1,5 @@ +org.gradle.caching=true + +commonplatform.android.compileSdk=30 +commonplatform.android.targetSdk=30 +commonplatform.android.minSdk=21 diff --git a/src/test/resources/library/settings.gradle b/src/test/resources/library/settings.gradle new file mode 100644 index 0000000..c98a169 --- /dev/null +++ b/src/test/resources/library/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'library' \ No newline at end of file diff --git a/src/test/resources/library/src/androidTest/kotlin/ATest.kt b/src/test/resources/library/src/androidTest/kotlin/ATest.kt new file mode 100644 index 0000000..a286df2 --- /dev/null +++ b/src/test/resources/library/src/androidTest/kotlin/ATest.kt @@ -0,0 +1,7 @@ +import org.junit.Test + +class ATest { + @Test + fun test() { + } +} diff --git a/src/test/resources/library/src/main/AndroidManifest.xml b/src/test/resources/library/src/main/AndroidManifest.xml new file mode 100644 index 0000000..aa94d2f --- /dev/null +++ b/src/test/resources/library/src/main/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + \ No newline at end of file