-
-
Notifications
You must be signed in to change notification settings - Fork 120
/
BaseAndroidDevice.kt
339 lines (299 loc) · 14.1 KB
/
BaseAndroidDevice.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
package com.malinskiy.marathon.android
import com.android.sdklib.AndroidVersion
import com.malinskiy.marathon.analytics.internal.pub.Track
import com.malinskiy.marathon.exceptions.TransferException
import com.malinskiy.marathon.android.executor.listeners.CompositeTestRunListener
import com.malinskiy.marathon.android.executor.listeners.DebugTestRunListener
import com.malinskiy.marathon.execution.listener.LogListener
import com.malinskiy.marathon.android.executor.listeners.NoOpTestRunListener
import com.malinskiy.marathon.android.executor.listeners.TestRunListenerAdapter
import com.malinskiy.marathon.android.executor.listeners.TestResultsListener
import com.malinskiy.marathon.android.executor.listeners.filesync.FileSyncTestRunListener
import com.malinskiy.marathon.android.executor.listeners.screenshot.AdamScreenCaptureTestRunListener
import com.malinskiy.marathon.android.executor.listeners.screenshot.ScreenCapturerTestRunListener
import com.malinskiy.marathon.android.executor.listeners.video.ScreenRecorderTestBatchListener
import com.malinskiy.marathon.android.model.ShellCommandResult
import com.malinskiy.marathon.device.screenshot.Rotation
import com.malinskiy.marathon.config.Configuration
import com.malinskiy.marathon.config.ScreenRecordingPolicy
import com.malinskiy.marathon.config.vendor.VendorConfiguration
import com.malinskiy.marathon.config.vendor.android.AggregationMode
import com.malinskiy.marathon.config.vendor.android.FileSyncEntry
import com.malinskiy.marathon.config.vendor.android.PathRoot
import com.malinskiy.marathon.config.vendor.android.SerialStrategy
import com.malinskiy.marathon.device.DeviceFeature
import com.malinskiy.marathon.device.DevicePoolId
import com.malinskiy.marathon.device.OperatingSystem
import com.malinskiy.marathon.device.toDeviceInfo
import com.malinskiy.marathon.exceptions.DeviceSetupException
import com.malinskiy.marathon.execution.TestBatchResults
import com.malinskiy.marathon.extension.withTimeoutOrNull
import com.malinskiy.marathon.io.FileManager
import com.malinskiy.marathon.log.MarathonLogging
import com.malinskiy.marathon.report.attachment.AttachmentProvider
import com.malinskiy.marathon.report.logs.LogWriter
import com.malinskiy.marathon.test.TestBatch
import com.malinskiy.marathon.time.Timer
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import java.util.UUID
import kotlin.system.measureTimeMillis
abstract class BaseAndroidDevice(
val adbSerial: String,
protected val serialStrategy: SerialStrategy,
protected val configuration: Configuration,
protected val androidConfiguration: VendorConfiguration.AndroidConfiguration,
protected val track: Track,
protected val timer: Timer
) : AndroidDevice, CoroutineScope {
override val logger = MarathonLogging.logger(AndroidDevice::class.java.simpleName)
override var abi: String = "Unknown"
override var version: AndroidVersion = AndroidVersion.DEFAULT
override var externalStorageMount: String = "Unknown"
override var model: String = "Unknown"
override var manufacturer: String = "Unknown"
override var deviceFeatures: Collection<DeviceFeature> = emptyList()
override var apiLevel: Int = version.apiLevel
override var operatingSystem: OperatingSystem = OperatingSystem(version.apiStringWithoutExtension)
override var initialRotation: Rotation = Rotation.ROTATION_0
var realSerialNumber: String = "Unknown"
var booted: Boolean = false
override val serialNumber: String
get() = when {
booted -> realSerialNumber
else -> adbSerial
}
override val fileManager = RemoteFileManager(this)
protected lateinit var md5cmd: String
/**
* The call to fetchRotation is a very expensive one on Android so we just keep returning the original orientation
*/
override val orientation: Rotation
get() = initialRotation
override suspend fun setup() {
booted = false
withTimeoutOrNull(androidConfiguration.timeoutConfiguration.boot) {
waitForBoot()
booted = true
} ?: throw DeviceSetupException("Unable to configure device $serialNumber: not booted")
abi = getProperty("ro.product.cpu.abi") ?: abi
val sdk = getProperty("ro.build.version.sdk")
val codename = getProperty("ro.build.version.codename")
version = if (sdk != null && codename != null) {
AndroidVersion(sdk.toInt(), codename)
} else AndroidVersion.DEFAULT
apiLevel = version.apiLevel
operatingSystem = OperatingSystem(version.apiStringWithoutExtension)
model = getProperty("ro.product.model") ?: "Unknown"
manufacturer = getProperty("ro.product.manufacturer") ?: "Unknown"
initialRotation = fetchRotation()
externalStorageMount = safeExecuteShellCommand("echo \$EXTERNAL_STORAGE")?.output?.trim {
when (it) {
'\n' -> true
'\r' -> true
else -> false
}
}
?: throw DeviceSetupException("Unable to configure device $serialNumber: externalStorageMount")
deviceFeatures = detectFeatures()
realSerialNumber = detectRealSerialNumber()
md5cmd = detectMd5Binary()
if (androidConfiguration.allureConfiguration.enabled) {
androidConfiguration.fileSyncConfiguration.pull.add(
FileSyncEntry(
relativePath = androidConfiguration.allureConfiguration.relativeResultsDirectory,
pathRoot = androidConfiguration.allureConfiguration.pathRoot,
aggregationMode = AggregationMode.TEST_RUN,
)
)
}
if (configuration.isCodeCoverageEnabled) {
androidConfiguration.fileSyncConfiguration.pull.add(
FileSyncEntry(
relativePath = "coverage",
pathRoot = PathRoot.APP_DATA,
aggregationMode = AggregationMode.POOL
)
)
}
}
override suspend fun safePullFile(remoteFilePath: String, localFilePath: String) {
try {
withTimeoutOrNull(androidConfiguration.timeoutConfiguration.pullFile) {
pullFile(remoteFilePath, localFilePath)
} ?: logger.warn { "Pulling $remoteFilePath timed out. Ignoring" }
} catch (e: TransferException) {
logger.warn(e) { "Pulling $remoteFilePath failed. Ignoring" }
}
}
override suspend fun safePullFolder(remoteFolderPath: String, localFolderPath: String) {
try {
pullFolder(remoteFolderPath, localFolderPath)
} catch (e: TransferException) {
logger.warn(e) { "Pulling $remoteFolderPath failed. Ignoring" }
}
}
/**
* We can only do this after the device finished booting
*/
protected open suspend fun detectRealSerialNumber(): String {
val marathonSerialProp: String = getProperty("marathon.serialno") ?: ""
val serialProp: String = getProperty("ro.boot.serialno") ?: ""
val hostName: String = getProperty("net.hostname") ?: ""
val serialNumber = adbSerial
return when (serialStrategy) {
SerialStrategy.AUTOMATIC -> {
marathonSerialProp.takeIf { it.isNotEmpty() }
?: serialNumber.takeIf { it.isNotEmpty() }
?: serialProp.takeIf { it.isNotEmpty() }
?: hostName.takeIf { it.isNotEmpty() }
?: UUID.randomUUID().toString()
}
SerialStrategy.MARATHON_PROPERTY -> marathonSerialProp
SerialStrategy.BOOT_PROPERTY -> serialProp
SerialStrategy.HOSTNAME -> hostName
SerialStrategy.DDMS -> serialNumber
}
}
private suspend fun detectFeatures(): List<DeviceFeature> {
val screenRecordSupport = when {
!version.isGreaterOrEqualThan(19) -> false
else -> hasBinary("/system/bin/screenrecord")
}
val screenshotSupport = version.isGreaterOrEqualThan(AndroidVersion.VersionCodes.JELLY_BEAN)
val features = mutableListOf<DeviceFeature>()
if (screenRecordSupport) features.add(DeviceFeature.VIDEO)
if (screenshotSupport) features.add(DeviceFeature.SCREENSHOT)
return features
}
override suspend fun clearPackage(packageName: String): ShellCommandResult? =
criticalExecuteShellCommand("pm clear $packageName", "Could not clear package $packageName on device: $serialNumber")
protected suspend fun clearLogcat() = safeExecuteShellCommand("logcat -c", "Could not clear logcat on device: $serialNumber")
protected suspend fun waitForRemoteFileSync(
md5: String,
remotePath: String
) {
if (md5.isNotEmpty() && md5cmd.isNotEmpty()) {
val syncTimeMillis = measureTimeMillis {
do {
val remoteMd5 = safeExecuteShellCommand("$md5cmd $remotePath")?.output ?: ""
delay(10)
} while (!remoteMd5.contains(md5))
}
logger.debug { "$remotePath synced in ${syncTimeMillis}ms" }
} else {
logger.warn { "no md5 was calculated for $remotePath. unable to sync" }
}
}
private suspend fun hasBinary(path: String): Boolean {
return safeExecuteShellCommand("ls $path")?.exitCode == 0
}
private suspend fun waitForBoot() {
while (getProperty("sys.boot_completed", false) == null) {
logger.debug { "Device $serialNumber is still booting..." }
delay(1000)
}
logger.debug { "Device $serialNumber booted!" }
}
fun isLocalEmulator() = adbSerial.startsWith("emulator-")
protected suspend fun AndroidDevice.isEmulator(): Boolean = when {
getProperty("ro.kernel.qemu")?.isNotBlank() ?: false -> true
getProperty("service.adb.transport") == "goldfish" -> true
else -> false
}
protected fun createExecutionListeners(
configuration: Configuration,
devicePoolId: DevicePoolId,
testBatch: TestBatch,
deferred: CompletableDeferred<TestBatchResults>,
): CompositeTestRunListener {
val fileManager = FileManager(
configuration.outputConfiguration.maxPath,
configuration.outputConfiguration.maxFilename,
configuration.outputDir
)
val attachmentProviders = mutableListOf<AttachmentProvider>()
val features = this.deviceFeatures
val recordConfiguration = this@BaseAndroidDevice.androidConfiguration.screenRecordConfiguration
val screenRecordingPolicy = configuration.screenRecordingPolicy
val recorderListener = RecorderTypeSelector.selectRecorderType(features, recordConfiguration)?.let { feature ->
prepareRecorderListener(feature, fileManager, devicePoolId, testBatch.id, screenRecordingPolicy, attachmentProviders)
} ?: NoOpTestRunListener()
val logListener = TestRunListenerAdapter(
LogListener(this.toDeviceInfo(), this, devicePoolId, testBatch.id, LogWriter(fileManager))
.also { attachmentProviders.add(it) }
)
val fileSyncTestRunListener =
FileSyncTestRunListener(devicePoolId, this, this@BaseAndroidDevice.androidConfiguration.fileSyncConfiguration, fileManager)
val adamScreenCaptureTestRunListener = AdamScreenCaptureTestRunListener(devicePoolId, this, fileManager, testBatch.id)
attachmentProviders.add(adamScreenCaptureTestRunListener)
return CompositeTestRunListener(
listOf(
recorderListener,
logListener,
TestResultsListener(testBatch, this, deferred, timer, devicePoolId, attachmentProviders),
DebugTestRunListener(this),
adamScreenCaptureTestRunListener,
fileSyncTestRunListener
)
)
}
private fun prepareRecorderListener(
feature: DeviceFeature, fileManager: FileManager, devicePoolId: DevicePoolId, testBatchId: String,
screenRecordingPolicy: ScreenRecordingPolicy,
attachmentProviders: MutableList<AttachmentProvider>
): NoOpTestRunListener =
when (feature) {
DeviceFeature.VIDEO -> {
ScreenRecorderTestBatchListener(
fileManager,
devicePoolId,
testBatchId,
this,
androidConfiguration.screenRecordConfiguration.videoConfiguration,
screenRecordingPolicy,
this
)
.also { attachmentProviders.add(it) }
}
DeviceFeature.SCREENSHOT -> {
ScreenCapturerTestRunListener(
fileManager,
devicePoolId,
testBatchId,
this,
screenRecordingPolicy,
androidConfiguration.screenRecordConfiguration.screenshotConfiguration,
androidConfiguration.timeoutConfiguration.screencapturer,
this
)
.also { attachmentProviders.add(it) }
}
}
private suspend fun detectMd5Binary(): String {
for (path in listOf("/system/bin/md5", "/system/bin/md5sum")) {
if (hasBinary(path)) return path.split("/").last()
}
return ""
}
private suspend fun fetchRotation() =
safeExecuteShellCommand("dumpsys input")?.output?.let { dumpsysOutput ->
val start = dumpsysOutput.indexOf("SurfaceOrientation")
if (start == -1) {
return@let null
}
val end = dumpsysOutput.indexOf('\n', startIndex = start)
if (end == -1) {
return@let null
}
val split = dumpsysOutput.substring(start, end).trim().split(":")
if (split.size != 2) {
return@let null
}
return@let split[1].trim().toIntOrNull()?.let { Rotation.of(it) }
} ?: Rotation.ROTATION_0
override fun toString(): String {
return "AndroidDevice(model=$model, serial=$serialNumber)"
}
}