-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_device.py
executable file
·1775 lines (1419 loc) · 69 KB
/
test_device.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 The Android Open Source Project
#
# 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
#
# http://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.
#
from __future__ import print_function
import contextlib
import hashlib
import os
import posixpath
import random
import re
import shlex
import shutil
import signal
import socket
import string
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from datetime import datetime
import adb
def requires_non_root(func):
def wrapper(self, *args):
was_root = self.device.shell(['id', '-un'])[0].strip() == 'root'
if was_root:
self.device.unroot()
self.device.wait()
try:
func(self, *args)
finally:
if was_root:
self.device.root()
self.device.wait()
return wrapper
class DeviceTest(unittest.TestCase):
device = adb.get_device()
class AbbTest(DeviceTest):
def test_smoke(self):
abb = subprocess.run(['adb', 'abb'], capture_output=True)
cmd = subprocess.run(['adb', 'shell', 'cmd'], capture_output=True)
# abb squashes all failures to 1.
self.assertEqual(abb.returncode == 0, cmd.returncode == 0)
self.assertEqual(abb.stdout, cmd.stdout)
self.assertEqual(abb.stderr, cmd.stderr)
class ForwardReverseTest(DeviceTest):
def _test_no_rebind(self, description, direction_list, direction,
direction_no_rebind, direction_remove_all):
msg = direction_list()
self.assertEqual('', msg.strip(),
description + ' list must be empty to run this test.')
# Use --no-rebind with no existing binding
direction_no_rebind('tcp:5566', 'tcp:6655')
msg = direction_list()
self.assertTrue(re.search(r'tcp:5566.+tcp:6655', msg))
# Use --no-rebind with existing binding
with self.assertRaises(subprocess.CalledProcessError):
direction_no_rebind('tcp:5566', 'tcp:6677')
msg = direction_list()
self.assertFalse(re.search(r'tcp:5566.+tcp:6677', msg))
self.assertTrue(re.search(r'tcp:5566.+tcp:6655', msg))
# Use the absence of --no-rebind with existing binding
direction('tcp:5566', 'tcp:6677')
msg = direction_list()
self.assertFalse(re.search(r'tcp:5566.+tcp:6655', msg))
self.assertTrue(re.search(r'tcp:5566.+tcp:6677', msg))
direction_remove_all()
msg = direction_list()
self.assertEqual('', msg.strip())
def test_forward_no_rebind(self):
self._test_no_rebind('forward', self.device.forward_list,
self.device.forward, self.device.forward_no_rebind,
self.device.forward_remove_all)
def test_reverse_no_rebind(self):
self._test_no_rebind('reverse', self.device.reverse_list,
self.device.reverse, self.device.reverse_no_rebind,
self.device.reverse_remove_all)
def test_forward(self):
msg = self.device.forward_list()
self.assertEqual('', msg.strip(),
'Forwarding list must be empty to run this test.')
self.device.forward('tcp:5566', 'tcp:6655')
msg = self.device.forward_list()
self.assertTrue(re.search(r'tcp:5566.+tcp:6655', msg))
self.device.forward('tcp:7788', 'tcp:8877')
msg = self.device.forward_list()
self.assertTrue(re.search(r'tcp:5566.+tcp:6655', msg))
self.assertTrue(re.search(r'tcp:7788.+tcp:8877', msg))
self.device.forward_remove('tcp:5566')
msg = self.device.forward_list()
self.assertFalse(re.search(r'tcp:5566.+tcp:6655', msg))
self.assertTrue(re.search(r'tcp:7788.+tcp:8877', msg))
self.device.forward_remove_all()
msg = self.device.forward_list()
self.assertEqual('', msg.strip())
def test_forward_old_protocol(self):
serialno = subprocess.check_output(self.device.adb_cmd + ['get-serialno']).strip()
msg = self.device.forward_list()
self.assertEqual('', msg.strip(),
'Forwarding list must be empty to run this test.')
s = socket.create_connection(("localhost", 5037))
service = b"host-serial:%s:forward:tcp:5566;tcp:6655" % serialno
cmd = b"%04x%s" % (len(service), service)
s.sendall(cmd)
msg = self.device.forward_list()
self.assertTrue(re.search(r'tcp:5566.+tcp:6655', msg))
self.device.forward_remove_all()
msg = self.device.forward_list()
self.assertEqual('', msg.strip())
def test_forward_tcp_port_0(self):
self.assertEqual('', self.device.forward_list().strip(),
'Forwarding list must be empty to run this test.')
try:
# If resolving TCP port 0 is supported, `adb forward` will print
# the actual port number.
port = self.device.forward('tcp:0', 'tcp:8888').strip()
if not port:
raise unittest.SkipTest('Forwarding tcp:0 is not available.')
self.assertTrue(re.search(r'tcp:{}.+tcp:8888'.format(port),
self.device.forward_list()))
finally:
self.device.forward_remove_all()
def test_reverse(self):
msg = self.device.reverse_list()
self.assertEqual('', msg.strip(),
'Reverse forwarding list must be empty to run this test.')
self.device.reverse('tcp:5566', 'tcp:6655')
msg = self.device.reverse_list()
self.assertTrue(re.search(r'tcp:5566.+tcp:6655', msg))
self.device.reverse('tcp:7788', 'tcp:8877')
msg = self.device.reverse_list()
self.assertTrue(re.search(r'tcp:5566.+tcp:6655', msg))
self.assertTrue(re.search(r'tcp:7788.+tcp:8877', msg))
self.device.reverse_remove('tcp:5566')
msg = self.device.reverse_list()
self.assertFalse(re.search(r'tcp:5566.+tcp:6655', msg))
self.assertTrue(re.search(r'tcp:7788.+tcp:8877', msg))
self.device.reverse_remove_all()
msg = self.device.reverse_list()
self.assertEqual('', msg.strip())
def test_reverse_tcp_port_0(self):
self.assertEqual('', self.device.reverse_list().strip(),
'Reverse list must be empty to run this test.')
try:
# If resolving TCP port 0 is supported, `adb reverse` will print
# the actual port number.
port = self.device.reverse('tcp:0', 'tcp:8888').strip()
if not port:
raise unittest.SkipTest('Reversing tcp:0 is not available.')
self.assertTrue(re.search(r'tcp:{}.+tcp:8888'.format(port),
self.device.reverse_list()))
finally:
self.device.reverse_remove_all()
def test_forward_reverse_echo(self):
"""Send data through adb forward and read it back via adb reverse"""
forward_port = 12345
reverse_port = forward_port + 1
forward_spec = 'tcp:' + str(forward_port)
reverse_spec = 'tcp:' + str(reverse_port)
forward_setup = False
reverse_setup = False
try:
# listen on localhost:forward_port, connect to remote:forward_port
self.device.forward(forward_spec, forward_spec)
forward_setup = True
# listen on remote:forward_port, connect to localhost:reverse_port
self.device.reverse(forward_spec, reverse_spec)
reverse_setup = True
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
with contextlib.closing(listener):
# Use SO_REUSEADDR so that subsequent runs of the test can grab
# the port even if it is in TIME_WAIT.
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Listen on localhost:reverse_port before connecting to
# localhost:forward_port because that will cause adb to connect
# back to localhost:reverse_port.
listener.bind(('127.0.0.1', reverse_port))
listener.listen(4)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
with contextlib.closing(client):
# Connect to the listener.
client.connect(('127.0.0.1', forward_port))
# Accept the client connection.
accepted_connection, addr = listener.accept()
with contextlib.closing(accepted_connection) as server:
data = b'hello'
# Send data into the port setup by adb forward.
client.sendall(data)
# Explicitly close() so that server gets EOF.
client.close()
# Verify that the data came back via adb reverse.
self.assertEqual(data, server.makefile().read().encode("utf8"))
finally:
if reverse_setup:
self.device.reverse_remove(forward_spec)
if forward_setup:
self.device.forward_remove(forward_spec)
class ShellTest(DeviceTest):
def _interactive_shell(self, shell_args, input):
"""Runs an interactive adb shell.
Args:
shell_args: List of string arguments to `adb shell`.
input: bytes input to send to the interactive shell.
Returns:
The remote exit code.
Raises:
unittest.SkipTest: The device doesn't support exit codes.
"""
if not self.device.has_shell_protocol():
raise unittest.SkipTest('exit codes are unavailable on this device')
proc = subprocess.Popen(
self.device.adb_cmd + ['shell'] + shell_args,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Closing host-side stdin doesn't trigger a PTY shell to exit so we need
# to explicitly add an exit command to close the session from the device
# side, plus the necessary newline to complete the interactive command.
proc.communicate(input + b'; exit\n')
return proc.returncode
def test_cat(self):
"""Check that we can at least cat a file."""
out = self.device.shell(['cat', '/proc/uptime'])[0].strip()
elements = out.split()
self.assertEqual(len(elements), 2)
uptime, idle = elements
self.assertGreater(float(uptime), 0.0)
self.assertGreater(float(idle), 0.0)
def test_throws_on_failure(self):
self.assertRaises(adb.ShellError, self.device.shell, ['false'])
def test_output_not_stripped(self):
out = self.device.shell(['echo', 'foo'])[0]
self.assertEqual(out, 'foo' + self.device.linesep)
def test_shell_command_length(self):
# Devices that have shell_v2 should be able to handle long commands.
if self.device.has_shell_protocol():
rc, out, err = self.device.shell_nocheck(['echo', 'x' * 16384])
self.assertEqual(rc, 0)
self.assertTrue(out == ('x' * 16384 + '\n'))
def test_shell_nocheck_failure(self):
rc, out, _ = self.device.shell_nocheck(['false'])
self.assertNotEqual(rc, 0)
self.assertEqual(out, '')
def test_shell_nocheck_output_not_stripped(self):
rc, out, _ = self.device.shell_nocheck(['echo', 'foo'])
self.assertEqual(rc, 0)
self.assertEqual(out, 'foo' + self.device.linesep)
def test_can_distinguish_tricky_results(self):
# If result checking on ADB shell is naively implemented as
# `adb shell <cmd>; echo $?`, we would be unable to distinguish the
# output from the result for a cmd of `echo -n 1`.
rc, out, _ = self.device.shell_nocheck(['echo', '-n', '1'])
self.assertEqual(rc, 0)
self.assertEqual(out, '1')
def test_line_endings(self):
"""Ensure that line ending translation is not happening in the pty.
Bug: http://b/19735063
"""
output = self.device.shell(['uname'])[0]
self.assertEqual(output, 'Linux' + self.device.linesep)
def test_pty_logic(self):
"""Tests that a PTY is allocated when it should be.
PTY allocation behavior should match ssh.
"""
def check_pty(args):
"""Checks adb shell PTY allocation.
Tests |args| for terminal and non-terminal stdin.
Args:
args: -Tt args in a list (e.g. ['-t', '-t']).
Returns:
A tuple (<terminal>, <non-terminal>). True indicates
the corresponding shell allocated a remote PTY.
"""
test_cmd = self.device.adb_cmd + ['shell'] + args + ['[ -t 0 ]']
terminal = subprocess.Popen(
test_cmd, stdin=None,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
terminal.communicate()
non_terminal = subprocess.Popen(
test_cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
non_terminal.communicate()
return (terminal.returncode == 0, non_terminal.returncode == 0)
# -T: never allocate PTY.
self.assertEqual((False, False), check_pty(['-T']))
# These tests require a new device.
if self.device.has_shell_protocol() and os.isatty(sys.stdin.fileno()):
# No args: PTY only if stdin is a terminal and shell is interactive,
# which is difficult to reliably test from a script.
self.assertEqual((False, False), check_pty([]))
# -t: PTY if stdin is a terminal.
self.assertEqual((True, False), check_pty(['-t']))
# -t -t: always allocate PTY.
self.assertEqual((True, True), check_pty(['-t', '-t']))
# -tt: always allocate PTY, POSIX style (http://b/32216152).
self.assertEqual((True, True), check_pty(['-tt']))
# -ttt: ssh has weird even/odd behavior with multiple -t flags, but
# we follow the man page instead.
self.assertEqual((True, True), check_pty(['-ttt']))
# -ttx: -x and -tt aren't incompatible (though -Tx would be an error).
self.assertEqual((True, True), check_pty(['-ttx']))
# -Ttt: -tt cancels out -T.
self.assertEqual((True, True), check_pty(['-Ttt']))
# -ttT: -T cancels out -tt.
self.assertEqual((False, False), check_pty(['-ttT']))
def test_shell_protocol(self):
"""Tests the shell protocol on the device.
If the device supports shell protocol, this gives us the ability
to separate stdout/stderr and return the exit code directly.
Bug: http://b/19734861
"""
if not self.device.has_shell_protocol():
raise unittest.SkipTest('shell protocol unsupported on this device')
# Shell protocol should be used by default.
result = self.device.shell_nocheck(
shlex.split('echo foo; echo bar >&2; exit 17'))
self.assertEqual(17, result[0])
self.assertEqual('foo' + self.device.linesep, result[1])
self.assertEqual('bar' + self.device.linesep, result[2])
self.assertEqual(17, self._interactive_shell([], b'exit 17'))
# -x flag should disable shell protocol.
result = self.device.shell_nocheck(
shlex.split('-x echo foo; echo bar >&2; exit 17'))
self.assertEqual(0, result[0])
self.assertEqual('foo{0}bar{0}'.format(self.device.linesep), result[1])
self.assertEqual('', result[2])
self.assertEqual(0, self._interactive_shell(['-x'], b'exit 17'))
def test_non_interactive_sigint(self):
"""Tests that SIGINT in a non-interactive shell kills the process.
This requires the shell protocol in order to detect the broken
pipe; raw data transfer mode will only see the break once the
subprocess tries to read or write.
Bug: http://b/23825725
"""
if not self.device.has_shell_protocol():
raise unittest.SkipTest('shell protocol unsupported on this device')
# Start a long-running process.
sleep_proc = subprocess.Popen(
self.device.adb_cmd + shlex.split('shell echo $$; sleep 60'),
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
remote_pid = sleep_proc.stdout.readline().strip().decode("utf8")
self.assertIsNone(sleep_proc.returncode, 'subprocess terminated early')
proc_query = shlex.split('ps {0} | grep {0}'.format(remote_pid))
# Verify that the process is running, send signal, verify it stopped.
self.device.shell(proc_query)
os.kill(sleep_proc.pid, signal.SIGINT)
sleep_proc.communicate()
# It can take some time for the process to receive the signal and die.
end_time = time.time() + 3
while self.device.shell_nocheck(proc_query)[0] != 1:
self.assertFalse(time.time() > end_time,
'subprocess failed to terminate in time')
def test_non_interactive_stdin(self):
"""Tests that non-interactive shells send stdin."""
if not self.device.has_shell_protocol():
raise unittest.SkipTest('non-interactive stdin unsupported '
'on this device')
# Test both small and large inputs.
small_input = b'foo'
characters = [c.encode("utf8") for c in string.ascii_letters + string.digits]
large_input = b'\n'.join(characters)
for input in (small_input, large_input):
proc = subprocess.Popen(self.device.adb_cmd + ['shell', 'cat'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate(input)
self.assertEqual(input.splitlines(), stdout.splitlines())
self.assertEqual(b'', stderr)
def test_sighup(self):
"""Ensure that SIGHUP gets sent upon non-interactive ctrl-c"""
log_path = "/data/local/tmp/adb_signal_test.log"
# Clear the output file.
self.device.shell_nocheck(["echo", ">", log_path])
script = """
trap "echo SIGINT > {path}; exit 0" SIGINT
trap "echo SIGHUP > {path}; exit 0" SIGHUP
echo Waiting
read
""".format(path=log_path)
script = ";".join([x.strip() for x in script.strip().splitlines()])
process = self.device.shell_popen([script], kill_atexit=False,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
self.assertEqual(b"Waiting\n", process.stdout.readline())
process.send_signal(signal.SIGINT)
process.wait()
# Waiting for the local adb to finish is insufficient, since it hangs
# up immediately.
time.sleep(1)
stdout, _ = self.device.shell(["cat", log_path])
self.assertEqual(stdout.strip(), "SIGHUP")
# Temporarily disabled because it seems to cause later instability.
# http://b/228114748
def disabled_test_exit_stress(self):
"""Hammer `adb shell exit 42` with multiple threads."""
thread_count = 48
result = dict()
def hammer(thread_idx, thread_count, result):
success = True
for i in range(thread_idx, 240, thread_count):
ret = subprocess.call(['adb', 'shell', 'exit {}'.format(i)])
if ret != i % 256:
success = False
break
result[thread_idx] = success
threads = []
for i in range(thread_count):
thread = threading.Thread(target=hammer, args=(i, thread_count, result))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
for i, success in result.items():
self.assertTrue(success)
def disabled_test_parallel(self):
"""Spawn a bunch of `adb shell` instances in parallel.
This was broken historically due to the use of select, which only works
for fds that are numerically less than 1024.
Bug: http://b/141955761"""
n_procs = 2048
procs = dict()
for i in range(0, n_procs):
procs[i] = subprocess.Popen(
['adb', 'shell', 'read foo; echo $foo; read rc; exit $rc'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
for i in range(0, n_procs):
procs[i].stdin.write("%d\n" % i)
for i in range(0, n_procs):
response = procs[i].stdout.readline()
assert(response == "%d\n" % i)
for i in range(0, n_procs):
procs[i].stdin.write("%d\n" % (i % 256))
for i in range(0, n_procs):
assert(procs[i].wait() == i % 256)
class ArgumentEscapingTest(DeviceTest):
def test_shell_escaping(self):
"""Make sure that argument escaping is somewhat sane."""
# http://b/19734868
# Note that this actually matches ssh(1)'s behavior --- it's
# converted to `sh -c echo hello; echo world` which sh interprets
# as `sh -c echo` (with an argument to that shell of "hello"),
# and then `echo world` back in the first shell.
result = self.device.shell(
shlex.split("sh -c 'echo hello; echo world'"))[0]
result = result.splitlines()
self.assertEqual(['', 'world'], result)
# If you really wanted "hello" and "world", here's what you'd do:
result = self.device.shell(
shlex.split(r'echo hello\;echo world'))[0].splitlines()
self.assertEqual(['hello', 'world'], result)
# http://b/15479704
result = self.device.shell(shlex.split("'true && echo t'"))[0].strip()
self.assertEqual('t', result)
result = self.device.shell(
shlex.split("sh -c 'true && echo t'"))[0].strip()
self.assertEqual('t', result)
# http://b/20564385
result = self.device.shell(shlex.split('FOO=a BAR=b echo t'))[0].strip()
self.assertEqual('t', result)
result = self.device.shell(
shlex.split(r'echo -n 123\;uname'))[0].strip()
self.assertEqual('123Linux', result)
def test_install_argument_escaping(self):
"""Make sure that install argument escaping works."""
# http://b/20323053, http://b/3090932.
for file_suffix in (b'-text;ls;1.apk', b"-Live Hold'em.apk"):
tf = tempfile.NamedTemporaryFile('wb', suffix=file_suffix,
delete=False)
tf.close()
# Installing bogus .apks fails if the device supports exit codes.
try:
output = self.device.install(tf.name.decode("utf8"))
except subprocess.CalledProcessError as e:
output = e.output
self.assertIn(file_suffix, output)
os.remove(tf.name)
class RootUnrootTest(DeviceTest):
def _test_root(self):
message = self.device.root()
if 'adbd cannot run as root in production builds' in message:
return
self.device.wait()
self.assertEqual('root', self.device.shell(['id', '-un'])[0].strip())
def _test_unroot(self):
self.device.unroot()
self.device.wait()
self.assertEqual('shell', self.device.shell(['id', '-un'])[0].strip())
def test_root_unroot(self):
"""Make sure that adb root and adb unroot work, using id(1)."""
if self.device.get_prop('ro.debuggable') != '1':
raise unittest.SkipTest('requires rootable build')
original_user = self.device.shell(['id', '-un'])[0].strip()
try:
if original_user == 'root':
self._test_unroot()
self._test_root()
elif original_user == 'shell':
self._test_root()
self._test_unroot()
finally:
if original_user == 'root':
self.device.root()
else:
self.device.unroot()
self.device.wait()
class TcpIpTest(DeviceTest):
def test_tcpip_failure_raises(self):
"""adb tcpip requires a port.
Bug: http://b/22636927
"""
self.assertRaises(
subprocess.CalledProcessError, self.device.tcpip, '')
self.assertRaises(
subprocess.CalledProcessError, self.device.tcpip, 'foo')
class SystemPropertiesTest(DeviceTest):
def test_get_prop(self):
self.assertEqual(self.device.get_prop('init.svc.adbd'), 'running')
def test_set_prop(self):
# debug.* prop does not require root privileges
prop_name = 'debug.foo'
self.device.shell(['setprop', prop_name, '""'])
val = random.random()
self.device.set_prop(prop_name, str(val))
self.assertEqual(
self.device.shell(['getprop', prop_name])[0].strip(), str(val))
def compute_md5(string):
hsh = hashlib.md5()
hsh.update(string)
return hsh.hexdigest()
def get_md5_prog(device):
"""Older platforms (pre-L) had the name md5 rather than md5sum."""
try:
device.shell(['md5sum', '/proc/uptime'])
return 'md5sum'
except adb.ShellError:
return 'md5'
class HostFile(object):
def __init__(self, handle, checksum):
self.handle = handle
self.checksum = checksum
self.full_path = handle.name
self.base_name = os.path.basename(self.full_path)
class DeviceFile(object):
def __init__(self, checksum, full_path):
self.checksum = checksum
self.full_path = full_path
self.base_name = posixpath.basename(self.full_path)
def make_random_host_files(in_dir, num_files):
min_size = 1 * (1 << 10)
max_size = 16 * (1 << 10)
files = []
for _ in range(num_files):
file_handle = tempfile.NamedTemporaryFile(dir=in_dir, delete=False)
size = random.randrange(min_size, max_size, 1024)
rand_str = os.urandom(size)
file_handle.write(rand_str)
file_handle.flush()
file_handle.close()
md5 = compute_md5(rand_str)
files.append(HostFile(file_handle, md5))
return files
def make_random_device_files(device, in_dir, num_files, prefix='device_tmpfile'):
min_size = 1 * (1 << 10)
max_size = 16 * (1 << 10)
files = []
for file_num in range(num_files):
size = random.randrange(min_size, max_size, 1024)
base_name = prefix + str(file_num)
full_path = posixpath.join(in_dir, base_name)
device.shell(['dd', 'if=/dev/urandom', 'of={}'.format(full_path),
'bs={}'.format(size), 'count=1'])
dev_md5, _ = device.shell([get_md5_prog(device), full_path])[0].split()
files.append(DeviceFile(dev_md5, full_path))
return files
class FileOperationsTest:
class Base(DeviceTest):
SCRATCH_DIR = '/data/local/tmp'
DEVICE_TEMP_FILE = SCRATCH_DIR + '/adb_test_file'
DEVICE_TEMP_DIR = SCRATCH_DIR + '/adb_test_dir'
def setUp(self):
self.previous_env = os.environ.get("ADB_COMPRESSION")
os.environ["ADB_COMPRESSION"] = self.compression
def tearDown(self):
if self.previous_env is None:
del os.environ["ADB_COMPRESSION"]
else:
os.environ["ADB_COMPRESSION"] = self.previous_env
def _verify_remote(self, checksum, remote_path):
dev_md5, _ = self.device.shell([get_md5_prog(self.device),
remote_path])[0].split()
self.assertEqual(checksum, dev_md5)
def _verify_local(self, checksum, local_path):
with open(local_path, 'rb') as host_file:
host_md5 = compute_md5(host_file.read())
self.assertEqual(host_md5, checksum)
def test_push(self):
"""Push a randomly generated file to specified device."""
kbytes = 512
tmp = tempfile.NamedTemporaryFile(mode='wb', delete=False)
rand_str = os.urandom(1024 * kbytes)
tmp.write(rand_str)
tmp.close()
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_FILE])
self.device.push(local=tmp.name, remote=self.DEVICE_TEMP_FILE)
self._verify_remote(compute_md5(rand_str), self.DEVICE_TEMP_FILE)
self.device.shell(['rm', '-f', self.DEVICE_TEMP_FILE])
os.remove(tmp.name)
def test_push_dir(self):
"""Push a randomly generated directory of files to the device."""
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
self.device.shell(['mkdir', self.DEVICE_TEMP_DIR])
try:
host_dir = tempfile.mkdtemp()
# Make sure the temp directory isn't setuid, or else adb will complain.
os.chmod(host_dir, 0o700)
# Create 32 random files.
temp_files = make_random_host_files(in_dir=host_dir, num_files=32)
self.device.push(host_dir, self.DEVICE_TEMP_DIR)
for temp_file in temp_files:
remote_path = posixpath.join(self.DEVICE_TEMP_DIR,
os.path.basename(host_dir),
temp_file.base_name)
self._verify_remote(temp_file.checksum, remote_path)
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
finally:
if host_dir is not None:
shutil.rmtree(host_dir)
def disabled_test_push_empty(self):
"""Push an empty directory to the device."""
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
self.device.shell(['mkdir', self.DEVICE_TEMP_DIR])
try:
host_dir = tempfile.mkdtemp()
# Make sure the temp directory isn't setuid, or else adb will complain.
os.chmod(host_dir, 0o700)
# Create an empty directory.
empty_dir_path = os.path.join(host_dir, 'empty')
os.mkdir(empty_dir_path);
self.device.push(empty_dir_path, self.DEVICE_TEMP_DIR)
remote_path = os.path.join(self.DEVICE_TEMP_DIR, "empty")
test_empty_cmd = ["[", "-d", remote_path, "]"]
rc, _, _ = self.device.shell_nocheck(test_empty_cmd)
self.assertEqual(rc, 0)
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
finally:
if host_dir is not None:
shutil.rmtree(host_dir)
@unittest.skipIf(sys.platform == "win32", "symlinks require elevated privileges on windows")
def test_push_symlink(self):
"""Push a symlink.
Bug: http://b/31491920
"""
try:
host_dir = tempfile.mkdtemp()
# Make sure the temp directory isn't setuid, or else adb will
# complain.
os.chmod(host_dir, 0o700)
with open(os.path.join(host_dir, 'foo'), 'w') as f:
f.write('foo')
symlink_path = os.path.join(host_dir, 'symlink')
os.symlink('foo', symlink_path)
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
self.device.shell(['mkdir', self.DEVICE_TEMP_DIR])
self.device.push(symlink_path, self.DEVICE_TEMP_DIR)
rc, out, _ = self.device.shell_nocheck(
['cat', posixpath.join(self.DEVICE_TEMP_DIR, 'symlink')])
self.assertEqual(0, rc)
self.assertEqual(out.strip(), 'foo')
finally:
if host_dir is not None:
shutil.rmtree(host_dir)
def test_multiple_push(self):
"""Push multiple files to the device in one adb push command.
Bug: http://b/25324823
"""
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
self.device.shell(['mkdir', self.DEVICE_TEMP_DIR])
try:
host_dir = tempfile.mkdtemp()
# Create some random files and a subdirectory containing more files.
temp_files = make_random_host_files(in_dir=host_dir, num_files=4)
subdir = os.path.join(host_dir, 'subdir')
os.mkdir(subdir)
subdir_temp_files = make_random_host_files(in_dir=subdir,
num_files=4)
paths = [x.full_path for x in temp_files]
paths.append(subdir)
self.device._simple_call(['push'] + paths + [self.DEVICE_TEMP_DIR])
for temp_file in temp_files:
remote_path = posixpath.join(self.DEVICE_TEMP_DIR,
temp_file.base_name)
self._verify_remote(temp_file.checksum, remote_path)
for subdir_temp_file in subdir_temp_files:
remote_path = posixpath.join(self.DEVICE_TEMP_DIR,
# BROKEN: http://b/25394682
# 'subdir';
temp_file.base_name)
self._verify_remote(temp_file.checksum, remote_path)
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
finally:
if host_dir is not None:
shutil.rmtree(host_dir)
@requires_non_root
def test_push_error_reporting(self):
"""Make sure that errors that occur while pushing a file get reported
Bug: http://b/26816782
"""
with tempfile.NamedTemporaryFile() as tmp_file:
tmp_file.write(b'\0' * 1024 * 1024)
tmp_file.flush()
try:
self.device.push(local=tmp_file.name, remote='/system/')
self.fail('push should not have succeeded')
except subprocess.CalledProcessError as e:
output = e.output
self.assertTrue(b'Permission denied' in output or
b'Read-only file system' in output)
@requires_non_root
def test_push_directory_creation(self):
"""Regression test for directory creation.
Bug: http://b/110953234
"""
with tempfile.NamedTemporaryFile() as tmp_file:
tmp_file.write(b'\0' * 1024 * 1024)
tmp_file.flush()
remote_path = self.DEVICE_TEMP_DIR + '/test_push_directory_creation'
self.device.shell(['rm', '-rf', remote_path])
remote_path += '/filename'
self.device.push(local=tmp_file.name, remote=remote_path)
def disabled_test_push_multiple_slash_root(self):
"""Regression test for pushing to //data/local/tmp.
Bug: http://b/141311284
Disabled because this broken on the adbd side as well: b/141943968
"""
with tempfile.NamedTemporaryFile() as tmp_file:
tmp_file.write(b'\0' * 1024 * 1024)
tmp_file.flush()
remote_path = '/' + self.DEVICE_TEMP_DIR + '/test_push_multiple_slash_root'
self.device.shell(['rm', '-rf', remote_path])
self.device.push(local=tmp_file.name, remote=remote_path)
def _test_pull(self, remote_file, checksum):
tmp_write = tempfile.NamedTemporaryFile(mode='wb', delete=False)
tmp_write.close()
self.device.pull(remote=remote_file, local=tmp_write.name)
with open(tmp_write.name, 'rb') as tmp_read:
host_contents = tmp_read.read()
host_md5 = compute_md5(host_contents)
self.assertEqual(checksum, host_md5)
os.remove(tmp_write.name)
@requires_non_root
def test_pull_error_reporting(self):
self.device.shell(['touch', self.DEVICE_TEMP_FILE])
self.device.shell(['chmod', 'a-rwx', self.DEVICE_TEMP_FILE])
try:
output = self.device.pull(remote=self.DEVICE_TEMP_FILE, local='x')
except subprocess.CalledProcessError as e:
output = e.output
self.assertIn(b'Permission denied', output)
self.device.shell(['rm', '-f', self.DEVICE_TEMP_FILE])
def test_pull(self):
"""Pull a randomly generated file from specified device."""
kbytes = 512
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_FILE])
cmd = ['dd', 'if=/dev/urandom',
'of={}'.format(self.DEVICE_TEMP_FILE), 'bs=1024',
'count={}'.format(kbytes)]
self.device.shell(cmd)
dev_md5, _ = self.device.shell(
[get_md5_prog(self.device), self.DEVICE_TEMP_FILE])[0].split()
self._test_pull(self.DEVICE_TEMP_FILE, dev_md5)
self.device.shell_nocheck(['rm', self.DEVICE_TEMP_FILE])
def test_pull_dir(self):
"""Pull a randomly generated directory of files from the device."""
try:
host_dir = tempfile.mkdtemp()
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
self.device.shell(['mkdir', '-p', self.DEVICE_TEMP_DIR])
# Populate device directory with random files.
temp_files = make_random_device_files(