-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
build_and_test_android.py
446 lines (326 loc) · 15.6 KB
/
build_and_test_android.py
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0.
#
import re
import os
import argparse
import subprocess
import shutil
import time
import datetime
import sys
TestName = "AndroidSDKTesting"
TestLowerName = TestName.lower()
def ArgumentException( Exception ):
def __init__( self, argumentName, argumentValue ):
self.m_argumentName = argumentName
self.m_argumentValue = argumentValue
def ParseArguments():
parser = argparse.ArgumentParser(description="AWSNativeSDK Android Test Script")
parser.add_argument("--clean", action="store_true")
parser.add_argument("--emu", action="store_true")
parser.add_argument("--abi", action="store")
parser.add_argument("--avd", action="store")
parser.add_argument("--nobuild", action="store_true")
parser.add_argument("--noinstall", action="store_true")
parser.add_argument("--runtest", action="store")
parser.add_argument("--credentials", action="store")
parser.add_argument("--build", action="store")
parser.add_argument("--so", action="store_true")
parser.add_argument("--stl", action="store")
args = vars( parser.parse_args() )
argMap = {}
argMap[ "clean" ] = args[ "clean" ]
argMap[ "abi" ] = args[ "abi" ] or "armeabi-v7a"
argMap[ "avd" ] = args[ "avd" ]
argMap[ "useExistingEmulator" ] = args[ "emu" ]
argMap[ "noBuild" ] = args[ "nobuild" ]
argMap[ "noInstall" ] = args[ "noinstall" ]
argMap[ "credentialsFile" ] = args[ "credentials" ] or "~/.aws/credentials"
argMap[ "buildType" ] = args[ "build" ] or "Release"
argMap[ "runTest" ] = args[ "runtest" ]
argMap[ "so" ] = args[ "so" ]
argMap[ "stl" ] = args[ "stl" ] or "libc++_shared"
return argMap
def IsValidABI(abi):
return abi == "armeabi-v7a"
def ShouldBuildClean(abi, buildDir):
if not os.path.exists( buildDir ):
return True
abiPattern = re.compile("ANDROID_ABI:STRING=\s*(?P<abi>\S+)")
for _, line in enumerate(open(buildDir + "/CMakeCache.txt")):
result = abiPattern.search(line)
if result != None:
return result.group("abi") != abi
return False
def BuildAvdAbiSet():
namePattern = re.compile("Name:\s*(?P<name>\S+)")
abiPattern = re.compile("ABI: default/(?P<abi>\S+)")
avdList = subprocess.check_output(["android", "list", "avds"])
avdABIs = {}
currentName = None
for _, line in enumerate(avdList.splitlines()):
if not currentName:
nameResult = namePattern.search(line)
if nameResult != None:
currentName = nameResult.group("name")
else:
abiResult = abiPattern.search(line)
if abiResult != None:
avdABIs[currentName] = abiResult.group("abi")
currentName = None
return avdABIs
def DoesAVDSupportABI(avdAbi, abi):
if avdAbi == "armeabi-v7a":
return abi == "armeabi-v7a" or abi == "armeabi"
else:
return abi == avdAbi
def FindAVDForABI(abi, avdABIs):
for avdName in avdABIs:
if DoesAVDSupportABI(avdABIs[avdName], abi):
return avdName
return None
def IsValidAVD(avd, abi, avdABIs):
return DoesAVDSupportABI(avdABIs[avd], abi)
def GetTestList(buildSharedObjects):
if buildSharedObjects:
return [ 'core', 's3', 'dynamodb', 'cloudfront', 'cognitoidentity', 'identity', 'lambda', 'logging', 'redshift', 'sqs', 'transfer' ]
else:
return [ 'unified' ]
def ValidateArguments(buildDir, avd, abi, clean, runTest, buildSharedObjects):
validTests = GetTestList( buildSharedObjects )
if runTest not in validTests:
print( 'Invalid value for runtest option: ' + runTest )
print( 'Valid values are: ' )
print( ' ' + ", ".join( validTests ) )
raise ArgumentException('runtest', runTest)
if not IsValidABI(abi):
print('Invalid argument value for abi: ', abi)
print(' Valid values are "armeabi-v7a"')
raise ArgumentException('abi', abi)
if not clean and ShouldBuildClean(abi, buildDir):
clean = True
avdABIs = BuildAvdAbiSet()
if not avd:
print('No virtual device specified (--avd), trying to find one in the existing avd set...')
avd = FindAVDForABI(abi, avdABIs)
if not IsValidAVD(avd, abi, avdABIs):
print('Invalid virtual device: ', avd)
print(' Use --avd to set the virtual device')
print(' Use "android lists avds" to see all usable virtual devices')
raise ArgumentException('avd', avd)
return (avd, abi, clean)
def SetupJniDirectory(abi, clean):
path = os.path.join( TestName, "app", "src", "main", "jniLibs", abi )
if clean and os.path.exists(path):
shutil.rmtree(path)
if os.path.exists( path ) == False:
os.makedirs( path )
return path
def CopyNativeLibraries(buildSharedObjects, jniDir, buildDir, abi, stl):
baseToolchainDir = os.path.join(buildDir, 'toolchains', 'android')
toolchainDirList = os.listdir(baseToolchainDir) # should only be one entry
toolchainDir = os.path.join(baseToolchainDir, toolchainDirList[0])
platformLibDir = os.path.join(toolchainDir, "sysroot", "usr", "lib")
shutil.copy(os.path.join(platformLibDir, "liblog.so"), jniDir)
stdLibDir = os.path.join(toolchainDir, 'arm-linux-androideabi', 'lib')
if stl == 'libc++_shared':
shutil.copy(os.path.join(stdLibDir, "libc++_shared.so"), jniDir)
elif stl == 'gnustl_shared':
shutil.copy(os.path.join(stdLibDir, "armv7-a", "libgnustl_shared.so"), jniDir) # TODO: remove armv7-a hardcoded path
if buildSharedObjects:
soPattern = re.compile(".*\.so$")
for rootDir, dirNames, fileNames in os.walk( buildDir ):
for fileName in fileNames:
if soPattern.search(fileName):
libFileName = os.path.join(rootDir, fileName)
shutil.copy(libFileName, jniDir)
else:
unifiedTestsLibrary = os.path.join(buildDir, "android-unified-tests", "libandroid-unified-tests.so")
shutil.copy(unifiedTestsLibrary, jniDir)
def RemoveTree(dir):
if os.path.exists( dir ):
shutil.rmtree( dir )
def BuildNative(abi, clean, buildDir, jniDir, installDir, buildType, buildSharedObjects, stl):
if clean:
RemoveTree(installDir)
RemoveTree(buildDir)
RemoveTree(jniDir)
for externalProjectDir in [ "openssl", "zlib", "curl" ]:
RemoveTree(externalProjectDir)
os.makedirs( jniDir )
os.makedirs( buildDir )
os.chdir( buildDir )
if not buildSharedObjects:
link_type_line = "-DBUILD_SHARED_LIBS=OFF"
else:
link_type_line = "-DBUILD_SHARED_LIBS=ON"
subprocess.check_call( [ "cmake",
link_type_line,
"-DCUSTOM_MEMORY_MANAGEMENT=ON",
"-DTARGET_ARCH=ANDROID",
"-DANDROID_ABI=" + abi,
"-DANDROID_STL=" + stl,
"-DCMAKE_BUILD_TYPE=" + buildType,
"-DENABLE_UNITY_BUILD=ON",
'-DTEST_CERT_PATH="/data/data/aws.' + TestLowerName + '/certs"',
'-DBUILD_ONLY=dynamodb;sqs;s3;lambda;kinesis;cognito-identity;transfer;iam;identity-management;access-management;s3-encryption',
".."] )
else:
os.chdir( buildDir )
if buildSharedObjects:
subprocess.check_call( [ "make", "-j12" ] )
else:
subprocess.check_call( [ "make", "-j12", "android-unified-tests" ] )
os.chdir( ".." )
CopyNativeLibraries(buildSharedObjects, jniDir, buildDir, abi, stl)
def BuildJava(clean):
os.chdir( TestName )
if clean:
subprocess.check_call( [ "./gradlew", "clean" ] )
subprocess.check_call( [ "./gradlew", "--refresh-dependencies" ] )
subprocess.check_call( [ "./gradlew", "assembleDebug" ] )
os.chdir( ".." )
def IsAnEmulatorRunning():
emulatorPattern = re.compile("(?P<emu>emulator-\d+)")
emulatorList = subprocess.check_output(["adb", "devices"])
for _, line in enumerate(emulatorList.splitlines()):
result = emulatorPattern.search(line)
if result:
return True
return False
def KillRunningEmulators():
emulatorPattern = re.compile("(?P<emu>emulator-\d+)")
emulatorList = subprocess.check_output(["adb", "devices"])
for _, line in enumerate(emulatorList.splitlines()):
result = emulatorPattern.search(line)
if result:
emulatorName = result.group( "emu" )
subprocess.check_call( [ "adb", "-s", emulatorName, "emu", "kill" ] )
def WaitForEmulatorToBoot():
time.sleep(5)
subprocess.check_call( [ "adb", "-e", "wait-for-device" ] )
print( "Device online; booting..." )
bootCompleted = False
bootAnimPlaying = True
while not bootCompleted or bootAnimPlaying:
time.sleep(1)
bootCompleted = subprocess.check_output( [ "adb", "-e", "shell", "getprop sys.boot_completed" ] ).strip() == "1"
bootAnimPlaying = subprocess.check_output( [ "adb", "-e", "shell", "getprop init.svc.bootanim" ] ).strip() != "stopped"
print( "Device booted" )
def InitializeEmulator(avd, useExistingEmu):
if not useExistingEmu:
KillRunningEmulators()
if not IsAnEmulatorRunning():
# this may not work on windows due to the shell and &
subprocess.Popen( "emulator -avd " + avd + " -gpu off &", shell=True ).communicate()
WaitForEmulatorToBoot()
#TEMPORARY: once we have android CI, we will adjust the emulator's CA set as a one-time step and then remove this step
def BuildAndInstallCertSet(pemSourceDir, buildDir):
# android's default cert set does not allow verification of Amazon's cert chain, so we build, install, and use our own set that works
certDir = os.path.join( buildDir, "certs" )
pemSourceFile = os.path.join( pemSourceDir, "cacert.pem" )
# assume that if the directory exists, then the cert set is valid and we just need to upload
if not os.path.exists( certDir ):
os.makedirs( certDir )
# extract all the certs in curl's master cacert.pem file out into individual .pem files
subprocess.check_call( "cat " + pemSourceFile + " | awk '{print > \"" + certDir + "/cert\" (1+n) \".pem\"} /-----END CERTIFICATE-----/ {n++}'", shell = True )
# use openssl to transform the certs into the hashname form that curl/openssl expects
subprocess.check_call( "c_rehash certs", shell = True, cwd = buildDir )
# The root (VeriSign 3) cert in Amazon's chain is missing from curl's master cacert.pem file and needs to be copied manually
shutil.copy(os.path.join( pemSourceDir, "certs", "415660c1.0" ), certDir)
shutil.copy(os.path.join( pemSourceDir, "certs", "7651b327.0" ), certDir)
subprocess.check_call( [ "adb", "shell", "rm -rf /data/data/aws." + TestLowerName + "/certs" ] )
subprocess.check_call( [ "adb", "shell", "mkdir /data/data/aws." + TestLowerName + "/certs" ] )
# upload all the hashed certs to the emulator
certPattern = re.compile(".*\.0$")
for rootDir, dirNames, fileNames in os.walk( certDir ):
for fileName in fileNames:
if certPattern.search(fileName):
certFileName = os.path.join(rootDir, fileName)
subprocess.check_call( [ "adb", "push", certFileName, "/data/data/aws." + TestLowerName + "/certs" ] )
def UploadTestResources(resourcesDir):
for rootDir, dirNames, fileNames in os.walk( resourcesDir ):
for fileName in fileNames:
resourceFileName = os.path.join( rootDir, fileName )
subprocess.check_call( [ "adb", "push", resourceFileName, os.path.join( "/data/data/aws." + TestLowerName + "/resources", fileName ) ] )
def UploadAwsSigV4TestSuite(resourceDir):
for rootDir, dirNames, fileNames in os.walk( resourceDir ):
for fileName in fileNames:
resourceFileName = os.path.join( rootDir, fileName )
subDir = os.path.basename( rootDir )
subprocess.check_call( [ "adb", "push", resourceFileName, os.path.join( "/data/data/aws." + TestLowerName + "/resources", subDir, fileName ) ] )
def InstallTests(credentialsFile):
subprocess.check_call( [ "adb", "install", "-r", TestName + "/app/build/outputs/apk/app-debug.apk" ] )
subprocess.check_call( [ "adb", "logcat", "-c" ] ) # this doesn't seem to work
if credentialsFile and credentialsFile != "":
print( "uploading credentials" )
subprocess.check_call( [ "adb", "push", credentialsFile, "/data/data/aws." + TestLowerName + "/.aws/credentials" ] )
def TestsAreRunning(timeStart):
shutdownCalledOutput = subprocess.check_output( "adb logcat -t " + timeStart + " *:V | grep \"Shutting down TestActivity\"; exit 0 ", shell = True )
return not shutdownCalledOutput
def RunTest(testName):
time.sleep(5)
print( "Attempting to unlock..." )
subprocess.check_call( [ "adb", "-e", "shell", "input keyevent 82" ] )
logTime = datetime.datetime.now() + datetime.timedelta(minutes=-1) # the emulator and the computer do not appear to be in perfect sync
logTimeString = logTime.strftime("\"%m-%d %H:%M:%S.000\"")
time.sleep(5)
print( "Attempting to run tests..." )
subprocess.check_call( [ "adb", "shell", "am start -e test " + testName + " -n aws." + TestLowerName + "/aws." + TestLowerName + ".RunSDKTests" ] )
time.sleep(10)
while TestsAreRunning(logTimeString):
print( "Tests still running..." )
time.sleep(5)
print( "Saving logs..." )
subprocess.Popen( "adb logcat -t " + logTimeString + " *:V | grep -a NativeSDK > AndroidTestOutput.txt", shell=True )
print( "Cleaning up..." )
subprocess.check_call( [ "adb", "shell", "pm clear aws." + TestLowerName ] )
def DidAllTestsSucceed():
failures = subprocess.check_output( "grep \"FAILED\" AndroidTestOutput.txt ; exit 0", shell = True )
return failures == ""
def Main():
args = ParseArguments()
avd = args[ "avd" ]
abi = args[ "abi" ]
clean = args[ "clean" ]
useExistingEmu = args[ "useExistingEmulator" ]
skipBuild = args[ "noBuild" ]
credentialsFile = args[ "credentialsFile" ]
buildType = args[ "buildType" ]
noInstall = args[ "noInstall" ]
buildSharedObjects = args[ "so" ]
runTest = args[ "runTest" ]
stl = args[ "stl" ]
buildDir = "_build" + buildType
installDir = os.path.join( "external", abi );
if runTest:
avd, abi, clean = ValidateArguments(buildDir, avd, abi, clean, runTest, buildSharedObjects)
jniDir = SetupJniDirectory(abi, clean)
if not skipBuild:
BuildNative(abi, clean, buildDir, jniDir, installDir, buildType, buildSharedObjects, stl)
BuildJava(clean)
if not runTest:
return 0
print("Starting emulator...")
InitializeEmulator(avd, useExistingEmu)
if not noInstall:
print("Installing tests...")
InstallTests(credentialsFile)
print("Installing certs...")
BuildAndInstallCertSet("tools/android-build", buildDir)
print("Uploading test resources")
UploadTestResources("aws-cpp-sdk-lambda-integration-tests/resources")
print("Uploading SigV4 test files")
UploadAwsSigV4TestSuite(os.path.join("aws-cpp-sdk-core-tests", "resources", "aws4_testsuite", "aws4_testsuite"))
print("Running tests...")
RunTest( runTest )
if not useExistingEmu:
KillRunningEmulators()
if DidAllTestsSucceed():
print( "All tests passed!" )
return 0
else:
print( "Some tests failed. See AndroidTestOutput.txt" )
return 1
Main()