aboutsummaryrefslogtreecommitdiff
path: root/tests/src/com/android/tradefed/device/TestDeviceTest.java
blob: 4e10a9d0faccb4e899d7d7a14572c11e5119abfd (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
/*
 * Copyright (C) 2010 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.
 */
package com.android.tradefed.device;

import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.IShellOutputReceiver;
import com.android.ddmlib.RawImage;
import com.android.ddmlib.ShellCommandUnresponsiveException;
import com.android.ddmlib.TimeoutException;
import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner;
import com.android.ddmlib.testrunner.ITestRunListener;
import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
import com.android.tradefed.device.ITestDevice.MountPointInfo;
import com.android.tradefed.device.ITestDevice.RecoveryMode;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.result.ByteArrayInputStreamSource;
import com.android.tradefed.result.InputStreamSource;
import com.android.tradefed.util.ArrayUtil;
import com.android.tradefed.util.CommandResult;
import com.android.tradefed.util.CommandStatus;
import com.android.tradefed.util.FileUtil;
import com.android.tradefed.util.IRunUtil;
import com.android.tradefed.util.RunUtil;
import com.android.tradefed.util.ZipUtil2;

import com.google.common.util.concurrent.SettableFuture;

import junit.framework.Assert;
import junit.framework.TestCase;

import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.easymock.IExpectationSetters;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Unit tests for {@link TestDevice}.
 */
public class TestDeviceTest extends TestCase {

    private static final String MOCK_DEVICE_SERIAL = "serial";
    // For getCurrentUser, the min api should be 24. We make the stub return 23, the logic should
    // increment it by one.
    private static final int MIN_API_LEVEL_GET_CURRENT_USER = 23;
    private static final String RAWIMAGE_RESOURCE = "/testdata/rawImage.zip";
    private IDevice mMockIDevice;
    private IShellOutputReceiver mMockReceiver;
    private TestDevice mTestDevice;
    private TestDevice mRecoveryTestDevice;
    private TestDevice mNoFastbootTestDevice;
    private IDeviceRecovery mMockRecovery;
    private IDeviceStateMonitor mMockStateMonitor;
    private IRunUtil mMockRunUtil;
    private IWifiHelper mMockWifi;
    private IDeviceMonitor mMockDvcMonitor;

    /**
     * A {@link TestDevice} that is suitable for running tests against
     */
    private class TestableTestDevice extends TestDevice {
        public TestableTestDevice() {
            super(mMockIDevice, mMockStateMonitor, mMockDvcMonitor);
        }

        @Override
        public void postBootSetup() {
            // too annoying to mock out postBootSetup actions everyone, so do nothing
        }

        @Override
        protected IRunUtil getRunUtil() {
            return mMockRunUtil;
        }

        @Override
        void doReboot() throws DeviceNotAvailableException, UnsupportedOperationException {
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mMockIDevice = EasyMock.createMock(IDevice.class);
        EasyMock.expect(mMockIDevice.getSerialNumber()).andReturn(MOCK_DEVICE_SERIAL).anyTimes();
        mMockReceiver = EasyMock.createMock(IShellOutputReceiver.class);
        mMockRecovery = EasyMock.createMock(IDeviceRecovery.class);
        mMockStateMonitor = EasyMock.createMock(IDeviceStateMonitor.class);
        mMockDvcMonitor = EasyMock.createMock(IDeviceMonitor.class);
        mMockRunUtil = EasyMock.createMock(IRunUtil.class);
        mMockWifi = EasyMock.createMock(IWifiHelper.class);

        // A TestDevice with a no-op recoverDevice() implementation
        mTestDevice = new TestableTestDevice() {
            @Override
            public void recoverDevice() throws DeviceNotAvailableException {
                // ignore
            }

            @Override
            IWifiHelper createWifiHelper() {
                return mMockWifi;
            }
        };
        mTestDevice.setRecovery(mMockRecovery);
        mTestDevice.setCommandTimeout(100);
        mTestDevice.setLogStartDelay(-1);

        // TestDevice with intact recoverDevice()
        mRecoveryTestDevice = new TestableTestDevice();
        mRecoveryTestDevice.setRecovery(mMockRecovery);
        mRecoveryTestDevice.setCommandTimeout(100);
        mRecoveryTestDevice.setLogStartDelay(-1);

        // TestDevice without fastboot
        mNoFastbootTestDevice = new TestableTestDevice();
        mNoFastbootTestDevice.setFastbootEnabled(false);
        mNoFastbootTestDevice.setRecovery(mMockRecovery);
        mNoFastbootTestDevice.setCommandTimeout(100);
        mNoFastbootTestDevice.setLogStartDelay(-1);
    }

    /**
     * Test {@link TestDevice#enableAdbRoot()} when adb is already root
     */
    public void testEnableAdbRoot_alreadyRoot() throws Exception {
        injectShellResponse("id", "uid=0(root) gid=0(root)");
        EasyMock.replay(mMockIDevice);
        assertTrue(mTestDevice.enableAdbRoot());
    }

    /**
     * Test {@link TestDevice#enableAdbRoot()} when adb is not root
     */
    public void testEnableAdbRoot_notRoot() throws Exception {
        setEnableAdbRootExpectations();
        EasyMock.replay(mMockIDevice, mMockRunUtil, mMockStateMonitor);
        assertTrue(mTestDevice.enableAdbRoot());
    }

    /**
     * Test {@link TestDevice#enableAdbRoot()} when "enable-root" is "false"
     */
    public void testEnableAdbRoot_noEnableRoot() throws Exception {
        boolean enableRoot = mTestDevice.getOptions().isEnableAdbRoot();
        mTestDevice.getOptions().setEnableAdbRoot(false);
        assertFalse(mTestDevice.enableAdbRoot());
        mTestDevice.getOptions().setEnableAdbRoot(enableRoot);
    }

    /**
     * Test {@link TestDevice#disableAdbRoot()} when adb is already unroot
     */
    public void testDisableAdbRoot_alreadyUnroot() throws Exception {
        injectShellResponse("id", "uid=2000(shell) gid=2000(shell) groups=2000(shell)");
        EasyMock.replay(mMockIDevice);
        assertTrue(mTestDevice.disableAdbRoot());
        EasyMock.verify(mMockIDevice);
    }

    /**
     * Test {@link TestDevice#disableAdbRoot()} when adb is root
     */
    public void testDisableAdbRoot_unroot() throws Exception {
        injectShellResponse("id", "uid=0(root) gid=0(root)");
        injectShellResponse("id", "uid=2000(shell) gid=2000(shell)");
        CommandResult adbResult = new CommandResult();
        adbResult.setStatus(CommandStatus.SUCCESS);
        adbResult.setStdout("restarting adbd as non root");
        setExecuteAdbCommandExpectations(adbResult, "unroot");
        EasyMock.expect(mMockStateMonitor.waitForDeviceNotAvailable(EasyMock.anyLong())).andReturn(
                Boolean.TRUE);
        EasyMock.expect(mMockStateMonitor.waitForDeviceOnline()).andReturn(
                mMockIDevice);
        EasyMock.replay(mMockIDevice, mMockRunUtil, mMockStateMonitor);
        assertTrue(mTestDevice.disableAdbRoot());
        EasyMock.verify(mMockIDevice, mMockRunUtil, mMockStateMonitor);
    }

    /**
     * Configure EasyMock expectations for a successful adb root call
     */
    private void setEnableAdbRootExpectations() throws Exception {
        injectShellResponse("id", "uid=2000(shell) gid=2000(shell)");
        injectShellResponse("id", "uid=0(root) gid=0(root)");
        CommandResult adbResult = new CommandResult();
        adbResult.setStatus(CommandStatus.SUCCESS);
        adbResult.setStdout("restarting adbd as root");
        setExecuteAdbCommandExpectations(adbResult, "root");
        EasyMock.expect(mMockStateMonitor.waitForDeviceNotAvailable(EasyMock.anyLong())).andReturn(
                Boolean.TRUE);
        EasyMock.expect(mMockStateMonitor.waitForDeviceOnline()).andReturn(
                mMockIDevice);
    }

    /**
     * COnfigure EasMock expectations for a successful adb command call
     * @param command the adb command to execute
     * @param result the {@link CommandResult} expected from the adb command execution
     * @throws Exception
     */
    private void setExecuteAdbCommandExpectations(CommandResult result, String command)
            throws Exception {
        EasyMock.expect(mMockRunUtil.runTimedCmd(EasyMock.anyLong(),
                EasyMock.eq("adb"), EasyMock.eq("-s"), EasyMock.eq(MOCK_DEVICE_SERIAL),
                EasyMock.eq(command))).andReturn(result);
    }

    /**
     * Test that {@link TestDevice#enableAdbRoot()} reattempts adb root
     */
    public void testEnableAdbRoot_rootRetry() throws Exception {
        injectShellResponse("id", "uid=2000(shell) gid=2000(shell)");
        injectShellResponse("id", "uid=2000(shell) gid=2000(shell)");
        injectShellResponse("id", "uid=0(root) gid=0(root)");
        CommandResult adbBadResult = new CommandResult(CommandStatus.SUCCESS);
        adbBadResult.setStdout("");
        setExecuteAdbCommandExpectations(adbBadResult, "root");
        CommandResult adbResult = new CommandResult(CommandStatus.SUCCESS);
        adbResult.setStdout("restarting adbd as root");
        setExecuteAdbCommandExpectations(adbResult, "root");
        EasyMock.expect(mMockStateMonitor.waitForDeviceNotAvailable(EasyMock.anyLong())).andReturn(
                Boolean.TRUE).times(2);
        EasyMock.expect(mMockStateMonitor.waitForDeviceOnline()).andReturn(
                mMockIDevice).times(2);
        EasyMock.replay(mMockIDevice, mMockRunUtil, mMockStateMonitor);
        assertTrue(mTestDevice.enableAdbRoot());
    }

    /**
     * Test that {@link TestDevice#isAdbRoot()} for device without adb root.
     */
    public void testIsAdbRootForNonRoot() throws Exception {
        injectShellResponse("id", "uid=2000(shell) gid=2000(shell)");
        EasyMock.replay(mMockIDevice);
        assertFalse(mTestDevice.isAdbRoot());
    }

    /**
     * Test that {@link TestDevice#isAdbRoot()} for device with adb root.
     */
    public void testIsAdbRootForRoot() throws Exception {
        injectShellResponse("id", "uid=0(root) gid=0(root)");
        EasyMock.replay(mMockIDevice);
        assertTrue(mTestDevice.isAdbRoot());
    }

    /**
     * Test {@link TestDevice#getProductType()} when device is in fastboot and IDevice has not
     * cached product type property
     */
    public void testGetProductType_fastboot() throws DeviceNotAvailableException {
        EasyMock.expect(mMockIDevice.getProperty(EasyMock.<String>anyObject())).andReturn(null);
        CommandResult fastbootResult = new CommandResult();
        fastbootResult.setStatus(CommandStatus.SUCCESS);
        // output of this cmd goes to stderr
        fastbootResult.setStdout("");
        fastbootResult.setStderr("product: nexusone\n" + "finished. total time: 0.001s");
        EasyMock.expect(
                mMockRunUtil.runTimedCmd(EasyMock.anyLong(), (String)EasyMock.anyObject(),
                        (String)EasyMock.anyObject(), (String)EasyMock.anyObject(),
                        (String)EasyMock.anyObject(), (String)EasyMock.anyObject())).andReturn(
                fastbootResult);
        EasyMock.replay(mMockIDevice, mMockRunUtil);
        mRecoveryTestDevice.setDeviceState(TestDeviceState.FASTBOOT);
        assertEquals("nexusone", mRecoveryTestDevice.getProductType());
    }

    /**
     * Test {@link TestDevice#getProductType()} for a device with a non-alphanumeric fastboot
     * product type
     */
    public void testGetProductType_fastbootNonalpha() throws DeviceNotAvailableException {
        EasyMock.expect(mMockIDevice.getProperty(EasyMock.<String>anyObject())).andReturn(null);
        CommandResult fastbootResult = new CommandResult();
        fastbootResult.setStatus(CommandStatus.SUCCESS);
        // output of this cmd goes to stderr
        fastbootResult.setStdout("");
        fastbootResult.setStderr("product: foo-bar\n" + "finished. total time: 0.001s");
        EasyMock.expect(
                mMockRunUtil.runTimedCmd(EasyMock.anyLong(), (String)EasyMock.anyObject(),
                        (String)EasyMock.anyObject(), (String)EasyMock.anyObject(),
                        (String)EasyMock.anyObject(), (String)EasyMock.anyObject())).andReturn(
                fastbootResult);
        EasyMock.replay(mMockIDevice, mMockRunUtil);
        mRecoveryTestDevice.setDeviceState(TestDeviceState.FASTBOOT);
        assertEquals("foo-bar", mRecoveryTestDevice.getProductType());
    }

    /**
     * Verify that {@link TestDevice#getProductType()} throws an exception if requesting a product
     * type directly fails while the device is in fastboot.
     */
    public void testGetProductType_fastbootFail() {
        EasyMock.expect(mMockIDevice.getProperty(EasyMock.<String>anyObject())).andStubReturn(null);
        CommandResult fastbootResult = new CommandResult();
        fastbootResult.setStatus(CommandStatus.SUCCESS);
        // output of this cmd goes to stderr
        fastbootResult.setStdout("");
        fastbootResult.setStderr("product: \n" + "finished. total time: 0.001s");
        EasyMock.expect(
                mMockRunUtil.runTimedCmd(EasyMock.anyLong(), (String)EasyMock.anyObject(),
                        (String)EasyMock.anyObject(), (String)EasyMock.anyObject(),
                        (String)EasyMock.anyObject(), (String)EasyMock.anyObject())).andReturn(
                fastbootResult).anyTimes();
        EasyMock.replay(mMockIDevice);
        EasyMock.replay(mMockRunUtil);
        mTestDevice.setDeviceState(TestDeviceState.FASTBOOT);
        try {
            String type = mTestDevice.getProductType();
            fail(String.format("DeviceNotAvailableException not thrown; productType was '%s'",
                    type));
        } catch (DeviceNotAvailableException e) {
            // expected
        }
    }

    /**
     * Test {@link TestDevice#getProductType()} when device is in adb and IDevice has not cached
     * product type property
     */
    public void testGetProductType_adb() throws Exception {
        EasyMock.expect(mMockIDevice.getProperty("ro.hardware")).andReturn(null);
        final String expectedOutput = "nexusone";
        injectSystemProperty("ro.hardware", expectedOutput);
        EasyMock.replay(mMockIDevice);
        assertEquals(expectedOutput, mTestDevice.getProductType());
    }

    /**
     * Verify that {@link TestDevice#getProductType()} throws an exception if requesting a product
     * type directly still fails.
     */
    public void testGetProductType_adbFail() throws Exception {
        EasyMock.expect(mMockIDevice.getProperty(EasyMock.<String>anyObject())).andStubReturn(null);
        injectSystemProperty("ro.hardware", null).times(3);
        EasyMock.replay(mMockIDevice);
        try {
            mTestDevice.getProductType();
            fail("DeviceNotAvailableException not thrown");
        } catch (DeviceNotAvailableException e) {
            // expected
        }
    }

    /**
     * Test {@link TestDevice#clearErrorDialogs()} when both a error and anr dialog are present.
     */
    public void testClearErrorDialogs() throws Exception {
        final String anrOutput = "debugging=false crashing=false null notResponding=true "
                + "com.android.server.am.AppNotRespondingDialog@4534aaa0 bad=false\n blah\n";
        final String crashOutput = "debugging=false crashing=true "
                + "com.android.server.am.AppErrorDialog@45388a60 notResponding=false null bad=false"
                + "blah \n";
        // construct a string with 2 error dialogs of each type to ensure proper detection
        final String fourErrors = anrOutput + anrOutput + crashOutput + crashOutput;
        injectShellResponse(null, fourErrors);
        mMockIDevice.executeShellCommand((String)EasyMock.anyObject(),
                (IShellOutputReceiver)EasyMock.anyObject(),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        // expect 4 key events to be sent - one for each dialog
        // and expect another dialog query - but return nothing
        EasyMock.expectLastCall().times(5);

        EasyMock.replay(mMockIDevice);
        mTestDevice.clearErrorDialogs();
    }

    /**
     * Test that the unresponsive device exception is propagated from the recovery to TestDevice.
     * @throws Exception
     */
    public void testRecoverDevice_ThrowException() throws Exception {
        TestDevice testDevice = new TestDevice(mMockIDevice, mMockStateMonitor, mMockDvcMonitor) {
            @Override
            public boolean enableAdbRoot() throws DeviceNotAvailableException {
                return true;
            }
        };
        testDevice.setRecovery(new IDeviceRecovery() {

            @Override
            public void recoverDeviceRecovery(IDeviceStateMonitor monitor)
                    throws DeviceNotAvailableException {
                throw new DeviceNotAvailableException();
            }

            @Override
            public void recoverDeviceBootloader(IDeviceStateMonitor monitor)
                    throws DeviceNotAvailableException {
                throw new DeviceNotAvailableException();
            }

            @Override
            public void recoverDevice(IDeviceStateMonitor monitor, boolean recoverUntilOnline)
                    throws DeviceNotAvailableException {
                throw new DeviceUnresponsiveException();
            }
        });
        testDevice.setRecoveryMode(RecoveryMode.AVAILABLE);
        mMockIDevice.executeShellCommand((String) EasyMock.anyObject(),
                (CollectingOutputReceiver)EasyMock.anyObject(), EasyMock.anyLong(),
                EasyMock.eq(TimeUnit.MILLISECONDS));
        EasyMock.expectLastCall();
        EasyMock.replay(mMockIDevice);
        try {
            testDevice.recoverDevice();
        } catch (DeviceNotAvailableException dnae) {
            assertTrue(dnae instanceof DeviceUnresponsiveException);
            return;
        }
        fail();
    }

    /**
     * Simple normal case test for
     * {@link TestDevice#executeShellCommand(String, IShellOutputReceiver)}.
     * <p/>
     * Verify that the shell command is routed to the IDevice.
     */
    public void testExecuteShellCommand_receiver() throws IOException, DeviceNotAvailableException,
            TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException {
        final String testCommand = "simple command";
        // expect shell command to be called
        mMockIDevice.executeShellCommand(EasyMock.eq(testCommand), EasyMock.eq(mMockReceiver),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        EasyMock.replay(mMockIDevice);
        mTestDevice.executeShellCommand(testCommand, mMockReceiver);
    }

    /**
     * Simple normal case test for
     * {@link TestDevice#executeShellCommand(String)}.
     * <p/>
     * Verify that the shell command is routed to the IDevice, and shell output is collected.
     */
    public void testExecuteShellCommand() throws Exception {
        final String testCommand = "simple command";
        final String expectedOutput = "this is the output\r\n in two lines\r\n";
        injectShellResponse(testCommand, expectedOutput);
        EasyMock.replay(mMockIDevice);
        assertEquals(expectedOutput, mTestDevice.executeShellCommand(testCommand));
    }

    /**
     * Test {@link TestDevice#executeShellCommand(String, IShellOutputReceiver)} behavior when
     * {@link IDevice} throws IOException and recovery immediately fails.
     * <p/>
     * Verify that a DeviceNotAvailableException is thrown.
     */
    public void testExecuteShellCommand_recoveryFail() throws Exception {
        final String testCommand = "simple command";
        // expect shell command to be called
        mMockIDevice.executeShellCommand(EasyMock.eq(testCommand), EasyMock.eq(mMockReceiver),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        EasyMock.expectLastCall().andThrow(new IOException());
        mMockRecovery.recoverDevice(EasyMock.eq(mMockStateMonitor), EasyMock.eq(false));
        EasyMock.expectLastCall().andThrow(new DeviceNotAvailableException());
        EasyMock.replay(mMockIDevice);
        EasyMock.replay(mMockRecovery);
        try {
            mRecoveryTestDevice.executeShellCommand(testCommand, mMockReceiver);
            fail("DeviceNotAvailableException not thrown");
        } catch (DeviceNotAvailableException e) {
            // expected
        }
    }

    /**
     * Test {@link TestDevice#executeShellCommand(String, IShellOutputReceiver)} behavior when
     * {@link IDevice} throws IOException and device is in recovery until online mode.
     * <p/>
     * Verify that a DeviceNotAvailableException is thrown.
     */
    public void testExecuteShellCommand_recoveryUntilOnline() throws Exception {
        final String testCommand = "simple command";
        // expect shell command to be called
        mRecoveryTestDevice.setRecoveryMode(RecoveryMode.ONLINE);
        mMockIDevice.executeShellCommand(EasyMock.eq(testCommand), EasyMock.eq(mMockReceiver),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        EasyMock.expectLastCall().andThrow(new IOException());
        mMockRecovery.recoverDevice(EasyMock.eq(mMockStateMonitor), EasyMock.eq(true));
        setEnableAdbRootExpectations();
        mMockIDevice.executeShellCommand(EasyMock.eq(testCommand), EasyMock.eq(mMockReceiver),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        EasyMock.replay(mMockIDevice, mMockRecovery, mMockRunUtil, mMockStateMonitor);
        mRecoveryTestDevice.executeShellCommand(testCommand, mMockReceiver);
    }

    /**
     * Test {@link TestDevice#executeShellCommand(String, IShellOutputReceiver)} behavior when
     * {@link IDevice} throws IOException and recovery succeeds.
     * <p/>
     * Verify that command is re-tried.
     */
    public void testExecuteShellCommand_recoveryRetry() throws Exception {
        final String testCommand = "simple command";
        // expect shell command to be called
        mMockIDevice.executeShellCommand(EasyMock.eq(testCommand), EasyMock.eq(mMockReceiver),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        EasyMock.expectLastCall().andThrow(new IOException());
        assertRecoverySuccess();
        mMockIDevice.executeShellCommand(EasyMock.eq(testCommand), EasyMock.eq(mMockReceiver),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        replayMocks();
        mTestDevice.executeShellCommand(testCommand, mMockReceiver);
    }

    /** Set expectations for a successful recovery operation
     */
    private void assertRecoverySuccess() throws DeviceNotAvailableException, IOException,
            TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException {
        mMockRecovery.recoverDevice(EasyMock.eq(mMockStateMonitor), EasyMock.eq(false));
        // expect post boot up steps
        mMockIDevice.executeShellCommand(EasyMock.eq(mTestDevice.getDisableKeyguardCmd()),
                (IShellOutputReceiver)EasyMock.anyObject(),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
    }

    /**
     * Test {@link TestDevice#executeShellCommand(String, IShellOutputReceiver)} behavior when
     * command times out and recovery succeeds.
     * <p/>
     * Verify that command is re-tried.
     */
    public void testExecuteShellCommand_recoveryTimeoutRetry() throws Exception {
        final String testCommand = "simple command";
        // expect shell command to be called - and never return from that call
        mMockIDevice.executeShellCommand(EasyMock.eq(testCommand), EasyMock.eq(mMockReceiver),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        EasyMock.expectLastCall().andThrow(new TimeoutException());
        assertRecoverySuccess();
        // now expect shellCommand to be executed again, and succeed
        mMockIDevice.executeShellCommand(EasyMock.eq(testCommand), EasyMock.eq(mMockReceiver),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        replayMocks();
        mTestDevice.executeShellCommand(testCommand, mMockReceiver);
    }

    /**
     * Test {@link TestDevice#executeShellCommand(String, IShellOutputReceiver)} behavior when
     * {@link IDevice} repeatedly throws IOException and recovery succeeds.
     * <p/>
     * Verify that DeviceNotAvailableException is thrown.
     */
    public void testExecuteShellCommand_recoveryAttempts() throws Exception {
        final String testCommand = "simple command";
        // expect shell command to be called
        mMockIDevice.executeShellCommand(EasyMock.eq(testCommand), EasyMock.eq(mMockReceiver),
                EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        EasyMock.expectLastCall().andThrow(new IOException()).times(
                TestDevice.MAX_RETRY_ATTEMPTS+1);
        for (int i=0; i <= TestDevice.MAX_RETRY_ATTEMPTS; i++) {
            assertRecoverySuccess();
        }
        replayMocks();
        try {
            mTestDevice.executeShellCommand(testCommand, mMockReceiver);
            fail("DeviceUnresponsiveException not thrown");
        } catch (DeviceUnresponsiveException e) {
            // expected
        }
    }

    /**
     * Puts all the mock objects into replay mode
     */
    private void replayMocks() {
        EasyMock.replay(mMockIDevice, mMockRecovery, mMockStateMonitor, mMockRunUtil, mMockWifi);
    }

    /**
     * Verify all the mock objects
     */
    private void verifyMocks() {
        EasyMock.verify(mMockIDevice, mMockRecovery, mMockStateMonitor, mMockRunUtil, mMockWifi);
    }


    /**
     * Unit test for {@link TestDevice#getExternalStoreFreeSpace()}.
     * <p/>
     * Verify that output of 'adb shell df' command is parsed correctly.
     */
    public void testGetExternalStoreFreeSpace() throws Exception {
        final String dfOutput =
            "/mnt/sdcard: 3864064K total, 1282880K used, 2581184K available (block size 32768)";
        assertGetExternalStoreFreeSpace(dfOutput, 2581184);
    }

    /**
     * Unit test for {@link TestDevice#getExternalStoreFreeSpace()}.
     * <p/>
     * Verify that the table-based output of 'adb shell df' command is parsed correctly.
     */
    public void testGetExternalStoreFreeSpace_table() throws Exception {
        final String dfOutput =
            "Filesystem             Size   Used   Free   Blksize\n" +
            "/mnt/sdcard              3G   787M     2G   4096";
        assertGetExternalStoreFreeSpace(dfOutput, 2 * 1024 * 1024);
    }

    /**
     * Unit test for {@link TestDevice#getExternalStoreFreeSpace()}.
     * <p/>
     * Verify that the coreutils-like output of 'adb shell df' command is parsed correctly.
     */
    public void testGetExternalStoreFreeSpace_toybox() throws Exception {
        final String dfOutput =
            "Filesystem      1K-blocks	Used  Available Use% Mounted on\n" +
            "/dev/fuse        11585536    1316348   10269188  12% /mnt/sdcard";
        assertGetExternalStoreFreeSpace(dfOutput, 10269188);
    }

    /**
     * Unit test for {@link TestDevice#getExternalStoreFreeSpace()}.
     * <p/>
     * Verify that the coreutils-like output of 'adb shell df' command is parsed correctly. This
     * variant tests the fact that the returned mount point in last column of command output may
     * not match the original path provided as parameter to df.
     */
    public void testGetExternalStoreFreeSpace_toybox2() throws Exception {
        final String dfOutput =
            "Filesystem     1K-blocks   Used Available Use% Mounted on\n" +
            "/dev/fuse       27240188 988872  26251316   4% /storage/emulated";
        assertGetExternalStoreFreeSpace(dfOutput, 26251316);
    }

    /**
     * Unit test for {@link TestDevice#getExternalStoreFreeSpace()}.
     * <p/>
     * Verify behavior when 'df' command returns unexpected content
     */
    public void testGetExternalStoreFreeSpace_badOutput() throws Exception {
        final String dfOutput =
            "/mnt/sdcard: blaH";
        assertGetExternalStoreFreeSpace(dfOutput, 0);
    }

    /**
     * Unit test for {@link TestDevice#getExternalStoreFreeSpace()}.
     * <p/>
     * Verify behavior when first 'df' attempt returns empty output
     */
    public void testGetExternalStoreFreeSpace_emptyOutput() throws Exception {
        final String mntPoint = "/mnt/sdcard";
        final String expectedCmd = "df " + mntPoint;
        EasyMock.expect(mMockStateMonitor.getMountPoint(IDevice.MNT_EXTERNAL_STORAGE)).andReturn(
                mntPoint);
        // expect shell command to be called, and return the empty df output
        injectShellResponse(expectedCmd, "");
        final String dfOutput =
                "/mnt/sdcard: 3864064K total, 1282880K used, 2581184K available (block size 32768)";
        injectShellResponse(expectedCmd, dfOutput);
        EasyMock.replay(mMockIDevice, mMockStateMonitor);
        assertEquals(2581184, mTestDevice.getExternalStoreFreeSpace());
    }

    /**
     * Helper method to verify the {@link TestDevice#getExternalStoreFreeSpace()} method under
     * different conditions.
     *
     * @param dfOutput the test output to inject
     * @param expectedFreeSpaceKB the expected free space
     */
    private void assertGetExternalStoreFreeSpace(final String dfOutput, long expectedFreeSpaceKB)
            throws Exception {
        final String mntPoint = "/mnt/sdcard";
        final String expectedCmd = "df " + mntPoint;
        EasyMock.expect(mMockStateMonitor.getMountPoint(IDevice.MNT_EXTERNAL_STORAGE)).andReturn(
                mntPoint);
        // expect shell command to be called, and return the test df output
        injectShellResponse(expectedCmd, dfOutput);
        EasyMock.replay(mMockIDevice, mMockStateMonitor);
        assertEquals(expectedFreeSpaceKB, mTestDevice.getExternalStoreFreeSpace());
    }

    /**
     * Unit test for {@link TestDevice#syncFiles(File, String)}.
     * <p/>
     * Verify behavior when given local file does not exist
     */
    public void testSyncFiles_missingLocal() throws Exception {
        EasyMock.replay(mMockIDevice);
        assertFalse(mTestDevice.syncFiles(new File("idontexist"), "/sdcard"));
    }

    /**
     * Test {@link TestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, Collection)}
     * success case.
     */
    public void testRunInstrumentationTests() throws Exception {
        IRemoteAndroidTestRunner mockRunner = EasyMock.createMock(IRemoteAndroidTestRunner.class);
        EasyMock.expect(mockRunner.getPackageName()).andStubReturn("com.example");
        Collection<ITestRunListener> listeners = new ArrayList<ITestRunListener>(0);
        mockRunner.setMaxTimeToOutputResponse(EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        // expect runner.run command to be called
        mockRunner.run(listeners);
        EasyMock.replay(mockRunner);
        mTestDevice.runInstrumentationTests(mockRunner, listeners);
    }

    /**
     * Test {@link TestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, Collection)}
     * when recovery fails.
     */
    public void testRunInstrumentationTests_recoveryFails() throws Exception {
        IRemoteAndroidTestRunner mockRunner = EasyMock.createMock(IRemoteAndroidTestRunner.class);
        Collection<ITestRunListener> listeners = new ArrayList<ITestRunListener>(1);
        ITestRunListener listener = EasyMock.createMock(ITestRunListener.class);
        listeners.add(listener);
        mockRunner.setMaxTimeToOutputResponse(EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        mockRunner.run(listeners);
        EasyMock.expectLastCall().andThrow(new IOException());
        EasyMock.expect(mockRunner.getPackageName()).andReturn("foo");
        listener.testRunFailed((String)EasyMock.anyObject());
        mMockRecovery.recoverDevice(EasyMock.eq(mMockStateMonitor), EasyMock.eq(false));
        EasyMock.expectLastCall().andThrow(new DeviceNotAvailableException());
        EasyMock.replay(listener, mockRunner, mMockIDevice, mMockRecovery);
        try {
            mRecoveryTestDevice.runInstrumentationTests(mockRunner, listeners);
            fail("DeviceNotAvailableException not thrown");
        } catch (DeviceNotAvailableException e) {
            // expected
        }
    }

    /**
     * Test {@link TestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, Collection)}
     * when recovery succeeds.
     */
    public void testRunInstrumentationTests_recoverySucceeds() throws Exception {
        IRemoteAndroidTestRunner mockRunner = EasyMock.createMock(IRemoteAndroidTestRunner.class);
        Collection<ITestRunListener> listeners = new ArrayList<ITestRunListener>(1);
        ITestRunListener listener = EasyMock.createMock(ITestRunListener.class);
        listeners.add(listener);
        mockRunner.setMaxTimeToOutputResponse(EasyMock.anyLong(), (TimeUnit)EasyMock.anyObject());
        mockRunner.run(listeners);
        EasyMock.expectLastCall().andThrow(new IOException());
        EasyMock.expect(mockRunner.getPackageName()).andReturn("foo");
        listener.testRunFailed((String)EasyMock.anyObject());
        assertRecoverySuccess();
        EasyMock.replay(listener, mockRunner, mMockIDevice, mMockRecovery);
        mTestDevice.runInstrumentationTests(mockRunner, listeners);
    }

    /**
     * Test {@link TestDevice#executeFastbootCommand(String...)} throws an exception when fastboot
     * is not available.
     */
    public void testExecuteFastbootCommand_nofastboot() throws Exception {
        try {
            mNoFastbootTestDevice.executeFastbootCommand("");
            fail("UnsupportedOperationException not thrown");
        } catch (UnsupportedOperationException e) {
            // expected
        }
    }

    /**
     * Test {@link TestDevice#executeLongFastbootCommand(String...)} throws an exception when
     * fastboot is not available.
     */
    public void testExecuteLongFastbootCommand_nofastboot() throws Exception {
        try {
            mNoFastbootTestDevice.executeFastbootCommand("");
            fail("UnsupportedOperationException not thrown");
        } catch (UnsupportedOperationException e) {
            // expected
        }
    }

    /**
     * Test that state changes are ignore while {@link TestDevice#executeFastbootCommand(String...)}
     * is active.
     */
    public void testExecuteFastbootCommand_state() throws Exception {
        final long waitTimeMs = 150;
        // build a fastboot response that will block
        IAnswer<CommandResult> blockResult = new IAnswer<CommandResult>() {
            @Override
            public CommandResult answer() throws Throwable {
                synchronized(this) {
                    // first inform this test that fastboot cmd is executing
                    notifyAll();
                    // now wait for test to unblock us when its done testing logic
                    wait(waitTimeMs);
                }
                return new CommandResult(CommandStatus.SUCCESS);
            }
        };
        EasyMock.expect(mMockRunUtil.runTimedCmd(EasyMock.anyLong(), EasyMock.eq("fastboot"),
                EasyMock.eq("-s"),EasyMock.eq(MOCK_DEVICE_SERIAL), EasyMock.eq("foo"))).andAnswer(
                        blockResult).times(2);

        // expect
        mMockStateMonitor.setState(TestDeviceState.FASTBOOT);
        mMockStateMonitor.setState(TestDeviceState.NOT_AVAILABLE);
        mMockRecovery.recoverDeviceBootloader((IDeviceStateMonitor)EasyMock.anyObject());
        EasyMock.expectLastCall().times(2);
        replayMocks();

        mTestDevice.setDeviceState(TestDeviceState.FASTBOOT);
        assertEquals(TestDeviceState.FASTBOOT, mTestDevice.getDeviceState());

        // start fastboot command in background thread
        Thread fastbootThread = new Thread() {
            @Override
            public void run() {
                try {
                    mTestDevice.executeFastbootCommand("foo");
                } catch (DeviceNotAvailableException e) {
                    CLog.e(e);
                }
            }
        };
        fastbootThread.start();
        try {
            synchronized (blockResult) {
                blockResult.wait(waitTimeMs);
            }
            // expect to ignore this
            mTestDevice.setDeviceState(TestDeviceState.NOT_AVAILABLE);
            assertEquals(TestDeviceState.FASTBOOT, mTestDevice.getDeviceState());
        } finally {
            synchronized (blockResult) {
                blockResult.notifyAll();
            }
        }
        fastbootThread.join();
        mTestDevice.setDeviceState(TestDeviceState.NOT_AVAILABLE);
        assertEquals(TestDeviceState.NOT_AVAILABLE, mTestDevice.getDeviceState());
        verifyMocks();
    }

    /**
     * Test recovery mode is entered when fastboot command fails
     */
    public void testExecuteFastbootCommand_recovery() throws UnsupportedOperationException,
           DeviceNotAvailableException {
        CommandResult result = new CommandResult(CommandStatus.EXCEPTION);
        EasyMock.expect(mMockRunUtil.runTimedCmd(
                EasyMock.anyLong(), EasyMock.eq("fastboot"), EasyMock.eq("-s"),
                EasyMock.eq(MOCK_DEVICE_SERIAL), EasyMock.eq("foo"))).andReturn(result);
        mMockRecovery.recoverDeviceBootloader((IDeviceStateMonitor)EasyMock.anyObject());
        CommandResult successResult = new CommandResult(CommandStatus.SUCCESS);
        successResult.setStderr("");
        successResult.setStdout("");
        // now expect a successful retry
        EasyMock.expect(mMockRunUtil.runTimedCmd(EasyMock.anyLong(), EasyMock.eq("fastboot"),
                EasyMock.eq("-s"),EasyMock.eq(MOCK_DEVICE_SERIAL), EasyMock.eq("foo"))).andReturn(
                        successResult);
        replayMocks();
        mTestDevice.executeFastbootCommand("foo");
        verifyMocks();

    }

    /**
     * Basic test for encryption if encryption is not supported.
     * <p>
     * Calls {@link TestDevice#encryptDevice(boolean)}, {@link TestDevice#unlockDevice()}, and
     * {@link TestDevice#unencryptDevice()} and makes sure that a
     * {@link UnsupportedOperationException} is thrown for each method.
     * </p>
     */
    public void testEncryptionUnsupported() throws Exception {
        setEncryptedUnsupportedExpectations();
        setEncryptedUnsupportedExpectations();
        setEncryptedUnsupportedExpectations();
        EasyMock.replay(mMockIDevice, mMockRunUtil, mMockStateMonitor);

        try {
            mTestDevice.encryptDevice(false);
            fail("encryptUserData() did not throw UnsupportedOperationException");
        } catch (UnsupportedOperationException e) {
            // Expected
        }
        try {
            mTestDevice.unlockDevice();
            fail("decryptUserData() did not throw UnsupportedOperationException");
        } catch (UnsupportedOperationException e) {
            // Expected
        }
        try {
            mTestDevice.unencryptDevice();
            fail("unencryptUserData() did not throw UnsupportedOperationException");
        } catch (UnsupportedOperationException e) {
            // Expected
        }
        return;
    }

    /**
     * Unit test for {@link TestDevice#encryptDevice(boolean)}.
     */
    public void testEncryptDevice_alreadyEncrypted() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public boolean isDeviceEncrypted() throws DeviceNotAvailableException {
                return true;
            }
        };
        setEncryptedSupported();
        EasyMock.replay(mMockIDevice, mMockRunUtil, mMockStateMonitor);
        assertTrue(mTestDevice.encryptDevice(false));
        EasyMock.verify(mMockIDevice, mMockRunUtil, mMockStateMonitor);
    }

    /**
     * Unit test for {@link TestDevice#encryptDevice(boolean)}.
     */
    public void testEncryptDevice_encryptionFails() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public boolean isDeviceEncrypted() throws DeviceNotAvailableException {
                return false;
            }
        };
        setEncryptedSupported();
        setEnableAdbRootExpectations();
        injectShellResponse("vdc cryptfs enablecrypto wipe \"android\"",
                "500 2280 Usage: cryptfs enablecrypto\r\n");
        injectShellResponse("vdc cryptfs enablecrypto wipe default", "200 0 -1\r\n");
        EasyMock.expect(mMockStateMonitor.waitForDeviceNotAvailable(EasyMock.anyLong())).andReturn(
                Boolean.TRUE);
        EasyMock.expect(mMockStateMonitor.waitForDeviceOnline()).andReturn(
                mMockIDevice);
        EasyMock.replay(mMockIDevice, mMockRunUtil, mMockStateMonitor);
        assertFalse(mTestDevice.encryptDevice(false));
        EasyMock.verify(mMockIDevice, mMockRunUtil, mMockStateMonitor);
    }

    /**
     * Unit test for {@link TestDevice#unencryptDevice()} with fastboot erase.
     */
    public void testUnencryptDevice_erase() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public boolean isDeviceEncrypted() throws DeviceNotAvailableException {
                return true;
            }
            @Override
            public void rebootIntoBootloader()
                    throws DeviceNotAvailableException, UnsupportedOperationException {
                // do nothing.
            }
            @Override
            public void rebootUntilOnline() throws DeviceNotAvailableException {
                // do nothing.
            }
            @Override
            public CommandResult fastbootWipePartition(String partition)
                    throws DeviceNotAvailableException {
                return null;
            }
        };
        setEncryptedSupported();
        EasyMock.expect(mMockStateMonitor.waitForDeviceAvailable(EasyMock.anyLong()))
                .andReturn(mMockIDevice);
        EasyMock.replay(mMockIDevice, mMockRunUtil, mMockStateMonitor);
        assertTrue(mTestDevice.unencryptDevice());
        EasyMock.verify(mMockIDevice, mMockRunUtil, mMockStateMonitor);
    }

    /**
     * Unit test for {@link TestDevice#unencryptDevice()} with fastboot wipe.
     */
    public void testUnencryptDevice_wipe() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public boolean isDeviceEncrypted() throws DeviceNotAvailableException {
                return true;
            }
            @Override
            public void rebootIntoBootloader()
                    throws DeviceNotAvailableException, UnsupportedOperationException {
                // do nothing.
            }
            @Override
            public void rebootUntilOnline() throws DeviceNotAvailableException {
                // do nothing.
            }
            @Override
            public CommandResult fastbootWipePartition(String partition)
                    throws DeviceNotAvailableException {
                return null;
            }
            @Override
            public void reboot() throws DeviceNotAvailableException {
                // do nothing.
            }
        };
        mTestDevice.getOptions().setUseFastbootErase(true);
        setEncryptedSupported();
        injectShellResponse("vdc volume list", "110 sdcard /mnt/sdcard1");
        injectShellResponse("vdc volume format sdcard", "200 0 -1:success");
        EasyMock.replay(mMockIDevice, mMockRunUtil, mMockStateMonitor);
        assertTrue(mTestDevice.unencryptDevice());
        EasyMock.verify(mMockIDevice, mMockRunUtil, mMockStateMonitor);
    }

    /**
     * Configure EasyMock for a encryption check call, that returns that encryption is unsupported
     */
    private void setEncryptedUnsupportedExpectations() throws Exception {
        setEnableAdbRootExpectations();
        injectShellResponse("vdc cryptfs enablecrypto", "\r\n");
    }

    /**
     * Configure EasyMock for a encryption check call, that returns that encryption is unsupported
     */
    private void setEncryptedSupported() throws Exception {
        setEnableAdbRootExpectations();
        injectShellResponse("vdc cryptfs enablecrypto",
                "500 29805 Usage: cryptfs enablecrypto <wipe|inplace> "
                + "default|password|pin|pattern [passwd] [noui]\r\n");
    }

    /**
     * Simple test for {@link TestDevice#switchToAdbUsb()}
     */
    public void testSwitchToAdbUsb() throws Exception  {
        setExecuteAdbCommandExpectations(new CommandResult(CommandStatus.SUCCESS), "usb");
        replayMocks();
        mTestDevice.switchToAdbUsb();
        verifyMocks();
    }

    /**
     * Test for {@link TestDevice#switchToAdbTcp()} when device has no ip address
     */
    public void testSwitchToAdbTcp_noIp() throws Exception {
        EasyMock.expect(mMockWifi.getIpAddress()).andReturn(null);
        replayMocks();
        assertNull(mTestDevice.switchToAdbTcp());
        verifyMocks();
    }

    /**
     * Test normal success case for {@link TestDevice#switchToAdbTcp()}.
     */
    public void testSwitchToAdbTcp() throws Exception {
        EasyMock.expect(mMockWifi.getIpAddress()).andReturn("ip");
        EasyMock.expect(mMockRunUtil.runTimedCmd(EasyMock.anyLong(), EasyMock.eq("adb"),
                EasyMock.eq("-s"), EasyMock.eq("serial"), EasyMock.eq("tcpip"),
                EasyMock.eq("5555"))).andReturn(
                        new CommandResult(CommandStatus.SUCCESS));
        replayMocks();
        assertEquals("ip:5555", mTestDevice.switchToAdbTcp());
        verifyMocks();
    }

    /**
     * Test simple success case for
     * {@link TestDevice#installPackage(File, File, boolean, String...)}.
     */
    public void testInstallPackages() throws Exception {
        final String certFile = "foo.dc";
        final String apkFile = "foo.apk";
        EasyMock.expect(mMockIDevice.syncPackageToDevice(EasyMock.contains(certFile))).andReturn(
                certFile);
        EasyMock.expect(mMockIDevice.syncPackageToDevice(EasyMock.contains(apkFile))).andReturn(
                apkFile);
        // expect apk path to be passed as extra arg
        mMockIDevice.installRemotePackage(EasyMock.eq(certFile), EasyMock.eq(true),
                EasyMock.eq("-l"), EasyMock.contains(apkFile));
        EasyMock.expectLastCall();
        mMockIDevice.removeRemotePackage(certFile);
        mMockIDevice.removeRemotePackage(apkFile);

        replayMocks();

        assertNull(mTestDevice.installPackage(new File(apkFile), new File(certFile), true, "-l"));
    }

    /**
     * Test that isRuntimePermissionSupported returns correct result for device reporting LRX22F
     * build attributes
     * @throws Exception
     */
    public void testRuntimePermissionSupportedLmpRelease() throws Exception {
        injectSystemProperty("ro.build.version.sdk", "21");
        injectSystemProperty(TestDevice.BUILD_CODENAME_PROP, "REL");
        injectSystemProperty(TestDevice.BUILD_ID_PROP, "1642709");
        replayMocks();
        assertFalse(mTestDevice.isRuntimePermissionSupported());
    }

    /**
     * Test that isRuntimePermissionSupported returns correct result for device reporting LMP MR1
     * dev build attributes
     * @throws Exception
     */
    public void testRuntimePermissionSupportedLmpMr1Dev() throws Exception {
        injectSystemProperty("ro.build.version.sdk", "22");
        injectSystemProperty(TestDevice.BUILD_CODENAME_PROP, "REL");
        injectSystemProperty(TestDevice.BUILD_ID_PROP, "1844090");
        replayMocks();
        assertFalse(mTestDevice.isRuntimePermissionSupported());
    }

    /**
     * Test that isRuntimePermissionSupported returns correct result for device reporting random
     * dev build attributes
     * @throws Exception
     */
    public void testRuntimePermissionSupportedNonMncLocal() throws Exception {
        injectSystemProperty("ro.build.version.sdk", "21");
        injectSystemProperty(TestDevice.BUILD_CODENAME_PROP, "LMP");
        injectSystemProperty(TestDevice.BUILD_ID_PROP, "eng.foo.20150414.190304");
        replayMocks();
        assertFalse(mTestDevice.isRuntimePermissionSupported());
    }

    /**
     * Test that isRuntimePermissionSupported returns correct result for device reporting early MNC
     * dev build attributes
     * @throws Exception
     */
    public void testRuntimePermissionSupportedEarlyMnc() throws Exception {
        setMockIDeviceRuntimePermissionNotSupported();
        replayMocks();
        assertFalse(mTestDevice.isRuntimePermissionSupported());
    }

    /**
     * Test that isRuntimePermissionSupported returns correct result for device reporting early MNC
     * dev build attributes
     * @throws Exception
     */
    public void testRuntimePermissionSupportedMncPostSwitch() throws Exception {
        setMockIDeviceRuntimePermissionSupported();
        replayMocks();
        assertTrue(mTestDevice.isRuntimePermissionSupported());
    }

    /**
     * Convenience method for setting up mMockIDevice to not support runtime permission
     */
    private void setMockIDeviceRuntimePermissionNotSupported() {
        injectSystemProperty("ro.build.version.sdk", "22");
    }

    /**
     * Convenience method for setting up mMockIDevice to support runtime permission
     */
    private void setMockIDeviceRuntimePermissionSupported() {
        injectSystemProperty("ro.build.version.sdk", "23");
    }

    /**
     * Test default installPackage on device not supporting runtime permission has expected
     * list of args
     * @throws Exception
     */
    public void testInstallPackage_default_runtimePermissionNotSupported() throws Exception {
        final String apkFile = "foo.apk";
        setMockIDeviceRuntimePermissionNotSupported();
        mMockIDevice.installPackage(EasyMock.contains(apkFile), EasyMock.eq(true));
        EasyMock.expectLastCall();
        replayMocks();
        assertNull(mTestDevice.installPackage(new File(apkFile), true));
    }

    /**
     * Test default installPackage on device supporting runtime permission has expected list of args
     * @throws Exception
     */
    public void testInstallPackage_default_runtimePermissionSupported() throws Exception {
        final String apkFile = "foo.apk";
        setMockIDeviceRuntimePermissionSupported();
        mMockIDevice.installPackage(EasyMock.contains(apkFile), EasyMock.eq(true),
                EasyMock.eq("-g"));
        EasyMock.expectLastCall();
        replayMocks();
        assertNull(mTestDevice.installPackage(new File(apkFile), true));
    }

    /**
     * Test default installPackageForUser on device not supporting runtime permission has expected
     * list of args
     * @throws Exception
     */
    public void testinstallPackageForUser_default_runtimePermissionNotSupported() throws Exception {
        final String apkFile = "foo.apk";
        int uid = 123;
        setMockIDeviceRuntimePermissionNotSupported();
        mMockIDevice.installPackage(EasyMock.contains(apkFile), EasyMock.eq(true),
                EasyMock.eq("--user"), EasyMock.eq(Integer.toString(uid)));
        EasyMock.expectLastCall();
        replayMocks();
        assertNull(mTestDevice.installPackageForUser(new File(apkFile), true, uid));
    }

    /**
     * Test default installPackageForUser on device supporting runtime permission has expected
     * list of args
     * @throws Exception
     */
    public void testinstallPackageForUser_default_runtimePermissionSupported() throws Exception {
        final String apkFile = "foo.apk";
        int uid = 123;
        setMockIDeviceRuntimePermissionSupported();
        mMockIDevice.installPackage(EasyMock.contains(apkFile), EasyMock.eq(true),
                EasyMock.eq("-g"), EasyMock.eq("--user"), EasyMock.eq(Integer.toString(uid)));
        EasyMock.expectLastCall();
        replayMocks();
        assertNull(mTestDevice.installPackageForUser(new File(apkFile), true, uid));
    }

    /**
     * Test runtime permission variant of installPackage throws exception on unsupported device
     * platform
     * @throws Exception
     */
    public void testInstallPackage_throw() throws Exception {
        final String apkFile = "foo.apk";
        setMockIDeviceRuntimePermissionNotSupported();
        replayMocks();
        try {
            mTestDevice.installPackage(new File(apkFile), true, true);
        } catch (UnsupportedOperationException uoe) {
            // ignore, exception thrown here is expected
            return;
        }
        fail("installPackage did not throw IllegalArgumentException");
    }

    /**
     * Test runtime permission variant of installPackage has expected list of args on a supported
     * device when granting
     * @throws Exception
     */
    public void testInstallPackage_grant_runtimePermissionSupported() throws Exception {
        final String apkFile = "foo.apk";
        setMockIDeviceRuntimePermissionSupported();
        mMockIDevice.installPackage(EasyMock.contains(apkFile), EasyMock.eq(true),
                EasyMock.eq("-g"));
        EasyMock.expectLastCall();
        replayMocks();
        assertNull(mTestDevice.installPackage(new File(apkFile), true, true));
    }

    /**
     * Test runtime permission variant of installPackage has expected list of args on a supported
     * device when not granting
     * @throws Exception
     */
    public void testInstallPackage_noGrant_runtimePermissionSupported() throws Exception {
        final String apkFile = "foo.apk";
        setMockIDeviceRuntimePermissionSupported();
        mMockIDevice.installPackage(EasyMock.contains(apkFile), EasyMock.eq(true));
        EasyMock.expectLastCall();
        replayMocks();
        assertNull(mTestDevice.installPackage(new File(apkFile), true, false));
    }

    /**
     * Test grant permission variant of installPackageForUser throws exception on unsupported
     * device platform
     * @throws Exception
     */
    public void testInstallPackageForUser_throw() throws Exception {
        final String apkFile = "foo.apk";
        setMockIDeviceRuntimePermissionNotSupported();
        replayMocks();
        try {
            mTestDevice.installPackageForUser(new File(apkFile), true, true, 123);
        } catch (UnsupportedOperationException uoe) {
            // ignore, exception thrown here is expected
            return;
        }
        fail("installPackage did not throw IllegalArgumentException");
    }

    /**
     * Test grant permission variant of installPackageForUser has expected list of args on a
     * supported device when granting
     * @throws Exception
     */
    public void testInstallPackageForUser_grant_runtimePermissionSupported() throws Exception {
        final String apkFile = "foo.apk";
        int uid = 123;
        setMockIDeviceRuntimePermissionSupported();
        mMockIDevice.installPackage(EasyMock.contains(apkFile), EasyMock.eq(true),
                EasyMock.eq("-g"), EasyMock.eq("--user"), EasyMock.eq(Integer.toString(uid)));
        EasyMock.expectLastCall();
        replayMocks();
        assertNull(mTestDevice.installPackageForUser(new File(apkFile), true, true, uid));
    }

    /**
     * Test grant permission variant of installPackageForUser has expected list of args on a
     * supported device when not granting
     * @throws Exception
     */
    public void testInstallPackageForUser_noGrant_runtimePermissionSupported() throws Exception {
        final String apkFile = "foo.apk";
        int uid = 123;
        setMockIDeviceRuntimePermissionSupported();
        mMockIDevice.installPackage(EasyMock.contains(apkFile), EasyMock.eq(true),
                EasyMock.eq("--user"), EasyMock.eq(Integer.toString(uid)));
        EasyMock.expectLastCall();
        replayMocks();
        assertNull(mTestDevice.installPackageForUser(new File(apkFile), true, false, uid));
    }

    /**
     * Helper method to build a response to a executeShellCommand call
     *
     * @param expectedCommand the shell command to expect or null to skip verification of command
     * @param response the response to simulate
     */
    private void injectShellResponse(final String expectedCommand, final String response)
            throws Exception {
        injectShellResponse(expectedCommand, response, false);
    }

    /**
     * Helper method to build a response to a executeShellCommand call
     *
     * @param expectedCommand the shell command to expect or null to skip verification of command
     * @param response the response to simulate
     * @param asStub whether to set a single expectation or a stub expectation
     */
    private void injectShellResponse(final String expectedCommand, final String response,
            boolean asStub) throws Exception {
        IAnswer<Object> shellAnswer = new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                IShellOutputReceiver receiver =
                    (IShellOutputReceiver)EasyMock.getCurrentArguments()[1];
                byte[] inputData = response.getBytes();
                receiver.addOutput(inputData, 0, inputData.length);
                return null;
            }
        };
        if (expectedCommand != null) {
            mMockIDevice.executeShellCommand(EasyMock.eq(expectedCommand),
                    EasyMock.<IShellOutputReceiver>anyObject(),
                    EasyMock.anyLong(), EasyMock.<TimeUnit>anyObject());
        } else {
            mMockIDevice.executeShellCommand(EasyMock.<String>anyObject(),
                    EasyMock.<IShellOutputReceiver>anyObject(),
                    EasyMock.anyLong(), EasyMock.<TimeUnit>anyObject());

        }
        if (asStub) {
            EasyMock.expectLastCall().andStubAnswer(shellAnswer);
        } else {
            EasyMock.expectLastCall().andAnswer(shellAnswer);
        }
    }

    /**
     * Helper method to inject a response to {@link TestDevice#getProperty(String)} calls
     * @param property property name
     * @param value property value
     * @return preset {@link IExpectationSetters} returned by {@link EasyMock} where further
     * expectations can be added
     */
    private IExpectationSetters<Future<String>> injectSystemProperty(
            final String property, final String value) {
        SettableFuture<String> valueResponse = SettableFuture.create();
        valueResponse.set(value);
        return EasyMock.expect(mMockIDevice.getSystemProperty(property)).andReturn(valueResponse);
    }

    /**
     * Helper method to build response to a reboot call
     * @throws Exception
     */
    private void setRebootExpectations() throws Exception {
        EasyMock.expect(mMockStateMonitor.waitForDeviceOnline()).andReturn(
                mMockIDevice);
        setEnableAdbRootExpectations();
        setEncryptedUnsupportedExpectations();
        EasyMock.expect(mMockStateMonitor.waitForDeviceAvailable(EasyMock.anyLong())).andReturn(
                mMockIDevice);
    }

    /**
     * Test normal success case for {@link TestDevice#reboot()}
     */
    public void testReboot() throws Exception {
        setRebootExpectations();
        replayMocks();
        mTestDevice.reboot();
        verifyMocks();
    }

    /**
     * Test {@link TestDevice#reboot()} attempts a recovery upon failure
     */
    public void testRebootRecovers() throws Exception {
        EasyMock.expect(mMockStateMonitor.waitForDeviceOnline()).andReturn(
                mMockIDevice);
        setEnableAdbRootExpectations();
        setEncryptedUnsupportedExpectations();
        EasyMock.expect(mMockStateMonitor.waitForDeviceAvailable(EasyMock.anyLong())).andReturn(null);
        mMockRecovery.recoverDevice(mMockStateMonitor, false);
        replayMocks();
        mRecoveryTestDevice.reboot();
        verifyMocks();
    }

    /**
     * Unit test for {@link TestDevice#getInstalledPackageNames()}.
     */
    public void testGetInstalledPackageNames() throws Exception {
        final String output = "package:/system/app/LiveWallpapers.apk=com.android.wallpaper\n" +
                "package:/system/app/LiveWallpapersPicker.apk=com.android.wallpaper.livepicker";
        injectShellResponse(TestDevice.LIST_PACKAGES_CMD, output);
        EasyMock.replay(mMockIDevice, mMockStateMonitor);
        Set<String> actualPkgs = mTestDevice.getInstalledPackageNames();
        assertEquals(2, actualPkgs.size());
        assertTrue(actualPkgs.contains("com.android.wallpaper"));
        assertTrue(actualPkgs.contains("com.android.wallpaper.livepicker"));
    }

    /**
     * Unit test for {@link TestDevice#getInstalledPackageNames()}.
     * <p/>
     * Test bad output.
     */
    public void testGetInstalledPackageNamesForBadOutput() throws Exception {
        final String output = "junk output";
        injectShellResponse(TestDevice.LIST_PACKAGES_CMD, output);
        EasyMock.replay(mMockIDevice, mMockStateMonitor);
        Set<String> actualPkgs = mTestDevice.getInstalledPackageNames();
        assertEquals(0, actualPkgs.size());
    }

    /**
     * Unit test to make sure that the simple convenience constructor for
     * {@link MountPointInfo#MountPointInfo(String, String, String, List)} works as expected.
     */
    public void testMountInfo_simple() throws Exception {
        List<String> empty = Collections.emptyList();
        MountPointInfo info = new MountPointInfo("filesystem", "mountpoint", "type", empty);
        assertEquals("filesystem", info.filesystem);
        assertEquals("mountpoint", info.mountpoint);
        assertEquals("type", info.type);
        assertEquals(empty, info.options);
    }

    /**
     * Unit test to make sure that the mount-option-parsing convenience constructor for
     * {@link MountPointInfo#MountPointInfo(String, String, String, List)} works as expected.
     */
    public void testMountInfo_parseOptions() throws Exception {
        MountPointInfo info = new MountPointInfo("filesystem", "mountpoint", "type", "rw,relatime");
        assertEquals("filesystem", info.filesystem);
        assertEquals("mountpoint", info.mountpoint);
        assertEquals("type", info.type);

        // options should be parsed
        assertNotNull(info.options);
        assertEquals(2, info.options.size());
        assertEquals("rw", info.options.get(0));
        assertEquals("relatime", info.options.get(1));
    }

    /**
     * A unit test to ensure {@link TestDevice#getMountPointInfo()} works as expected.
     */
    public void testGetMountPointInfo() throws Exception {
        injectShellResponse("cat /proc/mounts", ArrayUtil.join("\r\n",
                "rootfs / rootfs ro,relatime 0 0",
                "tmpfs /dev tmpfs rw,nosuid,relatime,mode=755 0 0",
                "devpts /dev/pts devpts rw,relatime,mode=600 0 0",
                "proc /proc proc rw,relatime 0 0",
                "sysfs /sys sysfs rw,relatime 0 0",
                "none /acct cgroup rw,relatime,cpuacct 0 0",
                "tmpfs /mnt/asec tmpfs rw,relatime,mode=755,gid=1000 0 0",
                "tmpfs /mnt/obb tmpfs rw,relatime,mode=755,gid=1000 0 0",
                "none /dev/cpuctl cgroup rw,relatime,cpu 0 0",
                "/dev/block/vold/179:3 /mnt/secure/asec vfat rw,dirsync,nosuid,nodev," +
                    "noexec,relatime,uid=1000,gid=1015,fmask=0702,dmask=0702," +
                    "allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed," +
                    "utf8,errors=remount-ro 0 0",
                "tmpfs /storage/sdcard0/.android_secure tmpfs " +
                    "ro,relatime,size=0k,mode=000 0 0"));
        replayMocks();
        List<MountPointInfo> info = mTestDevice.getMountPointInfo();
        verifyMocks();
        assertEquals(11, info.size());

        // spot-check
        MountPointInfo mpi = info.get(0);
        assertEquals("rootfs", mpi.filesystem);
        assertEquals("/", mpi.mountpoint);
        assertEquals("rootfs", mpi.type);
        assertEquals(2, mpi.options.size());
        assertEquals("ro", mpi.options.get(0));
        assertEquals("relatime", mpi.options.get(1));

        mpi = info.get(9);
        assertEquals("/dev/block/vold/179:3", mpi.filesystem);
        assertEquals("/mnt/secure/asec", mpi.mountpoint);
        assertEquals("vfat", mpi.type);
        assertEquals(16, mpi.options.size());
        assertEquals("dirsync", mpi.options.get(1));
        assertEquals("errors=remount-ro", mpi.options.get(15));
    }

    /**
     * A unit test to ensure {@link TestDevice#getMountPointInfo(String)} works as expected.
     */
    public void testGetMountPointInfo_filter() throws Exception {
        injectShellResponse("cat /proc/mounts", ArrayUtil.join("\r\n",
                "rootfs / rootfs ro,relatime 0 0",
                "tmpfs /dev tmpfs rw,nosuid,relatime,mode=755 0 0",
                "devpts /dev/pts devpts rw,relatime,mode=600 0 0",
                "proc /proc proc rw,relatime 0 0",
                "sysfs /sys sysfs rw,relatime 0 0",
                "none /acct cgroup rw,relatime,cpuacct 0 0",
                "tmpfs /mnt/asec tmpfs rw,relatime,mode=755,gid=1000 0 0",
                "tmpfs /mnt/obb tmpfs rw,relatime,mode=755,gid=1000 0 0",
                "none /dev/cpuctl cgroup rw,relatime,cpu 0 0",
                "/dev/block/vold/179:3 /mnt/secure/asec vfat rw,dirsync,nosuid,nodev," +
                    "noexec,relatime,uid=1000,gid=1015,fmask=0702,dmask=0702," +
                    "allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed," +
                    "utf8,errors=remount-ro 0 0",
                "tmpfs /storage/sdcard0/.android_secure tmpfs " +
                    "ro,relatime,size=0k,mode=000 0 0"),
                true /* asStub */);
        replayMocks();
        MountPointInfo mpi = mTestDevice.getMountPointInfo("/mnt/secure/asec");
        assertEquals("/dev/block/vold/179:3", mpi.filesystem);
        assertEquals("/mnt/secure/asec", mpi.mountpoint);
        assertEquals("vfat", mpi.type);
        assertEquals(16, mpi.options.size());
        assertEquals("dirsync", mpi.options.get(1));
        assertEquals("errors=remount-ro", mpi.options.get(15));

        assertNull(mTestDevice.getMountPointInfo("/a/mountpoint/too/far"));
    }

    public void testParseFreeSpaceFromFree() throws Exception {
        assertNotNull("Failed to parse free space size with decimal point",
                mTestDevice.parseFreeSpaceFromFree("/storage/emulated/legacy",
                "/storage/emulated/legacy    13.2G   296.4M    12.9G   4096"));
        assertNotNull("Failed to parse integer free space size",
                mTestDevice.parseFreeSpaceFromFree("/storage/emulated/legacy",
                "/storage/emulated/legacy     13G   395M    12G   4096"));
    }

    public void testIsDeviceInputReady_Ready() throws Exception {
        injectShellResponse("dumpsys input", ArrayUtil.join("\r\n", getDumpsysInputHeader(),
                "  DispatchEnabled: 1",
                "  DispatchFrozen: 0",
                "  FocusedApplication: <null>",
                "  FocusedWindow: name='Window{2920620f u0 com.android.launcher/"
                + "com.android.launcher2.Launcher}'",
                "  TouchStates: <no displays touched>"
                ));
        replayMocks();
        assertTrue(mTestDevice.isDeviceInputReady());
    }

    public void testIsDeviceInputReady_NotReady() throws Exception {
        injectShellResponse("dumpsys input", ArrayUtil.join("\r\n", getDumpsysInputHeader(),
                "  DispatchEnabled: 0",
                "  DispatchFrozen: 0",
                "  FocusedApplication: <null>",
                "  FocusedWindow: name='Window{2920620f u0 com.android.launcher/"
                + "com.android.launcher2.Launcher}'",
                "  TouchStates: <no displays touched>"
                ));
        replayMocks();
        assertFalse(mTestDevice.isDeviceInputReady());
    }

    public void testIsDeviceInputReady_NotSupported() throws Exception {
        injectShellResponse("dumpsys input", ArrayUtil.join("\r\n",
                "foo",
                "bar",
                "foobar",
                "barfoo"
                ));
        replayMocks();
        assertNull(mTestDevice.isDeviceInputReady());
    }

    private static String getDumpsysInputHeader() {
        return ArrayUtil.join("\r\n",
                "INPUT MANAGER (dumpsys input)",
                "",
                "Event Hub State:",
                "  BuiltInKeyboardId: -2",
                "  Devices:",
                "    -1: Virtual",
                "      Classes: 0x40000023",
                "Input Dispatcher State:"
                );
    }

    /**
     * Simple test for {@link TestDevice#handleAllocationEvent(DeviceEvent)}
     */
    public void testHandleAllocationEvent() {
        EasyMock.expect(mMockIDevice.getSerialNumber()).andStubReturn(MOCK_DEVICE_SERIAL);
        EasyMock.replay(mMockIDevice);

        assertEquals(DeviceAllocationState.Unknown, mTestDevice.getAllocationState());

        assertNotNull(mTestDevice.handleAllocationEvent(DeviceEvent.CONNECTED_ONLINE));
        assertEquals(DeviceAllocationState.Checking_Availability, mTestDevice.getAllocationState());

        assertNotNull(mTestDevice.handleAllocationEvent(DeviceEvent.AVAILABLE_CHECK_PASSED));
        assertEquals(DeviceAllocationState.Available, mTestDevice.getAllocationState());

        assertNotNull(mTestDevice.handleAllocationEvent(DeviceEvent.ALLOCATE_REQUEST));
        assertEquals(DeviceAllocationState.Allocated, mTestDevice.getAllocationState());

        assertNotNull(mTestDevice.handleAllocationEvent(DeviceEvent.FREE_AVAILABLE));
        assertEquals(DeviceAllocationState.Available, mTestDevice.getAllocationState());

        assertNotNull(mTestDevice.handleAllocationEvent(DeviceEvent.DISCONNECTED));
        assertEquals(DeviceAllocationState.Unknown, mTestDevice.getAllocationState());

        assertNotNull(mTestDevice.handleAllocationEvent(DeviceEvent.FORCE_ALLOCATE_REQUEST));
        assertEquals(DeviceAllocationState.Allocated, mTestDevice.getAllocationState());

        assertNotNull(mTestDevice.handleAllocationEvent(DeviceEvent.FREE_UNKNOWN));
        assertEquals(DeviceAllocationState.Unknown, mTestDevice.getAllocationState());
    }

    /**
     * Test that a single user is handled by {@link TestDevice#listUsers()}.
     */
    public void testListUsers_oneUser() throws Exception {
        final String listUsersCommand = "pm list users";
        injectShellResponse(listUsersCommand, ArrayUtil.join("\r\n",
                "Users:",
                "UserInfo{0:Foo:13} running"));
        replayMocks();
        ArrayList<Integer> actual = mTestDevice.listUsers();
        assertNotNull(actual);
        assertEquals(1, actual.size());
        assertEquals(0, actual.get(0).intValue());
    }

    /**
     * Test that invalid output is handled by {@link TestDevice#listUsers()}.
     */
    public void testListUsers_invalidOutput() throws Exception {
        final String listUsersCommand = "pm list users";
        injectShellResponse(listUsersCommand, "not really what we are looking for");
        replayMocks();
        ArrayList<Integer> actual = mTestDevice.listUsers();
        assertNull(actual);
    }

    /**
     * Test that multiple user is handled by {@link TestDevice#listUsers()}.
     */
    public void testListUsers_multiUsers() throws Exception {
        final String listUsersCommand = "pm list users";
        injectShellResponse(listUsersCommand, ArrayUtil.join("\r\n",
                "Users:",
                "UserInfo{0:Foo:13} running",
                "UserInfo{3:FooBar:14}"));
        replayMocks();
        ArrayList<Integer> actual = mTestDevice.listUsers();
        assertNotNull(actual);
        assertEquals(2, actual.size());
        assertEquals(0, actual.get(0).intValue());
        assertEquals(3, actual.get(1).intValue());
    }

    /**
     * Test that multi user output is handled by {@link TestDevice#getMaxNumberOfUsersSupported()}.
     */
    public void testMaxNumberOfUsersSupported() throws Exception {
        final String getMaxUsersCommand = "pm get-max-users";
        injectShellResponse(getMaxUsersCommand, "Maximum supported users: 4");
        replayMocks();
        assertEquals(4, mTestDevice.getMaxNumberOfUsersSupported());
    }

    /**
     * Test that invalid output is handled by {@link TestDevice#getMaxNumberOfUsersSupported()}.
     */
    public void testMaxNumberOfUsersSupported_invalid() throws Exception {
        final String getMaxUsersCommand = "pm get-max-users";
        injectShellResponse(getMaxUsersCommand, "not the output we expect");
        replayMocks();
        assertEquals(0, mTestDevice.getMaxNumberOfUsersSupported());
    }

    /**
     * Test that single user output is handled by {@link TestDevice#getMaxNumberOfUsersSupported()}.
     */
    public void testIsMultiUserSupported_singleUser() throws Exception {
        final String getMaxUsersCommand = "pm get-max-users";
        injectShellResponse(getMaxUsersCommand, "Maximum supported users: 1");
        replayMocks();
        assertFalse(mTestDevice.isMultiUserSupported());
    }

    /**
     * Test that {@link TestDevice#isMultiUserSupported()} works.
     */
    public void testIsMultiUserSupported() throws Exception {
        final String getMaxUsersCommand = "pm get-max-users";
        injectShellResponse(getMaxUsersCommand, "Maximum supported users: 4");
        replayMocks();
        assertTrue(mTestDevice.isMultiUserSupported());
    }

    /**
     * Test that invalid output is handled by {@link TestDevice#isMultiUserSupported()}.
     */
    public void testIsMultiUserSupported_invalidOutput() throws Exception {
        final String getMaxUsersCommand = "pm get-max-users";
        injectShellResponse(getMaxUsersCommand, "not the output we expect");
        replayMocks();
        assertFalse(mTestDevice.isMultiUserSupported());
    }

    /**
     * Test that successful user creation is handled by {@link TestDevice#createUser(String)}.
     */
    public void testCreateUser() throws Exception {
        final String createUserCommand = "pm create-user foo";
        injectShellResponse(createUserCommand, "Success: created user id 10");
        replayMocks();
        assertEquals(10, mTestDevice.createUser("foo"));
    }

    /**
     * Test that successful user creation is handled by
     * {@link TestDevice#createUser(String, boolean, boolean)}.
     */
    public void testCreateUserFlags() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Success: created user id 12";
            }
        };
        assertEquals(12, mTestDevice.createUser("TEST", true, true));
    }

    /**
     * Test that {@link TestDevice#createUser(String, boolean, boolean)} fails when bad output
     */
    public void testCreateUser_wrongOutput() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Success: created user id WRONG";
            }
        };
        try {
            mTestDevice.createUser("TEST", true, true);
        } catch (IllegalStateException e) {
            // expected
            return;
        }
        fail("CreateUser should have thrown an exception");
    }

    /**
     * Test that a failure to create a user is handled by {@link TestDevice#createUser(String)}.
     */
    public void testCreateUser_failed() throws Exception {
        final String createUserCommand = "pm create-user foo";
        injectShellResponse(createUserCommand, "Error");
        replayMocks();
        try {
            mTestDevice.createUser("foo");
            fail("IllegalStateException not thrown");
        } catch (IllegalStateException e) {
            // Expected
        }
    }

    /**
     * Test that successful user removal is handled by {@link TestDevice#removeUser(int)}.
     */
    public void testRemoveUser() throws Exception {
        final String removeUserCommand = "pm remove-user 10";
        injectShellResponse(removeUserCommand, "Success: removed user\n");
        replayMocks();
        assertTrue(mTestDevice.removeUser(10));
    }

    /**
     * Test that a failure to remove a user is handled by {@link TestDevice#removeUser(int)}.
     */
    public void testRemoveUser_failed() throws Exception {
        final String removeUserCommand = "pm remove-user 10";
        injectShellResponse(removeUserCommand, "Error: couldn't remove user id 10");
        replayMocks();
        assertFalse(mTestDevice.removeUser(10));
    }

    /**
     * Test that trying to run a test with a user with
     * {@link TestDevice#runInstrumentationTestsAsUser(IRemoteAndroidTestRunner, int, Collection)}
     * fails if the {@link IRemoteAndroidTestRunner} is not an instance of
     * {@link RemoteAndroidTestRunner}.
     */
    public void testrunInstrumentationTestsAsUser_failed() throws Exception {
        IRemoteAndroidTestRunner mockRunner = EasyMock.createMock(IRemoteAndroidTestRunner.class);
        EasyMock.expect(mockRunner.getPackageName()).andStubReturn("com.example");
        Collection<ITestRunListener> listeners = new ArrayList<ITestRunListener>();
        EasyMock.replay(mockRunner);
        try {
            mTestDevice.runInstrumentationTestsAsUser(mockRunner, 12, listeners);
            fail("IllegalStateException not thrown.");
        } catch (IllegalStateException e) {
            //expected
        }
    }

     /**
     * Test that successful user start is handled by {@link TestDevice#startUser(int)}.
     */
    public void testStartUser() throws Exception {
        final String startUserCommand = "am start-user 10";
        injectShellResponse(startUserCommand, "Success: user started\n");
        replayMocks();
        assertTrue(mTestDevice.startUser(10));
    }

    /**
     * Test that a failure to start user is handled by {@link TestDevice#startUser(int)}.
     */
    public void testStartUser_failed() throws Exception {
        final String startUserCommand = "am start-user 10";
        injectShellResponse(startUserCommand, "Error: could not start user\n");
        replayMocks();
        assertFalse(mTestDevice.startUser(10));
    }

    /**
     * Test that remount works as expected on a device not supporting dm verity
     * @throws Exception
     */
    public void testRemount_verityUnsupported() throws Exception {
        injectSystemProperty("partition.system.verified", "");
        setExecuteAdbCommandExpectations(new CommandResult(CommandStatus.SUCCESS), "remount");
        EasyMock.expect(mMockStateMonitor.waitForDeviceAvailable()).andReturn(mMockIDevice);
        replayMocks();
        mTestDevice.remountSystemWritable();
        verifyMocks();
    }

    /**
     * Test that remount works as expected on a device supporting dm verity v1
     * @throws Exception
     */
    public void testRemount_veritySupportedV1() throws Exception {
        injectSystemProperty("partition.system.verified", "1");
        setExecuteAdbCommandExpectations(
                new CommandResult(CommandStatus.SUCCESS), "disable-verity");
        setRebootExpectations();
        setExecuteAdbCommandExpectations(new CommandResult(CommandStatus.SUCCESS), "remount");
        EasyMock.expect(mMockStateMonitor.waitForDeviceAvailable()).andReturn(mMockIDevice);
        replayMocks();
        mTestDevice.remountSystemWritable();
        verifyMocks();
    }

    /**
     * Test that remount works as expected on a device supporting dm verity v2
     * @throws Exception
     */
    public void testRemount_veritySupportedV2() throws Exception {
        injectSystemProperty("partition.system.verified", "2");
        setExecuteAdbCommandExpectations(
                new CommandResult(CommandStatus.SUCCESS), "disable-verity");
        setRebootExpectations();
        setExecuteAdbCommandExpectations(new CommandResult(CommandStatus.SUCCESS), "remount");
        EasyMock.expect(mMockStateMonitor.waitForDeviceAvailable()).andReturn(mMockIDevice);
        replayMocks();
        mTestDevice.remountSystemWritable();
        verifyMocks();
    }

    /**
     * Test that remount works as expected on a device supporting dm verity but with unknown version
     * @throws Exception
     */
    public void testRemount_veritySupportedNonNumerical() throws Exception {
        injectSystemProperty("partition.system.verified", "foo");
        setExecuteAdbCommandExpectations(
                new CommandResult(CommandStatus.SUCCESS), "disable-verity");
        setRebootExpectations();
        setExecuteAdbCommandExpectations(new CommandResult(CommandStatus.SUCCESS), "remount");
        EasyMock.expect(mMockStateMonitor.waitForDeviceAvailable()).andReturn(mMockIDevice);
        replayMocks();
        mTestDevice.remountSystemWritable();
        verifyMocks();
    }

    /**
     * Test that {@link TestDevice#getBuildSigningKeys()} works for the typical "test-keys" case
     * @throws Exception
     */
    public void testGetBuildSigningKeys_test_keys() throws Exception {
        injectSystemProperty(TestDevice.BUILD_TAGS, "test-keys");
        replayMocks();
        assertEquals("test-keys", mTestDevice.getBuildSigningKeys());
    }

    /**
     * Test that {@link TestDevice#getBuildSigningKeys()} works for the case where build tags is a
     * comma separated list
     * @throws Exception
     */
    public void testGetBuildSigningKeys_test_keys_commas() throws Exception {
        injectSystemProperty(TestDevice.BUILD_TAGS, "test-keys,foo,bar,yadda");
        replayMocks();
        assertEquals("test-keys", mTestDevice.getBuildSigningKeys());
    }

    /**
     * Test that {@link TestDevice#getBuildSigningKeys()} returns null for non-matching case
     * @throws Exception
     */
    public void testGetBuildSigningKeys_not_matched() throws Exception {
        injectSystemProperty(TestDevice.BUILD_TAGS, "huh,foo,bar,yadda");
        replayMocks();
        assertNull(mTestDevice.getBuildSigningKeys());
    }

    /**
     * Test that {@link TestDevice#getCurrentUser()} returns the current user id.
     * @throws Exception
     */
    public void testGetCurrentUser() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "3\n";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "N\n";
            }
        };
        int res = mTestDevice.getCurrentUser();
        assertEquals(3, res);
    }

    /**
     * Test that {@link TestDevice#getCurrentUser()} returns null when output is not expected
     * @throws Exception
     */
    public void testGetCurrentUser_null() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "not found.";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "N\n";
            }
        };
        int res = mTestDevice.getCurrentUser();
        assertEquals(NativeDevice.INVALID_USER_ID, res);
    }

    /**
     * Test that {@link TestDevice#getCurrentUser()} returns null when api level is too low
     * @throws Exception
     */
    public void testGetCurrentUser_lowApi() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 15;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "REL\n";
            }
        };
        try {
            mTestDevice.getCurrentUser();
        } catch (IllegalArgumentException e) {
            // expected
            return;
        }
        fail("getCurrentUser should have thrown an exception.");
    }

    /**
     * Unit test for {@link TestDevice#getUserFlags(int)}.
     */
    public void testGetUserFlag() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Users:\n\tUserInfo{0:Owner:13} running";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        int flags = mTestDevice.getUserFlags(0);
        // Expected 19 because using radix 16 (so 13 becomes (1 * 16^1 + 3 * 16^0) = 19)
        assertEquals(19, flags);
    }

    /**
     * Unit test for {@link TestDevice#getUserFlags(int)} when command return empty list
     * of users.
     */
    public void testGetUserFlag_emptyReturn() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        int flags = mTestDevice.getUserFlags(2);
        assertEquals(NativeDevice.INVALID_USER_ID, flags);
    }

    /**
     * Unit test for {@link TestDevice#getUserFlags(int)} when there is multiple users in
     * the list.
     */
    public void testGetUserFlag_multiUser() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Users:\n\tUserInfo{0:Owner:13}\n\tUserInfo{WRONG:Owner:14}\n\t"
                        + "UserInfo{}\n\tUserInfo{3:Owner:15} Running";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        int flags = mTestDevice.getUserFlags(3);
        assertEquals(21, flags);
    }

    /**
     * Unit test for {@link TestDevice#getUserSerialNumber(int)}
     */
    public void testGetUserSerialNumber() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Users:\nUserInfo{0:Owner:13} serialNo=666";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        int serial = mTestDevice.getUserSerialNumber(0);
        assertEquals(666, serial);
    }

    /**
     * Unit test for {@link TestDevice#getUserSerialNumber(int)} when the dumpsys return some
     * bad data.
     */
    public void testGetUserSerialNumber_badData() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Users:\nUserInfo{0:Owner:13} serialNo=WRONG";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        int serial = mTestDevice.getUserSerialNumber(0);
        assertEquals(NativeDevice.INVALID_USER_ID, serial);
    }

    /**
     * Unit test for {@link TestDevice#getUserSerialNumber(int)} when the dumpsys return an empty
     * serial
     */
    public void testGetUserSerialNumber_emptySerial() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Users:\nUserInfo{0:Owner:13} serialNo=";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        int serial = mTestDevice.getUserSerialNumber(0);
        assertEquals(NativeDevice.INVALID_USER_ID, serial);
    }

    /**
     * Unit test for {@link TestDevice#getUserSerialNumber(int)} when there is multiple users in
     * the dumpsys
     */
    public void testGetUserSerialNumber_multiUsers() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Users:\nUserInfo{0:Owner:13} serialNo=1\nUserInfo{1:Owner:13} serialNo=2"
                        + "\nUserInfo{2:Owner:13} serialNo=3";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        int serial = mTestDevice.getUserSerialNumber(2);
        assertEquals(3, serial);
    }

    /**
     * Unit test for {@link TestDevice#switchUser(int)} when user requested is already is current
     * user.
     */
    public void testSwitchUser_alreadySameUser() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public int getCurrentUser() throws DeviceNotAvailableException {
                return 0;
            }
            @Override
            public void prePostBootSetup() {
                // skip for this test
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "N\n";
            }
        };
        assertTrue(mTestDevice.switchUser(0));
    }

    /**
     * Unit test for {@link TestDevice#switchUser(int)} when user switch instantly.
     */
    public void testSwitchUser() throws Exception {
        mTestDevice = new TestableTestDevice() {
            int ret = 0;
            @Override
            public int getCurrentUser() throws DeviceNotAvailableException {
                return ret;
            }
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                ret = 10;
                return "";
            }
            @Override
            public void prePostBootSetup() {
                // skip for this test
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "N\n";
            }
        };
        assertTrue(mTestDevice.switchUser(10));
    }

    /**
     * Unit test for {@link TestDevice#switchUser(int)} when user switch with a short delay.
     */
    public void testSwitchUser_delay() throws Exception {
        mTestDevice = new TestableTestDevice() {
            int ret = 0;
            @Override
            public int getCurrentUser() throws DeviceNotAvailableException {
                return ret;
            }
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                test.start();
                return "";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "N\n";
            }
            @Override
            public void prePostBootSetup() {
                // skip for this test
            }
            @Override
            protected long getCheckNewUserSleep() {
                return 100;
            }
            Thread test = new Thread(new Runnable() {
                @Override
                public void run() {
                    RunUtil.getDefault().sleep(100);
                    ret = 10;
                }
            });
        };
        assertTrue(mTestDevice.switchUser(10));
    }

    /**
     * Unit test for {@link TestDevice#switchUser(int)} when user never change.
     */
    public void testSwitchUser_noChange() throws Exception {
        mTestDevice = new TestableTestDevice() {
            int ret = 0;
            @Override
            public int getCurrentUser() throws DeviceNotAvailableException {
                return ret;
            }
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                ret = 0;
                return "";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "N\n";
            }
            @Override
            protected long getCheckNewUserSleep() {
                return 50;
            }
            @Override
            public void prePostBootSetup() {
                // skip for this test
            }
        };
        assertFalse(mTestDevice.switchUser(10, 100));
    }

    /**
     * Unit test for {@link TestDevice#stopUser(int)}, cannot stop current user.
     */
    public void testStopUser_notCurrent() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public int getCurrentUser() throws DeviceNotAvailableException {
                return 0;
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "N\n";
            }
        };
        assertFalse(mTestDevice.stopUser(0));
    }

    /**
     * Unit test for {@link TestDevice#stopUser(int)}, cannot stop system
     */
    public void testStopUser_notSystem() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Error: Can't stop system user 0";
            }
            @Override
            public int getCurrentUser() throws DeviceNotAvailableException {
                return 10;
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "N\n";
            }
        };
        assertFalse(mTestDevice.stopUser(0));
    }

    /**
     * Unit test for {@link TestDevice#stopUser(int, boolean, boolean)}, for a success stop
     */
    public void testStopUser_success() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                if (command.contains("am")) {
                    assertEquals("am stop-user -w -f 0", command);
                } else if (command.contains("pm")) {
                    assertEquals("pm list users", command);
                } else {
                    fail("Unexpected command");
                }
                return "Users:\n\tUserInfo{0:Test:13}";
            }
            @Override
            public int getCurrentUser() throws DeviceNotAvailableException {
                return 10;
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "N\n";
            }
        };
        assertTrue(mTestDevice.stopUser(0, true, true));
    }

    /**
     * Unit test for {@link TestDevice#stopUser(int)}, for a failed stop
     */
    public void testStopUser_failed() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                if (command.contains("am")) {
                    assertEquals("am stop-user 0", command);
                } else if (command.contains("pm")) {
                    assertEquals("pm list users", command);
                } else {
                    fail("Unexpected command");
                }
                return "Users:\n\tUserInfo{0:Test:13} running";
            }
            @Override
            public int getCurrentUser() throws DeviceNotAvailableException {
                return 10;
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
            @Override
            public String getProperty(String name) throws DeviceNotAvailableException {
                return "N\n";
            }
        };
        assertFalse(mTestDevice.stopUser(0));
    }

    /**
     * Unit test for {@link TestDevice#isUserRunning(int)}.
     */
    public void testIsUserIdRunning_true() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Users:\n\tUserInfo{0:Test:13} running";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return MIN_API_LEVEL_GET_CURRENT_USER;
            }
        };
        assertTrue(mTestDevice.isUserRunning(0));
    }

    /**
     * Unit test for {@link TestDevice#isUserRunning(int)}.
     */
    public void testIsUserIdRunning_false() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Users:\n\tUserInfo{0:Test:13} running\n\tUserInfo{10:New user:10}";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        assertFalse(mTestDevice.isUserRunning(10));
    }

    /**
     * Unit test for {@link TestDevice#isUserRunning(int)}.
     */
    public void testIsUserIdRunning_badFormat() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Users:\n\tUserInfo{WRONG:Test:13} running";
            }
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        assertFalse(mTestDevice.isUserRunning(0));
    }

    /**
     * Unit test for {@link TestDevice#hasFeature(String)} on success.
     */
    public void testHasFeature_true() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "feature:com.google.android.feature.EXCHANGE_6_2\n" +
                        "feature:com.google.android.feature.GOOGLE_BUILD\n" +
                        "feature:com.google.android.feature.GOOGLE_EXPERIENCE";
            }
        };
        assertTrue(mTestDevice.hasFeature("com.google.android.feature.EXCHANGE_6_2"));
    }

    /**
     * Unit test for {@link TestDevice#hasFeature(String)} on failure.
     */
    public void testHasFeature_fail() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "feature:com.google.android.feature.EXCHANGE_6_2\n" +
                        "feature:com.google.android.feature.GOOGLE_BUILD\n" +
                        "feature:com.google.android.feature.GOOGLE_EXPERIENCE";
            }
        };
        assertFalse(mTestDevice.hasFeature("feature:test"));
    }

    /**
     * Unit test for {@link TestDevice#getSetting(int, String, String)}.
     */
    public void testGetSetting() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "78";
            }
        };
        assertEquals("78", mTestDevice.getSetting(0, "system", "screen_brightness"));
    }

    /**
     * Unit test for {@link TestDevice#getSetting(String, String)}.
     */
    public void testGetSetting_SystemUser() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "78";
            }
        };
        assertEquals("78", mTestDevice.getSetting("system", "screen_brightness"));
    }

    /**
     * Unit test for {@link TestDevice#getSetting(int, String, String)}.
     */
    public void testGetSetting_nulloutput() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "null";
            }
        };
        assertNull(mTestDevice.getSetting(0, "system", "screen_brightness"));
    }

    /**
     * Unit test for {@link TestDevice#getSetting(int, String, String)} with a namespace
     * that is not in {global, system, secure}.
     */
    public void testGetSetting_unexpectedNamespace() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        assertNull(mTestDevice.getSetting(0, "TEST", "screen_brightness"));
    }

    /**
     * Unit test for {@link TestDevice#setSetting(int, String, String, String)}
     * with a namespace that is not in {global, system, secure}.
     */
    public void testSetSetting_unexpectedNamespace() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        try {
            mTestDevice.setSetting(0, "TEST", "screen_brightness", "75");
        } catch (IllegalArgumentException e) {
            // expected
            return;
        }
        fail("putSettings should have thrown an exception.");
    }

    /**
     * Unit test for {@link TestDevice#setSetting(int, String, String, String)}
     * with a normal case.
     */
    public void testSetSettings() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        try {
            mTestDevice.setSetting(0, "system", "screen_brightness", "75");
        } catch (IllegalArgumentException e) {
            fail("putSettings should not have thrown an exception.");
        }
    }

    /**
     * Unit test for {@link TestDevice#setSetting(String, String, String)}
     * with a normal case.
     */
    public void testSetSettings_SystemUser() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 22;
            }
        };
        try {
            mTestDevice.setSetting("system", "screen_brightness", "75");
        } catch (IllegalArgumentException e) {
            fail("putSettings should not have thrown an exception.");
        }
    }

    /**
     * Unit test for {@link TestDevice#setSetting(int, String, String, String)}
     * when API level is too low
     */
    public void testSetSettings_lowApi() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public int getApiLevel() throws DeviceNotAvailableException {
                return 21;
            }
        };
        try {
            mTestDevice.setSetting(0, "system", "screen_brightness", "75");
        } catch (IllegalArgumentException e) {
            // expected
            return;
        }
        fail("putSettings should have thrown an exception.");
    }

    /**
     * Unit test for {@link TestDevice#getAndroidId(int)}.
     */
    public void testGetAndroidId() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "4433829313704884235";
            }
            @Override
            public boolean isAdbRoot() throws DeviceNotAvailableException {
                return true;
            }
        };
        assertEquals("4433829313704884235", mTestDevice.getAndroidId(0));
    }

    /**
     * Unit test for {@link TestDevice#getAndroidId(int)} when db containing the id is not found
     */
    public void testGetAndroidId_notFound() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public String executeShellCommand(String command) throws DeviceNotAvailableException {
                return "Error: unable to open database"
                        + "\"/data/0/com.google.android.gsf/databases/gservices.db\": "
                        + "unable to open database file";
            }
            @Override
            public boolean isAdbRoot() throws DeviceNotAvailableException {
                return true;
            }
        };
        assertNull(mTestDevice.getAndroidId(0));
    }

    /**
     * Unit test for {@link TestDevice#getAndroidId(int)} when adb root not enabled.
     */
    public void testGetAndroidId_notRoot() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public boolean isAdbRoot() throws DeviceNotAvailableException {
                return false;
            }
        };
        assertNull(mTestDevice.getAndroidId(0));
    }

    /**
     * Unit test for {@link TestDevice#getAndroidIds()}
     */
    public void testGetAndroidIds() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public ArrayList<Integer> listUsers() throws DeviceNotAvailableException {
                ArrayList<Integer> test = new ArrayList<Integer>();
                test.add(0);
                test.add(1);
                return test;
            }
            @Override
            public String getAndroidId(int userId) throws DeviceNotAvailableException {
                return "44444";
            }
        };
        Map<Integer, String> expected = new HashMap<Integer, String>();
        expected.put(0, "44444");
        expected.put(1, "44444");
        assertEquals(expected, mTestDevice.getAndroidIds());
    }

    /**
     * Unit test for {@link TestDevice#getAndroidIds()} when no user are found.
     */
    public void testGetAndroidIds_noUser() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public ArrayList<Integer> listUsers() throws DeviceNotAvailableException {
                return null;
            }
        };
        assertNull(mTestDevice.getAndroidIds());
    }

    /**
     * Unit test for {@link TestDevice#getAndroidIds()} when no match is found for user ids.
     */
    public void testGetAndroidIds_noMatch() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            public ArrayList<Integer> listUsers() throws DeviceNotAvailableException {
                ArrayList<Integer> test = new ArrayList<Integer>();
                test.add(0);
                test.add(1);
                return test;
            }
            @Override
            public String getAndroidId(int userId) throws DeviceNotAvailableException {
                return null;
            }
        };
        Map<Integer, String> expected = new HashMap<Integer, String>();
        expected.put(0, null);
        expected.put(1, null);
        assertEquals(expected, mTestDevice.getAndroidIds());
    }

    /**
     * Test for {@link TestDevice#getScreenshot()} when action failed.
     */
    public void testGetScreenshot_failure() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            protected boolean performDeviceAction(
                    String actionDescription, DeviceAction action, int retryAttempts)
                    throws DeviceNotAvailableException {
                return false;
            }
        };
        assertNull(mTestDevice.getScreenshot());
    }

    /**
     * Test for {@link TestDevice#getScreenshot()} when action succeed.
     */
    public void testGetScreenshot() throws Exception {
        mTestDevice = new TestableTestDevice() {
            @Override
            protected boolean performDeviceAction(
                    String actionDescription, DeviceAction action, int retryAttempts)
                    throws DeviceNotAvailableException {
                return true;
            }
            @Override
            public byte[] compressRawImage(RawImage rawImage, String format) {
                return "image".getBytes();
            }
        };
        InputStreamSource data = mTestDevice.getScreenshot();
        assertNotNull(data);
        assertTrue(data instanceof ByteArrayInputStreamSource);
    }

    /**
     * Helper to retrieve the test file
     */
    private File getTestImageResource() throws Exception {
        InputStream imageZip = getClass().getResourceAsStream(RAWIMAGE_RESOURCE);
        File imageZipFile = FileUtil.createTempFile("rawImage", ".zip");
        try {
            FileUtil.writeToFile(imageZip, imageZipFile);
            File dir = ZipUtil2.extractZipToTemp(imageZipFile, "test-raw-image");
            return new File(dir, "rawImageScreenshot.raw");
        } finally {
            FileUtil.deleteFile(imageZipFile);
        }
    }

    /**
     * Helper to create the rawImage to test.
     */
    private RawImage prepareRawImage(File rawImageFile) throws Exception {
        RawImage sRawImage = null;
        String data = FileUtil.readStringFromFile(rawImageFile);
        sRawImage = new RawImage();
        sRawImage.alpha_length = 8;
        sRawImage.alpha_offset = 24;
        sRawImage.blue_length = 8;
        sRawImage.blue_offset = 16;
        sRawImage.bpp = 32;
        sRawImage.green_length = 8;
        sRawImage.green_offset = 8;
        sRawImage.height = 1920;
        sRawImage.red_length = 8;
        sRawImage.red_offset = 0;
        sRawImage.size = 8294400;
        sRawImage.version = 1;
        sRawImage.width = 1080;
        sRawImage.data = data.getBytes();
        return sRawImage;
    }

    /**
     * Test for {@link TestDevice#compressRawImage(RawImage, String)} properly reduce the image
     * size with different encoding.
     */
    public void testCompressScreenshot() throws Exception {
        File testImageFile = getTestImageResource();
        RawImage testImage = prepareRawImage(testImageFile);
        try {
            // Size of the raw test data
            Assert.assertEquals(12441600, testImage.data.length);
            byte[] result = mTestDevice.compressRawImage(testImage, "PNG");
            // Size after compressing
            Assert.assertEquals(4082, result.length);

            // Do it again with JPEG encoding
            Assert.assertEquals(12441600, testImage.data.length);
            result = mTestDevice.compressRawImage(testImage, "JPEG");
            // Size after compressing as JPEG
            Assert.assertEquals(119998, result.length);
        } finally {
            FileUtil.recursiveDelete(testImageFile.getParentFile());
        }
    }
}