This file is indexed.

/usr/lib/python2.7/dist-packages/linaro_image_tools/media_create/tests/test_media_create.py is in python-linaro-image-tools 2016.05-1.1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
# Copyright (C) 2010, 2011 Linaro
#
# Author: Guilherme Salgado <guilherme.salgado@linaro.org>
#
# This file is part of Linaro Image Tools.
#
# Linaro Image Tools is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Linaro Image Tools is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import atexit
import glob
import os
import random
import string
import subprocess
import sys
import tempfile
import textwrap
import time
import types
import struct
import tarfile
import dbus
import shutil

from mock import MagicMock
from StringIO import StringIO
from testtools import TestCase

from linaro_image_tools import cmd_runner
from linaro_image_tools.hwpack.handler import HardwarepackHandler
from linaro_image_tools.hwpack.packages import PackageMaker
import linaro_image_tools.media_create
from linaro_image_tools.media_create import (
    android_boards,
    boards,
    check_device,
    partitions,
    rootfs,
)
from linaro_image_tools.media_create.boards import (
    SECTOR_SIZE,
    align_up,
    align_partition,
    get_plain_boot_script_contents,
    make_flashable_env,
    install_mx5_boot_loader,
    install_omap_boot_loader,
    make_boot_script,
    make_uImage,
    make_uInitrd,
    make_dtb,
    _get_file_matching,
    _get_mlo_file,
    _run_mkimage,
    BoardConfig,
    get_board_config,
)
from linaro_image_tools.media_create.android_boards import (
    AndroidSnowballEmmcConfig,
)
from linaro_image_tools.media_create.chroot_utils import (
    copy_file,
    install_hwpack,
    install_hwpacks,
    install_packages,
    mount_chroot_proc,
    prepare_chroot,
    run_local_atexit_funcs,
    temporarily_overwrite_file_on_dir,
)
from linaro_image_tools.media_create.partitions import (
    MIN_IMAGE_SIZE,
    Media,
    _check_min_size,
    _get_device_file_for_partition_number,
    _parse_blkid_output,
    calculate_android_partition_size_and_offset,
    calculate_partition_size_and_offset,
    create_partitions,
    ensure_partition_is_not_mounted,
    get_android_loopback_devices,
    get_boot_and_root_loopback_devices,
    get_boot_and_root_partitions_for_media,
    get_partition_size_in_bytes,
    get_uuid,
    partition_mounted,
    run_sfdisk_commands,
    setup_partitions,
    wait_partition_to_settle,
)
from linaro_image_tools.media_create.rootfs import (
    append_to_fstab,
    create_flash_kernel_config,
    has_space_left_for_swap,
    move_contents,
    populate_rootfs,
    rootfs_mount_options,
    update_network_interfaces,
    write_data_to_protected_file,
)
from linaro_image_tools.media_create.tests.fixtures import (
    CreateTarballFixture,
    MockRunSfdiskCommandsFixture,
)
from linaro_image_tools.media_create.unpack_binary_tarball import (
    unpack_binary_tarball,
)
from linaro_image_tools.testing import TestCaseWithFixtures
from linaro_image_tools.tests.fixtures import (
    CreateTempDirFixture,
    MockCmdRunnerPopenFixture,
    MockSomethingFixture,
)
from linaro_image_tools.utils import find_command, preferred_tools_dir

from linaro_image_tools.hwpack.testing import ContextManagerFixture

chroot_args = " ".join(cmd_runner.CHROOT_ARGS)
sudo_args = " ".join(cmd_runner.SUDO_ARGS)


class TestHardwarepackHandler(TestCaseWithFixtures):
    def setUp(self):
        super(TestHardwarepackHandler, self).setUp()
        self.tar_dir_fixture = CreateTempDirFixture()
        self.useFixture(self.tar_dir_fixture)

        self.tarball_fixture = CreateTarballFixture(
            self.tar_dir_fixture.get_temp_dir())
        self.useFixture(self.tarball_fixture)

        self.metadata = (
            "NAME=ahwpack\nVERSION=4\nARCHITECTURE=armel\nORIGIN=linaro\n")

    def test_hardwarepack_bootloaders(self):
        metadata = ("format: 3.0\nname: ahwpack\nversion: 4\narchitecture: "
                    "armel\norigin: linaro\n")
        metadata += ("bootloaders:\n u_boot:\n  file: a_file\n uefi:\n  file: "
                     "b_file\n")
        data = '3.0'
        format = "%s\n" % data
        tarball = self.add_to_tarball(
            [('FORMAT', format), ('metadata', metadata)])
        hp = HardwarepackHandler([tarball], bootloader='u_boot')
        with hp:
            self.assertEquals(hp.get_field('bootloader_file')[0], 'a_file')

    def test_hardwarepack_boards(self):
        metadata = ("format: 3.0\nname: ahwpack\nversion: 4\narchitecture: "
                    "armel\norigin: linaro\n")
        metadata += ("bootloaders:\n u_boot:\n  file: a_file\n uefi:\n  file: "
                     "b_file\n")
        metadata += ("boards:\n panda:\n  bootloaders:\n   u_boot:\n    "
                     "file: panda_file")
        data = '3.0'
        format = "%s\n" % data
        tarball = self.add_to_tarball(
            [('FORMAT', format), ('metadata', metadata)])
        hp = HardwarepackHandler([tarball], board='panda')
        with hp:
            self.assertEquals(hp.get_field('bootloader_file')[0], 'panda_file')

    def test_hardwarepack_boards_and_bootloaders(self):
        metadata = ("format: 3.0\nname: ahwpack\nversion: 4\narchitecture: "
                    "armel\norigin: linaro\n")
        metadata += ("bootloaders:\n u_boot:\n  file: a_file\n uefi:\n  file: "
                     "b_file\n")
        metadata += ("boards:\n panda:\n  bootloaders:\n   u_boot:\n    "
                     "file: panda_file\n   uefi:\n    file: "
                     "uefi_panda_file\n")
        metadata += (" panda-lt:\n bootloaders:\n   u_boot:\n    "
                     "file: panda_lt_file")
        data = '3.0'
        format = "%s\n" % data
        tarball = self.add_to_tarball(
            [('FORMAT', format), ('metadata', metadata)])
        hp = HardwarepackHandler([tarball], board='panda', bootloader='uefi')
        with hp:
            self.assertEquals(hp.get_field('bootloader_file')[0],
                              'uefi_panda_file')

    def add_to_tarball(self, files, tarball=None):
        if tarball is None:
            tarball = self.tarball_fixture.get_tarball()
        tar_file = tarfile.open(tarball, mode='w:gz')
        for filename, data in files:
            tarinfo = tarfile.TarInfo(filename)
            tarinfo.size = len(data)
            tar_file.addfile(tarinfo, StringIO(data))
        tar_file.close()
        return tarball

    def test_get_format_1(self):
        data = HardwarepackHandler.FORMAT_1
        format = "%s\n" % data
        tarball = self.add_to_tarball(
            [('FORMAT', format), ('metadata', self.metadata)])
        hp = HardwarepackHandler([tarball])
        with hp:
            self.assertEquals(hp.get_format(), data)

    def test_get_format_2(self):
        data = '2.0'
        format = "%s\n" % data
        tarball = self.add_to_tarball(
            [('FORMAT', format), ('metadata', self.metadata)])
        hp = HardwarepackHandler([tarball])
        with hp:
            self.assertEquals(hp.get_format(), data)

    def test_get_unknown_format_raises(self):
        data = '9.9'
        format = "%s\n" % data
        tarball = self.add_to_tarball(
            [('FORMAT', format), ('metadata', self.metadata)])
        hp = HardwarepackHandler([tarball])
        with hp:
            self.assertRaises(AssertionError, hp.get_format)

    def test_mixed_formats(self):
        format1 = "%s\n" % HardwarepackHandler.FORMAT_1
        format2 = "%s\n" % HardwarepackHandler.FORMAT_2
        tarball1 = self.add_to_tarball(
            [('FORMAT', format1), ('metadata', self.metadata)],
            tarball=self.tarball_fixture.get_tarball())
        tarball_fixture2 = CreateTarballFixture(
            self.tar_dir_fixture.get_temp_dir(), reldir='tarfile2',
            filename='secondtarball.tar.gz')
        self.useFixture(tarball_fixture2)
        tarball2 = self.add_to_tarball(
            [('FORMAT', format2), ('metadata', self.metadata)],
            tarball=tarball_fixture2.get_tarball())
        hp = HardwarepackHandler([tarball2, tarball1])
        with hp:
            self.assertEquals(hp.get_format(), '1.0and2.0')

    def test_identical_formats_ok(self):
        format1 = "%s\n" % HardwarepackHandler.FORMAT_2
        format2 = "%s\n" % HardwarepackHandler.FORMAT_2
        tarball1 = self.add_to_tarball(
            [('FORMAT', format1), ('metadata', self.metadata)],
            tarball=self.tarball_fixture.get_tarball())
        tarball_fixture2 = CreateTarballFixture(
            self.tar_dir_fixture.get_temp_dir(), reldir='tarfile2',
            filename='secondtarball.tar.gz')
        self.useFixture(tarball_fixture2)
        tarball2 = self.add_to_tarball(
            [('FORMAT', format2), ('metadata', self.metadata)],
            tarball=tarball_fixture2.get_tarball())
        hp = HardwarepackHandler([tarball1, tarball2])
        with hp:
            self.assertEquals(hp.get_format(), '2.0')

    def test_get_metadata(self):
        data = 'data to test'
        metadata = self.metadata + "U_BOOT=%s\n" % data
        tarball = self.add_to_tarball(
            [('metadata', metadata)])
        hp = HardwarepackHandler([tarball])
        with hp:
            test_data, _ = hp.get_field('bootloader_file')
            self.assertEqual(test_data, data)

    def test_preserves_formatters(self):
        data = '%s%d'
        metadata = self.metadata + "U_BOOT=%s\n" % data
        tarball = self.add_to_tarball(
            [('metadata', metadata)])
        hp = HardwarepackHandler([tarball])
        with hp:
            test_data, _ = hp.get_field('bootloader_file')
            self.assertEqual(test_data, data)

    def test_creates_tempdir(self):
        tarball = self.add_to_tarball(
            [('metadata', self.metadata)])
        hp = HardwarepackHandler([tarball])
        with hp:
            self.assertTrue(os.path.exists(hp.tempdir))

    def test_tempfiles_are_removed(self):
        tempdir = None
        tarball = self.add_to_tarball(
            [('metadata', self.metadata)])
        hp = HardwarepackHandler([tarball])
        with hp:
            tempdir = hp.tempdir
        self.assertFalse(os.path.exists(tempdir))

    def test_get_file(self):
        data = 'test file contents\n'
        file_in_archive = 'testfile'
        metadata = self.metadata + "%s=%s\n" % ('U_BOOT', file_in_archive)
        tarball = self.add_to_tarball(
            [('metadata', metadata),
             (file_in_archive, data)])
        hp = HardwarepackHandler([tarball])
        with hp:
            test_file = hp.get_file('bootloader_file')
            self.assertEquals(data, open(test_file, 'r').read())

    def test_list_packages(self):
        metadata = ("format: 3.0\nname: ahwpack\nversion: 4\narchitecture: "
                    "armel\norigin: linaro\n")
        format = "3.0\n"
        tarball = self.add_to_tarball([
            ("FORMAT", format),
            ("metadata", metadata),
            ("pkgs/foo_1-1_all.deb", ''),
            ("pkgs/bar_1-1_all.deb", ''),
        ])

        hp = HardwarepackHandler([tarball], board='panda', bootloader='uefi')
        with hp:
            packages = hp.list_packages()
            names = [p[1] for p in packages]
            self.assertIn('pkgs/foo_1-1_all.deb', names)
            self.assertIn('pkgs/bar_1-1_all.deb', names)
            self.assertEqual(len(packages), 2)

    def test_find_package_for(self):
        metadata = ("format: 3.0\nname: ahwpack\nversion: 4\narchitecture: "
                    "armel\norigin: linaro\n")
        format = "3.0\n"
        tarball = self.add_to_tarball([
            ("FORMAT", format),
            ("metadata", metadata),
            ("pkgs/foo_1-3_all.deb", ''),
            ("pkgs/foo_2-5_arm.deb", ''),
            ("pkgs/bar_1-3_arm.deb", ''),
        ])

        hp = HardwarepackHandler([tarball], board='panda', bootloader='uefi')
        with hp:
            self.assertEqual(hp.find_package_for("foo")[1],
                             "pkgs/foo_1-3_all.deb")
            self.assertEqual(hp.find_package_for("bar")[1],
                             "pkgs/bar_1-3_arm.deb")
            self.assertEqual(hp.find_package_for("foo", version=2)[1],
                             "pkgs/foo_2-5_arm.deb")
            self.assertEqual(hp.find_package_for("foo", version=2,
                                                 revision=5)[1],
                             "pkgs/foo_2-5_arm.deb")
            self.assertEqual(hp.find_package_for("foo", version=2, revision=5,
                                                 architecture="arm")[1],
                             "pkgs/foo_2-5_arm.deb")
            self.assertEqual(hp.find_package_for("foo", architecture="arm")[1],
                             "pkgs/foo_2-5_arm.deb")
            self.assertEqual(hp.find_package_for("foo", architecture="all")[1],
                             "pkgs/foo_1-3_all.deb")

    def test_get_file_from_package(self):
        metadata = ("format: 3.0\nname: ahwpack\nversion: 4\narchitecture: "
                    "armel\norigin: linaro\n")
        format = "3.0\n"

        names = ['package0', 'package1', 'package2']
        files = {
            names[0]:
            ["usr/lib/u-boot/omap4_panda/u-boot.img",
             "usr/share/doc/u-boot-linaro-omap4-panda/copyright"],
            names[1]: ["usr/lib/u-boot/omap4_panda/u-boot2.img",
                       "foo/bar",
                       "flim/flam"],
            names[2]: ["some/path/config"]}

        # Generate some test packages
        maker = PackageMaker()
        self.useFixture(ContextManagerFixture(maker))

        tarball_content = [("FORMAT", format), ("metadata", metadata)]

        package_names = []
        for package_name in names:
            # The files parameter to make_package is a list of files to create.
            # These files are text files containing package_name and their
            # path. Since package_name is different for each package, this
            # gives each file a unique content.
            deb_file_path = maker.make_package(package_name, '1.0', {},
                                               files=files[package_name])
            name = os.path.basename(deb_file_path)
            tarball_content.append((os.path.join("pkgs", name),
                                    open(deb_file_path).read()))
            package_names.append(name)

        tarball = self.add_to_tarball(tarball_content)

        hp = HardwarepackHandler([tarball], board='panda', bootloader='uefi')
        with hp:
            path = hp.get_file_from_package("some/path/config", "package2")
            self.assertTrue(path.endswith("some/path/config"))


class TestSetMetadata(TestCaseWithFixtures):

    class MockHardwarepackHandler(HardwarepackHandler):
        metadata_dict = {}

        def __enter__(self):
            return self

        def get_field(self, field):
            try:
                return self.metadata_dict[field], None
            except:
                return None, None

        def get_format(self):
            return '2.0'

        def get_file(self, file_alias):
            return None

    def test_does_not_set_if_old_format(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(None, board_conf.kernel_addr)

    def test_sets_kernel_addr(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'kernel_addr'
        data_to_set = '0x8123ABCD'
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(data_to_set, board_conf.kernel_addr)

    def test_sets_initrd_addr(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'initrd_addr'
        data_to_set = '0x8123ABCD'
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(data_to_set, board_conf.initrd_addr)

    def test_sets_load_addr(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'load_addr'
        data_to_set = '0x8123ABCD'
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(data_to_set, board_conf.load_addr)

    def test_sets_serial_tty(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'serial_tty'
        data_to_set = 'ttyAA'
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(data_to_set, board_conf.serial_tty)

    def test_sets_wired_interfaces(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'wired_interfaces'
        data_to_set = 'eth0 eth1'
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(data_to_set, board_conf.wired_interfaces)

    def test_sets_wireless_interfaces(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'wireless_interfaces'
        data_to_set = 'wlan0 wl1'
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(data_to_set, board_conf.wireless_interfaces)

    def test_sets_mmc_id(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'mmc_id'
        data_to_set = '0:1'
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(data_to_set, board_conf.mmc_option)
        self.assertEquals(0, board_conf.mmc_device_id)
        self.assertEquals(0, board_conf.mmc_part_offset)

    def test_sets_boot_min_size(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'boot_min_size'
        data_to_set = '100'
        expected = align_up(int(data_to_set) * 1024 * 1024,
                            SECTOR_SIZE) / SECTOR_SIZE
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(expected, board_conf.BOOT_MIN_SIZE_S)

    def test_sets_root_min_size(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'root_min_size'
        data_to_set = '3'
        expected = align_up(int(data_to_set) * 1024 * 1024,
                            SECTOR_SIZE) / SECTOR_SIZE
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(expected, board_conf.ROOT_MIN_SIZE_S)

    def test_sets_loader_min_size(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'loader_min_size'
        data_to_set = '2'
        expected = align_up(int(data_to_set) * 1024 * 1024,
                            SECTOR_SIZE) / SECTOR_SIZE
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(expected, board_conf.LOADER_MIN_SIZE_S)

    def test_sets_partition_layout_32(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'partition_layout'
        data_to_set = 'bootfs_rootfs'
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(32, board_conf.fat_size)

    def test_sets_partition_layout_16(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'partition_layout'
        data_to_set = 'bootfs16_rootfs'
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(16, board_conf.fat_size)

    def test_sets_partition_layout_raises(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'partition_layout'
        data_to_set = 'bootfs_bogus_rootfs'
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        self.assertRaises(
            AssertionError, board_conf.set_metadata, 'ahwpack.tar.gz')

    def test_sets_copy_files(self):
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards, 'HardwarepackHandler',
            self.MockHardwarepackHandler))
        field_to_test = 'bootloader_copy_files'
        data_to_set = {'package':
                       [{"source1": "dest1"},
                        {"source2": "dest2"}]}
        self.MockHardwarepackHandler.metadata_dict = {
            field_to_test: data_to_set,
        }

        board_conf = BoardConfig()
        board_conf.set_metadata('ahwpack.tar.gz')
        self.assertEquals(data_to_set, board_conf.bootloader_copy_files)


class TestGetMLOFile(TestCaseWithFixtures):

    def test_mlo_from_new_xloader(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        path = os.path.join(
            tempdir, 'usr', 'lib', 'x-loader', 'omap3530beagle')
        os.makedirs(path)
        mlo_path = os.path.join(path, 'MLO')
        open(mlo_path, 'w').close()
        self.assertEquals(
            mlo_path, _get_mlo_file(tempdir))

    def test_mlo_from_old_xloader(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        path = os.path.join(tempdir, 'usr', 'lib', 'x-loader-omap4')
        os.makedirs(path)
        mlo_path = os.path.join(path, 'MLO')
        open(mlo_path, 'w').close()
        self.assertEquals(
            mlo_path, _get_mlo_file(tempdir))

    def test_no_mlo_found(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        self.assertRaises(
            AssertionError, _get_mlo_file, tempdir)

    def test_more_than_one_mlo_found(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        for directory in ['x-loader-omap4', 'x-loader-omap3']:
            path = os.path.join(tempdir, 'usr', 'lib', directory)
            os.makedirs(path)
            mlo_path = os.path.join(path, 'MLO')
            open(mlo_path, 'w').close()
        self.assertRaises(
            AssertionError, _get_mlo_file, tempdir)


def _create_uboot_dir(root, flavor):
    path = os.path.join(root, 'usr', 'lib', 'u-boot', flavor)
    os.makedirs(path)
    return path


class TestGetSMDKSPL(TestCaseWithFixtures):
    def setUp(self):
            super(TestGetSMDKSPL, self).setUp()
            self.config = boards.SMDKV310Config()
            self.config.hwpack_format = HardwarepackHandler.FORMAT_1

    def test_no_file_present(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        self.assertRaises(
            AssertionError, self.config._get_samsung_spl, tempdir)

    def test_old_file_present(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        path = _create_uboot_dir(tempdir, self.config.bootloader_flavor)
        spl_path = os.path.join(path, 'v310_mmc_spl.bin')
        open(spl_path, 'w').close()
        self.assertEquals(spl_path, self.config._get_samsung_spl(tempdir))

    def test_new_file_present(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        path = _create_uboot_dir(tempdir, self.config.bootloader_flavor)
        spl_path = os.path.join(path, 'u-boot-mmc-spl.bin')
        open(spl_path, 'w').close()
        self.assertEquals(spl_path, self.config._get_samsung_spl(tempdir))

    def test_prefers_old_path(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        path = _create_uboot_dir(tempdir, self.config.bootloader_flavor)
        old_spl_path = os.path.join(path, 'v310_mmc_spl.bin')
        new_spl_path = os.path.join(path, 'u-boot-mmc-spl.bin')
        open(old_spl_path, 'w').close()
        open(new_spl_path, 'w').close()
        self.assertEquals(old_spl_path, self.config._get_samsung_spl(tempdir))


class TestGetSMDKUboot(TestCaseWithFixtures):
    def setUp(self):
        super(TestGetSMDKUboot, self).setUp()
        self.config = boards.SMDKV310Config()
        self.config.hwpack_format = HardwarepackHandler.FORMAT_1

    def test_uses_uboot_flavour(self):
        chroot_dir = "chroot"
        uboot_file = os.path.join(chroot_dir, 'usr', 'lib', 'u-boot',
                                  self.config.bootloader_flavor, 'u-boot.bin')
        self.assertEquals(
            uboot_file, self.config._get_samsung_bootloader(chroot_dir))


class TestGetOrigenSPL(TestCaseWithFixtures):
    def setUp(self):
        super(TestGetOrigenSPL, self).setUp()
        self.config = boards.OrigenConfig()
        self.config.hwpack_format = HardwarepackHandler.FORMAT_1

    def test_no_file_present(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        self.assertRaises(
            AssertionError, self.config._get_samsung_spl, tempdir)

    def test_new_file_present(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        path = _create_uboot_dir(tempdir, self.config.bootloader_flavor)
        spl_path = os.path.join(path, 'u-boot-mmc-spl.bin')
        open(spl_path, 'w').close()
        self.assertEquals(spl_path, self.config._get_samsung_spl(tempdir))


class TestGetOrigenUboot(TestGetSMDKUboot):
    def setUp(self):
        super(TestGetOrigenUboot, self).setUp()
        self.config = boards.OrigenConfig()
        self.config.hwpack_format = HardwarepackHandler.FORMAT_1


class TestGetOrigenQuadSPL(TestCaseWithFixtures):
    def setUp(self):
        super(TestGetOrigenQuadSPL, self).setUp()
        self.config = boards.OrigenQuadConfig()
        self.config.hwpack_format = HardwarepackHandler.FORMAT_1

    def test_no_file_present(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        self.assertRaises(
            AssertionError, self.config._get_samsung_spl, tempdir)

    def test_new_file_present(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        path = _create_uboot_dir(tempdir, self.config.bootloader_flavor)
        spl_path = os.path.join(path, 'origen_quad-spl.bin')
        open(spl_path, 'w').close()
        self.assertEquals(spl_path, self.config._get_samsung_spl(tempdir))


class TestGetOrigenQuadUboot(TestGetSMDKUboot):
    def setUp(self):
        super(TestGetOrigenQuadUboot, self).setUp()
        self.config = boards.OrigenQuadConfig()
        self.config.hwpack_format = HardwarepackHandler.FORMAT_1


class TestGetArndaleSPL(TestCaseWithFixtures):
    def setUp(self):
        super(TestGetArndaleSPL, self).setUp()
        self.config = boards.ArndaleConfig()
        self.config.hwpack_format = HardwarepackHandler.FORMAT_1

    def test_no_file_present(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        self.assertRaises(
            AssertionError, self.config._get_samsung_spl, tempdir)

    def test_new_file_present(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        path = _create_uboot_dir(tempdir, self.config.bootloader_flavor)
        spl_path = os.path.join(path, 'smdk5250-spl.bin')
        open(spl_path, 'w').close()
        self.assertEquals(spl_path, self.config._get_samsung_spl(tempdir))


class TestGetArndaleUboot(TestGetSMDKUboot):
    config = boards.ArndaleConfig


class TestArndaleBootFiles(TestCaseWithFixtures):
    def test_arndale_make_boot_files_v2(self):
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        board_conf = boards.ArndaleConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        board_conf.load_addr = '0x40008000'
        board_conf.boot_script = None

        board_conf.hardwarepack_handler = (
            TestSetMetadata.MockHardwarepackHandler('ahwpack.tar.gz'))

        self.tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        self.temp_bootdir_path = os.path.join(self.tempdir, 'boot')
        self.temp_bl0_path = os.path.join(self.tempdir,
                                          'lib', 'firmware', 'arndale')
        k_img_file = os.path.join(self.tempdir, 'vmlinuz-1-arndale')
        i_img_file = os.path.join(self.tempdir, 'initrd.img-1-arndale')
        bl0_file = os.path.join(self.temp_bl0_path, 'arndale-bl1.bin')
        os.makedirs(self.temp_bl0_path)
        open(bl0_file, 'w').close()

        boot_env = {'ethact': 'smc911x-0',
                    'initrd_high': '0xffffffff',
                    'ethaddr': '00:40:5c:26:0a:5b',
                    'fdt_high': '0xffffffff',
                    'bootcmd': 'fatload mmc 0:2 None uImage; bootm None',
                    'bootargs': 'root=UUID=test_boot_env_uuid rootwait ro'}

        board_conf._make_boot_files_v2(
            boot_env=boot_env,
            chroot_dir=self.tempdir,
            boot_dir=self.temp_bootdir_path,
            boot_device_or_file='boot_device_or_file',
            k_img_data=k_img_file,
            i_img_data=i_img_file,
            d_img_data=None)

        expected_commands = [
            ('sudo -E dd if=%s of=boot_device_or_file bs=512 conv=notrunc '
             'seek=1' % bl0_file),
            ('sudo -E mkimage -A arm -O linux -T kernel -C none -a %s -e %s '
             '-n Linux -d %s %s/uImage'
             % (board_conf.load_addr, board_conf.load_addr,
                k_img_file, self.temp_bootdir_path)),
            ('sudo -E mkimage -A arm -O linux -T ramdisk -C none -a 0 -e 0 '
             '-n initramfs -d %s %s/uInitrd'
             % (i_img_file, self.temp_bootdir_path))]
        self.assertEqual(expected_commands,
                         popen_fixture.mock.commands_executed)
        shutil.rmtree(self.tempdir)


class TestCreateToc(TestCaseWithFixtures):
    ''' Tests boards.SnowballEmmcConfig.create_toc()'''

    def setUp(self):
        ''' Create a temporary directory to work in'''
        super(TestCreateToc, self).setUp()
        self.tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        #Create the test's input data structures
        zero = '\x00\x00\x00\x00'
        line1 = zero + zero + zero + zero + zero + 'b' + zero + zero + \
            '\x00\x00\x00'
        maxint = '\xFF\xFF\xFF\x7F'
        minint = '\xFF\xFF\xFF\xFF'
        line2 = maxint + maxint + zero + minint + minint + \
            'hello' + zero + '\x00\x00\x00'
        line3 = '\x01\x00\x00\x00' '\x64\x00\x00\x00' + zero + \
            '\x05\x00\x00\x00' '\x05\x00\x00\x00' \
            'hello' + zero + '\x00\x00\x00'
        self.expected = line1 + line2 + line3
        self.board_conf = boards.SnowballEmmcConfig()

    def create_files_structure(self, src_data):
        ''' Creates the data structure that the tested function
            needs as input'''
        files = []
        for line in src_data:
            files.append({'section_name': line[5],
                          'filename': 'N/A',
                          'align': line[3],
                          'offset': line[0],
                          'size': line[1],
                          'load_adress': 'N/A'})
        return files

    def test_create_toc_normal_case(self):
        ''' Creates a toc file, and then reads the created
            file and compares it to precomputed data'''
        correct_data = [(0, 0, 0, 0, 0, 'b'),
                        (0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, -1, -1, 'hello'),
                        (1, 100, 1000, 5, 10, 'hello')]
        files = self.create_files_structure(correct_data)
        filename = os.path.join(self.tempdir, 'toc')
        with open(filename, 'w') as f:
            self.board_conf.create_toc(f, files)
        with open(filename, 'r') as f:
            actual = f.read()
        self.assertEquals(96, len(actual))
        for i in range(len(actual)):
            self.assertEquals(
                self.expected[i], actual[i], 'Mismatch at ix'
                ' %d, ref=%c, actual=%c' % (i, self.expected[i], actual[i]))

    def test_create_toc_error_too_large_section_name(self):
        '''Verify that trying to write past the end of the
           section name field raises an exception'''
        illegal_name_data = [(0, 0, 0, 0, 0, 'Too_longName')]
        files = self.create_files_structure(illegal_name_data)
        with open(os.path.join(self.tempdir, 'toc'), 'w') as f:
            self.assertRaises(AssertionError,
                              self.board_conf.create_toc,
                              f, files)

    def test_create_toc_error_negative_unsigned(self):
        '''Verify that trying to write a negative number to an unsigned
           field raises an exception'''
        illegal_unsigned_data = [(-3, 0, 0, 0, 0, 'xxx')]
        files = self.create_files_structure(illegal_unsigned_data)
        with open(os.path.join(self.tempdir, 'toc'), 'w') as f:
            self.assertRaises(struct.error,
                              self.board_conf.create_toc,
                              f, files)


class TestSnowballBootFiles(TestCaseWithFixtures):
    ''' Tests boards.SnowballEmmcConfig.install_snowball_boot_loader()'''
    ''' Tests boards.SnowballEmmcConfig._make_boot_files()'''
    ''' Tests boards.SnowballEmmcConfig.get_file_info()'''

    def setUp(self):
        ''' Create temporary directory to work in'''
        super(TestSnowballBootFiles, self).setUp()
        self.tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        self.temp_bootdir_path = os.path.join(self.tempdir, 'boot')
        self.temp_configdir_path = os.path.join(self.tempdir, 'startfiles')
        if not os.path.exists(self.temp_bootdir_path):
            os.makedirs(self.temp_bootdir_path)
        if not os.path.exists(self.temp_configdir_path):
            os.makedirs(self.temp_configdir_path)
        self.snowball_config = get_board_config('snowball_emmc')
        self.snowball_config.hwpack_format = HardwarepackHandler.FORMAT_1

    def setupFiles(self):
        return self.create_test_files(self.temp_bootdir_path)

    def setupAndroidFiles(self):
        return self.create_test_files(self.temp_configdir_path)

    def create_test_files(self, path):
        ''' Adds some files in the temp dir that the tested function
            can use as input:
            * A config file, which the tested function reads to
              discover which binary files should be written to
              the loader partition.
            * Test versions of the binary files themselves,
              containing dummy data.
            Returns the expected value that the tested function should
            return, given these input files.  '''
        src_data = [('ISSW', 'boot_image_issw.bin', -1, 0, '5'),
                    ('X-LOADER', 'boot_image_x-loader.bin', -1, 0, '6'),
                    ('MEM_INIT', 'mem_init.bin', 0, 0x160000, '7'),
                    ('PWR_MGT', 'power_management.bin', 0, 0x170000, '8'),
                    ('NORMAL', 'u-boot.bin', 0, 0xBA0000, '9'),
                    ('UBOOT_ENV', 'u-boot-env.bin', 0, 0x00C1F000, '10')]
        # Create a config file
        cfg_file = os.path.join(
            path, self.snowball_config.snowball_startup_files_config)
        with open(cfg_file, 'w') as f:
            for line in src_data:
                # Write comments, so we test that the parser can read them
                f.write('#Yet another comment\n')
                # Write whitespace, so we test that the parser can handle them
                f.write('   \n\t\n \t \t \n')
                f.write('%s %s %i %#x %s\n' % line)
        expected = []
        # Define dummy binary files, containing nothing but their own
        # section names.
        for line in src_data:
            with open(os.path.join(path, line[1]), 'w') as f:
                f.write(line[0])
        #define the expected values read from the config file
        expected = []
        ofs = [self.snowball_config.TOC_SIZE,
               self.snowball_config.TOC_SIZE + len('ISSW'), 0x160000,
               0x170000, 0xBA0000, 0xC1F000]
        size = [len('ISSW'), len('X-LOADER'), len('MEM_INIT'),
                len('PWR_MGT'), len('NORMAL'), len('UBOOT_ENV')]
        i = 0
        for line in src_data:
            filename = os.path.join(path, line[1])
            expected.append({'section_name': line[0],
                             'filename': filename,
                             'align': int(line[2]),
                             'offset': ofs[i],
                             'size': long(size[i]),
                             'load_adress': line[4]})
            i += 1
        return expected

    def test_get_file_info_relative_path(self):
        # Create a config file
        cfg_file = os.path.join(
            self.temp_bootdir_path,
            self.snowball_config.snowball_startup_files_config)
        uboot_file = 'u-boot.bin'
        with open(cfg_file, 'w') as f:
                f.write('%s %s %i %#x %s\n' % ('NORMAL', uboot_file, 0,
                                               0xBA0000, '9'))
        with open(os.path.join(self.temp_bootdir_path, uboot_file), 'w') as f:
            file_info = self.snowball_config.get_file_info(
                self.tempdir, self.temp_bootdir_path)
        self.assertEquals(file_info[0]['filename'],
                          os.path.join(self.temp_bootdir_path, uboot_file))

    def test_get_file_info_abs_path(self):
        # Create a config file
        cfg_file = os.path.join(
            self.temp_bootdir_path,
            self.snowball_config.snowball_startup_files_config)
        uboot_dir = tempfile.mkdtemp(dir=self.tempdir)
        uboot_file = os.path.join(uboot_dir, 'u-boot.bin')
        uboot_relative_file = uboot_file.replace(self.tempdir, '')
        with open(cfg_file, 'w') as f:
                f.write('%s %s %i %#x %s\n' % (
                        'NORMAL', uboot_relative_file, 0, 0xBA0000, '9'))
        with open(uboot_file, 'w') as f:
            file_info = self.snowball_config.get_file_info(
                self.tempdir, self.temp_bootdir_path)
        self.assertEquals(file_info[0]['filename'], uboot_file)

    def test_get_file_info_raises(self):
        # Create a config file
        cfg_file = os.path.join(
            self.temp_bootdir_path,
            self.snowball_config.snowball_startup_files_config)
        with open(cfg_file, 'w') as f:
                f.write('%s %s %i %#x %s\n' % ('NORMAL', 'u-boot.bin', 0,
                                               0xBA0000, '9'))
        self.assertRaises(
            AssertionError, self.snowball_config.get_file_info,
            self.tempdir, self.temp_bootdir_path)

    def test_file_name_size(self):
        ''' Test using a to large toc file '''
        _, toc_filename = tempfile.mkstemp()
        atexit.register(os.unlink, toc_filename)
        filedata = 'X'
        bytes = self.snowball_config.TOC_SIZE + 1
        tmpfile = open(toc_filename, 'wb')
        for n in xrange(bytes):
            tmpfile.write(filedata)
        tmpfile.close()
        files = self.setupFiles()
        self.assertRaises(
            AssertionError,
            self.snowball_config.install_snowball_boot_loader,
            toc_filename, files, "boot_device_or_file",
            self.snowball_config.SNOWBALL_LOADER_START_S)

    def test_install_snowball_boot_loader_toc_dont_delete(self):
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        toc_filename = self.createTempFileAsFixture()
        files = self.setupFiles()
        self.snowball_config.install_snowball_boot_loader(
            toc_filename,
            files, "boot_device_or_file",
            self.snowball_config.SNOWBALL_LOADER_START_S)
        expected = [
            '%s dd if=%s of=boot_device_or_file bs=512 conv=notrunc'
            ' seek=%s' % (sudo_args, toc_filename,
                          self.snowball_config.SNOWBALL_LOADER_START_S),
            '%s dd if=%s/boot_image_issw.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=257' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/boot_image_x-loader.bin of=boot_device_or_file'
            ' bs=1 conv=notrunc seek=131588'
            % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/mem_init.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=3072' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/power_management.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=3200' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/u-boot.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=24064' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/u-boot-env.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=25080' % (sudo_args, self.temp_bootdir_path)]

        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_install_snowball_boot_loader_toc_delete(self):
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        toc_filename = self.createTempFileAsFixture()
        files = self.setupFiles()
        self.snowball_config.install_snowball_boot_loader(
            toc_filename,
            files, "boot_device_or_file",
            self.snowball_config.SNOWBALL_LOADER_START_S, True)
        expected = [
            '%s dd if=%s of=boot_device_or_file bs=512 conv=notrunc'
            ' seek=%s' % (sudo_args, toc_filename,
                          self.snowball_config.SNOWBALL_LOADER_START_S),
            '%s dd if=%s/boot_image_issw.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=257' % (sudo_args, self.temp_bootdir_path),
            '%s rm %s/boot_image_issw.bin' % (sudo_args,
                                              self.temp_bootdir_path),
            '%s dd if=%s/boot_image_x-loader.bin of=boot_device_or_file'
            ' bs=1 conv=notrunc seek=131588'
            % (sudo_args, self.temp_bootdir_path),
            '%s rm %s/boot_image_x-loader.bin' % (sudo_args,
                                                  self.temp_bootdir_path),
            '%s dd if=%s/mem_init.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=3072' % (sudo_args, self.temp_bootdir_path),
            '%s rm %s/mem_init.bin' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/power_management.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=3200' % (sudo_args, self.temp_bootdir_path),
            '%s rm %s/power_management.bin' % (sudo_args,
                                               self.temp_bootdir_path),
            '%s dd if=%s/u-boot.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=24064' % (sudo_args, self.temp_bootdir_path),
            '%s rm %s/u-boot.bin' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/u-boot-env.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=25080' % (sudo_args, self.temp_bootdir_path),
            '%s rm %s/u-boot-env.bin' % (sudo_args, self.temp_bootdir_path)]

        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_install_snowball_boot_loader_toc_android(self):
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        toc_filename = self.createTempFileAsFixture()
        files = self.setupFiles()
        board_conf = AndroidSnowballEmmcConfig()
        board_conf.install_snowball_boot_loader(
            toc_filename, files, "boot_device_or_file",
            board_conf.SNOWBALL_LOADER_START_S)
        expected = [
            '%s dd if=%s of=boot_device_or_file bs=512 conv=notrunc'
            ' seek=%s' % (sudo_args, toc_filename,
                          board_conf.SNOWBALL_LOADER_START_S),
            '%s dd if=%s/boot_image_issw.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=257' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/boot_image_x-loader.bin of=boot_device_or_file'
            ' bs=1 conv=notrunc seek=131588'
            % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/mem_init.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=3072' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/power_management.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=3200' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/u-boot.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=24064' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/u-boot-env.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=25080' % (sudo_args, self.temp_bootdir_path)]

        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_snowball_make_boot_files(self):
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        self.useFixture(
            MockSomethingFixture(tempfile, 'mkstemp',
                                 lambda:
                                 (-1, '/tmp/temp_snowball_make_boot_files')))
        self.setupFiles()
        k_img_file = os.path.join(self.tempdir, 'vmlinuz-1-ux500')
        i_img_file = os.path.join(self.tempdir, 'initrd.img-1-ux500')

        boot_env = self.snowball_config._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=test_boot_env_uuid",
            i_img_data=None, d_img_data=None)
        self.snowball_config._make_boot_files(boot_env, self.tempdir,
                                              self.temp_bootdir_path,
                                              'boot_device_or_file',
                                              k_img_file, i_img_file, None)
        expected = [
            '%s mkimage -A arm -O linux -T kernel -C none -a 0x00008000 -e'
            ' 0x00008000 -n Linux -d %s %s/boot/uImage'
            % (sudo_args, k_img_file, self.tempdir),
            '%s cp /tmp/temp_snowball_make_boot_files %s/boot/boot.txt'
            % (sudo_args, self.tempdir),
            '%s mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n boot'
            ' script -d %s/boot/boot.txt %s/boot/flash.scr'
            % (sudo_args, self.tempdir, self.tempdir),
            '%s dd if=/tmp/temp_snowball_make_boot_files'
            ' of=boot_device_or_file bs=512 conv=notrunc seek=256'
            % (sudo_args),
            '%s dd if=%s/boot/boot_image_issw.bin of=boot_device_or_file'
            ' bs=512 conv=notrunc seek=257' % (sudo_args, self.tempdir),
            '%s rm %s/boot_image_issw.bin' % (sudo_args,
                                              self.temp_bootdir_path),
            '%s dd if=%s/boot/boot_image_x-loader.bin of=boot_device_or_file'
            ' bs=1 conv=notrunc seek=131588' % (sudo_args, self.tempdir),
            '%s rm %s/boot_image_x-loader.bin' % (sudo_args,
                                                  self.temp_bootdir_path),
            '%s dd if=%s/boot/mem_init.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=3072' % (sudo_args, self.tempdir),
            '%s rm %s/mem_init.bin' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/boot/power_management.bin of=boot_device_or_file'
            ' bs=512 conv=notrunc seek=3200' % (sudo_args, self.tempdir),
            '%s rm %s/power_management.bin' % (sudo_args,
                                               self.temp_bootdir_path),
            '%s dd if=%s/boot/u-boot.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=24064' % (sudo_args, self.tempdir),
            '%s rm %s/u-boot.bin' % (sudo_args, self.temp_bootdir_path),
            '%s dd if=%s/boot/u-boot-env.bin of=boot_device_or_file bs=512'
            ' conv=notrunc seek=25080' % (sudo_args, self.tempdir),
            '%s rm %s/u-boot-env.bin' % (sudo_args, self.temp_bootdir_path),
            '%s rm /tmp/temp_snowball_make_boot_files' % (sudo_args),
            '%s rm %s/startfiles.cfg' % (sudo_args, self.temp_bootdir_path)]

        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_missing_files(self):
        '''When the files cannot be read, an IOError should be raised'''
        self.assertRaises(IOError,
                          self.snowball_config.get_file_info,
                          self.tempdir, self.temp_bootdir_path)

    def test_normal_case(self):
        expected = self.setupFiles()
        actual = self.snowball_config.get_file_info(
            self.tempdir, self.temp_bootdir_path)
        self.assertEquals(expected, actual)


class TestBootSteps(TestCaseWithFixtures):

    def setUp(self):
        super(TestBootSteps, self).setUp()
        self.funcs_calls = []
        self.mock_all_boards_funcs()

    def mock_all_boards_funcs(self):
        """Mock functions of boards module with a call tracer."""

        def mock_func_creator(name):
            return lambda *args, **kwargs: self.funcs_calls.append(name)

        for name in dir(boards):
            attr = getattr(boards, name)
            if isinstance(attr, types.FunctionType):
                self.useFixture(MockSomethingFixture(
                    linaro_image_tools.media_create.boards, name,
                    mock_func_creator(name)))

    def mock_set_appropriate_serial_tty(self, config):

        def set_appropriate_serial_tty_mock(chroot_dir):
            config.serial_tty = config._serial_tty

        config.set_appropriate_serial_tty = MagicMock(
            side_effect=set_appropriate_serial_tty_mock)

    def make_boot_files(self, config):
        def _get_kflavor_files_mock(path):
            if config.dtb_name is None:
                return (path, path, None)
            return (path, path, path)

        config._get_kflavor_files = MagicMock(
            side_effect=_get_kflavor_files_mock)

        config.make_boot_files('', False, False, [], '', '', '', '')

    def test_vexpress_steps(self):
        board_conf = boards.VexpressConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.make_boot_files(board_conf)
        expected = ['make_uImage', 'make_uInitrd']
        self.assertEqual(expected, self.funcs_calls)

    def test_vexpress_a9_steps(self):
        board_conf = boards.VexpressA9Config()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.make_boot_files(board_conf)
        expected = ['make_uImage', 'make_uInitrd']
        self.assertEqual(expected, self.funcs_calls)

    def test_mx5_steps(self):
        board_conf = boards.Mx5Config()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        board_conf.bootloader_flavor = 'bootloader_flavor'
        board_conf.hardwarepack_handler = (
            TestSetMetadata.MockHardwarepackHandler('ahwpack.tar.gz'))
        board_conf.hardwarepack_handler.get_format = (
            lambda: HardwarepackHandler.FORMAT_1)
        self.make_boot_files(board_conf)
        expected = [
            'install_mx5_boot_loader', 'make_uImage', 'make_uInitrd',
            'make_dtb', 'make_boot_script']
        self.assertEqual(expected, self.funcs_calls)

    def test_smdkv310_steps(self):
        board_conf = boards.SMDKV310Config()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        board_conf.install_samsung_boot_loader = MagicMock()
        board_conf.install_samsung_boot_loader.return_value = \
            self.funcs_calls.append('install_samsung_boot_loader')
        self.useFixture(MockSomethingFixture(os.path, 'exists',
                                             lambda file: True))
        board_conf.hardwarepack_handler = (
            TestSetMetadata.MockHardwarepackHandler('ahwpack.tar.gz'))
        board_conf.hardwarepack_handler.get_format = (
            lambda: HardwarepackHandler.FORMAT_1)
        self.make_boot_files(board_conf)
        expected = [
            'install_samsung_boot_loader', 'make_flashable_env', '_dd',
            'make_uImage', 'make_uInitrd', 'make_boot_script']
        self.assertEqual(expected, self.funcs_calls)

    def test_origen_steps(self):
        board_conf = boards.OrigenConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        board_conf.install_samsung_boot_loader = MagicMock()
        board_conf.install_samsung_boot_loader.return_value = \
            self.funcs_calls.append('install_samsung_boot_loader')
        self.useFixture(MockSomethingFixture(os.path, 'exists',
                                             lambda file: True))
        board_conf.hardwarepack_handler = (
            TestSetMetadata.MockHardwarepackHandler('ahwpack.tar.gz'))
        board_conf.hardwarepack_handler.get_format = (
            lambda: HardwarepackHandler.FORMAT_1)
        self.make_boot_files(board_conf)
        expected = [
            'install_samsung_boot_loader', 'make_flashable_env', '_dd',
            'make_uImage', 'make_uInitrd', 'make_boot_script']
        self.assertEqual(expected, self.funcs_calls)

    def test_origen_quad_steps(self):
        board_conf = boards.OrigenQuadConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        board_conf.install_samsung_boot_loader = MagicMock()
        board_conf.install_samsung_boot_loader.return_value = \
            self.funcs_calls.append('install_samsung_boot_loader')

        self.useFixture(MockSomethingFixture(os.path, 'exists',
                                             lambda file: True))
        board_conf.hardwarepack_handler = (
            TestSetMetadata.MockHardwarepackHandler('ahwpack.tar.gz'))
        board_conf.hardwarepack_handler.get_format = (
            lambda: HardwarepackHandler.FORMAT_1)
        self.make_boot_files(board_conf)
        expected = [
            'install_samsung_boot_loader', 'make_flashable_env', '_dd',
            'make_uImage', 'make_uInitrd', 'make_boot_script']
        self.assertEqual(expected, self.funcs_calls)

    def test_arndale_steps(self):
        board_conf = boards.ArndaleConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        board_conf.install_samsung_boot_loader = MagicMock()
        board_conf.install_samsung_boot_loader.return_value = \
            self.funcs_calls.append('install_samsung_boot_loader')

        self.useFixture(MockSomethingFixture(os.path, 'exists',
                                             lambda file: True))
        board_conf.hardwarepack_handler = (
            TestSetMetadata.MockHardwarepackHandler('ahwpack.tar.gz'))
        board_conf.hardwarepack_handler.get_format = (
            lambda: '1.0')
        self.make_boot_files(board_conf)
        expected = [
            'install_samsung_boot_loader', 'make_flashable_env', '_dd',
            'make_uImage', 'make_uInitrd', 'make_boot_script']
        self.assertEqual(expected, self.funcs_calls)

    def test_ux500_steps(self):
        board_conf = boards.Ux500Config()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.make_boot_files(board_conf)
        expected = ['make_uImage', 'make_uInitrd', 'make_boot_script']
        self.assertEqual(expected, self.funcs_calls)

    def test_snowball_sd_steps(self):
        board_conf = boards.SnowballSdConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.make_boot_files(board_conf)
        expected = ['make_uImage', 'make_boot_script']
        self.assertEqual(expected, self.funcs_calls)

    def test_panda_steps(self):
        board_conf = boards.PandaConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.mock_set_appropriate_serial_tty(board_conf)
        self.make_boot_files(board_conf)
        expected = [
            'install_omap_boot_loader', 'make_uImage', 'make_uInitrd',
            'make_dtb', 'make_boot_script', 'make_boot_ini']
        self.assertEqual(expected, self.funcs_calls)

    def test_beagle_steps(self):
        board_conf = boards.BeagleConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.mock_set_appropriate_serial_tty(board_conf)
        self.make_boot_files(board_conf)
        expected = [
            'install_omap_boot_loader', 'make_uImage', 'make_uInitrd',
            'make_dtb', 'make_boot_script', 'make_boot_ini']
        self.assertEqual(expected, self.funcs_calls)

    def test_igep_steps(self):
        board_conf = boards.IgepConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.mock_set_appropriate_serial_tty(board_conf)
        self.make_boot_files(board_conf)
        expected = [
            'make_uImage', 'make_uInitrd', 'make_dtb', 'make_boot_script',
            'make_boot_ini']
        self.assertEqual(expected, self.funcs_calls)

    def test_overo_steps(self):
        board_conf = boards.OveroConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.mock_set_appropriate_serial_tty(board_conf)
        self.make_boot_files(board_conf)
        expected = [
            'install_omap_boot_loader', 'make_uImage', 'make_uInitrd',
            'make_dtb', 'make_boot_script', 'make_boot_ini']
        self.assertEqual(expected, self.funcs_calls)

    def test_highbank_steps(self):
        board_conf = boards.HighBankConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_beaglbone_steps(self):
        board_conf = boards.BeagleBoneConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.mock_set_appropriate_serial_tty(board_conf)
        self.make_boot_files(board_conf)
        expected = [
            'install_omap_boot_loader', 'make_uImage', 'make_uInitrd',
            'make_dtb', 'make_boot_script', 'make_boot_ini']
        self.assertEqual(expected, self.funcs_calls)

    def test_aa9_steps(self):
        board_conf = boards.Aa9Config()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        expected = []
        self.assertEqual(expected, self.funcs_calls)


class TestPopulateRawPartition(TestCaseWithFixtures):

    def setUp(self):
        super(TestPopulateRawPartition, self).setUp()
        self.funcs_calls = []
        self.mock_all_boards_funcs()

    def mock_all_boards_funcs(self):
        """Mock functions of boards module with a call tracer."""

        def mock_func_creator(name):
            return lambda *args, **kwargs: self.funcs_calls.append(name)

        for name in dir(boards):
            attr = getattr(boards, name)
            if isinstance(attr, types.FunctionType):
                self.useFixture(MockSomethingFixture(
                    linaro_image_tools.media_create.boards, name,
                    mock_func_creator(name)))

    def populate_raw_partition(self, config):
        config.populate_raw_partition('', '')

    def test_snowball_config_raises(self):
        self.assertRaises(NotImplementedError,
                          boards.SnowballSdConfig().snowball_config, '')

    def test_beagle_raw(self):
        self.populate_raw_partition(android_boards.AndroidBeagleConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_panda_raw(self):
        self.populate_raw_partition(android_boards.AndroidPandaConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_snowball_sd_raw(self):
        self.populate_raw_partition(boards.SnowballSdConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_snowball_emmc_raw(self):
        def mock_func_creator(name):
            return classmethod(
                lambda *args, **kwargs: self.funcs_calls.append(name))

        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards.SnowballEmmcConfig,
            'get_file_info',
            mock_func_creator('get_file_info')))
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards.SnowballEmmcConfig,
            'create_toc',
            mock_func_creator('create_toc')))
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards.SnowballEmmcConfig,
            'install_snowball_boot_loader',
            mock_func_creator('install_snowball_boot_loader')))
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.boards.SnowballEmmcConfig,
            'delete_file',
            mock_func_creator('delete_file')))
        self.populate_raw_partition(boards.SnowballEmmcConfig())
        expected = ['get_file_info', 'create_toc',
                    'install_snowball_boot_loader', 'delete_file',
                    'delete_file']
        # Test that we run the Snowball populate_raw_partition() and
        # delete both the toc and startfiles.
        self.assertEqual(expected, self.funcs_calls)

    def test_smdkv310_raw(self):
        self.useFixture(MockSomethingFixture(os.path, 'getsize',
                                             lambda file: 1))

        self.populate_raw_partition(boards.SMDKV310Config())
        expected = ['_dd', '_dd', '_dd']
        self.assertEqual(expected, self.funcs_calls)

    def test_mx53loco_raw(self):
        self.populate_raw_partition(boards.Mx53LoCoConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_origen_raw(self):
        self.useFixture(MockSomethingFixture(os.path, 'getsize',
                                             lambda file: 1))

        self.populate_raw_partition(boards.OrigenConfig())
        expected = ['_dd', '_dd', '_dd']
        self.assertEqual(expected, self.funcs_calls)

    def test_origen_quad_raw(self):
        # Need to mock this since files do not exist here, and
        # an Exception is raised.
        self.useFixture(
            MockSomethingFixture(os.path, 'exists', lambda exists: True))

        self.populate_raw_partition(boards.OrigenQuadConfig())
        expected = ['_dd', '_dd', '_dd', '_dd', '_dd']
        self.assertEqual(expected, self.funcs_calls)

    def test_origen_quad_raises(self):
        board_conf = boards.OrigenQuadConfig()
        self.assertRaises(
            boards.BoardException, board_conf.populate_raw_partition, '', '')

    def test_arndale_raw(self):
        self.useFixture(MockSomethingFixture(os.path, 'getsize',
                                             lambda file: 1))

        self.populate_raw_partition(boards.ArndaleConfig())
        expected = ['_dd', '_dd', '_dd']
        self.assertEqual(expected, self.funcs_calls)

    def test_vexpress_a9_raw(self):
        self.populate_raw_partition(boards.VexpressA9Config())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_highbank_raw(self):
        self.populate_raw_partition(boards.HighBankConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_beaglebone_raw(self):
        self.populate_raw_partition(boards.BeagleBoneConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_aa9_raw(self):
        self.populate_raw_partition(boards.Aa9Config())
        expected = []
        self.assertEqual(expected, self.funcs_calls)


class TestPopulateRawPartitionAndroid(TestCaseWithFixtures):

    def setUp(self):
        super(TestPopulateRawPartitionAndroid, self).setUp()
        self.funcs_calls = []

    def populate_raw_partition(self, config):
        config.populate_raw_partition('', '')

    def test_beagle_raw(self):
        self.populate_raw_partition(android_boards.AndroidBeagleConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_panda_raw(self):
        self.populate_raw_partition(android_boards.AndroidPandaConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_snowball_sd_raw(self):
        self.populate_raw_partition(android_boards.AndroidSnowballSdConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_snowball_emmc_raw(self):
        def mock_func_creator(name):
            return classmethod(
                lambda *args, **kwargs: self.funcs_calls.append(name))

        self.useFixture(MockSomethingFixture(os.path, 'exists',
                                             lambda file: True))
        fixture = MockCmdRunnerPopenFixture()
        self.useFixture(fixture)
        expected_commands = ['sudo -E cp boot/u-boot.bin ./startupfiles']

        self.useFixture(MockSomethingFixture(
            android_boards.AndroidSnowballEmmcConfig,
            'get_file_info',
            mock_func_creator('get_file_info')))
        self.useFixture(MockSomethingFixture(
            android_boards.AndroidSnowballEmmcConfig,
            'create_toc',
            mock_func_creator('create_toc')))
        self.useFixture(MockSomethingFixture(
            android_boards.AndroidSnowballEmmcConfig,
            'install_snowball_boot_loader',
            mock_func_creator('install_snowball_boot_loader')))
        self.useFixture(MockSomethingFixture(
            android_boards.AndroidSnowballEmmcConfig,
            'delete_file',
            mock_func_creator('delete_file')))
        self.populate_raw_partition(android_boards.AndroidSnowballEmmcConfig())
        expected_calls = ['get_file_info', 'create_toc',
                          'install_snowball_boot_loader', 'delete_file']
        # Test that we copy the u-boot files to the local startupfiles dir.
        self.assertEqual(expected_commands, fixture.mock.commands_executed)
        # Test that we run the Snowball populate_raw_partition() and only
        # delete the toc.
        self.assertEqual(expected_calls, self.funcs_calls)

    def test_smdkv310_raw(self):
        fixture = MockCmdRunnerPopenFixture()
        self.useFixture(fixture)
        expected_commands = [
            'sudo -E dd if=/dev/zero of= bs=512 conv=notrunc count=32 seek=33',
            ('sudo -E dd if=boot/u-boot-mmc-spl.bin of= '
             'bs=512 conv=notrunc seek=1'),
            'sudo -E dd if=boot/u-boot.bin of= bs=512 conv=notrunc seek=65']
        self.useFixture(MockSomethingFixture(os.path, 'getsize',
                                             lambda file: 1))

        self.populate_raw_partition(android_boards.AndroidSMDKV310Config())
        expected_calls = []
        # Test that we dd the files
        self.assertEqual(expected_commands, fixture.mock.commands_executed)
        self.assertEqual(expected_calls, self.funcs_calls)

    def test_mx53loco_raw(self):
        self.populate_raw_partition(android_boards.AndroidMx53LoCoConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)

    def test_origen_raw(self):
        fixture = MockCmdRunnerPopenFixture()
        self.useFixture(fixture)
        expected_commands = [
            'sudo -E dd if=/dev/zero of= bs=512 conv=notrunc count=32 seek=33',
            ('sudo -E dd if=boot/u-boot-mmc-spl.bin of= bs=512 '
             'conv=notrunc seek=1'),
            'sudo -E dd if=boot/u-boot.bin of= bs=512 conv=notrunc seek=65']
        self.useFixture(MockSomethingFixture(os.path, 'getsize',
                                             lambda file: 1))

        self.populate_raw_partition(android_boards.AndroidOrigenConfig())
        expected = []
        # Test that we dd the files
        self.assertEqual(expected_commands, fixture.mock.commands_executed)
        self.assertEqual(expected, self.funcs_calls)

    def test_origen_quad_raw(self):
        fixture = MockCmdRunnerPopenFixture()
        self.useFixture(fixture)
        expected_commands = [
            ('sudo -E dd if=/dev/zero of= bs=512 conv=notrunc count=32 '
             'seek=1601'),
            ('sudo -E dd if=boot/origen_quad.bl1.bin of= bs=512 '
             'conv=notrunc seek=1'),
            ('sudo -E dd if=boot/origen_quad-spl.bin.signed of= bs=512 '
             'conv=notrunc seek=31'),
            ('sudo -E dd if=boot/u-boot.bin of= bs=512 conv=notrunc '
             'seek=63'),
            ('sudo -E dd if=boot/exynos4x12.tzsw.signed.img of= bs=512 '
             'conv=notrunc seek=761')
        ]

        self.useFixture(
            MockSomethingFixture(os.path, 'exists', lambda exists: True))

        self.populate_raw_partition(android_boards.AndroidOrigenQuadConfig())
        expected = []
        # Test that we dd the files
        self.assertEqual(expected_commands, fixture.mock.commands_executed)
        self.assertEqual(expected, self.funcs_calls)

    def test_vexpress_raw(self):
        self.populate_raw_partition(android_boards.AndroidVexpressConfig())
        expected = []
        self.assertEqual(expected, self.funcs_calls)


class TestAlignPartition(TestCase):

    def test_align_up_none(self):
        self.assertEqual(1024, align_up(1024, 1))

    def test_align_up_no_rounding(self):
        self.assertEqual(512, align_up(512, 512))

    def test_align_up_rounding(self):
        self.assertEqual(512, align_up(1, 512))

    def test_align_partition_4_mib_4_mib(self):
        expected = (4 * 1024 * 1024, 8 * 1024 * 1024 - 1, 4 * 1024 * 1024)
        self.assertEqual(expected,
                         align_partition(1, 1,
                                         4 * 1024 * 1024, 4 * 1024 * 1024))

    def test_align_partition_none_4_mib(self):
        expected = (1, 4 * 1024 * 1024 - 1, 4 * 1024 * 1024 - 1)
        self.assertEqual(expected,
                         align_partition(1, 1, 1, 4 * 1024 * 1024))


class TestFixForBug697824(TestCaseWithFixtures):

    def mock_set_appropriate_serial_tty(self, config):

        def set_appropriate_serial_tty_mock(arg):
            self.set_appropriate_serial_tty_called = True

        # Need to mock all the calls done from make_boot_files in order
        # to be able to correctly call it.
        config._get_kflavor_files = MagicMock(return_value=('', '', ''))
        config._get_boot_env = MagicMock(return_value=None)
        config._make_boot_files = MagicMock()
        config._make_boot_files_v2 = MagicMock()
        config.set_appropriate_serial_tty = MagicMock(
            side_effect=set_appropriate_serial_tty_mock)

    def test_omap_make_boot_files(self):
        self.set_appropriate_serial_tty_called = False

        board_conf = boards.BeagleConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.mock_set_appropriate_serial_tty(board_conf)
        # We don't need to worry about what's passed to make_boot_files()
        # because we mock the method which does the real work above and here
        # we're only interested in ensuring that OmapConfig.make_boot_files()
        # calls set_appropriate_serial_tty().
        board_conf.make_boot_files(
            None, None, None, None, None, None, None, None)
        self.assertTrue(
            self.set_appropriate_serial_tty_called,
            "make_boot_files didn't call set_appropriate_serial_tty")

    def test_omap_make_boot_files_v2(self):
        self.set_appropriate_serial_tty_called = False

        board_conf = boards.BeagleConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_2
        self.mock_set_appropriate_serial_tty(board_conf)
        # We don't need to worry about what's passed to make_boot_files()
        # because we mock the method which does the real work above and here
        # we're only interested in ensuring that OmapConfig.make_boot_files()
        # does not call set_appropriate_serial_tty().
        board_conf.make_boot_files(
            None, None, None, None, None, None, None, None)
        self.assertFalse(
            self.set_appropriate_serial_tty_called,
            "make_boot_files called set_appropriate_serial_tty")

    def test_set_appropriate_serial_tty_old_kernel(self):
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        boot_dir = os.path.join(tempdir, 'boot')
        os.makedirs(boot_dir)
        open(os.path.join(boot_dir, 'vmlinuz-2.6.35-23-foo'), 'w').close()
        board_conf = boards.BeagleConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        board_conf.set_appropriate_serial_tty(tempdir)
        self.assertEquals('ttyS2', board_conf.serial_tty)

    def test_set_appropriate_serial_tty_new_kernel(self):
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        boot_dir = os.path.join(tempdir, 'boot')
        os.makedirs(boot_dir)
        open(os.path.join(boot_dir, 'vmlinuz-2.6.36-13-foo'), 'w').close()
        board_conf = boards.BeagleConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        board_conf.set_appropriate_serial_tty(tempdir)
        self.assertEquals('ttyO2', board_conf.serial_tty)

    def test_set_appropriate_serial_tty_three_dot_oh_kernel(self):
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        boot_dir = os.path.join(tempdir, 'boot')
        os.makedirs(boot_dir)
        open(os.path.join(boot_dir, 'vmlinuz-3.0-13-foo'), 'w').close()
        board_conf = boards.BeagleConfig()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        board_conf.set_appropriate_serial_tty(tempdir)
        self.assertEquals('ttyO2', board_conf.serial_tty)


class TestGetSfdiskCmd(TestCase):

    def set_up_config(self, config):
        config.hwpack_format = HardwarepackHandler.FORMAT_1

    def test_default(self):
        board_conf = BoardConfig()
        self.set_up_config(board_conf)
        self.assertEqual(
            '63,106432,0x0C,*\n106496,,,-', board_conf.get_sfdisk_cmd())

    def test_default_aligned(self):
        board_conf = BoardConfig()
        self.set_up_config(board_conf)
        self.assertEqual(
            '8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd(should_align_boot_part=True))

    def test_mx5(self):
        board_conf = boards.Mx5Config()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        self.assertEqual(
            '1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_snowball_sd(self):
        board_conf = boards.SnowballSdConfig()
        self.set_up_config(board_conf)
        self.assertEqual(
            '63,106432,0x0C,*\n106496,,,-', board_conf.get_sfdisk_cmd())

    def test_snowball_emmc(self):
        board_conf = boards.SnowballEmmcConfig()
        self.set_up_config(board_conf)
        self.assertEqual(
            '256,7936,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_smdkv310(self):
        board_conf = get_board_config('smdkv310')
        self.set_up_config(board_conf)
        self.assertEquals(
            '1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_origen(self):
        board_conf = get_board_config('origen')
        self.set_up_config(board_conf)
        self.assertEquals(
            '1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_origen_quad(self):
        board_conf = get_board_config('origen_quad')
        self.set_up_config(board_conf)
        self.assertEquals(
            '1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_arndale(self):
        board_conf = get_board_config('arndale')
        self.set_up_config(board_conf)
        self.assertEquals(
            '1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_highbank(self):
        board_conf = get_board_config('highbank')
        self.set_up_config(board_conf)
        self.assertEquals(
            '63,106432,0x83,*\n106496,,,-',
            board_conf.get_sfdisk_cmd())

    def test_beaglebone(self):
        board_conf = get_board_config('beaglebone')
        self.set_up_config(board_conf)
        self.assertEquals(
            '63,106432,0x0C,*\n106496,,,-',
            board_conf.get_sfdisk_cmd())

    def test_aa9(self):
        board_conf = get_board_config('aa9')
        self.set_up_config(board_conf)
        self.assertEquals(
            '63,106432,0x0C,*\n106496,,,-',
            board_conf.get_sfdisk_cmd())

    def test_panda_android(self):
        self.assertEqual(
            '63,270272,0x0C,*\n270336,1835008,L\n2105344,524288,L\n'
            '2629632,-,E\n2629632,1179648,L\n3809280,,,-',
            android_boards.AndroidPandaConfig().get_sfdisk_cmd())

    def test_origen_android(self):
        self.assertEqual(
            '1,8191,0xDA\n8253,270274,0x0C,*\n278528,1835008,L\n'
            '2113536,-,E\n2113536,524288,L\n2637824,1179648,L\n3817472,,,-',
            android_boards.AndroidOrigenConfig().get_sfdisk_cmd())

    def test_origen_quad_android(self):
        self.assertEqual(
            '1,8191,0xDA\n8253,270274,0x0C,*\n278528,1835008,L\n'
            '2113536,-,E\n2113536,524288,L\n2637824,1179648,L\n3817472,,,-',
            android_boards.AndroidOrigenQuadConfig().get_sfdisk_cmd())

    def test_snowball_emmc_android(self):
        self.assertEqual(
            '256,7936,0xDA\n8192,262144,0x0C,*\n270336,1835008,L\n'
            '2105344,-,E\n2105344,524288,L\n2629632,1179648,L\n3809280,,,-',
            android_boards.AndroidSnowballEmmcConfig().get_sfdisk_cmd())

    def test_vexpress_android(self):
        self.assertEqual(
            '63,270272,0x0E,*\n270336,1835008,L\n2105344,524288,L\n'
            '2629632,-,E\n2629632,1179648,L\n3809280,,,-',
            android_boards.AndroidVexpressConfig().get_sfdisk_cmd())

    def test_mx5_android(self):
        self.assertEqual(
            '1,8191,0xDA\n8192,262144,0x0C,*\n270336,1835008,L\n'
            '2105344,-,E\n2105344,524288,L\n2629632,1179648,L\n3809280,,,-',
            android_boards.AndroidMx53LoCoConfig().get_sfdisk_cmd())

    def test_mx6_android(self):
        self.assertEqual(
            '1,8191,0xDA\n8192,262144,0x0C,*\n270336,1835008,L\n'
            '2105344,-,E\n2105344,524288,L\n2629632,1179648,L\n3809280,,,-',
            android_boards.AndroidMx6QSabreliteConfig().get_sfdisk_cmd())


class TestGetSfdiskCmdV2(TestCase):

    def test_mx5(self):
        board_conf = boards.Mx5Config()
        board_conf.partition_layout = 'reserved_bootfs_rootfs'
        self.assertEqual(
            '1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_snowball_sd(self):
        board_conf = boards.SnowballSdConfig()
        board_conf.partition_layout = 'bootfs_rootfs'
        self.assertEqual(
            '63,106432,0x0C,*\n106496,,,-',
            board_conf.get_sfdisk_cmd())

    def test_snowball_emmc(self):
        board_conf = boards.SnowballEmmcConfig()
        board_conf.partition_layout = 'reserved_bootfs_rootfs'
        board_conf.loader_start_s = (128 * 1024) / SECTOR_SIZE
        self.assertEqual(
            '256,7936,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_smdkv310(self):
        board_conf = get_board_config('smdkv310')
        board_conf.partition_layout = 'reserved_bootfs_rootfs'
        board_conf.LOADER_MIN_SIZE_S = (
            board_conf.samsung_bl1_start +
            board_conf.samsung_bl1_len +
            board_conf.samsung_bl2_len +
            board_conf.samsung_env_len)
        self.assertEquals(
            '1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_origen(self):
        board_conf = get_board_config('origen')
        board_conf.partition_layout = 'reserved_bootfs_rootfs'
        board_conf.LOADER_MIN_SIZE_S = (
            board_conf.samsung_bl1_start +
            board_conf.samsung_bl1_len +
            board_conf.samsung_bl2_len +
            board_conf.samsung_env_len)
        self.assertEquals(
            '1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_origen_quad(self):
        board_conf = get_board_config('origen_quad')
        board_conf.partition_layout = 'reserved_bootfs_rootfs'
        board_conf.LOADER_MIN_SIZE_S = (
            board_conf.samsung_bl1_start +
            board_conf.samsung_bl1_len +
            board_conf.samsung_bl2_len +
            board_conf.samsung_env_len)
        self.assertEquals(
            '1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_arndale(self):
        board_conf = get_board_config('arndale')
        board_conf.partition_layout = 'reserved_bootfs_rootfs'
        board_conf.LOADER_MIN_SIZE_S = (
            board_conf.samsung_bl1_start +
            board_conf.samsung_bl1_len +
            board_conf.samsung_bl2_len +
            board_conf.samsung_env_len)
        self.assertEquals(
            '1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-',
            board_conf.get_sfdisk_cmd())

    def test_highbank(self):
        board_conf = get_board_config('highbank')
        board_conf.partition_layout = 'bootfs_rootfs'
        self.assertEquals(
            '63,106432,0x83,*\n106496,,,-',
            board_conf.get_sfdisk_cmd())

    def test_beaglebone(self):
        board_conf = get_board_config('beaglebone')
        board_conf.partition_layout = 'bootfs_rootfs'
        self.assertEquals(
            '63,106432,0x0C,*\n106496,,,-',
            board_conf.get_sfdisk_cmd())

    def test_aa9(self):
        board_conf = get_board_config('aa9')
        board_conf.partition_layout = 'bootfs_rootfs'
        self.assertEquals(
            '63,106432,0x0C,*\n106496,,,-',
            board_conf.get_sfdisk_cmd())


class TestGetBootCmd(TestCase):

    def test_vexpress(self):
        board_conf = get_board_config('vexpress')
        boot_commands = board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=['ttyXXX'],
            rootfs_id="UUID=deadbeef", i_img_data="initrd", d_img_data=None)
        expected = {
            'bootargs': 'console=tty0 console=ttyAMA0,38400n8 '
                        'console=ttyXXX  root=UUID=deadbeef rootwait ro',
            'bootcmd': 'fatload mmc 0:1 0x60000000 uImage; '
                       'fatload mmc 0:1 0x62000000 uInitrd; '
                       'bootm 0x60000000 0x62000000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_vexpress_a9(self):
        board_conf = get_board_config('vexpress-a9')
        boot_commands = board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=['ttyXXX'],
            rootfs_id="UUID=deadbeef", i_img_data="initrd", d_img_data=None)
        expected = {
            'bootargs': 'console=tty0 console=ttyAMA0,38400n8 '
                        'console=ttyXXX  root=UUID=deadbeef rootwait ro',
            'bootcmd': 'fatload mmc 0:1 0x60000000 uImage; '
                       'fatload mmc 0:1 0x62000000 uInitrd; '
                       'bootm 0x60000000 0x62000000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_mx51(self):
        board_conf = boards.Mx51Config()
        boot_commands = board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd",
            d_img_data="mx51.dtb")
        expected = {
            'bootargs': 'console=tty0 console=ttymxc0,115200n8  '
                        'root=UUID=deadbeef rootwait ro',
            'bootcmd': 'fatload mmc 0:2 0x90000000 uImage; '
                       'fatload mmc 0:2 0x92000000 uInitrd; '
                       'fatload mmc 0:2 0x91ff0000 board.dtb; '
                       'bootm 0x90000000 0x92000000 0x91ff0000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_smdkv310(self):
        board_conf = get_board_config('smdkv310')
        boot_commands = board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd", d_img_data=None)
        expected = {
            'bootargs': 'console=ttySAC1,115200n8  root=UUID=deadbeef '
            'rootwait ro',
            'bootcmd': 'fatload mmc 0:2 0x40007000 uImage; '
            'fatload mmc 0:2 0x42000000 uInitrd; '
            'bootm 0x40007000 0x42000000',
            'ethact': 'smc911x-0',
            'ethaddr': '00:40:5c:26:0a:5b',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_origen(self):
        board_conf = get_board_config('origen')
        boot_commands = board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd", d_img_data=None)
        expected = {
            'bootargs': 'console=ttySAC2,115200n8  root=UUID=deadbeef '
            'rootwait ro',
            'bootcmd': 'fatload mmc 0:2 0x40007000 uImage; '
            'fatload mmc 0:2 0x42000000 uInitrd; '
            'bootm 0x40007000 0x42000000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_origen_quad(self):
        board_conf = get_board_config('origen_quad')
        boot_commands = board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd", d_img_data=None)
        expected = {
            'bootargs': 'console=ttySAC2,115200n8  root=UUID=deadbeef '
                        'rootwait ro',
            'bootcmd': 'fatload mmc 0:2 0x40007000 uImage; '
            'fatload mmc 0:2 0x42000000 uInitrd; '
            'bootm 0x40007000 0x42000000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_arndale(self):
        board_conf = get_board_config('arndale')
        boot_commands = board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd", d_img_data=None)
        expected = {
            'bootargs': 'root=UUID=deadbeef rootwait ro',
            'bootcmd': 'fatload mmc 0:2 None uImage; '
            'fatload mmc 0:2 None uInitrd; '
            'bootm None None',
            'ethact': 'smc911x-0',
            'ethaddr': '00:40:5c:26:0a:5b',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_ux500(self):
        board_conf = get_board_config('ux500')
        boot_commands = board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd", d_img_data=None)
        expected = {
            'bootargs': 'console=tty0 console=ttyAMA2,115200n8  '
                        'root=UUID=deadbeef rootwait ro earlyprintk '
                        'rootdelay=1 fixrtc nocompcache mem=96M@0 '
                        'mem_modem=32M@96M mem=44M@128M pmem=22M@172M '
                        'mem=30M@194M mem_mali=32M@224M pmem_hwb=54M@256M '
                        'hwmem=48M@302M mem=152M@360M',
            'bootcmd': 'fatload mmc 1:1 0x00100000 uImage; '
                       'fatload mmc 1:1 0x08000000 uInitrd; '
                       'bootm 0x00100000 0x08000000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_snowball_emmc(self):
        board_conf = get_board_config('snowball_emmc')
        boot_commands = board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd", d_img_data=None)
        expected = {
            'bootargs': 'console=tty0 console=ttyAMA2,115200n8  '
                        'root=UUID=deadbeef rootwait ro earlyprintk '
                        'rootdelay=1 fixrtc nocompcache mem=96M@0 '
                        'mem_modem=32M@96M mem=44M@128M pmem=22M@172M '
                        'mem=30M@194M mem_mali=32M@224M pmem_hwb=54M@256M '
                        'hwmem=48M@302M mem=152M@360M',
            'bootcmd': 'fatload mmc 0:2 0x00100000 uImage; '
                       'fatload mmc 0:2 0x08000000 uInitrd; '
                       'bootm 0x00100000 0x08000000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_panda(self):
        # XXX: To fix bug 697824 we have to change class attributes of our
        # OMAP board configs, and some tests do that so to make sure they
        # don't interfere with us we'll reset that before doing anything.
        config = get_board_config('panda')
        config.serial_tty = config._serial_tty
        boot_commands = config._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd",
            d_img_data="panda.dtb")
        expected = {
            'bootargs': 'console=tty0 console=ttyO2,115200n8  '
                        'root=UUID=deadbeef rootwait ro earlyprintk fixrtc '
                        'nocompcache vram=48M omapfb.vram=0:24M '
                        'mem=456M@0x80000000 mem=512M@0xA0000000',
            'bootcmd': 'fatload mmc 0:1 0x80200000 uImage; '
                       'fatload mmc 0:1 0x81600000 uInitrd; '
                       'fatload mmc 0:1 0x815f0000 board.dtb; '
                       'bootm 0x80200000 0x81600000 0x815f0000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_beagle(self):
        # XXX: To fix bug 697824 we have to change class attributes of our
        # OMAP board configs, and some tests do that so to make sure they
        # don't interfere with us we'll reset that before doing anything.
        config = get_board_config('beagle')
        config.serial_tty = config._serial_tty
        boot_commands = config._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd",
            d_img_data="beagle.dtb")
        expected = {
            'bootargs': 'console=tty0 console=ttyO2,115200n8  '
                        'root=UUID=deadbeef rootwait ro earlyprintk fixrtc '
                        'nocompcache vram=12M '
                        'omapfb.mode=dvi:1280x720MR-16@60 mpurate=${mpurate}',
            'bootcmd': 'fatload mmc 0:1 0x80000000 uImage; '
                       'fatload mmc 0:1 0x81600000 uInitrd; '
                       'fatload mmc 0:1 0x815f0000 board.dtb; '
                       'bootm 0x80000000 0x81600000 0x815f0000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_igep(self):
        # XXX: To fix bug 697824 we have to change class attributes of our
        # OMAP board configs, and some tests do that so to make sure they
        # don't interfere with us we'll reset that before doing anything.
        config = boards.IgepConfig()
        config.serial_tty = config._serial_tty
        boot_cmd = config._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd",
            d_img_data="igep.dtb")
        expected = {
            'bootargs': 'console=tty0 console=ttyO2,115200n8  '
                        'root=UUID=deadbeef rootwait ro earlyprintk fixrtc '
                        'nocompcache vram=12M '
                        'omapfb.mode=dvi:1280x720MR-16@60 mpurate=${mpurate}',
            'bootcmd': 'fatload mmc 0:1 0x80000000 uImage; '
                       'fatload mmc 0:1 0x81600000 uInitrd; '
                       'fatload mmc 0:1 0x815f0000 board.dtb; '
                       'bootm 0x80000000 0x81600000 0x815f0000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_cmd)

    def test_overo(self):
        # XXX: To fix bug 697824 we have to change class attributes of our
        # OMAP board configs, and some tests do that so to make sure they
        # don't interfere with us we'll reset that before doing anything.
        config = get_board_config('overo')
        config.serial_tty = config._serial_tty
        boot_commands = config._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd",
            d_img_data="overo.dtb")
        expected = {
            'bootargs': 'console=tty0 console=ttyO2,115200n8  '
                        'root=UUID=deadbeef rootwait ro earlyprintk '
                        'mpurate=${mpurate} vram=12M '
                        'omapdss.def_disp=${defaultdisplay} '
                        'omapfb.mode=dvi:${dvimode}',
            'bootcmd': 'fatload mmc 0:1 0x80000000 uImage; '
                       'fatload mmc 0:1 0x81600000 uInitrd; '
                       'fatload mmc 0:1 0x815f0000 board.dtb; '
                       'bootm 0x80000000 0x81600000 0x815f0000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_highbank(self):
        board_conf = get_board_config('highbank')
        boot_commands = board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd",
            d_img_data="board.dtb")
        expected = {
            'bootargs': 'root=UUID=deadbeef rootwait ro',
            'bootcmd': 'ext2load scsi 0:1 0x00800000 uImage; '
            'ext2load scsi 0:1 0x01000000 uInitrd; '
            'ext2load scsi 0:1 0x00001000 board.dtb; '
            'bootm 0x00800000 0x01000000 0x00001000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_beaglebone(self):
        config = get_board_config('beaglebone')
        config.serial_tty = config._serial_tty
        boot_commands = config._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd",
            d_img_data="board.dtb")
        expected = {
            'bootargs': 'console=ttyO0,115200n8  '
                        'root=UUID=deadbeef rootwait ro fixrtc',
            'bootcmd': 'fatload mmc 0:1 0x80200000 uImage; '
                       'fatload mmc 0:1 0x81600000 uInitrd; '
                       'fatload mmc 0:1 0x815f0000 board.dtb; '
                       'bootm 0x80200000 0x81600000 0x815f0000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)

    def test_aa9(self):
        config = get_board_config('aa9')
        config.serial_tty = config._serial_tty
        boot_commands = config._get_boot_env(
            is_live=False, is_lowmem=False, consoles=[],
            rootfs_id="UUID=deadbeef", i_img_data="initrd",
            d_img_data="board.dtb")
        expected = {
            'bootargs': 'console=ttyS0,115200n8  '
                        'root=UUID=deadbeef rootwait ro',
            'bootcmd': 'fatload mmc 0:1 0x40000000 uImage; '
                       'fatload mmc 0:1 0x41100000 uInitrd; '
                       'fatload mmc 0:1 0x41000000 board.dtb; '
                       'bootm 0x40000000 0x41100000 0x41000000',
            'fdt_high': '0xffffffff',
            'initrd_high': '0xffffffff'}
        self.assertEqual(expected, boot_commands)


class TestExtraBootCmd(TestCaseWithFixtures):

    def setUp(self):
        super(TestExtraBootCmd, self).setUp()
        self.board_conf = BoardConfig()

    def test_extra_boot_args_options_is_picked_by_get_boot_env(self):
        boot_args = 'whatever'

        self.board_conf.extra_boot_args_options = boot_args
        boot_commands = self.board_conf._get_boot_env(
            is_live=False, is_lowmem=False, consoles=['ttyXXX'],
            rootfs_id="UUID=deadbeef", i_img_data=None, d_img_data=None)
        expected = (
            'console=ttyXXX  root=UUID=deadbeef rootwait ro %s' % boot_args)
        self.assertEqual(expected, boot_commands['bootargs'])

    def test_passing_None_to_add_boot_args(self):
        boot_args = 'extra-args'

        self.board_conf.extra_boot_args_options = boot_args
        self.board_conf.add_boot_args(None)
        self.assertEqual(boot_args, self.board_conf.extra_boot_args_options)

    def test_passing_string_to_add_boot_args(self):
        boot_args = 'extra-args'
        extra_args = 'user-args'

        self.board_conf.extra_boot_args_options = boot_args
        self.board_conf.add_boot_args(extra_args)
        self.assertEqual(
            "%s %s" % (boot_args, extra_args),
            self.board_conf.extra_boot_args_options)

    def test_passing_string_to_add_boot_args_with_no_default_extra_args(self):
        extra_args = 'user-args'

        self.board_conf.add_boot_args(extra_args)
        self.assertEqual(extra_args, self.board_conf.extra_boot_args_options)

    def test_add_boot_args_from_file(self):
        boot_args = 'extra-args'
        extra_args = 'user-args'
        boot_arg_path = self.createTempFileAsFixture()
        with open(boot_arg_path, 'w') as boot_arg_file:
            boot_arg_file.write(extra_args)

        self.board_conf.extra_boot_args_options = boot_args
        self.board_conf.add_boot_args_from_file(boot_arg_path)
        self.assertEqual(
            "%s %s" % (boot_args, extra_args),
            self.board_conf.extra_boot_args_options)

    def test_passing_None_to_add_boot_args_from_file(self):
        boot_args = 'extra-args'

        self.board_conf.extra_boot_args_options = boot_args
        self.board_conf.add_boot_args_from_file(None)
        self.assertEqual(boot_args, self.board_conf.extra_boot_args_options)

    def test_add_boot_args_from_file_strips_whitespace_from_file(self):
        boot_args = 'extra-args'
        extra_args = 'user-args'
        boot_arg_path = self.createTempFileAsFixture()
        with open(boot_arg_path, 'w') as boot_arg_file:
            boot_arg_file.write('\n\n \t ' + extra_args + '  \n\n')

        self.board_conf.extra_boot_args_options = boot_args
        self.board_conf.add_boot_args_from_file(boot_arg_path)
        self.assertEqual(
            "%s %s" % (boot_args, extra_args),
            self.board_conf.extra_boot_args_options)


class TestUnpackBinaryTarball(TestCaseWithFixtures):

    def setUp(self):
        super(TestUnpackBinaryTarball, self).setUp()

        self.tar_dir_fixture = CreateTempDirFixture()
        self.useFixture(self.tar_dir_fixture)

        self.tarball_fixture = CreateTarballFixture(
            self.tar_dir_fixture.get_temp_dir())
        self.useFixture(self.tarball_fixture)

    def test_unpack_binary_tarball(self):
        tmp_dir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        rc = unpack_binary_tarball(
            self.tarball_fixture.get_tarball(), tmp_dir, as_root=False)
        self.assertEqual(rc, 0)


class TestGetUuid(TestCaseWithFixtures):

    def setUp(self):
        super(TestGetUuid, self).setUp()

    def test_get_uuid(self):
        fixture = MockCmdRunnerPopenFixture()
        self.useFixture(fixture)
        get_uuid("/dev/rootfs")
        self.assertEquals(
            ["%s blkid -o udev -p -c /dev/null /dev/rootfs" % sudo_args],
            fixture.mock.commands_executed)

    def test_parse_blkid_output(self):
        output = (
            "ID_FS_UUID=67d641db-ea7d-4acf-9f46-5f1f8275dce2\n"
            "ID_FS_UUID_ENC=67d641db-ea7d-4acf-9f46-5f1f8275dce2\n"
            "ID_FS_TYPE=ext4\n")
        uuid = _parse_blkid_output(output)
        self.assertEquals("67d641db-ea7d-4acf-9f46-5f1f8275dce2", uuid)


class TestBoards(TestCaseWithFixtures):

    def _mock_get_file_matching(self):
        self.useFixture(MockSomethingFixture(
            boards, '_get_file_matching',
            lambda regex: regex))

    def _mock_Popen(self):
        fixture = MockCmdRunnerPopenFixture()
        self.useFixture(fixture)
        return fixture

    def test_make_uImage(self):
        self._mock_get_file_matching()
        fixture = self._mock_Popen()
        make_uImage('load_addr', 'parts_dir/vmlinuz-*-sub_arch', 'boot_disk')
        expected = [
            '%s mkimage -A arm -O linux -T kernel -C none -a load_addr '
            '-e load_addr -n Linux -d parts_dir/vmlinuz-*-sub_arch '
            'boot_disk/uImage' % sudo_args]
        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_make_uInitrd(self):
        self._mock_get_file_matching()
        fixture = self._mock_Popen()
        make_uInitrd('parts_dir/initrd.img-*-sub_arch', 'boot_disk')
        expected = [
            '%s mkimage -A arm -O linux -T ramdisk -C none -a 0 -e 0 '
            '-n initramfs -d parts_dir/initrd.img-*-sub_arch '
            'boot_disk/uInitrd' % sudo_args]
        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_make_dtb(self):
        self._mock_get_file_matching()
        fixture = self._mock_Popen()
        make_dtb('parts_dir/dt-*-sub_arch/board_name.dtb', 'boot_disk')
        expected = [
            '%s cp parts_dir/dt-*-sub_arch/board_name.dtb '
            'boot_disk/board.dtb' % sudo_args]
        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_make_flashable_env_too_small_env(self):
        env = {'verylong': 'evenlonger'}
        self.assertRaises(AssertionError, make_flashable_env, env, 8)

    def test_make_flashable_env(self):
        env_file = self.createTempFileAsFixture()
        self.useFixture(MockSomethingFixture(
            tempfile, "mkstemp", lambda: (None, env_file)))
        env = {'a': 'b', 'x': 'y'}
        make_flashable_env(env, 12)
        with open(env_file, "r") as fd:
            self.assertEqual("\x80\x29\x2E\x89a=b\x00x=y\x00", fd.read())

    def test_install_mx5_boot_loader(self):
        fixture = self._mock_Popen()
        imx_file = self.createTempFileAsFixture()
        install_mx5_boot_loader(imx_file, "boot_device_or_file",
                                BoardConfig.LOADER_MIN_SIZE_S)
        expected = [
            '%s dd if=%s of=boot_device_or_file bs=512 '
            'conv=notrunc seek=2' % (sudo_args, imx_file)]
        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_install_mx5_boot_loader_too_large(self):
        self.useFixture(MockSomethingFixture(
            os.path, "getsize",
            lambda s: (BoardConfig.LOADER_MIN_SIZE_S - 1) * SECTOR_SIZE + 1))
        self.assertRaises(
            AssertionError,
            install_mx5_boot_loader, "imx_file", "boot_device_or_file",
            BoardConfig.LOADER_MIN_SIZE_S)

    def test_install_omap_boot_loader(self):
        fixture = self._mock_Popen()
        self.useFixture(MockSomethingFixture(
            boards, '_get_mlo_file',
            lambda chroot_dir: "%s/MLO" % chroot_dir))

        board_conf = BoardConfig()
        board_conf.set_metadata([])
        install_omap_boot_loader("chroot_dir", "boot_disk", board_conf)
        expected = [
            '%s cp -v chroot_dir/MLO boot_disk' % sudo_args]
        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_install_smdk_u_boot(self):
        fixture = self._mock_Popen()
        board_conf = boards.SMDKV310Config()
        bootloader_flavor = board_conf.bootloader_flavor
        self.useFixture(MockSomethingFixture(os.path, 'getsize',
                                             lambda file: 1))
        board_conf.install_samsung_boot_loader(
            "%s/%s/SPL" % ("chroot_dir", bootloader_flavor),
            "%s/%s/uboot" % ("chroot_dir", bootloader_flavor), "boot_disk")
        expected = [
            '%s dd if=chroot_dir/%s/SPL of=boot_disk bs=512 conv=notrunc '
            'seek=%d' % (sudo_args, bootloader_flavor,
                         board_conf.samsung_bl1_start),
            '%s dd if=chroot_dir/%s/uboot of=boot_disk bs=512 conv=notrunc '
            'seek=%d' % (sudo_args, bootloader_flavor,
                         board_conf.samsung_bl2_start)]
        self.assertEqual(expected, fixture.mock.commands_executed)

    def _set_up_board_config(self, board_name):
        """Internal method to set-up correctly board config, with the
        appropriate mock objects.

        :param board_name: The name of the board to set-up.
        :return A 3-tuple: the config, the name of the bootloader, and the
        value of chroot_dir.
        """
        board_conf = get_board_config(board_name)
        bootloader_flavor = board_conf.bootloader_flavor
        # Made-up value to be used as the chroot directory.
        chroot_dir_value = 'chroot_dir'
        board_conf._get_samsung_spl = MagicMock()
        board_conf._get_samsung_spl.return_value = ("%s/%s/SPL" %
                                                    (chroot_dir_value,
                                                     bootloader_flavor))
        board_conf._get_samsung_bootloader = MagicMock()
        board_conf._get_samsung_bootloader.return_value = ("%s/%s/uboot" %
                                                           (chroot_dir_value,
                                                            bootloader_flavor))
        board_conf.hardwarepack_handler = (
            TestSetMetadata.MockHardwarepackHandler('ahwpack.tar.gz'))
        board_conf.hardwarepack_handler.get_format = (
            lambda: HardwarepackHandler.FORMAT_1)
        return board_conf, bootloader_flavor, chroot_dir_value

    def test_install_origen_u_boot(self):
        fixture = self._mock_Popen()
        board_conf, bootloader_flavor, chroot_dir_value = \
            self._set_up_board_config('origen')
        self.useFixture(MockSomethingFixture(os.path, 'getsize',
                                             lambda file: 1))
        board_conf.install_samsung_boot_loader(
            board_conf._get_samsung_spl(chroot_dir_value),
            board_conf._get_samsung_bootloader(chroot_dir_value),
            "boot_disk")
        expected = [
            '%s dd if=chroot_dir/%s/SPL of=boot_disk bs=512 conv=notrunc '
            'seek=%d' % (sudo_args, bootloader_flavor,
                         board_conf.samsung_bl1_start),
            '%s dd if=chroot_dir/%s/uboot of=boot_disk bs=512 conv=notrunc '
            'seek=%d' % (sudo_args, bootloader_flavor,
                         board_conf.samsung_bl2_start)]
        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_install_origen_quad_u_boot(self):
        fixture = self._mock_Popen()
        board_conf, bootloader_flavor, chroot_dir_value = \
            self._set_up_board_config('origen_quad')
        self.useFixture(MockSomethingFixture(os.path, 'getsize',
                                             lambda file: 1))
        board_conf.install_samsung_boot_loader(
            board_conf._get_samsung_spl(chroot_dir_value),
            board_conf._get_samsung_bootloader(chroot_dir_value),
            "boot_disk")
        expected = [
            '%s dd if=chroot_dir/%s/SPL of=boot_disk bs=512 conv=notrunc '
            'seek=%d' % (sudo_args, bootloader_flavor,
                         board_conf.samsung_bl1_start),
            '%s dd if=chroot_dir/%s/uboot of=boot_disk bs=512 conv=notrunc '
            'seek=%d' % (sudo_args, bootloader_flavor,
                         board_conf.samsung_bl2_start)]
        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_install_arndale_u_boot(self):
        fixture = self._mock_Popen()
        board_conf, bootloader_flavor, chroot_dir_value = \
            self._set_up_board_config('arndale')
        self.useFixture(MockSomethingFixture(os.path, 'getsize',
                                             lambda file: 1))
        board_conf.install_samsung_boot_loader(
            board_conf._get_samsung_spl(chroot_dir_value),
            board_conf._get_samsung_bootloader(chroot_dir_value),
            "boot_disk")
        expected = [
            '%s dd if=chroot_dir/%s/SPL of=boot_disk bs=512 conv=notrunc '
            'seek=%d' % (sudo_args, bootloader_flavor,
                         board_conf.samsung_bl1_start),
            '%s dd if=chroot_dir/%s/uboot of=boot_disk bs=512 conv=notrunc '
            'seek=%d' % (sudo_args, bootloader_flavor,
                         board_conf.samsung_bl2_start)]
        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_get_plain_boot_script_contents(self):
        boot_env = {'bootargs': 'mybootargs', 'bootcmd': 'mybootcmd',
                    'initrd_high': '0xffffffff', 'fdt_high': '0xffffffff'}
        boot_script_data = get_plain_boot_script_contents(boot_env)
        self.assertEqual(textwrap.dedent("""\
            setenv initrd_high "0xffffffff"
            setenv fdt_high "0xffffffff"
            setenv bootcmd "mybootcmd"
            setenv bootargs "mybootargs"
            boot"""), boot_script_data)

    def test_make_boot_script(self):
        self.useFixture(MockSomethingFixture(
            tempfile, 'mkstemp', lambda: (-1, '/tmp/random-abxzr')))
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        self._mock_get_file_matching()
        fixture = self._mock_Popen()
        boot_script_path = os.path.join(tempdir, 'boot.scr')
        plain_boot_script_path = os.path.join(tempdir, 'boot.txt')
        boot_env = {'bootargs': 'mybootargs', 'bootcmd': 'mybootcmd',
                    'initrd_high': '0xffffffff', 'fdt_high': '0xffffffff'}
        make_boot_script(boot_env, boot_script_path)
        expected = [
            '%s cp /tmp/random-abxzr %s' % (
                sudo_args, plain_boot_script_path),
            '%s mkimage -A arm -O linux -T script -C none -a 0 -e 0 '
            '-n boot script -d %s %s' % (
                sudo_args, plain_boot_script_path, boot_script_path)]
        self.assertEqual(expected, fixture.mock.commands_executed)

    def test_get_file_matching(self):
        prefix = ''.join(
            random.choice(string.ascii_lowercase) for x in range(5))
        file1 = self.createTempFileAsFixture(prefix)
        directory = os.path.dirname(file1)
        self.assertEqual(
            file1, _get_file_matching('%s/%s*' % (directory, prefix)))

    def test_get_file_matching_too_many_files_found(self):
        prefix = ''.join(
            random.choice(string.ascii_lowercase) for x in range(5))
        file1 = self.createTempFileAsFixture(prefix)
        file2 = self.createTempFileAsFixture(prefix)
        directory = os.path.dirname(file1)
        assert directory == os.path.dirname(file2), (
            "file1 and file2 should be in the same directory")
        self.assertRaises(
            ValueError, _get_file_matching, '%s/%s*' % (directory, prefix))

    def test_get_kflavor_files_more_specific(self):
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        flavorx = 'flavorX'
        flavorxy = 'flavorXY'

        board_conf = BoardConfig()
        board_conf.kernel_flavors = [flavorx, flavorxy]
        for f in reversed(board_conf.kernel_flavors):
            kfile = os.path.join(tempdir, 'vmlinuz-1-%s' % f)
            ifile = os.path.join(tempdir, 'initrd.img-1-%s' % f)
            open(kfile, "w").close()
            open(ifile, "w").close()
        self.assertEqual(
            (kfile, ifile, None), board_conf._get_kflavor_files(tempdir))

    def test_get_dt_kflavor_files_more_specific(self):
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        flavorx = 'flavorX'
        flavorxy = 'flavorXY'

        board_conf = BoardConfig()
        board_conf.kernel_flavors = [flavorx, flavorxy]
        board_conf.dtb_name = 'board_name.dtb'
        for f in reversed(board_conf.kernel_flavors):
            kfile = os.path.join(tempdir, 'vmlinuz-1-%s' % f)
            ifile = os.path.join(tempdir, 'initrd.img-1-%s' % f)
            dt = os.path.join(tempdir, 'dt-1-%s' % f)
            os.mkdir(dt)
            dfile = os.path.join(dt, board_conf.dtb_name)
            open(kfile, "w").close()
            open(ifile, "w").close()
            open(dfile, "w").close()
        self.assertEqual(
            (kfile, ifile, dfile), board_conf._get_kflavor_files(tempdir))

    def test_get_kflavor_files_later_in_flavors(self):
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        flavor1 = 'flavorXY'
        flavor2 = 'flavorAA'

        board_conf = BoardConfig()
        board_conf.kernel_flavors = [flavor1, flavor2]
        kfile = os.path.join(tempdir, 'vmlinuz-1-%s' % flavor1)
        ifile = os.path.join(tempdir, 'initrd.img-1-%s' % flavor1)
        open(kfile, "w").close()
        open(ifile, "w").close()
        self.assertEqual(
            (kfile, ifile, None), board_conf._get_kflavor_files(tempdir))

    def test_get_dt_kflavor_files_later_in_flavors(self):
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        flavor1 = 'flavorXY'
        flavor2 = 'flavorAA'

        board_conf = BoardConfig()
        board_conf.kernel_flavors = [flavor1, flavor2]
        board_conf.dtb_name = 'board_name.dtb'
        kfile = os.path.join(tempdir, 'vmlinuz-1-%s' % flavor1)
        ifile = os.path.join(tempdir, 'initrd.img-1-%s' % flavor1)
        dt = os.path.join(tempdir, 'dt-1-%s' % flavor1)
        os.mkdir(dt)
        dfile = os.path.join(dt, board_conf.dtb_name)
        open(kfile, "w").close()
        open(ifile, "w").close()
        open(dfile, "w").close()
        self.assertEqual(
            (kfile, ifile, dfile), board_conf._get_kflavor_files(tempdir))

    def test_get_kflavor_files_raises_when_no_match(self):
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        flavor1 = 'flavorXY'
        flavor2 = 'flavorAA'

        board_conf = BoardConfig()
        board_conf.kernel_flavors = [flavor1, flavor2]
        self.assertRaises(ValueError, board_conf._get_kflavor_files, tempdir)

    def test_get_file_matching_no_files_found(self):
        self.assertEqual(
            None, _get_file_matching('/foo/bar/baz/*non-existent'))

    def test_run_mkimage(self):
        # Create a fake boot script.
        filename = self.createTempFileAsFixture()
        f = open(filename, 'w')
        f.write("setenv bootcmd 'fatload mmc 0:1 0x80000000 uImage;\nboot")
        f.close()

        img = self.createTempFileAsFixture()
        # Use that fake boot script to create a boot loader using mkimage.
        # Send stdout to /dev/null as mkimage will print to stdout and we
        # don't want that.
        retval = _run_mkimage(
            'script', '0', '0', 'boot script', filename, img,
            stdout=open('/dev/null', 'w'), as_root=False)

        self.assertEqual(0, retval)


class TestCreatePartitions(TestCaseWithFixtures):

    media = Media('/dev/xdz')

    def setUp(self):
        super(TestCreatePartitions, self).setUp()
        # Stub time.sleep() as create_partitions() use that.
        self.orig_sleep = time.sleep
        time.sleep = lambda s: None

    def tearDown(self):
        super(TestCreatePartitions, self).tearDown()
        time.sleep = self.orig_sleep

    def test_create_partitions_for_mx5(self):
        # For this board we create a one cylinder partition at the beginning.
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        sfdisk_fixture = self.useFixture(MockRunSfdiskCommandsFixture())

        board_conf = boards.Mx5Config()
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        create_partitions(board_conf, self.media)

        self.assertEqual(
            ['%s parted -s %s mklabel msdos' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path)],
            popen_fixture.mock.commands_executed)
        # Notice that we create all partitions in a single sfdisk run because
        # every time we run sfdisk it actually repartitions the device,
        # erasing any partitions created previously.
        self.assertEqual(
            [('1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-', self.media.path)],
            sfdisk_fixture.mock.calls)

    def test_create_partitions_for_smdkv310(self):
        # For this board we create a one cylinder partition at the beginning.
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        sfdisk_fixture = self.useFixture(MockRunSfdiskCommandsFixture())

        board_conf = get_board_config('smdkv310')
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        create_partitions(board_conf, self.media)

        self.assertEqual(
            ['%s parted -s %s mklabel msdos' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path)],
            popen_fixture.mock.commands_executed)
        # Notice that we create all partitions in a single sfdisk run because
        # every time we run sfdisk it actually repartitions the device,
        # erasing any partitions created previously.
        self.assertEqual(
            [('1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-', self.media.path)],
            sfdisk_fixture.mock.calls)

    def test_create_partitions_for_origen(self):
        # For this board we create a one cylinder partition at the beginning.
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        sfdisk_fixture = self.useFixture(MockRunSfdiskCommandsFixture())

        board_conf = get_board_config('origen')
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        create_partitions(board_conf, self.media)

        self.assertEqual(
            ['%s parted -s %s mklabel msdos' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path)],
            popen_fixture.mock.commands_executed)
        # Notice that we create all partitions in a single sfdisk run because
        # every time we run sfdisk it actually repartitions the device,
        # erasing any partitions created previously.
        self.assertEqual(
            [('1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-', self.media.path)],
            sfdisk_fixture.mock.calls)

    def test_create_partitions_for_origen_quad(self):
        # For this board we create a one cylinder partition at the beginning.
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        sfdisk_fixture = self.useFixture(MockRunSfdiskCommandsFixture())

        board_conf = get_board_config('origen_quad')
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        create_partitions(
            board_conf, self.media)

        self.assertEqual(
            ['%s parted -s %s mklabel msdos' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path)],
            popen_fixture.mock.commands_executed)
        # Notice that we create all partitions in a single sfdisk run because
        # every time we run sfdisk it actually repartitions the device,
        # erasing any partitions created previously.
        self.assertEqual(
            [('1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-', self.media.path)],
            sfdisk_fixture.mock.calls)

    def test_create_partitions_for_arndale(self):
        # For this board we create a one cylinder partition at the beginning.
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        sfdisk_fixture = self.useFixture(MockRunSfdiskCommandsFixture())

        board_conf = get_board_config('arndale')
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        create_partitions(
            board_conf, self.media)

        self.assertEqual(
            ['%s parted -s %s mklabel msdos' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path)],
            popen_fixture.mock.commands_executed)
        # Notice that we create all partitions in a single sfdisk run because
        # every time we run sfdisk it actually repartitions the device,
        # erasing any partitions created previously.
        self.assertEqual(
            [('1,8191,0xDA\n8192,106496,0x0C,*\n114688,,,-', self.media.path)],
            sfdisk_fixture.mock.calls)

    def test_create_partitions_for_beagle(self):
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        sfdisk_fixture = self.useFixture(MockRunSfdiskCommandsFixture())

        board_conf = get_board_config('beagle')
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        create_partitions(board_conf, self.media)

        self.assertEqual(
            ['%s parted -s %s mklabel msdos' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path),
             '%s sfdisk -l %s' % (sudo_args, self.media.path)],
            popen_fixture.mock.commands_executed)
        self.assertEqual(
            [('63,106432,0x0C,*\n106496,,,-', self.media.path)],
            sfdisk_fixture.mock.calls)

    def test_create_partitions_with_img_file(self):
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        sfdisk_fixture = self.useFixture(MockRunSfdiskCommandsFixture())

        tmpfile = self.createTempFileAsFixture()
        board_conf = get_board_config('beagle')
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1
        create_partitions(board_conf, Media(tmpfile))

        # Unlike the test for partitioning of a regular block device, in this
        # case parted was not called as there's no existing partition table
        # for us to overwrite on the image file.
        self.assertEqual(
            ['%s sfdisk -l %s' % (sudo_args, tmpfile),
             '%s sfdisk -l %s' % (sudo_args, tmpfile)],
            popen_fixture.mock.commands_executed)

        self.assertEqual(
            [('63,106432,0x0C,*\n106496,,,-', tmpfile)],
            sfdisk_fixture.mock.calls)

    def test_run_sfdisk_commands(self):
        tmpfile = self.createTempFileAsFixture()
        proc = cmd_runner.run(
            ['dd', 'of=%s' % tmpfile, 'bs=1', 'seek=10M', 'count=0'],
            stderr=open('/dev/null', 'w'))
        proc.communicate()
        stdout, stderr = run_sfdisk_commands(
            '2,16063,0xDA', tmpfile, as_root=False,
            stderr=subprocess.PIPE)
        self.assertIn('Successfully wrote the new partition table', stdout)

    def test_run_sfdisk_commands_raises_on_non_zero_returncode(self):
        tmpfile = self.createTempFileAsFixture()
        self.assertRaises(
            cmd_runner.SubcommandNonZeroReturnValue,
            run_sfdisk_commands,
            ',1,0xDA', tmpfile, as_root=False,
            stderr=subprocess.PIPE)

    def test_wait_partitions_to_settle(self):
        class Namespace:
            pass

        ns = Namespace()
        ns.count = 0

        class MockCmdRunnerPopen(object):
            def __call__(self, cmd, *args, **kwargs):
                ns.count += 1
                self.returncode = 0
                if ns.count < 5:
                    raise cmd_runner.SubcommandNonZeroReturnValue(args, 1)
                else:
                    return self

            def communicate(self, input=None):
                self.wait()
                return '', ''

            def wait(self):
                return self.returncode

        self.useFixture(MockCmdRunnerPopenFixture())

        tmpfile = self.createTempFileAsFixture()
        media = Media(tmpfile)
        media.is_block_device = True

        self.assertEqual(0, wait_partition_to_settle(media, 'mbr'))

    def test_wait_partitions_to_settle_raises_SubcommandNonZeroReturnValue(
            self):
        def mock_run(args, as_root=False, chroot=None, stdin=None, stdout=None,
                     stderr=None, cwd=None):
            raise cmd_runner.SubcommandNonZeroReturnValue(args, 1)

        self.useFixture(MockSomethingFixture(
            cmd_runner, 'run',
            mock_run))

        tmpfile = self.createTempFileAsFixture()
        media = Media(tmpfile)
        media.is_block_device = True

        self.assertRaises(cmd_runner.SubcommandNonZeroReturnValue,
                          wait_partition_to_settle, media, 'mbr')


class TestPartitionSetup(TestCaseWithFixtures):

    def setUp(self):
        super(TestPartitionSetup, self).setUp()
        # Stub time.sleep() as create_partitions() use that.
        self.orig_sleep = time.sleep
        time.sleep = lambda s: None
        self.linux_image_size = 30 * 1024 ** 2
        self.linux_offsets_and_sizes = [
            (16384 * SECTOR_SIZE, 15746 * SECTOR_SIZE),
            (32768 * SECTOR_SIZE, (self.linux_image_size -
                                   32768 * SECTOR_SIZE))
        ]
        self.android_image_size = 256 * 1024 ** 2
        # Extended partition info takes 32 sectors from the first ext partition
        ext_part_size = 32
        self.android_offsets_and_sizes = [
            (63 * SECTOR_SIZE, 32768 * SECTOR_SIZE),
            (32831 * SECTOR_SIZE, 65536 * SECTOR_SIZE),
            (98367 * SECTOR_SIZE, 65536 * SECTOR_SIZE),
            ((294944 + ext_part_size) * SECTOR_SIZE,
             (131103 - ext_part_size) * SECTOR_SIZE),
            ((426016 + ext_part_size) * SECTOR_SIZE,
             self.android_image_size - (426016 + ext_part_size) * SECTOR_SIZE)
        ]

        self.android_snowball_offsets_and_sizes = [
            (8192 * SECTOR_SIZE, 24639 * SECTOR_SIZE),
            (32831 * SECTOR_SIZE, 65536 * SECTOR_SIZE),
            ((98367 + ext_part_size) * SECTOR_SIZE,
             (65536 - ext_part_size) * SECTOR_SIZE),
            (294975 * SECTOR_SIZE, 131072 * SECTOR_SIZE),
            ((426047 + ext_part_size) * SECTOR_SIZE,
             self.android_image_size - (426047 + ext_part_size) * SECTOR_SIZE)
        ]

    def tearDown(self):
        super(TestPartitionSetup, self).tearDown()
        time.sleep = self.orig_sleep

    def _create_tmpfile(self):
        # boot part at +8 MiB, root part at +16 MiB
        return self._create_qemu_img_with_partitions(
            '16384,15746,0x0C,*\n32768,,,-', '%s' % self.linux_image_size)

    def _create_android_tmpfile(self):
        # boot, system, cache, (extended), userdata and sdcard partitions
        return self._create_qemu_img_with_partitions(
            '63,32768,0x0C,*\n32831,65536,L\n98367,65536,L\n294975,-,E\n'
            '294975,131072,L\n426047,,,-', '%s' % self.android_image_size)

    def _create_snowball_android_tmpfile(self):
        # raw, boot, system, cache, (extended), userdata and sdcard partitions
        return self._create_qemu_img_with_partitions(
            '256,7936,0xDA\n8192,24639,0x0C,*\n32831,65536,L\n'
            '98367,-,E\n98367,65536,L\n294975,131072,L\n'
            '426047,,,-', '%s' % self.android_image_size)

    def test_check_min_size_small(self):
        """Check that we get back the minimum size as expeceted."""
        self.assertEqual(MIN_IMAGE_SIZE, _check_min_size(12345))

    def test_check_min_size_big(self):
        """Check that we get back the same value we pass."""
        self.assertEqual(MIN_IMAGE_SIZE * 3, _check_min_size(3145728))

    def test_convert_size_wrong_suffix(self):
        self.assertRaises(ValueError, get_partition_size_in_bytes, "123456H")

    def test_convert_size_no_suffix(self):
        self.assertEqual(2 ** 20, get_partition_size_in_bytes('123456'))

    def test_convert_size_one_mbyte(self):
        self.assertEqual(2 ** 20, get_partition_size_in_bytes('1M'))

    def test_convert_size_in_kbytes_to_bytes(self):
        self.assertEqual(2 * 2 ** 20, get_partition_size_in_bytes('2048K'))

    def test_convert_size_in_mbytes_to_bytes(self):
        self.assertEqual(100 * 2 ** 20, get_partition_size_in_bytes('100M'))

    def test_convert_size_in_gbytes_to_bytes(self):
        self.assertEqual(12 * 2 ** 30, get_partition_size_in_bytes('12G'))

    def test_convert_size_float_no_suffix(self):
        self.assertEqual(3 * 2 ** 20,
                         get_partition_size_in_bytes('2348576.91'))

    def test_convert_size_float_in_kbytes_to_bytes(self):
        self.assertEqual(3 * 2 ** 20, get_partition_size_in_bytes('2345.8K'))

    def test_convert_size_float_in_mbytes_to_bytes_double(self):
        self.assertEqual(2 * 2 ** 20,
                         get_partition_size_in_bytes('1.0000001M'))

    def test_convert_size_float_in_mbytes_to_bytes(self):
        self.assertEqual(877 * 2 ** 20,
                         get_partition_size_in_bytes('876.123M'))

    def test_convert_size_float_in_gbytes_to_bytes(self):
        self.assertEqual(1946 * 2 ** 20, get_partition_size_in_bytes('1.9G'))

    def test_calculate_partition_size_and_offset(self):
        tmpfile = self._create_tmpfile()
        vfat_size, vfat_offset, linux_size, linux_offset = (
            calculate_partition_size_and_offset(tmpfile))
        self.assertEqual(
            self.linux_offsets_and_sizes,
            [(vfat_offset, vfat_size), (linux_offset, linux_size)])

    def test_calculate_android_partition_size_and_offset(self):
        tmpfile = self._create_android_tmpfile()
        device_info = calculate_android_partition_size_and_offset(tmpfile)
        # We use map(None, ...) since it would catch if the lists are not of
        # equal length and zip() would not in all cases.
        for device_pair, expected_pair in map(None, device_info,
                                              self.android_offsets_and_sizes):
            self.assertEqual(device_pair, expected_pair)

    def test_calculate_snowball_android_partition_size_and_offset(self):
        tmpfile = self._create_snowball_android_tmpfile()
        device_info = calculate_android_partition_size_and_offset(tmpfile)
        # We use map(None, ...) since it would catch if the lists are not of
        # equal length and zip() would not in all cases.
        snowball_info = map(None, device_info,
                            self.android_snowball_offsets_and_sizes)
        for device_pair, expected_pair in snowball_info:
            self.assertEqual(device_pair, expected_pair)

    def test_partition_numbering(self):
        # another Linux partition at +24 MiB after the boot/root parts
        tmpfile = self._create_qemu_img_with_partitions(
            '16384,15746,0x0C,*\n32768,15427,,-\n49152,,,-',
            '%s' % self.linux_image_size)
        vfat_size, vfat_offset, linux_size, linux_offset = (
            calculate_partition_size_and_offset(tmpfile))
        # check that the linux partition offset starts at +16 MiB so that it's
        # the partition immediately following the vfat one
        self.assertEqual(linux_offset, 32768 * 512)

    def test_get_boot_and_root_partitions_for_media_beagle(self):
        self.useFixture(MockSomethingFixture(
            partitions, '_get_device_file_for_partition_number',
            lambda dev, partition: '%s%d' % (tmpfile, partition)))
        tmpfile = self.createTempFileAsFixture()
        media = Media(tmpfile)
        media.is_block_device = True
        self.assertEqual(
            ("%s%d" % (tmpfile, 1), "%s%d" % (tmpfile, 2)),
            get_boot_and_root_partitions_for_media(
                media, get_board_config('beagle')))

    def test_get_boot_and_root_partitions_for_media_mx5(self):
        self.useFixture(MockSomethingFixture(
            partitions, '_get_device_file_for_partition_number',
            lambda dev, partition: '%s%d' % (tmpfile, partition)))
        tmpfile = self.createTempFileAsFixture()
        media = Media(tmpfile)
        media.is_block_device = True
        self.assertEqual(
            ("%s%d" % (tmpfile, 2), "%s%d" % (tmpfile, 3)),
            get_boot_and_root_partitions_for_media(media, boards.Mx5Config()))

    def _create_qemu_img_with_partitions(self, sfdisk_commands, tempfile_size):
        tmpfile = self.createTempFileAsFixture()
        proc = cmd_runner.run(
            ['dd', 'of=%s' % tmpfile, 'bs=1', 'seek=%s' % tempfile_size,
             'count=0'],
            stderr=open('/dev/null', 'w'))
        proc.communicate()
        stdout, stderr = run_sfdisk_commands(
            sfdisk_commands, tmpfile, as_root=False,
            # Throw away stderr as sfdisk complains a lot when operating on a
            # qemu image.
            stderr=subprocess.PIPE)
        self.assertIn('Successfully wrote the new partition table', stdout)
        return tmpfile

    def test_ensure_partition_is_not_mounted_for_mounted_partition(self):
        self.useFixture(MockSomethingFixture(
            partitions, 'is_partition_mounted', lambda part: True))
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        ensure_partition_is_not_mounted('/dev/whatever')
        self.assertEqual(
            ['%s umount /dev/whatever' % sudo_args],
            popen_fixture.mock.commands_executed)

    def test_ensure_partition_is_not_mounted_for_umounted_partition(self):
        self.useFixture(MockSomethingFixture(
            partitions, 'is_partition_mounted', lambda part: False))
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        ensure_partition_is_not_mounted('/dev/whatever')
        self.assertEqual(None, popen_fixture.mock.calls)

    def test_get_boot_and_root_loopback_devices(self):
        tmpfile = self._create_tmpfile()
        atexit_fixture = self.useFixture(MockSomethingFixture(
            atexit, 'register', AtExitRegister()))
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        # We can't test the return value of get_boot_and_root_loopback_devices
        # because it'd require running losetup as root, so we just make sure
        # it calls losetup correctly.
        get_boot_and_root_loopback_devices(tmpfile)
        self.assertEqual(
            ['%s losetup -f --show %s --offset %s --sizelimit %s'
                % (sudo_args, tmpfile, offset, size) for (offset, size) in
             self.linux_offsets_and_sizes],
            popen_fixture.mock.commands_executed)

        # get_boot_and_root_loopback_devices will also setup two exit handlers
        # to de-register the loopback devices set up above.
        self.assertEqual(2, len(atexit_fixture.mock.funcs))
        popen_fixture.mock.calls = []
        atexit_fixture.mock.run_funcs()
        # We did not really run losetup above (as it requires root) so here we
        # don't have a device to pass to 'losetup -d', but when a device is
        # setup it is passed to the atexit handler.
        self.assertEquals(
            ['%s losetup -d ' % sudo_args,
             '%s losetup -d ' % sudo_args],
            popen_fixture.mock.commands_executed)

    def test_get_android_loopback_devices(self):
        tmpfile = self._create_android_tmpfile()
        atexit_fixture = self.useFixture(MockSomethingFixture(
            atexit, 'register', AtExitRegister()))
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        # We can't test the return value of get_boot_and_root_loopback_devices
        # because it'd require running losetup as root, so we just make sure
        # it calls losetup correctly.
        get_android_loopback_devices(tmpfile)
        self.assertEqual(
            ['%s losetup -f --show %s --offset %s --sizelimit %s'
                % (sudo_args, tmpfile, offset, size) for (offset, size) in
             self.android_offsets_and_sizes],
            popen_fixture.mock.commands_executed)

        # get_boot_and_root_loopback_devices will also setup two exit handlers
        # to de-register the loopback devices set up above.
        self.assertEqual(5, len(atexit_fixture.mock.funcs))
        popen_fixture.mock.calls = []
        atexit_fixture.mock.run_funcs()
        # We did not really run losetup above (as it requires root) so here we
        # don't have a device to pass to 'losetup -d', but when a device is
        # setup it is passed to the atexit handler.
        self.assertEquals(
            ['%s losetup -d ' % sudo_args,
             '%s losetup -d ' % sudo_args,
             '%s losetup -d ' % sudo_args,
             '%s losetup -d ' % sudo_args,
             '%s losetup -d ' % sudo_args],
            popen_fixture.mock.commands_executed)

    def test_setup_partitions_for_image_file(self):
        # In practice we could pass an empty image file to setup_partitions,
        # but here we mock Popen() and thanks to that the image is not setup
        # (via dd) inside setup_partitions.  That's why we pass an
        # already setup image file.
        tmpfile = self._create_tmpfile()
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))

        def ensure_partition_not_mounted(part):
            raise AssertionError(
                "ensure_partition_is_not_mounted must not be called when "
                "generating image files. It makes no sense to do that and "
                "it depends on UDisks, thus making it hard to run on a "
                "chroot")
        self.useFixture(MockSomethingFixture(
            partitions,
            'ensure_partition_is_not_mounted', ensure_partition_not_mounted))
        self.useFixture(MockSomethingFixture(
            partitions, 'get_boot_and_root_loopback_devices',
            lambda image: ('/dev/loop99', '/dev/loop98')))

        board_conf = get_board_config('beagle')
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1

        bootfs_dev, rootfs_dev = setup_partitions(
            board_conf, Media(tmpfile), '2G', 'boot',
            'root', 'ext3', True, True, True)
        self.assertEqual(
            # This is the call that would create a 2 GiB image file.
            ['dd of=%s bs=1 seek=2147483648 count=0' % tmpfile,
             '%s sfdisk -l %s' % (sudo_args, tmpfile),
             # This call would partition the image file.
             '%s sfdisk --force -uS %s' % (sudo_args, tmpfile),
             # Make sure changes are written to disk.
             '%s sfdisk -l %s' % (sudo_args, tmpfile),
             '%s mkfs.vfat -F 32 %s -n boot' % (sudo_args, bootfs_dev),
             '%s mkfs.ext3 -F %s -L root' % (sudo_args, rootfs_dev)],
            popen_fixture.mock.commands_executed)

    def test_setup_partitions_for_block_device(self):
        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))
        # Pretend the partitions are mounted.
        self.useFixture(MockSomethingFixture(
            partitions, 'is_partition_mounted', lambda part: True))
        tmpfile = self._create_tmpfile()
        self.useFixture(MockSomethingFixture(
            partitions, '_get_device_file_for_partition_number',
            lambda dev, partition: '%s%d' % (tmpfile, partition)))
        media = Media(tmpfile)
        # Pretend our tmpfile is a block device.
        media.is_block_device = True
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())

        board_conf = get_board_config('beagle')
        board_conf.hwpack_format = HardwarepackHandler.FORMAT_1

        bootfs_dev, rootfs_dev = setup_partitions(
            board_conf, media, '2G', 'boot', 'root', 'ext3',
            True, True, True)
        self.assertEqual(
            ['%s parted -s %s mklabel msdos' % (sudo_args, tmpfile),
             '%s sfdisk -l %s' % (sudo_args, tmpfile),
             '%s sfdisk --force -uS %s' % (sudo_args, tmpfile),
             '%s sfdisk -l %s' % (sudo_args, tmpfile),
             # Since the partitions are mounted, setup_partitions will umount
             # them before running mkfs.
             '%s umount %s' % (sudo_args, bootfs_dev),
             '%s umount %s' % (sudo_args, rootfs_dev),
             '%s mkfs.vfat -F 32 %s -n boot' % (sudo_args, bootfs_dev),
             '%s mkfs.ext3 -F %s -L root' % (sudo_args, rootfs_dev)],
            popen_fixture.mock.commands_executed)

    def test_get_device_file_for_partition_number_raises_DBusException(self):
        def mock_get_udisks_device_path(d):
            raise dbus.exceptions.DBusException

        self.useFixture(MockSomethingFixture(
            partitions, '_get_udisks_device_path',
            mock_get_udisks_device_path))

        tmpfile = self.createTempFileAsFixture()
        partition = get_board_config('beagle').mmc_part_offset

        self.useFixture(MockSomethingFixture(
            glob, 'glob',
            lambda pathname: ['%s%d' % (tmpfile, partition)]))

        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))

        media = Media(tmpfile)
        media.is_block_device = True
        self.assertRaises(dbus.exceptions.DBusException,
                          _get_device_file_for_partition_number,
                          media.path, partition)

    def test_get_device_file_for_partition_number(self):
        class Namespace:
            pass
        ns = Namespace()
        ns.count = 0

        def mock_get_udisks_device_path(dev):
            ns.count += 1
            if ns.count < 5:
                raise dbus.exceptions.DBusException
            else:
                return '/abc/123'

        def mock_get_udisks_device_file(dev, part):
            if ns.count < 5:
                raise dbus.exceptions.DBusException
            else:
                return '/abc/123'

        self.useFixture(MockSomethingFixture(
            partitions, '_get_udisks_device_path',
            mock_get_udisks_device_path))

        self.useFixture(MockSomethingFixture(
            partitions, '_get_udisks_device_file',
            mock_get_udisks_device_file))

        tmpfile = self.createTempFileAsFixture()
        partition = get_board_config('beagle').mmc_part_offset

        self.useFixture(MockSomethingFixture(
            glob, 'glob',
            lambda pathname: ['%s%d' % (tmpfile, partition)]))

        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))

        media = Media(tmpfile)
        media.is_block_device = True
        self.assertIsNotNone(_get_device_file_for_partition_number(
            media.path, partition))


class TestException(Exception):
    """Just a test exception."""


class TestMountedPartitionContextManager(TestCaseWithFixtures):

    def test_basic(self):
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())

        def test_func():
            with partition_mounted('foo', 'bar', '-t', 'proc'):
                pass
        test_func()
        expected = ['%s mount foo bar -t proc' % sudo_args,
                    '%s umount bar' % sudo_args]
        self.assertEqual(expected, popen_fixture.mock.commands_executed)

    def test_exception_raised_inside_with_block(self):
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())

        def test_func():
            with partition_mounted('foo', 'bar'):
                raise TestException('something')
        try:
            test_func()
        except TestException:
            pass
        expected = ['%s mount foo bar' % sudo_args,
                    '%s umount bar' % sudo_args]
        self.assertEqual(expected, popen_fixture.mock.commands_executed)

    def test_umount_failure(self):
        # We ignore a SubcommandNonZeroReturnValue from umount because
        # otherwise it could shadow an exception raised inside the 'with'
        # block.
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())

        def failing_umount(path):
            raise cmd_runner.SubcommandNonZeroReturnValue('umount', 1)
        self.useFixture(MockSomethingFixture(
            partitions, 'umount', failing_umount))

        def test_func():
            with partition_mounted('foo', 'bar'):
                pass
        test_func()
        expected = ['sudo -E mount foo bar']
        self.assertEqual(expected, popen_fixture.mock.commands_executed)


class TestPopulateBoot(TestCaseWithFixtures):

    expected_args = (
        'chroot_dir/boot', False, False, [], 'chroot_dir', 'rootfs_id',
        'boot_disk', 'boot_device_or_file')
    expected_args_live = (
        'chroot_dir/casper', True, False, [], 'chroot_dir', 'rootfs_id',
        'boot_disk', 'boot_device_or_file')
    expected_calls = [
        'mkdir -p boot_disk',
        '%s mount boot_partition boot_disk' % sudo_args,
        '%s umount boot_disk' % sudo_args]

    def save_args(self, *args):
        self.saved_args = args

    def prepare_config(self, config):
        self.config = config
        self.config.boot_script = 'boot_script'
        self.config.hardwarepack_handler = \
            TestSetMetadata.MockHardwarepackHandler('ahwpack.tar.gz')
        self.config.hardwarepack_handler.get_format = \
            lambda: HardwarepackHandler.FORMAT_1
        self.popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        self.useFixture(MockSomethingFixture(
            self.config, 'make_boot_files', self.save_args))
        self.config.hardwarepack_handler.get_file_from_package = \
            self.get_file_from_package
        self.config.bootloader_copy_files = None

    def get_file_from_package(self, source_path, source_package):
        if source_package in self.config.bootloader_copy_files:
            for file_info in self.config.bootloader_copy_files[source_package]:
                if source_path in file_info:
                    return source_path
        return None

    def prepare_config_v3(self, config):
        self.config = config
        self.config.boot_script = 'boot_script'
        self.config.hardwarepack_handler = \
            TestSetMetadata.MockHardwarepackHandler('ahwpack.tar.gz')
        self.config.hardwarepack_handler.get_format = lambda: '3.0'
        self.config.hardwarepack_handler.get_file = \
            lambda file_alias: ['file1', 'file2']
        self.config.hardwarepack_handler.get_file_from_package = \
            self.get_file_from_package
        self.config.bootloader_copy_files = {
            "package1":
            [{"file1": "/boot/"},
             {"file2": "/boot/grub/renamed"}]}

        self.popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        self.useFixture(MockSomethingFixture(
            self.config, 'make_boot_files', self.save_args))

    def call_populate_boot(self, config, is_live=False):
        config.populate_boot(
            'chroot_dir', 'rootfs_id', 'boot_partition', 'boot_disk',
            'boot_device_or_file', is_live, False, [])

    def test_populate_boot_live(self):
        self.prepare_config(BoardConfig())
        self.call_populate_boot(self.config, is_live=True)
        self.assertEquals(
            self.expected_calls, self.popen_fixture.mock.commands_executed)
        self.assertEquals(self.expected_args_live, self.saved_args)

    def test_populate_boot_regular(self):
        self.prepare_config(BoardConfig())
        self.call_populate_boot(self.config)
        self.assertEquals(
            self.expected_calls, self.popen_fixture.mock.commands_executed)
        self.assertEquals(self.expected_args, self.saved_args)

    def test_populate_boot_bootloader_flavor(self):
        self.prepare_config(BoardConfig())
        self.config.bootloader_flavor = "bootloader_flavor"
        self.call_populate_boot(self.config)
        self.assertEquals(
            self.expected_calls, self.popen_fixture.mock.commands_executed)
        self.assertEquals(self.expected_args, self.saved_args)

    def test_populate_boot_bootloader_file_in_boot_part(self):
        self.prepare_config(BoardConfig())
        self.config.bootloader_flavor = "bootloader_flavor"
        self.config.bootloader_file_in_boot_part = True
        self.config.bootloader = "u_boot"
        self.call_populate_boot(self.config)
        expected_calls = self.expected_calls[:]
        expected_calls.insert(
            2,
            '%s cp -v chroot_dir/usr/lib/u-boot/bootloader_flavor/u-boot.bin '
            'boot_disk' % sudo_args)
        self.assertEquals(
            expected_calls, self.popen_fixture.mock.commands_executed)
        self.assertEquals(self.expected_args, self.saved_args)

    def test_populate_boot_bootloader_file_in_boot_part_false(self):
        self.prepare_config(BoardConfig())
        self.config.bootloader_flavor = "bootloader_flavor"
        self.config.bootloader_file_in_boot_part = False
        self.call_populate_boot(self.config)
        expected_calls = self.expected_calls[:]
        self.assertEquals(
            expected_calls, self.popen_fixture.mock.commands_executed)
        self.assertEquals(self.expected_args, self.saved_args)

    def test_populate_bootloader_copy_files(self):
        self.prepare_config_v3(BoardConfig())
        self.config.bootloader_flavor = "bootloader_flavor"
        # Test that copy_files works per spec (puts stuff in boot partition)
        # even if bootloader not in_boot_part.
        self.config.bootloader_file_in_boot_part = False
        self.call_populate_boot(self.config)
        expected_calls = self.expected_calls[:]
        expected_calls.insert(2, '%s mkdir -p boot_disk/boot' % sudo_args)
        expected_calls.insert(3,
                              '%s cp -v file1 '
                              'boot_disk/boot/' % sudo_args)
        expected_calls.insert(4, '%s mkdir -p boot_disk/boot/grub' % sudo_args)
        expected_calls.insert(5,
                              '%s cp -v file2 '
                              'boot_disk/boot/grub/renamed' % sudo_args)
        self.assertEquals(
            expected_calls, self.popen_fixture.mock.commands_executed)
        self.assertEquals(self.expected_args, self.saved_args)

    def test_populate_bootloader_copy_files_bootloader_set(self):
        self.prepare_config_v3(BoardConfig())
        self.config.bootloader_flavor = "bootloader_flavor"
        # Test that copy_files works per spec (puts stuff in boot partition)
        # even if bootloader not in_boot_part.
        self.config.bootloader_file_in_boot_part = False
        self.config.bootloader = "u_boot"
        self.call_populate_boot(self.config)
        expected_calls = self.expected_calls[:]
        expected_calls.insert(2, '%s mkdir -p boot_disk/boot' % sudo_args)
        expected_calls.insert(3,
                              '%s cp -v file1 '
                              'boot_disk/boot/' % sudo_args)
        expected_calls.insert(4, '%s mkdir -p boot_disk/boot/grub' % sudo_args)
        expected_calls.insert(5,
                              '%s cp -v file2 '
                              'boot_disk/boot/grub/renamed' % sudo_args)
        self.assertEquals(
            expected_calls, self.popen_fixture.mock.commands_executed)
        self.assertEquals(self.expected_args, self.saved_args)

    def test_populate_boot_no_bootloader_flavor(self):
        self.prepare_config(BoardConfig())
        self.config.bootloader_file_in_boot_part = True
        self.assertRaises(
            AssertionError, self.call_populate_boot, self.config)


class TestPopulateRootFS(TestCaseWithFixtures):

    lines_added_to_fstab = None
    create_flash_kernel_config_called = False

    def test_populate_rootfs(self):
        def fake_append_to_fstab(disk, additions):
            self.lines_added_to_fstab = additions

        def fake_create_flash_kernel_config(disk, mmc_device_id,
                                            partition_offset):
            self.create_flash_kernel_config_called = True

        # Mock stdout, cmd_runner.Popen(), append_to_fstab and
        # create_flash_kernel_config.
        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))
        self.useFixture(MockSomethingFixture(
            rootfs, 'append_to_fstab', fake_append_to_fstab))
        self.useFixture(MockSomethingFixture(
            rootfs, 'create_flash_kernel_config',
            fake_create_flash_kernel_config))
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        # Store a dummy rootdisk and contents_dir in a tempdir.
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        root_disk = os.path.join(tempdir, 'rootdisk')
        contents_dir = os.path.join(tempdir, 'contents')
        contents_bin = os.path.join(contents_dir, 'bin')
        contents_etc = os.path.join(contents_dir, 'etc')
        os.makedirs(contents_bin)
        os.makedirs(contents_etc)

        # Must mock rootfs._list_files() because populate_rootfs() uses its
        # return value but since we mock cmd_runner.run() _list_files() would
        # return an invalid value.
        def mock_list_files(directory):
            return [contents_bin, contents_etc]
        self.useFixture(MockSomethingFixture(
            rootfs, '_list_files', mock_list_files))

        populate_rootfs(
            contents_dir, root_disk, partition='/dev/rootfs',
            rootfs_type='ext3', rootfs_id='UUID=uuid', should_create_swap=True,
            swap_size=100, mmc_device_id=0, partition_offset=0,
            os_release_id='ubuntu', board_config=None)

        self.assertEqual(
            ['UUID=uuid / ext3  errors=remount-ro 0 1',
             '/SWAP.swap  none  swap  sw  0 0'],
            self.lines_added_to_fstab)
        self.assertEqual(True, self.create_flash_kernel_config_called)
        swap_file = os.path.join(root_disk, 'SWAP.swap')
        expected = [
            '%s mount /dev/rootfs %s' % (sudo_args, root_disk),
            '%s mv %s %s %s' % (
                sudo_args, contents_bin, contents_etc, root_disk),
            '%s dd if=/dev/zero of=%s bs=1M count=100' % (
                sudo_args, swap_file),
            '%s mkswap %s' % (sudo_args, swap_file),
            '%s umount %s' % (sudo_args, root_disk)]
        self.assertEqual(expected, popen_fixture.mock.commands_executed)

    def test_create_flash_kernel_config(self):
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir

        create_flash_kernel_config(tempdir, mmc_device_id=0,
                                   boot_partition_number=1)

        calls = fixture.mock.calls
        self.assertEqual(1, len(calls), calls)
        call = calls[0]
        # The call writes to a tmpfile and then moves it to the,
        # /etc/flash-kernel.conf, so the tmpfile is the next to last in the
        # list of arguments stored.
        tmpfile = call[-2]
        self.assertEqual(
            '%s mv -f %s %s/etc/flash-kernel.conf' % (
                sudo_args, tmpfile, tempdir),
            fixture.mock.commands_executed[0])
        self.assertEqual('UBOOT_PART=/dev/mmcblk0p1',
                         open(tmpfile).read().rstrip())

    def test_list_files(self):
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        # We don't want to mock cmd_runner.run() because we're testing the
        # command that it runs, but we need to monkey-patch SUDO_ARGS because
        # we don't want to use 'sudo' in tests.
        orig_sudo_args = cmd_runner.SUDO_ARGS

        def restore_sudo_args():
            cmd_runner.SUDO_ARGS = orig_sudo_args
        self.addCleanup(restore_sudo_args)
        cmd_runner.SUDO_ARGS = []
        file1 = self.createTempFileAsFixture(dir=tempdir)
        self.assertEqual([file1], rootfs._list_files(tempdir))

    def test_move_contents(self):
        tempdir = self.useFixture(CreateTempDirFixture()).tempdir
        popen_fixture = self.useFixture(MockCmdRunnerPopenFixture())
        file1 = self.createTempFileAsFixture(dir=tempdir)

        def mock_list_files(directory):
            return [file1]
        self.useFixture(MockSomethingFixture(
            rootfs, '_list_files', mock_list_files))

        move_contents(tempdir, '/tmp/')

        self.assertEqual(['%s mv %s /tmp/' % (sudo_args, file1)],
                         popen_fixture.mock.commands_executed)

    def test_has_space_left_for_swap(self):
        statvfs = os.statvfs('/')
        space_left = statvfs.f_bavail * statvfs.f_bsize
        swap_size_in_megs = space_left / (1024 ** 2)
        self.assertTrue(
            has_space_left_for_swap('/', swap_size_in_megs))

    def test_has_no_space_left_for_swap(self):
        statvfs = os.statvfs('/')
        space_left = statvfs.f_bavail * statvfs.f_bsize
        swap_size_in_megs = (space_left / (1024 ** 2)) + 1
        self.assertFalse(
            has_space_left_for_swap('/', swap_size_in_megs))

    def mock_write_data_to_protected_file(self, path, data):
        # Duplicate of write_data_to_protected_file() but does not sudo.
        _, tmpfile = tempfile.mkstemp()
        with open(tmpfile, 'w') as fd:
            fd.write(data)
            cmd_runner.run(['mv', '-f', tmpfile, path], as_root=False).wait()

    def test_update_interfaces_no_interfaces_no_update(self):
        self.useFixture(MockSomethingFixture(
            rootfs, 'write_data_to_protected_file',
            self.mock_write_data_to_protected_file))
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        os.makedirs(os.path.join(tempdir, 'etc', 'network'))
        if_path = os.path.join(tempdir, 'etc', 'network', 'interfaces')

        update_network_interfaces(tempdir, BoardConfig())
        self.assertFalse(os.path.exists(if_path))

    def test_update_interfaces_creates_entry(self):
        self.useFixture(MockSomethingFixture(
            rootfs, 'write_data_to_protected_file',
            self.mock_write_data_to_protected_file))
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        os.makedirs(os.path.join(tempdir, 'etc', 'network'))
        if_path = os.path.join(tempdir, 'etc', 'network', 'interfaces')

        board_conf = BoardConfig()
        board_conf.wired_interfaces = ['eth0']

        expected = 'auto eth0\n' \
            'iface eth0 inet dhcp\n'
        update_network_interfaces(tempdir, board_conf)
        self.assertEqual(expected, open(if_path).read())

    def test_update_interfaces_creates_entries(self):
        self.useFixture(MockSomethingFixture(
            rootfs, 'write_data_to_protected_file',
            self.mock_write_data_to_protected_file))
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        os.makedirs(os.path.join(tempdir, 'etc', 'network'))
        if_path = os.path.join(tempdir, 'etc', 'network', 'interfaces')

        board_conf = BoardConfig()
        board_conf.wired_interfaces = ['eth0', 'eth1']
        board_conf.wireless_interfaces = ['wlan0']

        expected = 'auto %(if)s\n' \
            'iface %(if)s inet dhcp\n'

        update_network_interfaces(tempdir, board_conf)
        self.assertIn(expected % {'if': 'eth1'}, open(if_path).read())
        self.assertIn(expected % {'if': 'eth0'}, open(if_path).read())
        self.assertIn(expected % {'if': 'wlan0'}, open(if_path).read())

    def test_update_interfaces_leaves_original(self):
        self.useFixture(MockSomethingFixture(
            rootfs, 'write_data_to_protected_file',
            self.mock_write_data_to_protected_file))
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        os.makedirs(os.path.join(tempdir, 'etc', 'network'))
        if_path = os.path.join(tempdir, 'etc', 'network', 'interfaces')
        with open(if_path, 'w') as interfaces:
            interfaces.write('Original contents of file.\n')

        board_conf = BoardConfig()
        board_conf.wired_interfaces = ['eth0']

        expected = 'Original contents of file.\n' \
            'auto eth0\n' \
            'iface eth0 inet dhcp\n'
        update_network_interfaces(tempdir, board_conf)
        self.assertEqual(expected, open(if_path).read())

    def test_write_data_to_protected_file(self):
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        data = 'foo'
        path = '/etc/nonexistant'

        write_data_to_protected_file(path, data)

        calls = fixture.mock.calls
        self.assertEqual(1, len(calls), calls)
        call = calls[0]
        # The call moves tmpfile to the given path, so tmpfile is the next to
        # last in the list of arguments stored.
        tmpfile = call[-2]
        self.assertEqual(['%s mv -f %s %s' % (sudo_args, tmpfile, path)],
                         fixture.mock.commands_executed)
        self.assertEqual(data, open(tmpfile).read())

    def test_rootfs_mount_options_for_btrfs(self):
        self.assertEqual("defaults", rootfs_mount_options('btrfs'))

    def test_rootfs_mount_options_for_ext4(self):
        self.assertEqual("errors=remount-ro", rootfs_mount_options('ext4'))

    def test_rootfs_mount_options_for_unknown(self):
        self.assertRaises(ValueError, rootfs_mount_options, 'unknown')

    def test_append_to_fstab(self):
        tempdir = self.useFixture(CreateTempDirFixture()).get_temp_dir()
        # we don't really need root (sudo) as we're not writing to a real
        # root owned /etc
        self.useFixture(MockSomethingFixture(os, 'getuid', lambda: 0))
        etc = os.path.join(tempdir, 'etc')
        os.mkdir(etc)
        fstab = os.path.join(etc, 'fstab')
        open(fstab, "w").close()
        append_to_fstab(tempdir, ['foo', 'bar'])
        f = open(fstab)
        contents = f.read()
        f.close()
        self.assertEquals("\nfoo\nbar\n", contents)


class TestCheckDevice(TestCaseWithFixtures):

    def _mock_does_device_exist_true(self):
        self.useFixture(MockSomethingFixture(
            check_device, '_does_device_exist', lambda device: True))

    def _mock_does_device_exist_false(self):
        self.useFixture(MockSomethingFixture(
            check_device, '_does_device_exist', lambda device: False))

    def _mock_print_devices(self):
        self.useFixture(MockSomethingFixture(
            check_device, '_print_devices', lambda: None))

    def _mock_select_device(self):
        self.useFixture(MockSomethingFixture(
            check_device, '_select_device', lambda device: True))

    def _mock_deselect_device(self):
        self.useFixture(MockSomethingFixture(
            check_device, '_select_device', lambda device: False))

    def _mock_sys_stdout(self):
        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open(os.devnull, 'w')))

    def setUp(self):
        super(TestCheckDevice, self).setUp()
        self._mock_sys_stdout()
        self._mock_print_devices()

    def test_ensure_device_partitions_not_mounted(self):
        partitions_umounted = []

        def ensure_partition_is_not_mounted_mock(part):
            partitions_umounted.append(part)
        self.useFixture(MockSomethingFixture(
            partitions, 'ensure_partition_is_not_mounted',
            ensure_partition_is_not_mounted_mock))
        self.useFixture(MockSomethingFixture(
            glob, 'glob', lambda pattern: ['/dev/sdz1', '/dev/sdz2']))
        check_device._ensure_device_partitions_not_mounted('/dev/sdz')
        self.assertEquals(['/dev/sdz1', '/dev/sdz2'], partitions_umounted)

    def test_check_device_and_select(self):
        self._mock_does_device_exist_true()
        self._mock_select_device()
        self.assertTrue(
            check_device.confirm_device_selection_and_ensure_it_is_ready(
                None))

    def test_check_device_and_deselect(self):
        self._mock_does_device_exist_true()
        self._mock_deselect_device()
        self.assertFalse(
            check_device.confirm_device_selection_and_ensure_it_is_ready(
                None))

    def test_check_device_not_found(self):
        self._mock_does_device_exist_false()
        self.assertFalse(
            check_device.confirm_device_selection_and_ensure_it_is_ready(
                None))


class AtExitRegister(object):

    funcs = None

    def __call__(self, func, *args, **kwargs):
        if self.funcs is None:
            self.funcs = []
        self.funcs.append((func, args, kwargs))

    def run_funcs(self):
        for func, args, kwargs in self.funcs:
            func(*args, **kwargs)


class TestInstallHWPack(TestCaseWithFixtures):
    def create_minimal_v3_hwpack(self, location, name, version, architecture):
        metadata = "\n".join([
            "name: " + name,
            "version: " + version,
            "architecture: " + architecture,
            "format: 3.0"
        ])
        print metadata
        tar_file = tarfile.open(location, mode='w:gz')
        tarinfo = tarfile.TarInfo("metadata")
        tarinfo.size = len(metadata)
        tar_file.addfile(tarinfo, StringIO(metadata))
        tar_file.close()

    def mock_prepare_chroot(self, chroot_dir, tmp_dir):
        def fake_prepare_chroot(chroot_dir, tmp_dir):
            cmd_runner.run(['prepare_chroot %s %s' % (chroot_dir, tmp_dir)],
                           as_root=True).wait()
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.chroot_utils, 'prepare_chroot',
            fake_prepare_chroot))

    def test_temporarily_overwrite_file_on_dir(self):
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        temporarily_overwrite_file_on_dir('/path/to/file', '/dir', '/tmp/dir')
        self.assertEquals(
            ['%s cp -a /path/to/file /dir' % sudo_args],
            fixture.mock.commands_executed)

        fixture.mock.calls = []
        run_local_atexit_funcs()
        self.assertEquals(
            ['%s rm -f /dir/file' % sudo_args],
            fixture.mock.commands_executed)

    def test_copy_file(self):
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        copy_file('/path/to/file', '/dir')
        self.assertEquals(
            ['%s cp /path/to/file /dir' % sudo_args],
            fixture.mock.commands_executed)

        fixture.mock.calls = []
        run_local_atexit_funcs()
        self.assertEquals(
            ['%s rm -f /dir/file' % sudo_args],
            fixture.mock.commands_executed)

    def test_mount_chroot_proc(self):
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        mount_chroot_proc('chroot')
        self.assertEquals(
            ['%s mount proc chroot/proc -t proc' % sudo_args],
            fixture.mock.commands_executed)

        fixture.mock.calls = []
        run_local_atexit_funcs()
        self.assertEquals(
            ['%s umount -v chroot/proc' % sudo_args],
            fixture.mock.commands_executed)

    def test_install_hwpack(self):
        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        chroot_dir = 'chroot_dir'
        hwpack_dir = tempfile.mkdtemp()
        hwpack_file_name = 'hwpack.tgz'
        hwpack_tgz_location = os.path.join(hwpack_dir, hwpack_file_name)
        hwpack_name = "foo"
        hwpack_version = "4"
        hwpack_architecture = "armel"
        extract_kpkgs = False
        self.create_minimal_v3_hwpack(hwpack_tgz_location, hwpack_name,
                                      hwpack_version, hwpack_architecture)
        force_yes = False
        install_hwpack(chroot_dir, hwpack_tgz_location,
                       extract_kpkgs, force_yes, 'linaro-hwpack-install')
        self.assertEquals(
            ['%s cp %s %s' % (sudo_args, hwpack_tgz_location, chroot_dir),
             '%s %s %s linaro-hwpack-install --hwpack-version %s '
             '--hwpack-arch %s --hwpack-name %s /%s'
                % (sudo_args, chroot_args, chroot_dir,
                   hwpack_version, hwpack_architecture, hwpack_name,
                   hwpack_file_name)],
            fixture.mock.commands_executed)

        fixture.mock.calls = []
        run_local_atexit_funcs()
        self.assertEquals(
            ['%s rm -f %s/hwpack.tgz' % (sudo_args, chroot_dir)],
            fixture.mock.commands_executed)

    def test_install_hwpack_extract(self):
        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        chroot_dir = 'chroot_dir'
        hwpack_dir = tempfile.mkdtemp()
        hwpack_file_name = 'hwpack.tgz'
        hwpack_tgz_location = os.path.join(hwpack_dir, hwpack_file_name)
        hwpack_name = "foo"
        hwpack_version = "4"
        hwpack_architecture = "armel"
        extract_kpkgs = True
        self.create_minimal_v3_hwpack(hwpack_tgz_location, hwpack_name,
                                      hwpack_version, hwpack_architecture)
        force_yes = False
        install_hwpack(chroot_dir, hwpack_tgz_location,
                       extract_kpkgs, force_yes, 'linaro-hwpack-install')
        self.assertEquals(
            ['%s cp %s %s' % (sudo_args, hwpack_tgz_location, chroot_dir),
             '%s linaro-hwpack-install --hwpack-version %s '
             '--hwpack-arch %s --hwpack-name %s --extract-kernel-only %s/%s'
                % (sudo_args, hwpack_version, hwpack_architecture, hwpack_name,
                   chroot_dir, hwpack_file_name)],
            fixture.mock.commands_executed)

        fixture.mock.calls = []
        run_local_atexit_funcs()
        self.assertEquals(
            ['%s rm -f %s/hwpack.tgz' % (sudo_args, chroot_dir)],
            fixture.mock.commands_executed)

    def test_install_hwpacks(self):
        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        chroot_dir = 'chroot_dir'
        tmp_dir = 'tmp_dir'
        self.mock_prepare_chroot(chroot_dir, tmp_dir)
        force_yes = True

        prefer_dir = preferred_tools_dir()

        hwpack_dir = tempfile.mkdtemp()
        hwpack_file_names = ['hwpack1.tgz', 'hwpack2.tgz']
        hwpack_tgz_locations = []
        hwpack_names = []
        extract_kpkgs = False
        for hwpack_file_name in hwpack_file_names:
            hwpack_tgz_location = os.path.join(hwpack_dir, hwpack_file_name)
            hwpack_tgz_locations.append(hwpack_tgz_location)
            hwpack_names.append(hwpack_file_name)
            hwpack_version = "4"
            hwpack_architecture = "armel"
            self.create_minimal_v3_hwpack(
                hwpack_tgz_location, hwpack_file_name, hwpack_version,
                hwpack_architecture)

        install_hwpacks(
            chroot_dir, tmp_dir, prefer_dir, force_yes, [], extract_kpkgs,
            hwpack_tgz_locations[0], hwpack_tgz_locations[1])
        linaro_hwpack_install = find_command(
            'linaro-hwpack-install', prefer_dir=prefer_dir)
        expected = [
            'prepare_chroot %(chroot_dir)s %(tmp_dir)s',
            'cp %(linaro_hwpack_install)s %(chroot_dir)s/usr/bin',
            'mount proc %(chroot_dir)s/proc -t proc',
            'chroot %(chroot_dir)s true',
            'cp %(hwpack1)s %(chroot_dir)s',
            ('%(chroot_args)s %(chroot_dir)s linaro-hwpack-install '
             '--hwpack-version %(hp_version)s '
             '--hwpack-arch %(hp_arch)s --hwpack-name %(hp_name1)s'
             ' --force-yes /hwpack1.tgz'),
            'cp %(hwpack2)s %(chroot_dir)s',
            ('%(chroot_args)s %(chroot_dir)s linaro-hwpack-install '
             '--hwpack-version %(hp_version)s '
             '--hwpack-arch %(hp_arch)s --hwpack-name %(hp_name2)s'
             ' --force-yes /hwpack2.tgz'),
            'rm -f %(chroot_dir)s/hwpack2.tgz',
            'rm -f %(chroot_dir)s/hwpack1.tgz',
            'umount -v %(chroot_dir)s/proc',
            'rm -f %(chroot_dir)s/usr/bin/linaro-hwpack-install']
        keywords = dict(
            chroot_dir=chroot_dir, tmp_dir=tmp_dir, chroot_args=chroot_args,
            linaro_hwpack_install=linaro_hwpack_install,
            hwpack1=hwpack_tgz_locations[0],
            hwpack2=hwpack_tgz_locations[1],
            hp_version=hwpack_version, hp_name1=hwpack_names[0],
            hp_name2=hwpack_names[1], hp_arch=hwpack_architecture)
        expected = [
            "%s %s" % (sudo_args, line % keywords) for line in expected]
        self.assertEquals(expected, fixture.mock.commands_executed)

    def test_install_packages(self):
        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))
        fixture = self.useFixture(MockCmdRunnerPopenFixture())
        chroot_dir = 'chroot_dir'
        tmp_dir = 'tmp_dir'
        self.mock_prepare_chroot(chroot_dir, tmp_dir)

        install_packages(chroot_dir, tmp_dir, 'pkg1', 'pkg2')
        expected = [
            'prepare_chroot %(chroot_dir)s %(tmp_dir)s',
            'mount proc %(chroot_dir)s/proc -t proc',
            '%(chroot_args)s %(chroot_dir)s apt-get --yes install pkg1 pkg2',
            '%(chroot_args)s %(chroot_dir)s apt-get clean',
            'umount -v %(chroot_dir)s/proc']
        keywords = dict(
            chroot_dir=chroot_dir, tmp_dir=tmp_dir, chroot_args=chroot_args)
        expected = [
            "%s %s" % (sudo_args, line % keywords) for line in expected]
        self.assertEquals(expected, fixture.mock.commands_executed)

    def test_prepare_chroot(self):
        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))
        fixture = self.useFixture(MockCmdRunnerPopenFixture())

        prepare_chroot('chroot', '/tmp/dir')
        run_local_atexit_funcs()
        expected = [
            'cp -a /etc/resolv.conf chroot/etc',
            'cp -a /etc/hosts chroot/etc',
            'cp /usr/bin/qemu-armeb-static chroot/usr/bin',
            'cp /usr/bin/qemu-arm-static chroot/usr/bin',
            'cp /usr/bin/qemu-aarch64-static chroot/usr/bin',
            'rm -f chroot/usr/bin/qemu-aarch64-static',
            'rm -f chroot/usr/bin/qemu-arm-static',
            'rm -f chroot/usr/bin/qemu-armeb-static',
            'rm -f chroot/etc/hosts',
            'rm -f chroot/etc/resolv.conf']
        expected = [
            "%s %s" % (sudo_args, line) for line in expected]
        self.assertEquals(expected, fixture.mock.commands_executed)

    def test_run_local_atexit_funcs(self):
        self.useFixture(MockSomethingFixture(
            sys, 'stderr', open('/dev/null', 'w')))
        self.call_order = []

        class TestException(Exception):
            pass

        def raising_func():
            self.call_order.append('raising_func')
            raise TestException()

        def behaving_func():
            self.call_order.append('behaving_func')
            self.behaving_func_called = True
        # run_local_atexit_funcs() runs the atexit handlers in LIFO order, but
        # even though the first function called (raising_func) will raise
        # an exception, the second one will still be called after it.
        linaro_image_tools.media_create.chroot_utils.local_atexit = [
            behaving_func, raising_func]
        # run_local_atexit_funcs() also propagates the last exception raised
        # by one of the functions.
        chroot_utils = linaro_image_tools.media_create.chroot_utils
        self.assertRaises(TestException, chroot_utils.run_local_atexit_funcs)
        self.assertEquals(
            ['raising_func', 'behaving_func'], self.call_order)

    def test_hwpack_atexit(self):
        self.run_local_atexit_functions_called = False

        def mock_run_local_atexit_functions():
            self.run_local_atexit_functions_called = True

        def mock_install_hwpack(p1, p2, p3, p4):
            raise Exception('hwpack mock exception')

        self.useFixture(MockSomethingFixture(
            sys, 'stdout', open('/dev/null', 'w')))
        self.useFixture(MockCmdRunnerPopenFixture())
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.chroot_utils, 'install_hwpack',
            mock_install_hwpack))
        self.useFixture(MockSomethingFixture(
            linaro_image_tools.media_create.chroot_utils,
            'run_local_atexit_funcs',
            mock_run_local_atexit_functions))

        force_yes = True
        exception_caught = False
        extract_kpkgs = False
        try:
            install_hwpacks(
                'chroot', '/tmp/dir', preferred_tools_dir(), force_yes, [],
                extract_kpkgs, 'hwp.tgz', 'hwp2.tgz')
        except:
            exception_caught = True
        self.assertTrue(self.run_local_atexit_functions_called)
        self.assertTrue(exception_caught)

    def setUp(self):
        super(TestInstallHWPack, self).setUp()

        # Ensure the list of cleanup functions gets cleared to make sure tests
        # don't interfere with one another.

        def clear_atexits():
            linaro_image_tools.media_create.chroot_utils.local_atexit = []
        self.addCleanup(clear_atexits)