-
Notifications
You must be signed in to change notification settings - Fork 18
/
FirebaseTestLabPlugin.kt
375 lines (324 loc) · 16.2 KB
/
FirebaseTestLabPlugin.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package com.appunite.firebasetestlabplugin
import com.android.build.VariantOutput
import com.android.build.gradle.AppExtension
import com.android.build.gradle.api.BaseVariantOutput
import com.android.build.gradle.api.TestVariant
import com.appunite.firebasetestlabplugin.cloud.CloudTestResultDownloader
import com.appunite.firebasetestlabplugin.cloud.FirebaseTestLabProcessCreator
import com.appunite.firebasetestlabplugin.cloud.TestType
import com.appunite.firebasetestlabplugin.model.Device
import com.appunite.firebasetestlabplugin.model.TestResults
import com.appunite.firebasetestlabplugin.utils.Constants
import org.apache.tools.ant.taskdefs.condition.Os
import org.gradle.api.*
import org.gradle.api.tasks.Exec
import org.gradle.kotlin.dsl.closureOf
import org.gradle.kotlin.dsl.createTask
import org.gradle.kotlin.dsl.task
import java.io.ByteArrayOutputStream
import java.io.File
internal class FirebaseTestLabPlugin : Plugin<Project> {
open class HiddenExec : Exec() {
init {
standardOutput = ByteArrayOutputStream()
errorOutput = standardOutput
isIgnoreExitValue = true
doLast {
if (execResult.exitValue != 0) {
println(standardOutput.toString())
throw GradleException("exec failed; see output above")
}
}
}
}
companion object {
private const val GRADLE_METHOD_NAME = "firebaseTestLab"
private const val ANDROID = "android"
private const val ensureGCloudSdk = "firebaseTestLabEnsureGCloudSdk"
private const val taskAuth = "firebaseTestLabAuth"
private const val taskSetup = "firebaseTestLabSetup"
private const val taskSetProject = "firebaseTestLabSetProject"
}
private lateinit var project: Project
/**
* Create extension used to configure testing properties, platforms..
* After that @param[setup] check for required fields validity
* and throw @param[GradleException] if needed
*/
override fun apply(project: Project) {
this.project = project
project.extensions.create(
GRADLE_METHOD_NAME,
FirebaseTestLabPluginExtension::class.java,
project)
project.afterEvaluate {
setup()
}
}
data class Sdk(val gcloud: File, val gsutil: File)
private fun createDownloadSdkTask(project: Project, cloudSdkPath: String?): Sdk =
if (cloudSdkPath != null) {
val sdkPath = File(cloudSdkPath)
val gcloud = File(sdkPath, Constants.GCLOUD)
val gsutil = File(sdkPath, Constants.GSUTIL)
project.task(ensureGCloudSdk, {
group = Constants.FIREBASE_TEST_LAB
description = "Check if google cloud sdk is installed"
doFirst {
if (!gcloud.exists()) {
throw IllegalStateException("gcloud does not exist in path ${sdkPath.absoluteFile}, but downloading is not supported on Windows")
}
if (!gsutil.exists()) {
throw IllegalStateException("gsutil does not exist in path ${sdkPath.absoluteFile}, but downloading is not supported on Windows")
}
}
})
Sdk(gcloud, gsutil)
} else {
val env = System.getenv("CLOUDSDK_INSTALL_DIR")
val installDir = when {
!env.isNullOrEmpty() -> File(env)
else -> File(project.buildDir, "gcloud")
}
project.logger.lifecycle("gCloud sdk installation dir: $installDir")
val cloudSdkDir = File(installDir, "google-cloud-sdk")
val sdkPath = File(cloudSdkDir, "bin")
project.logger.lifecycle("gCloud sdk path: $sdkPath")
val gcloud = File(sdkPath, Constants.GCLOUD)
val gsutil = File(sdkPath, Constants.GSUTIL)
project.createTask(ensureGCloudSdk, HiddenExec::class, {
group = Constants.FIREBASE_TEST_LAB
description = "Install google cloud SDK if necessary"
outputs.files(gcloud, gsutil)
doFirst {
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
throw IllegalStateException("Fetching gcloud and gsutil is not supported on Windows. " +
"You need to install it manually. Look for instructions: https://cloud.google.com/sdk/downloads#windows ." +
"Than you need to set:\n " +
"firebaseTestLab {\n" +
" cloudSdkPath = \"Xyz\"\n" +
"}\n")
}
}
commandLine = listOf("bash", "-c", "rm -r \"${cloudSdkDir.absolutePath}\";export CLOUDSDK_CORE_DISABLE_PROMPTS=1 && export CLOUDSDK_INSTALL_DIR=\"${installDir.absolutePath}\" && curl https://sdk.cloud.google.com | bash")
doLast {
if (!gcloud.exists()) throw IllegalStateException("Installation failed")
if (!gsutil.exists()) throw IllegalStateException("Installation failed")
}
})
Sdk(gcloud, gsutil)
}
private fun setup() {
project.extensions.findByType(FirebaseTestLabPluginExtension::class.java)?.apply {
val devices = devices.toList()
val sdk = createDownloadSdkTask(project, cloudSdkPath)
project.createTask(taskAuth, HiddenExec::class, {
group = Constants.FIREBASE_TEST_LAB
description = "Authorize google cloud sdk"
dependsOn(ensureGCloudSdk)
val keyFile = keyFile
doFirst {
if (keyFile == null) {
throw GradleException("You need to set firebaseTestLab.keyFile = file(\"key-file.json\") before run")
} else if (!keyFile.exists()) {
throw GradleException("Key file (${keyFile.absolutePath} does not exists")
}
}
commandLine = listOf(sdk.gcloud.absolutePath, "auth", "activate-service-account", "--key-file=${keyFile?.absolutePath}")
})
project.createTask(taskSetProject, HiddenExec::class, {
group = Constants.FIREBASE_TEST_LAB
description = "Configure google cloud sdk project"
dependsOn(ensureGCloudSdk)
doFirst {
if (googleProjectId == null) {
throw GradleException("You need to set firebaseTestLab.googleProjectId before run")
}
}
commandLine = listOf(sdk.gcloud.absolutePath, "config", "set", "project", "$googleProjectId")
})
project.task(taskSetup, {
group = Constants.FIREBASE_TEST_LAB
description = "Setup and configure google cloud sdk"
dependsOn(taskSetProject)
dependsOn(taskAuth)
})
val downloader: CloudTestResultDownloader? = if (cloudBucketName != null) {
CloudTestResultDownloader(
sdk,
resultsTypes,
File(cloudDirectoryName),
File(project.buildDir, cloudDirectoryName),
cloudBucketName!!,
project.logger
)
} else {
null
}
if (clearDirectoryBeforeRun && downloader == null) {
throw IllegalStateException("If you want to clear directory before run you need to setup cloudBucketName")
}
val firebaseTestLabProcessCreator = FirebaseTestLabProcessCreator(
sdk,
cloudBucketName,
cloudDirectoryName,
project.logger
)
(project.extensions.findByName(ANDROID) as AppExtension).apply {
testVariants.toList().forEach { testVariant ->
createGroupedTestLabTask(devices, testVariant, firebaseTestLabProcessCreator, ignoreFailures, downloader)
}
}
}
}
data class DeviceAppMap(val device: Device, val apk: BaseVariantOutput)
data class Test(val device: Device, val apk: BaseVariantOutput, val testApk: BaseVariantOutput)
private fun createGroupedTestLabTask(
devices: List<Device>,
variant: TestVariant,
firebaseTestLabProcessCreator: FirebaseTestLabProcessCreator,
ignoreFailures: Boolean,
downloader: CloudTestResultDownloader?) {
val variantName = variant.testedVariant?.name?.capitalize() ?: ""
val cleanTask = "firebaseTestLabClean${variantName.capitalize()}"
val runTestsTask = "firebaseTestLabExecute${variantName.capitalize()}"
val runTestsTaskInstrumentation = "${runTestsTask}Instrumentation"
val runTestsTaskRobo = "${runTestsTask}Robo"
val downloadTask = "firebaseTestLabDownload${variantName.capitalize()}"
if (downloader != null) {
project.task(cleanTask, closureOf<Task> {
group = Constants.FIREBASE_TEST_LAB
description = "Clean test lab artifacts on google storage"
dependsOn(taskSetup)
doLast {
downloader.clearResultsDir()
}
})
}
val appVersions = combineAll(devices, variant.testedVariant.outputs, ::DeviceAppMap)
.filter {
val hasAbiSplits = it.apk.filterTypes.contains(VariantOutput.ABI)
if (hasAbiSplits) {
if (it.device.filterAbiSplits) {
val abi = it.apk.filters.first { it.filterType == VariantOutput.ABI }.identifier
it.device.abiSplits.contains(abi)
} else {
true
}
} else {
it.device.testUniversalApk
}
}
val roboTasks = appVersions
.map {
test ->
val devicePart = test.device.name.capitalize()
val apkPart = dashToCamelCase(test.apk.name).capitalize()
val taskName = "$runTestsTaskRobo$devicePart$apkPart"
project.task(taskName, closureOf<Task> {
inputs.files(test.apk.outputFile)
group = Constants.FIREBASE_TEST_LAB
description = "Run Robo test for ${test.device.name} device on $variantName/${test.apk.name} in Firebase Test Lab"
if (downloader != null) {
mustRunAfter(cleanTask)
}
dependsOn(taskSetup)
dependsOn(arrayOf(test.apk.assemble))
doLast {
val result = firebaseTestLabProcessCreator.callFirebaseTestLab(test.device, test.apk.outputFile, TestType.Robo)
processResult(result, ignoreFailures)
}
})
}
val instrumentationTasks = combineAll(appVersions, variant.outputs, {deviceAndMap, testApk -> Test(deviceAndMap.device, deviceAndMap.apk, testApk)})
.map {
test ->
val devicePart = test.device.name.capitalize()
val apkPart = dashToCamelCase(test.apk.name).capitalize()
val testApkPart = test.testApk.let { if (it.filters.isEmpty()) "" else dashToCamelCase(it.name).capitalize() }
val taskName = "$runTestsTaskInstrumentation$devicePart$apkPart$testApkPart"
project.task(taskName, closureOf<Task> {
inputs.files(test.testApk.outputFile, test.apk.outputFile)
group = Constants.FIREBASE_TEST_LAB
description = "Run Instrumentation test for ${test.device.name} device on $variantName/${test.apk.name} in Firebase Test Lab"
if (downloader != null) {
mustRunAfter(cleanTask)
}
dependsOn(taskSetup)
dependsOn(arrayOf(test.apk.assemble, test.testApk.assemble))
doLast {
val result = firebaseTestLabProcessCreator.callFirebaseTestLab(test.device, test.apk.outputFile, TestType.Instrumentation(test.testApk.outputFile))
processResult(result, ignoreFailures)
}
})
}
val allInstrumentation = project.task(runTestsTaskInstrumentation, closureOf<Task> {
group = Constants.FIREBASE_TEST_LAB
description = "Run all Instrumentation tests for $variantName in Firebase Test Lab"
dependsOn(instrumentationTasks)
doFirst {
if (devices.isEmpty()) throw IllegalStateException("You need to set et least one device in:\n" +
"firebaseTestLab {" +
" devices {\n" +
" nexus6 {\n" +
" androidApiLevels = [21]\n" +
" deviceIds = [\"Nexus6\"]\n" +
" locales = [\"en\"]\n" +
" }\n" +
" } " +
"}")
if (instrumentationTasks.isEmpty()) throw IllegalStateException("Nothing match your filter")
}
})
val allRobo = project.task(runTestsTaskRobo, closureOf<Task> {
group = Constants.FIREBASE_TEST_LAB
description = "Run all Robo tests for $variantName in Firebase Test Lab"
dependsOn(roboTasks)
doFirst {
if (devices.isEmpty()) throw IllegalStateException("You need to set et least one device in:\n" +
"firebaseTestLab {" +
" devices {\n" +
" nexus6 {\n" +
" androidApiLevels = [21]\n" +
" deviceIds = [\"Nexus6\"]\n" +
" locales = [\"en\"]\n" +
" }\n" +
" } " +
"}")
if (roboTasks.isEmpty()) throw IllegalStateException("Nothing match your filter")
}
})
project.task(runTestsTask, closureOf<Task> {
group = Constants.FIREBASE_TEST_LAB
description = "Run all tests for $variantName in Firebase Test Lab"
dependsOn(allRobo, allInstrumentation)
})
if (downloader != null) {
project.task(downloadTask, closureOf<Task> {
group = Constants.FIREBASE_TEST_LAB
description = "Run Android Tests in Firebase Test Lab and download artifacts from google storage"
dependsOn(taskSetup)
dependsOn(runTestsTask)
mustRunAfter(cleanTask)
doLast {
downloader.getResults()
}
})
}
}
private fun processResult(result: TestResults, ignoreFailures: Boolean) {
if (result.isSuccessful) {
project.logger.lifecycle(result.message)
} else {
if (ignoreFailures) {
project.logger.error("Error: ${result.message}")
} else {
throw GradleException(result.message)
}
}
}
}
private fun <T1, T2, R> combineAll(l1: Collection<T1>, l2: Collection<T2>, func: (T1, T2) -> R): List<R> =
l1.flatMap { t1 -> l2.map { t2 -> func(t1, t2)} }
private fun dashToCamelCase(dash: String): String =
dash.split('-', '_').joinToString("") { it.capitalize() }