~jcsackett/charmworld/bac-tag-constraints

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
# Copyright 2012-2014 Marco Ceppi, Canonical Ltd.  This software is
# licensed under the GNU Affero General Public License version 3 (see
# the file LICENSE).

"""Unit tests for our application models."""
from bzrlib.branch import Branch
from datetime import (
    date,
    datetime,
    timedelta,
)
import hashlib
import logging
import md5
from mock import patch
import os
from os.path import dirname
from os.path import join
from os.path import split
from pyelasticsearch.exceptions import (
    ElasticHttpError,
)
import pymongo
import stat
from textwrap import dedent
from xml.etree import ElementTree
import yaml

from charmworld.models import (
    acquire_session_secret,
    BadSVGError,
    Bundle,
    BundledCharmDescription,
    Charm,
    CharmFile,
    CharmFileSet,
    CharmSource,
    construct_charm_id,
    DatedMetric,
    DatedMetricSource,
    FeaturedSource,
    find_charms,
    _find_charms,
    make_bundle_doc,
    make_constraints_space_separated,
    METRIC_DAYS_TO_KEEP,
    options_to_storage,
    QAData,
    QADataSource,
    resolve_charm_from_description,
    set_view_box,
    slurp_files,
    storage_to_options,
    store_bundles,
    sync_index,
    UserMgr,
)
from charmworld.search import (
    BUNDLE,
    CHARM,
)
from charmworld.testing import (
    factory,
    force_index_client,
    INI,
    MongoTestBase,
    temp_dir,
    TestCase,
)
from charmworld.testing.factory import (
    bundle_branch,
    charm_branch,
)
from charmworld.migrations.migrate import setup_mongo_indices
from charmworld.utils import (
    quote_key,
    quote_yaml,
    read_locked,
)


class TestConstructCharmID(TestCase):

    def test_construct_charm_id(self):
        payload = factory.get_payload_json(owner='foo', series='bar',
                                           name='baz', promulgated=False)
        factory.add_store_data(payload, revision=25, promulgated=False)
        charm_id = construct_charm_id(payload)
        self.assertEqual('~foo/bar/baz/25', charm_id)

    def test_construct_charm_id_promulgated(self):
        # Promulgation has no effect on this ID.
        payload = factory.get_payload_json(owner='foo', series='bar',
                                           name='baz', promulgated=True)
        factory.add_store_data(payload, revision=25, promulgated=True)
        charm_id = construct_charm_id(payload)
        self.assertEqual('~foo/bar/baz/25', charm_id)

    def test_construct_charm_id_error(self):
        payload = factory.get_payload_json(owner='foo', series='bar',
                                           name='baz')
        factory.add_store_data(payload, charm_error=True, revision=25)
        charm_id = construct_charm_id(payload)
        self.assertEqual('~foo/bar/baz/0', charm_id)

    def test_construct_charm_id_no_revision(self):
        payload = factory.get_payload_json(owner='foo', series='bar',
                                           name='baz')
        charm_id = construct_charm_id(payload, use_revision=False)
        self.assertEqual('~foo/bar/baz', charm_id)


class CharmTestCase(TestCase):
    """Unit tests for the Charm model that wraps charm representations."""

    def test_init_with_invalid_charm(self):
        charm_data = {}
        charm = Charm(charm_data)
        self.assertIs(charm_data, charm._raw_representation)
        self.assertEqual(charm._COMMON_REPRESENTATION, charm._representation)

    def test_init_with_valid_charm(self):
        charm_data = factory.get_charm_json(
            name='name', owner='owner', series='series', promulgated=True)
        charm = Charm(charm_data)
        self.assertIs('name', charm._representation['name'])
        self.assertIs('owner', charm._representation['owner'])
        self.assertIs('series', charm._representation['series'])
        self.assertIs(True, charm._representation['promulgated'])

    def test_eq(self):
        charm_1 = Charm(factory.get_charm_json(
            owner='owner', series='series', name='name'))
        charm_2 = Charm(factory.get_charm_json(
            owner='other', series='series', name='name'))
        charm_3 = Charm(factory.get_charm_json(
            owner=charm_1.owner, series=charm_1.series, name=charm_1.name))
        self.assertNotEqual(charm_1, charm_2)
        self.assertEqual(charm_1, charm_3)

    def test_address(self):
        # The address property is a string.
        charm_data = factory.get_charm_json(
            owner='owner', series='series', name='name')
        charm = Charm(charm_data)
        self.assertEqual(
            'cs:~owner/series/name', charm.address)

    def test_branch_spec(self):
        # The branch_spec property is a string.
        charm_data = factory.get_charm_json(
            owner='owner', series='series', name='name')
        charm = Charm(charm_data)
        self.assertEqual(
            '~owner/charms/series/name/trunk', charm.branch_spec)

    def test_bzr_branch(self):
        # The bzr_branch property is a string.
        charm_data = factory.get_charm_json(
            owner='owner', series='series', name='name')
        charm = Charm(charm_data)
        self.assertEqual(
            'lp:~owner/charms/series/name/trunk', charm.bzr_branch)

    def test_owner(self):
        # The owner property is a string.
        charm_data = factory.get_charm_json(owner='owner')
        charm = Charm(charm_data)
        self.assertEqual('owner', charm.owner)

    def test_series(self):
        # The series property is a string.
        charm_data = factory.get_charm_json(series='series')
        charm = Charm(charm_data)
        self.assertEqual('series', charm.series)

    def test_name(self):
        # The name property is a string.
        charm_data = factory.get_charm_json(name='name')
        charm = Charm(charm_data)
        self.assertEqual('name', charm.name)

    def test_bname(self):
        # The bname property is a string.
        charm_data = factory.get_charm_json(bname='trunk')
        charm = Charm(charm_data)
        self.assertEqual('trunk', charm.bname)

    def test_commit(self):
        # The commit property is a revid string.
        charm_data = factory.get_charm_json()
        charm_data['commit'] = 'joe@example.com-20120723223205-babble'
        charm = Charm(charm_data)
        self.assertEqual(
            'joe@example.com-20120723223205-babble', charm.commit)
        # The default is an empty string that happens when a branch is empty.
        charm = Charm({})
        self.assertEqual('', charm.commit)

    def test_distro_series(self):
        # The distro_series property is a list of series names.
        charm_data = factory.get_charm_json()
        charm_data['distro_series'] = distro_series = ['series']
        charm = Charm(charm_data)
        self.assertIs(distro_series, charm.distro_series)
        # The default is an empty list.
        charm = Charm({})
        self.assertEqual([], charm.distro_series)

    def test_promulgated(self):
        # The promulgated property is a bool.
        charm_data = factory.get_charm_json(promulgated=True)
        charm = Charm(charm_data)
        self.assertIs(True, charm.promulgated)
        # The default is False.
        charm = Charm({})
        self.assertIs(False, charm.promulgated)

    def test_id(self):
        # The _id property is string string based on the branch_spec.
        charm_data = factory.get_charm_json(
            owner='owner', series='series', name='name')
        charm_data['_id'] = '~owner/charms/series/name/trunk'
        charm = Charm(charm_data)
        self.assertEqual('~owner/charms/series/name/trunk', charm._id)
        # The _id property is actually arbitrary.
        charm = Charm({'_id': 'boing'})
        self.assertEqual('boing', charm._id)

    def test_date_created(self):
        # The date_created property is an ISO timestamp.
        date_created = factory.random_date()
        charm_data = factory.get_charm_json(date_created=date_created)
        charm = Charm(charm_data)
        self.assertEqual(date_created.isoformat(), charm.date_created)
        # The default is None, which happens when the branch cannot be found.
        charm = Charm({})
        self.assertEquals(None, charm.date_created)

    def test_error(self):
        # The error property is a string.
        charm_data = {'error': 'Paris is burning'}
        charm = Charm(charm_data)
        self.assertEqual('Paris is burning', charm.error)
        # The default is an empty string.
        charm = Charm({})
        self.assertEquals('', charm.error)

    def test_branch_dir(self):
        # The branch_dir property is a string.
        charm_data = {'branch_dir': '/var/charms/series/owner/name/bname'}
        charm = Charm(charm_data)
        self.assertEqual(
            '/var/charms/series/owner/name/bname', charm.branch_dir)
        # The default is an empty string.
        charm = Charm({})
        self.assertEquals('', charm.branch_dir)

    def test_files(self):
        # The files property is a dict.
        files = {
            'install': {
                'filename': 'install',
                'subdir': 'hooks',
            },
        }
        charm_data = factory.get_charm_json(files=files)
        charm = Charm(charm_data)
        self.assertIs(files, charm.files)
        # The default is an empty string.
        charm = Charm({})
        self.assertEquals({}, charm.files)

    def test_downloads(self):
        """The downloads property is an int."""
        charm_data = {'downloads': 30}
        charm = Charm(charm_data)
        self.assertEqual(30, charm.downloads)
        # The default is zero.
        charm = Charm({})
        self.assertEquals(0, charm.downloads)

    def test_downloads_in_past_30_days(self):
        # The downloads_in_past_30_days property is an int.
        charm_data = {'downloads_in_past_30_days': 30}
        charm = Charm(charm_data)
        self.assertEqual(30, charm.downloads_in_past_30_days)
        # The default is zero.
        charm = Charm({})
        self.assertEquals(0, charm.downloads_in_past_30_days)

    def test_downloads_in_past_7_days(self):
        # The downloads_in_past_7_days property is an int.
        charm_data = {'downloads_in_past_7_days': 7}
        charm = Charm(charm_data)
        self.assertEqual(7, charm.downloads_in_past_7_days)
        # The default is zero.
        charm = Charm({})
        self.assertEquals(0, charm.downloads_in_past_7_days)

    def test_downloads_in_past_half_year(self):
        # The downloads_in_past_half_year property is an int.
        charm_data = {'downloads_in_past_half_year': 180}
        charm = Charm(charm_data)
        self.assertEqual(180, charm.downloads_in_past_half_year)
        # The default is zero.
        charm = Charm({})
        self.assertEquals(0, charm.downloads_in_past_half_year)

    def test_store_url(self):
        # The store_url property is a string.
        charm_data = {'store_url': 'cs:~owner/series/name-1'}
        charm = Charm(charm_data)
        self.assertEqual('cs:~owner/series/name-1', charm.store_url)
        # The default is an empty sting..
        charm = Charm({})
        self.assertEquals('', charm.store_url)

    def test_store_revision(self):
        # The store_revision property is an int.
        charm_data = {'store_data': {'revision': 17}}
        charm = Charm(charm_data)
        self.assertEqual(17, charm.store_revision)
        # The default is 1 if revision is missing from store_data.
        charm = Charm({'store_data': {}})
        self.assertEquals(1, charm.store_revision)
        # The default is 1 if there is no store_data.
        charm = Charm({})
        self.assertEquals(1, charm.store_revision)

    def test_store_data(self):
        # The store_data property dict.
        charm_data = factory.get_charm_json()
        store_data = {
            'address': 'cs:~owner/series/name-1',
            'store_checked': 'Thu Dec  6 17:42:05 2012',
            'digest': 'jdoe@example.com-20120723223205-babble',
            'revision': 1,
            'sha256': '107c230dc3481f8b8de9decfff6439a23caae2ea670bddb413ddf1',
        }
        charm_data['store_data'] = store_data
        charm = Charm(charm_data)
        self.assertIs(store_data, charm.store_data)
        # The default is an empty dict.
        charm = Charm({})
        self.assertEqual({}, charm.store_data)

    def test_proof(self):
        # The proof property is a dict.
        proof = {
            'w': [' no README file']
        }
        charm_data = factory.get_charm_json()
        charm_data['proof'] = proof
        charm = Charm(charm_data)
        self.assertIs(proof, charm.proof)
        # The default is an empty dict.
        charm = Charm({})
        self.assertEqual({}, charm.proof)

    def test_tests(self):
        # The tests property is a dict.
        tests = {
            'ec2': 'PASS'
        }
        charm_data = factory.get_charm_json()
        charm_data['tests'] = tests
        charm = Charm(charm_data)
        self.assertIs(tests, charm.tests)
        # The default is an empty dict.
        charm = Charm({})
        self.assertEqual({}, charm.tests)

    def test_test_results(self):
        # The test_results property is a dict.
        test_results = {
            'openstack': 987654321
        }
        charm_data = factory.get_charm_json()
        charm_data['test_results'] = test_results
        charm = Charm(charm_data)
        self.assertIs(test_results, charm.test_results)
        # The default is an empty dict.
        charm = Charm({})
        self.assertEqual({}, charm.test_results)

    def test_changes(self):
        # The changes property is a list of revision info dicts.
        changes = [factory.makeChange()]
        charm_data = factory.get_charm_json(changes=changes)
        charm = Charm(charm_data)
        self.assertIs(changes, charm.changes)
        # The default is an empty list.
        charm = Charm({})
        self.assertEqual([], charm.changes)

    def test_first_change(self):
        # The first_change property is a revision info dict.
        change = factory.makeChange()
        charm_data = factory.get_charm_json()
        charm_data['first_change'] = change
        charm = Charm(charm_data)
        self.assertIs(change, charm.first_change)
        # The default is some dummy data.
        charm = Charm({})
        expected = {
            'authors': [],
            'committer': '',
            'created': None,
            'message': '',
            'revno': 0,
        }
        self.assertEqual(expected, charm.first_change)

    def test_last_change(self):
        # The last_change property is a revision info dict.
        change = factory.makeChange()
        charm_data = factory.get_charm_json()
        charm_data['last_change'] = change
        charm = Charm(charm_data)
        self.assertIs(change, charm.last_change)
        # The default is some dummy data.
        charm = Charm({})
        expected = {
            'authors': [],
            'committer': '',
            'created': None,
            'message': '',
            'revno': 0,
        }
        self.assertEqual(expected, charm.last_change)

    def test_revision(self):
        # The revision property is an int.
        charm_data = factory.get_charm_json(revision=5)
        charm = Charm(charm_data)
        self.assertEqual(5, charm.revision)
        # The default is zero.
        charm = Charm({})
        self.assertEquals(0, charm.revision)

    def test_summary(self):
        # The summary property is string.
        summary = 'text'
        charm_data = factory.get_charm_json()
        charm_data['summary'] = summary
        charm = Charm(charm_data)
        self.assertIs(summary, charm.summary)
        # The default is an empty string.
        charm = Charm({})
        self.assertEqual('', charm.summary)

    def test_description(self):
        # The description property is string.
        description = 'text'
        charm_data = factory.get_charm_json()
        charm_data['description'] = description
        charm = Charm(charm_data)
        self.assertIs(description, charm.description)
        # The default is an empty string.
        charm = Charm({})
        self.assertEqual('', charm.description)

    def test_categories(self):
        # The categories property is a list of category names.
        categories = ['cache-proxy', 'app-servers']
        charm_data = factory.get_charm_json(categories=categories)
        charm = Charm(charm_data)
        self.assertEqual(categories, charm.categories)
        # The default is an empty list.
        charm = Charm({})
        self.assertEqual([], charm.categories)

    def test_categories_are_official(self):
        # Unofficial categories are filtered out of the list.
        categories = ['application']
        charm_data = factory.get_charm_json(categories=categories)
        charm = Charm(charm_data)
        self.assertEqual(
            ['applications', 'app-servers', 'cache-proxy', 'databases',
             'file-servers', 'misc'],
            charm.OFFICIAL_CATEGORIES)
        self.assertEqual([], charm.categories)

    def test_maintainer_default(self):
        # The default is an empty list.
        charm = Charm({})
        self.assertEqual([], charm.maintainers)

    def test_maintainer_single(self):
        # The maintainer property is a single string or a list of maintainers
        # in RFC 2822 name/email format.
        # It is deprecated in favor of 'maintainers'.
        maintainer = 'Jane <jane@example.com>'
        charm_data = factory.get_charm_json(maintainer=maintainer)
        charm = Charm(charm_data)
        self.assertEqual([maintainer], charm.maintainers)

    def test_maintainer_list(self):
        # The maintainer property is a list of maintainers in RFC 2822
        # name/email format.
        # It is deprecated in favor of 'maintainers'.
        maintainer = ['Jane <jane@example.com>', 'Ian <ian@example.com>']
        charm_data = factory.get_charm_json(maintainer=maintainer)
        charm = Charm(charm_data)
        self.assertEqual(sorted(maintainer), charm.maintainers)

    def test_maintainers_single(self):
        # The maintainers field is the same.
        maintainers = 'Jane <jane@example.com>'
        charm_data = factory.get_charm_json(maintainers=maintainers)
        # Forcibly remove the default maintainer.
        del charm_data['maintainer']
        charm = Charm(charm_data)
        self.assertEqual([maintainers], charm.maintainers)

    def test_maintainers_list(self):
        # The maintainer property is a list of maintainers in RFC 2822
        # name/email format.
        # It is deprecated in favor of 'maintainers'.
        maintainers = ['Jane <jane@example.com>', 'Ian <ian@example.com>']
        charm_data = factory.get_charm_json(maintainers=maintainers)
        # Forcibly remove the default maintainer.
        del charm_data['maintainer']
        charm = Charm(charm_data)
        self.assertEqual(sorted(maintainers), charm.maintainers)

    def test_both_maintainer_and_maintainers(self):
        # If both the old 'maintainer' and new 'maintainers' are given, then
        # the output is the de-duplicated union.
        maintainer = ['Alice <alice@example.com>', 'Ian <ian@example.com>']
        maintainers = ['Jane <jane@example.com>', 'Ian <ian@example.com>']
        charm_data = factory.get_charm_json(
            maintainer=maintainer,
            maintainers=maintainers)
        charm = Charm(charm_data)
        union = set(maintainer)
        union.update(maintainers)
        self.assertEqual(3, len(charm.maintainers))
        self.assertEqual(sorted(union), charm.maintainers)

    def test_subordinate(self):
        # The subordinate property is a bool.
        charm_data = factory.get_charm_json(subordinate=True)
        charm = Charm(charm_data)
        self.assertIs(True, charm.subordinate)
        # The default is False.
        charm = Charm({})
        self.assertIs(False, charm.subordinate)

    @staticmethod
    def make_provides():
        return {
            "website": {
                "interface": "https",
            }
        }

    def test_provides(self):
        # The provides property is a dict of charm options.
        provides = self.make_provides()
        charm_data = factory.get_charm_json(provides=provides)
        charm = Charm(charm_data)
        self.assertIs(provides, charm.provides)
        # The default is an empty dict.
        charm = Charm({})
        self.assertEqual({}, charm.provides)

    def test_i_provides(self):
        # The i_provides property is a list of interface names.
        provides = self.make_provides()
        charm_data = factory.get_charm_json(provides=provides)
        charm = Charm(charm_data)
        self.assertIs(charm_data['i_provides'], charm.i_provides)
        # The default is an empty list.
        charm = Charm({})
        self.assertEqual([], charm.i_provides)

    @staticmethod
    def make_requires():
        return {
            'database': {
                'interface': 'mongodb',
            }
        }

    def test_requires(self):
        # The requires property is a dict of charm options.
        requires = self.make_requires()
        charm_data = factory.get_charm_json(requires=requires)
        charm = Charm(charm_data)
        self.assertIs(requires, charm.requires)
        # The default is an empty dict.
        charm = Charm({})
        self.assertEqual({}, charm.requires)

    def test_i_requires(self):
        # The i_provides property is a list of interface names.
        requires = self.make_requires()
        charm_data = factory.get_charm_json(requires=requires)
        charm = Charm(charm_data)
        self.assertIs(charm_data['i_requires'], charm.i_requires)
        # The default is an empty list.
        charm = Charm({})
        self.assertEqual([], charm.i_requires)

    def test_config(self):
        # The config property is a dict of charm options.
        config = {'options': {'key': {'default': 'value', 'type': 'string'}}}
        charm_data = factory.get_charm_json(options=config['options'])
        charm = Charm(charm_data)
        self.assertEqual(config, charm.config)
        # The default is a dict with a single key named 'options' set to
        # an empty dict.
        charm = Charm({})
        self.assertEqual({'options': {}}, charm.config)

    def test_config_raw(self):
        # The config_raw property is string of YAML.
        config_raw = 'option: 0'
        charm_data = factory.get_charm_json()
        charm_data['config_raw'] = config_raw
        charm = Charm(charm_data)
        self.assertIs(config_raw, charm.config_raw)
        # The default is an empty string.
        charm = Charm({})
        self.assertEqual('', charm.config_raw)

    def test_options(self):
        # The options property is a dict from the charm's config.
        options = {'key': {'default': 'value', 'type': 'string'}}
        charm_data = factory.get_charm_json(options=options)
        charm = Charm(charm_data)
        self.assertEqual(options, charm.options)
        # The default is a dict.
        charm = Charm({})
        self.assertEqual({}, charm.options)

    def test_options_when_config_is_none(self):
        # The options property is a dict even if the config is None.
        charm = Charm({})
        charm._representation['config'] = None
        self.assertEqual({}, charm.options)

    def test_hooks(self):
        # The hooks property is a list of life cycle and relation names.
        hooks = ['install', 'start', 'stop']
        charm_data = factory.get_charm_json()
        charm_data['hooks'] = hooks
        charm = Charm(charm_data)
        self.assertIs(hooks, charm.hooks)
        # The default is an empty list.
        charm = Charm({})
        self.assertEqual([], charm.hooks)

    def test_label(self):
        # The label property is string.
        label = 'user:series/name'
        charm_data = factory.get_charm_json()
        charm_data['label'] = label
        charm = Charm(charm_data)
        self.assertIs(label, charm.label)
        # The default is an empty string.
        charm = Charm({})
        self.assertEqual('', charm.label)

    def test_short_url(self):
        # The short_url property is string.
        short_url = 'user:series/name'
        charm_data = factory.get_charm_json()
        charm_data['short_url'] = short_url
        charm = Charm(charm_data)
        self.assertIs(short_url, charm.short_url)
        # The default is an empty string.
        charm = Charm({})
        self.assertEqual('', charm.short_url)

    def test_changes_since(self):
        changes = [factory.makeChange(created=date(2013, 6, num))
                   for num in xrange(1, 31)]
        charm = Charm(factory.get_charm_json(changes=changes))
        self.assertEqual([], charm.changes_since(datetime(2013, 7, 1)))
        self.assertEqual(30, len(charm.changes_since(datetime(2013, 5, 1))))
        self.assertEqual(5, len(charm.changes_since(datetime(2013, 6, 26))))

    def test_hash(self):
        charm_data = factory.get_charm_json()
        self.assertFalse('hash' in charm_data)
        charm = Charm(charm_data)
        self.assertIs(None, charm.hash)
        charm_data['hash'] = 'whatever'
        charm = Charm(charm_data)
        self.assertEqual('whatever', charm.hash)


class TestUser(MongoTestBase):
    """Unit tests for our User object wrapping of the mongo dict."""

    def test_model_from_sso(self):
        """Given an SSO dump we can get back a decent model object."""
        payload = factory.makeSSOResponse()
        user = UserMgr.from_sso(payload)

        self.assertEqual(payload['openid.claimed_id'], user.userid)
        self.assertEqual(payload['openid.sreg.nickname'], user.nickname)
        self.assertEqual(payload['openid.sreg.fullname'], user.fullname)
        self.assertEqual(payload['openid.sreg.email'], user.email)
        self.assertEqual(payload['openid.sreg.timezone'], user.timezone)
        self.assertEqual(payload['openid.lp.is_member'], ','.join(user.groups))

    def test_user_limited_sharing(self):
        """The user might limit information shared."""
        claimed_id = u'https://login.ubuntu.com/+id/MSbTCYM'

        user = UserMgr.from_sso({
            'openid.claimed_id': claimed_id,
            # When a user chooses not to share teams, an empty is_member is
            # returned.
            'openid.lp.is_member': '',
        })

        self.assertEqual(claimed_id, user.userid)
        self.assertEqual('Not Provided', user.nickname)
        self.assertEqual('Not Provided', user.fullname)
        self.assertEqual(None, user.email)
        self.assertEqual('GMT', user.timezone)
        self.assertEqual([], user.groups)

    def test_can_dict_user(self):
        """We need to be able to turn User into a dict for mongo."""
        payload = factory.makeSSOResponse()
        user = UserMgr.from_sso(payload)

        dict_user = dict(user)
        self.assertEqual(
            payload['openid.claimed_id'],
            dict_user['userid'])
        self.assertEqual(
            payload['openid.sreg.nickname'],
            dict_user['nickname'])

    def test_user_stored_in_mongo(self):
        """The user should store in mongo correctly on save."""
        payload = factory.makeSSOResponse()
        user = UserMgr.from_sso(payload)
        user.save(self.db)

        found = self.db.users.find_one({'userid': user.userid})
        self.assertEqual(user.userid, found['userid'])

    def test_user_from_mongo(self):
        """Pulling the user from mongo via UserMgr should get a User out."""
        payload = factory.makeSSOResponse()
        user = UserMgr.from_sso(payload)
        user.save(self.db)

        found = UserMgr.find_one(self.db, user.userid)
        self.assertEqual(user.userid, found.userid)

    def test_user_updated(self):
        """Saving will either insert or save as required."""
        payload = factory.makeSSOResponse()
        user = UserMgr.from_sso(payload)
        # Does the insert
        user.save(self.db)

        found = UserMgr.find_one(self.db, user.userid)
        self.assertEqual(user.userid, found.userid)
        self.assertEqual(user.fullname, found.fullname)

        found.fullname = 'Changed in test'
        found.save(self.db)

        found2 = UserMgr.find_one(self.db, found.userid)
        self.assertEqual(found.userid, found2.userid)
        self.assertEqual(found.fullname, found2.fullname)

    def test_update_from_sso(self):
        """A new set of SSO data updates the user found."""
        payload = factory.makeSSOResponse()
        user = UserMgr.from_sso(payload)
        # Does the insert
        user.save(self.db)

        new_groups = ['launchpad']
        payload['openid.lp.is_member'] = new_groups[0]
        user.update_from_sso(payload)
        self.assertEqual(new_groups, user.groups)

    def test_auth_principalfinder(self):
        class Request:
            user = UserMgr.from_sso(
                factory.makeSSOResponse(groups=['charmers', 'canonical']))
        expected_principals = [
            'user https://login.ubuntu.com/+id/MSbTCYM',
            'group charmers',
            'group canonical']
        principals = UserMgr.auth_principalfinder('', Request)
        self.assertEqual(expected_principals, principals)


class TestQADataSource(MongoTestBase):

    def test_load_question_set(self):
        data_source = QADataSource.from_db(self.db)
        self.assertEqual({}, data_source.load_question_set())
        category = factory.makeQAQuestionGroup()
        self.db.qa.insert(category)
        question_set = data_source.load_question_set()
        self.assertEqual(['reliable'], question_set.keys())
        self.assertEqual(category['questions'],
                         question_set['reliable']['questions'])

    def test_save_qa_data(self):
        charm_data = factory.makeCharm(self.db)[1]
        charm = Charm(charm_data)
        qa_data_source = QADataSource.from_db(self.db)
        qa_data_source.save_qa_data(charm, {'a': 'b'})
        charm_id = construct_charm_id(charm_data)
        qa_data = self.db.charm_qa_answers.find_one(charm_id)
        self.assertEqual({
            '_id': charm_id,
            'name': charm.name,
            'owner': charm.owner,
            'series': charm.series,
            'revision': charm.store_data['revision'],
            'answers': {'a': 'b'},
        }, qa_data)

    def test_get_qa_data(self):
        charm_data = factory.makeCharm(self.db)[1]
        charm_id = construct_charm_id(charm_data)
        charm = Charm(charm_data)
        self.db.charm_qa_answers.save({
            '_id': charm_id,
            'name': charm.name,
            'owner': charm.owner,
            'series': charm.series,
            'revision': charm.store_data['revision'],
            'answers': {'a': 'b'},
        })
        qa_data_source = QADataSource.from_db(self.db)
        self.assertEqual(
            {'a': 'b'},
            qa_data_source.get_qa_data(charm).charm_data,
        )

    def test_stores_multiple_versions(self):
        charm_data = factory.get_charm_json()
        qa_data_source = QADataSource.from_db(self.db)
        charm = Charm(charm_data)
        charm.store_data['revision'] = 1
        qa_data_source.save_qa_data(charm, {'new': 'data'})
        charm.store_data['revision'] = 0
        qa_data_source.save_qa_data(charm, {'old': 'data'})
        self.assertEqual(2, qa_data_source.answers.find().count())

    def test_get_qa_data_matches_unversioned_values(self):
        charm_data = factory.get_charm_json()
        qa_data_source = QADataSource.from_db(self.db)
        charm = Charm(charm_data)
        qa_data_source.save_qa_data(charm, {'qa': 'data'})
        wrong_name = Charm(factory.get_charm_json(series=charm.series,
                           owner=charm.owner))
        wrong_name_qa = qa_data_source.get_qa_data(wrong_name)
        self.assertIs(None, wrong_name_qa.charm_data)
        wrong_series = Charm(factory.get_charm_json(name=charm.name,
                             owner=charm.owner, series='wrong'))
        wrong_series_qa = qa_data_source.get_qa_data(wrong_series)
        self.assertIs(None, wrong_series_qa.charm_data)
        wrong_owner = Charm(factory.get_charm_json(name=charm.name,
                            series=charm.series, owner='wrong'))
        wrong_owner_qa = qa_data_source.get_qa_data(wrong_owner)
        self.assertIs(None, wrong_owner_qa.charm_data)
        right_unversioned = Charm(factory.get_charm_json(name=charm.name,
                                  series=charm.series, owner=charm.owner))
        right_unversioned_qa = qa_data_source.get_qa_data(right_unversioned)
        self.assertEqual({'qa': 'data'}, right_unversioned_qa.charm_data)

    def test_get_qa_data_retrieves_newest(self):
        # Retrieves the newest QA available.
        charm_data = factory.makeCharm(self.db)[1]
        charm = Charm(charm_data)
        qa_data_source = QADataSource.from_db(self.db)
        charm.store_data['revision'] = 0
        qa_data_source.save_qa_data(charm, {'old': 'data'})
        charm.store_data['revision'] = 1
        qa_data_source.save_qa_data(charm, {'new': 'data'})
        charm.store_data['revision'] = 2
        self.assertEqual({'new': 'data'},
                         qa_data_source.get_qa_data(charm).charm_data)

    def test_get_qa_data_omits_newer(self):
        # Omits QA that is newer than the charm.
        charm_data = factory.makeCharm(self.db)[1]
        charm = Charm(charm_data)
        qa_data_source = QADataSource.from_db(self.db)
        charm.store_data['revision'] = 0
        qa_data_source.save_qa_data(charm, {'old': 'data'})
        charm.store_data['revision'] = 1
        qa_data_source.save_qa_data(charm, {'new': 'data'})
        charm.store_data['revision'] = 0
        self.assertEqual({'old': 'data'},
                         qa_data_source.get_qa_data(charm).charm_data)


class TestQAData(MongoTestBase):
    """Unit tests for our User object wrapping of the mongo dict."""

    def setUp(self):
        super(TestQAData, self).setUp()
        category = factory.makeQAQuestionGroup()
        self.db.qa.insert(category)
        self.qa_data_source = QADataSource.from_db(self.db)

    def test_category_property(self):
        qadata = QAData(self.qa_data_source)
        self.assertEqual(['reliable'], qadata.categories)

    def test_none_overall_if_no_data(self):
        """When no charm qa data we get None to indicate N/A."""
        qadata = QAData(self.qa_data_source)
        self.assertIsNone(qadata.score)

    def test_overall_score(self):
        scores = factory.makeQAScore()
        qadata = QAData(self.qa_data_source, charm_data=scores)
        self.assertEqual(4, qadata.score)

    def test_none_category_score_if_missing_data(self):
        """When no scores are available for the cateogry we get None

        None is our indicator of a score that's N/A

        """
        qadata = QAData(self.qa_data_source)
        self.assertIsNone(qadata.category_score('reliable'))

    def test_category_score(self):
        scores = factory.makeQAScore()
        qadata = QAData(self.qa_data_source, charm_data=scores)

        self.assertEqual(4, qadata.category_score('reliable'))

    def test_category_max_score(self):
        """Determine the total available points for the category."""
        qadata = QAData(self.qa_data_source)
        self.assertEqual(9, qadata.category_max_score('reliable'))


class TestCharmFileSet(MongoTestBase):
    # Escape the base_fileid since all code will escape this. We're comparing
    # against this string so it needs to also be escaped.
    base_fileid = 'charmers/precise/charmworld%2Etest/trunk/'
    charm_data = {
        'series': 'precise',
        'owner': 'charmers',
        'name': 'charmworld.test',
        'bname': 'trunk',
    }
    charm_path = join(
        dirname(dirname(__file__)),
        'testing/data/sample_charm'
    )

    def setUp(self):
        super(TestCharmFileSet, self).setUp()
        self.logger = logging.getLogger(self.__class__.__name__)
        self.log_handler = self.get_handler(self.logger.name)

    def save_files(self, charm_path=None, extra_revisions=[]):
        with charm_branch(charm_path, extra_revisions) as (
                branch_dir, revision, path):
            charm_data = self.charm_data.copy()
            charm_data['branch_dir'] = branch_dir
            charm_data['store_data'] = {'digest': revision}
            return CharmFileSet.save_files(
                self.fs,
                charm_data,
                branch_dir,
                self.logger)

    def save_revision_files(self, charm_path=None, extra_revisions=[]):
        with charm_branch(charm_path, extra_revisions) as (
                branch_dir, revision, path):
            charm_data = self.charm_data.copy()
            charm_data['branch_dir'] = branch_dir
            charm_data['store_data'] = {'digest': revision}
            CharmFileSet.save_revision_files(
                self.fs, charm_data, branch_dir, self.logger)
            return charm_data

    def test_fileid_generation(self):
        """A charm must generate an unique fileid."""
        self.assertEqual(
            'charmers/precise/charmworld%2Etest/trunk/readme',
            CharmFileSet.gen_fileid(self.charm_data, 'readme')
        )

    saved_sample_charm_files = [
        'config.yaml',
        'metadata.yaml',
        'README.md',
        'icon.svg',
        'revision',
        'hooks/config-changed',
        'hooks/database-relation-broken',
        'hooks/database-relation-changed',
        'hooks/install',
        'hooks/linkstart',
        'hooks/restart',
        'hooks/start',
        'hooks/stop',
        'hooks/upgrade-charm',
        'hooks/website-relation-changed',
    ]

    def check_bzr_files(self, expected_files, saved_files):
        # There should be the following files stored into the gridfs
        # filestore.
        for name in expected_files:
            fileid = self.base_fileid + quote_key(name)
            self.assertTrue(
                self.fs.exists(fileid),
                'Should find file:' + fileid)
            existing_content = self.fs.get(fileid).read()
            self.assertEqual(expected_files[name], existing_content)
        saved_ids = set(f._id for f in saved_files)
        expected_ids = set(
            self.base_fileid + quote_key(name) for name in expected_files)
        self.assertEqual(expected_ids, saved_ids)

    def expected_files(self):
        result = {}
        sample_data_path = split(split(__file__)[0])[0]
        sample_data_path = join(sample_data_path, 'testing/data/sample_charm')
        for name in self.saved_sample_charm_files:
            result[name] = open(join(sample_data_path, name)).read()
        return result

    def test_load_bzr_files(self):
        """Processing a charm dir loads the file contents."""
        saved = self.save_files()
        self.check_bzr_files(self.expected_files(), saved)

    def test_load_bzr_files_from_old_revision(self):
        """Processing a charm dir loads the file contents."""
        def add_revision_two(cwd, tree):
            path = join(cwd, 'branch/trunk/hooks/new_hook')
            with open(path, 'w') as f:
                f.write('A new hook')
            tree.add(['hooks/new_hook'])
            tree.commit('revision 2')

        saved = self.save_files(extra_revisions=[add_revision_two])
        self.check_bzr_files(self.expected_files(), saved)

    def test_load_bzr_files_from_new_revision(self):
        """Processing a charm dir loads the file contents."""
        def add_revision_two(cwd, tree):
            path = join(cwd, 'branch/trunk/hooks/new_hook')
            with open(path, 'w') as f:
                f.write('A new hook')
            tree.add(['hooks/new_hook'])
            return tree.commit('revision 2')

        saved = self.save_files(extra_revisions=[add_revision_two])
        expected = self.expected_files()
        expected['hooks/new_hook'] = 'A new hook'
        self.check_bzr_files(expected, saved)

    def test_save_files_with_non_existent_bzr_revision(self):
        """Attempts to retrieve a non-existent branch revision result in
        an empty return value of save_files and a log entry."""
        with charm_branch() as (branch_dir, revision, path):
            charm_data = self.charm_data.copy()
            charm_data['branch_dir'] = branch_dir
            charm_data['store_data'] = {'digest': 'bad-revision-id'}
            result = CharmFileSet.save_files(
                self.fs,
                charm_data,
                branch_dir,
                self.logger)
        self.assertEqual([], result)
        messages = [rec.msg for rec in self.log_handler.buffer]
        self.assertEqual(['Revision bad-revision-id not found'], messages)

    def test_case_kept_for_filenames(self):
        """README.md is lower cased in the key, but upper in filename."""
        self.save_files()

        # Verify that the filename of the README is kept.
        found = self.fs.get_last_version('README.md')
        # fileid is escaped because it's used as a mongo key.
        expected = self.base_fileid + quote_key('README.md')
        self.assertEqual(expected, found._id)

    def test_get_by_id(self):
        """Load a CharmFile instance from the datastore."""
        self.save_files()

        readme_id = self.base_fileid + quote_key('README.md')

        cf = CharmFileSet.get_by_id(self.fs, readme_id)
        self.assertEqual('README.md', cf.filename)
        self.assertEqual(readme_id, cf.fileid)

        # We need to be able to dict the metadata to store in the charm record
        # itself.
        gridout = cf._gridout
        metadata = dict(cf)
        self.assertEqual('README.md', metadata['filename'])
        self.assertEqual(readme_id, metadata['fileid'])
        self.assertEqual(u'charmers/precise/charmworld.test/trunk',
                         metadata['charmid'])
        self.assertEqual(gridout.length, metadata['length'])
        self.assertEqual(gridout.md5, metadata['md5'])
        self.assertEqual('', metadata['subdir'])

    def test_get_by_id_hooks_file(self):
        """The hooks file is a subdir down and we want to track that."""
        self.save_files()

        install_id = self.base_fileid + 'hooks/install'

        cf = CharmFileSet.get_by_id(self.fs, install_id)
        self.assertEqual('install', cf.filename)
        self.assertEqual('hooks', cf.subdir)
        self.assertEqual(install_id, cf.fileid)

        # We need to be able to dict the metadata to store in the charm record
        # itself.
        metadata = dict(cf)
        self.assertEqual('hooks', metadata['subdir'])

    def test_save_files_handles_missing_dir(self):
        path = self.use_context(temp_dir())
        files = self.save_files(path)
        self.assertEqual([], files)

    def test_save_file_ignores_symlink_without_target(self):
        # Symlinks that point to nowhere are not saved.
        path = self.use_context(temp_dir())
        link_path = join(path, 'readme')
        target_name = 'does-not-exist'
        os.symlink(target_name, link_path)
        files = self.save_files(path)
        expected = [
            'File does not exist: readme (resolving to does-not-exist).',
        ]
        messages = [rec.msg for rec in self.log_handler.buffer]
        self.assertEqual(expected, messages)
        self.assertEqual([], files)

    def test_save_file_ignores_symlink_with_outside_target(self):
        # Symlinks that point to a location outside the charm's root
        # directory are also ignored.
        path = self.use_context(temp_dir())
        link_path = join(path, 'readme')
        target_name = '../no-trespassing'
        os.symlink(target_name, link_path)
        files = self.save_files(path)
        expected = [
            "Invalid file path: Path readme points to ../no-trespassing, "
            "which is not inside the charm's root directory"
        ]
        messages = [rec.msg for rec in self.log_handler.buffer]
        self.assertEqual(expected, messages)
        self.assertEqual([], files)

    def test_save_file_ignores_symlink_with_absolute_target_path(self):
        # Symlinks that point to an absolute location are ignored.
        path = self.use_context(temp_dir())
        link_path = join(path, 'readme')
        target_name = '/etc/passwd'
        os.symlink(target_name, link_path)
        files = self.save_files(path)
        expected = [
            "Invalid file path: symlink readme points to the absolute path "
            "/etc/passwd."
        ]
        messages = [rec.msg for rec in self.log_handler.buffer]
        self.assertEqual(expected, messages)
        self.assertEqual([], files)

    def test_save_file_ignores_invalid_icons(self):
        path = self.use_context(temp_dir())
        # Not an SVG.
        with open(join(path, 'icon.svg'), 'w') as f:
            f.write('foo')
        files = self.save_files(path)
        self.assertEqual([], files)
        # No width or height provided.
        with open(join(path, 'icon.svg'), 'w') as f:
            f.write('<?xml version="1.0"?><svg></svg>')
        files = self.save_files(path)
        self.assertEqual([], files)

    def test_adds_viewbox_to_icons(self):
        path = self.use_context(temp_dir())
        with open(join(path, 'icon.svg'), 'w') as f:
            f.write('<?xml version="1.0"?><svg width="10" height="10"></svg>')
        self.save_files(path)
        icon_id = self.base_fileid + quote_key('icon.svg')
        cf = CharmFileSet.get_by_id(self.fs, icon_id)
        # Note that ElementTree generates the processing instruction with
        # single quotes, but elements with double quotes.  To keep from having
        # to escape everything, the strings are quoted accordingly below.
        self.assertEqual(
            "<?xml version='1.0' encoding='UTF-8'?>\n"
            + '<svg height="10" viewBox="0 0 10 10" width="10" />',
            cf.read())

    def test_provides_content_type(self):
        path = self.use_context(temp_dir())
        with open(join(path, 'icon.svg'), 'w') as f:
            f.write('<?xml version="1.0"?><svg width="10" height="10"></svg>')
        with open(join(path, 'readme.txt'), 'w') as f:
            f.write('foo')
        self.save_files(path)
        icon_id = self.base_fileid + quote_key('icon.svg')
        cf = CharmFileSet.get_by_id(self.fs, icon_id)
        self.assertEqual('image/svg+xml', cf.contentType)
        readme_id = self.base_fileid + quote_key('readme.txt')
        cf = CharmFileSet.get_by_id(self.fs, readme_id)
        self.assertEqual('text/plain', cf.contentType)

    def test_directories_match(self):
        path = self.use_context(temp_dir())
        os.mkdir(join(path, 'hooks'))
        os.mkdir(join(path, 'hooks_lib'))
        with open(join(path, 'hooks/a_hook'), 'w') as f:
            f.write('hook')
        with open(join(path, 'hooks_lib/hook_lib'), 'w') as f:
            f.write('not stored in our DB')
        saved = self.save_files(path)
        saved = [charm_file._filename for charm_file in saved]
        self.assertEqual(['a_hook'], saved)

    def check_revision_files(self, expected_files, charm_revision):
        expected_names = set(expected_files)
        found_names = set(charm_revision['files'])
        self.assertEqual(expected_names, found_names)
        for name in expected_names:
            expected_fs_id = hashlib.sha256(expected_files[name]).hexdigest()
            self.assertEqual(expected_fs_id, charm_revision['files'][name])

    def test_save_revision_files(self):
        charm_revision = self.save_revision_files()
        self.check_revision_files(self.expected_files(), charm_revision)

    def add_revision(self, cwd, tree, return_new_revision):
        path = join(cwd, 'branch/trunk/hooks/new_hook')
        with open(path, 'w') as f:
            f.write('A new hook')
            tree.add(['hooks/new_hook'])
        path = join(cwd, 'branch/trunk/README.md')
        with open(path, 'a') as f:
            f.write('appended text')
        if return_new_revision:
            return tree.commit('revision 2')
        else:
            return None

    def test_save_revision_files_from_old_revision(self):
        def add_revision_two(cwd, tree):
            return self.add_revision(cwd, tree, False)
        revision = self.save_revision_files(extra_revisions=[add_revision_two])
        self.check_revision_files(self.expected_files(), revision)

    def test_save_revision_files_from_new_revision(self):
        def add_revision_two(cwd, tree):
            return self.add_revision(cwd, tree, True)
        revision = self.save_revision_files(extra_revisions=[add_revision_two])
        expected = self.expected_files()
        expected['hooks/new_hook'] = 'A new hook'
        expected['README.md'] = expected['README.md'] + 'appended text'
        self.check_revision_files(expected, revision)

    def test_save_revision_files_with_non_existent_bzr_revision(self):
        with charm_branch() as (branch_dir, revision, path):
            charm_data = self.charm_data.copy()
            charm_data['branch_dir'] = branch_dir
            charm_data['store_data'] = {'digest': 'bad-revision-id'}
            CharmFileSet.save_revision_files(
                self.fs,
                charm_data,
                branch_dir,
                self.logger)
        self.assertEqual({}, charm_data['files'])
        messages = [rec.msg for rec in self.log_handler.buffer]
        self.assertEqual(['Revision bad-revision-id not found'], messages)


class TestCharmFile(MongoTestBase):

    def test_filename_parsing(self):
        """The filename is the end of the fileid."""
        cf = CharmFile(
            self.fs, '/test/file/path.txt', '/charmers/precise/redis')
        self.assertEqual('path.txt', cf.filename)

    def test_filename_with_caps(self):
        """Whe can specifiy the filename to keep it original."""

        cf = CharmFile(
            self.fs, '/test/file/path.txt', '/charmers/precise/redis',
            filename='PATH.txt')
        self.assertEqual('PATH.txt', cf.filename)

    def test_storing_file_contents(self):
        contents = 'Contents of the file.'
        fileid = '/test/file/path.txt'
        cf = CharmFile(self.fs, fileid, '/charmers/precise/redis')
        cf.save(contents)

        # Make sure we check for the escaped fileid to see it exists.
        self.assertTrue(self.fs.exists(cf.fileid))

        found = self.fs.get(cf.fileid)
        self.assertEqual(contents, found.read())

    def test_save_with_orphan_chunks(self):
        file_id = 'file-id'
        cf = CharmFile(self.fs, file_id, 'baz')
        cf.save('foo')
        # Create orphan chunk
        self.db.fs.files.remove({'_id': file_id})
        self.assertFalse(self.fs.exists(file_id))
        cf.save('bar')
        self.assertEqual('bar', self.fs.get(file_id).read())

    def test_md5(self):
        cf = CharmFile(self.fs, 'file-id', 'baz')
        self.assertIs(None, cf.md5)
        cf.save('asdf')
        self.assertEqual(cf.md5, md5.new('asdf').hexdigest())

    def test_no_contentType(self):
        result = self.fs.put(
            'foo',
            filename='bar',
        )
        instance = self.fs.get(result)
        sentry = object()
        self.assertIs(sentry, getattr(instance, 'contentType', sentry))
        cf = CharmFile(self.fs, None, None, instance=instance)
        self.assertIs(None, cf.contentType)


class TestAcquireSessionSecret(MongoTestBase):

    def test_acquire_session_secret(self):
        """Multiple calls to acquire_session_secret return the same value."""
        secret = acquire_session_secret(self.db)
        self.assertIs(str, type(secret))
        self.assertEqual(secret, acquire_session_secret(self.db))

    def test_db_backed(self):
        """The secret is stored in the database.

        An existing session-secret is used if present.  Deleting it causes a
        new secret to be generated.
        """
        self.db.app_config.insert({'_id': 'session-secret',
                                   'secret': 'arbitrary-string'})
        first_secret = acquire_session_secret(self.db)
        self.assertEqual('arbitrary-string', first_secret)
        self.db.app_config.remove('session-secret')
        second_secret = acquire_session_secret(self.db)
        self.assertNotEqual(first_secret, second_secret)


class TestFindCharms(MongoTestBase):

    def test_find_charms_default(self):
        # By default, find_charms() does not return charms with errors.
        ignore, valid_charm = factory.makeCharm(self.db, name='valid_charm')
        ignore, charm_with_error = factory.makeCharm(
            self.db, name='charm_with_error', charm_error=True)
        result = find_charms(self.db)
        self.assertEqual(1, len(result))
        self.assertEqual(valid_charm, result[0])

    def test_find_charms_invalid_included(self):
        # If the parameter valid_charms_only is set to False, find_charms()
        # returns invalid charms too.
        ignore, valid_charm = factory.makeCharm(self.db, name='valid_charm')
        ignore, charm_with_error = factory.makeCharm(
            self.db, name='charm_with_error', charm_error=True)
        result = find_charms(self.db, valid_charms_only=False)
        self.assertEqual(2, len(result))

    def test_find_charms_with_more_parameters(self):
        # Any parameter of Collection.find() can be specified.
        ignore, charm_1 = factory.makeCharm(self.db, name='valid_charm_1')
        ignore, charm_2 = factory.makeCharm(self.db, name='valid_charm_2')
        result = find_charms(self.db, {'name': 'does-not-exist'})
        self.assertEqual(0, len(result))
        result = find_charms(self.db, spec={'name': 'valid_charm_1'})
        self.assertEqual(1, len(result))
        self.assertEqual(charm_1, result[0])
        result = find_charms(
            self.db, spec={'name': 'valid_charm_1'}, fields=('bname', 'name'))
        expected = {
            '_id': charm_1['_id'],
            'name': charm_1['name'],
            'bname': charm_1['bname']
        }
        self.assertEqual(expected, result[0])

    def test_dont_hide_with_processing_error(self):
        # Charms with errors that occured during the ingest script
        # are returned by find_charms()
        charm_id, charm_data = factory.makeCharm(self.db)
        charm_data['error'] = {}
        self.db.charms.save(charm_data)
        self.assertIn(charm_data,
                      find_charms(self.db, valid_charms_only=False))

    def test_only_promulgated(self):
        ignore, promulgated_charm = factory.makeCharm(
            self.db, promulgated=True)
        factory.makeCharm(self.db)
        result = find_charms(self.db, only_promulgated=True)
        self.assertEqual(1, len(result))
        self.assertEqual(promulgated_charm, result[0])

    def test_all_revisons_not_default(self):
        factory.makeCharm(self.db, owner='a', series='b', name='c',
                          store_revision=3)
        factory.makeCharm(self.db, owner='a', series='b', name='c',
                          store_revision=1)
        self.assertEqual([3], [charm['store_data']['revision']
                         for charm in find_charms(self.db)])

    def test_all_revisons_true(self):
        factory.makeCharm(self.db, owner='a', series='b', name='c',
                          store_revision=3)
        factory.makeCharm(self.db, owner='a', series='b', name='c',
                          store_revision=1)
        self.assertItemsEqual(
            [3, 1], [charm['store_data']['revision'] for charm in
                     find_charms(self.db, all_revisions=True)])

    def test_sort(self):
        charm_1 = factory.makeCharm(self.db, owner='a', series='b')[0]
        charm_2 = factory.makeCharm(self.db, owner='b', series='a')[0]
        charms = find_charms(self.db, sort=[('owner', pymongo.ASCENDING)])
        self.assertEqual([charm_1, charm_2], [c['_id'] for c in charms])
        charms = find_charms(self.db, sort=[('owner', pymongo.DESCENDING)])
        self.assertEqual([charm_2, charm_1], [c['_id'] for c in charms])

    def test_sort_stress(self):
        # This test is to ensure a large collection of charms can be found,
        # which requires sorting.  It ensures the proper index is in place
        # because without it a Mongo error will be raised.
        setup_mongo_indices(self.db.charms)
        charm_dict = factory.makeCharms(self.db, 2000, 10)
        results = list(
            _find_charms(
                self.db.charms,
                spec={},
                fields={'name': 1, 'i_provides': 1},
                sort=[('name', pymongo.ASCENDING)]))
        sorted_result_names = [res['name'] for res in results]
        names = sorted(set([c['name'] for c in charm_dict.values()]))
        self.assertEqual(names, sorted_result_names)

    def test__find_charms_gets_unique_fields(self):
        # __find_charms takes appropriate precautions to ensure that the same
        # results are returned, even when there are charms that might be
        # expected to sort between them.
        factory.makeCharm(self.db, owner='a', series='b', name='c',
                          downloads=3, store_revision=2)[1]
        # different owner, 2 downloads
        factory.makeCharm(self.db, series='b', name='c', downloads=2)
        # different name, 2 downloads
        factory.makeCharm(self.db, owner='a', series='b', downloads=2)
        # different series, 2 downloads
        factory.makeCharm(self.db, owner='a', name='c', downloads=2)
        charm_1 = factory.makeCharm(self.db, owner='a', series='b', name='c',
                                    downloads=1, store_revision=1)[1]
        results = list(_find_charms(self.db.charms,
                                    sort=[('downloads', pymongo.DESCENDING)]))
        self.assertNotIn(charm_1, results)


class TestCharmSource(MongoTestBase):

    def test_sync_index(self):
        self.use_index_client()
        one = factory.makeCharm(self.db)[0]
        two = factory.makeCharm(self.db)[0]
        three = factory.makeCharm(self.db)[0]
        charm_source = CharmSource.from_request(self)
        ids = list(charm_source.sync_index())
        self.assertItemsEqual([one, two, three], ids)
        for charm_id in ids:
            foo, bar = charm_source._get_all(charm_id)
            self.assertEqual(foo, bar)

    def test_sync_index_script(self):
        factory.makeCharm(self.db, owner='b')[0]
        # Create a charm which is index-incompatible with the previous one.
        factory.makeCharm(self.db, owner='a',
                          description={'text': 'whatever'})[0]
        handler = self.get_handler('sync-index')
        with patch('charmworld.models.configure_logging'):
            with patch('charmworld.models.get_ini', lambda: INI):
                with force_index_client(self.use_index_client()):
                    sync_index()
            messages = [r.getMessage() for r in handler.buffer]
            self.assertIn('Unable to index charm.', messages)
        self.assertEqual(1, len(self.index_client.api_search()))

    def test_save_deletes_on_error(self):
        self.use_index_client()
        source = CharmSource.from_request(self)
        source.save({
            '_id': 'a',
            'owner': 'foo',
            'series': 'bar',
            'name': 'baz',
            'description': 'whatever',
        })
        with self.assertRaises(ElasticHttpError):
            source.save({
                '_id': 'a',
                'owner': 'foo',
                'series': 'bar',
                'name': 'baz',
                # A dictionary as the value conflicts with the mapping.
                'description': {'text': 'whatever'},
            })
        self.assertIs(None, self.index_client.get('a'))

    def test_sync_index_uses_latest(self):
        self.use_index_client()
        factory.makeCharm(self.db, owner='a', series='b', name='c',
                          store_revision=1)[0]
        two = factory.makeCharm(self.db, owner='a', series='b', name='c',
                                store_revision=2)[0]
        charm_source = CharmSource.from_request(self)
        ids = list(charm_source.sync_index())
        self.assertItemsEqual([two], ids)
        for charm_id in ids:
            foo, bar = charm_source._get_all(charm_id)
            self.assertEqual(foo, bar)

    def test_find_proof_error_charms(self):
        client = self.use_index_client()
        proof_with_errors = {'e': ['error 1']}
        proof_with_warnings = {'w': ['warning 1']}
        ignore, charm_1 = factory.makeCharm(
            self.db, owner='joe', promulgated=True, proof=proof_with_errors)
        client.index_charm(charm_1)
        ignore, charm_2 = factory.makeCharm(
            self.db, promulgated=True, proof=proof_with_warnings)
        client.index_charm(charm_2)
        ignore, charm_3 = factory.makeCharm(
            self.db, promulgated=False, proof=proof_with_errors)
        client.index_charm(charm_3)
        charm_source = CharmSource.from_request(self)
        errors = list(charm_source.find_proof_error_charms())
        self.assertEqual(1, len(errors))
        self.assertEqual(charm_1['name'], errors[0].name)

    def test_obsolete_charms_ignored_by_find_proof_error_charms(self):
        client = self.use_index_client()
        proof_with_errors = {'e': ['error 1']}
        # The view retrieves promulgated charms with proof errors.
        ignore, charm_1 = factory.makeCharm(
            self.db, owner='joe', promulgated=True, proof=proof_with_errors,
            series='oneiric')
        client.index_charm(charm_1)
        charm_source = CharmSource.from_request(self)
        errors = list(charm_source.find_proof_error_charms())
        self.assertEqual([], errors)

    def test_find_proof_error_charms_ignores_old_revisions(self):
        client = self.use_index_client()
        proof_with_errors = {'e': ['error 1']}
        # The view retrieves promulgated charms with proof errors.
        ignore, charm_1 = factory.makeCharm(
            self.db, name='foo', owner='joe', promulgated=True,
            proof=proof_with_errors, store_revision=1, series='precise')
        client.index_charm(charm_1)
        ignore, charm_2 = factory.makeCharm(
            self.db, name='foo', owner='joe', promulgated=True,
            series='precise', store_revision=2)
        client.index_charm(charm_2)
        charm_source = CharmSource.from_request(self)
        errors = list(charm_source.find_proof_error_charms())
        self.assertEqual([], errors)

    def test_store_errors_in_queue(self):
        client = self.use_index_client()
        ignore, charm = factory.makeCharm(self.db, charm_error=True)
        client.index_charm(charm)
        factory.makeCharm(self.db, charm_error=False)
        charm_source = CharmSource.from_request(self)
        errors = list(charm_source.find_mia_charms())
        self.assertEqual(charm['name'], errors[0].name)
        self.assertEqual(charm['branch_spec'], errors[0].branch_spec)

    def test_obsolete_charms_ignored_by_find_mia_charms(self):
        client = self.use_index_client()
        ignore, charm = factory.makeCharm(
            self.db, charm_error=True, series='oneiric')
        client.index_charm(charm)
        charm_source = CharmSource.from_request(self)
        errors = list(charm_source.find_mia_charms())
        self.assertEqual([], errors)

    def test_is_latest(self):
        client = self.use_index_client()
        ignore, charm_1 = factory.makeCharm(
            self.db, name='foo', owner='joe', promulgated=True,
            store_revision=1, series='precise')
        client.index_charm(charm_1)
        ignore, charm_2 = factory.makeCharm(
            self.db, name='foo', owner='joe', promulgated=True,
            series='precise', store_revision=2)
        client.index_charm(charm_2)
        charm_source = CharmSource.from_request(self)
        self.assertEqual(
            [False, True],
            [charm_source._is_latest(c) for c in [charm_1, charm_2]])


class TestOptionsStorage(TestCase):

    yaml = {
        'foo': {
            'default': 'bar',
            'type': 'string',
            'description': 'Hello.'
        },
        'baz': {
            'default': 42,
            'type': 'int',
            'description': 'Hello.'
        },
    }
    storage = [{
        'name': 'baz',
        'default': 42,
        'type': 'int',
        'description': 'Hello.'
    }, {
        'name': 'foo',
        'default': 'bar',
        'type': 'string',
        'description': 'Hello.'
    }]

    def test_options_to_storage(self):
        self.assertItemsEqual(self.storage, options_to_storage(self.yaml))

    def test_options_to_storage_none(self):
        self.assertItemsEqual([], options_to_storage(None))

    def test_storage_to_options(self):
        self.assertEqual(self.yaml, storage_to_options(self.storage))

    def test_storage_to_options_duplicate_key(self):
        with self.assertRaises(ValueError) as exc_context:
            storage_to_options([{'name': 'same'}, {'name': 'same'}])
        self.assertEqual('Option name "same" occurs multiple times.',
                         str(exc_context.exception))

    def test_roundtrip(self):
        self.assertEqual(
            self.yaml, storage_to_options(options_to_storage(self.yaml)))
        self.assertItemsEqual(
            self.storage,
            options_to_storage(storage_to_options(self.storage)))


class TestStoreBundles(MongoTestBase):

    def test_store_bundles(self):
        # The bundles can be stored in the database.

        deployer_config = dedent("""\
            wordpress-stage:
                series: precise
                services:
                    blog:
                        charm: cs:precise/wordpress
                        constraints: mem=2
                        options:
                            tuning: optimized
                            engine: apache
        """)
        parsed = yaml.safe_load(deployer_config)
        owner = 'bac'
        bundle_name = 'wordpress-stage'
        basket_name = 'wordpress-basket'
        basket_rev = 5
        basket_id = "%s/%d" % (basket_name, basket_rev)
        _id = Bundle.construct_id(owner, basket_name, bundle_name, basket_rev)
        store_bundles(
            self.db.bundles, parsed, 'bac', basket_id, None, None, None, None,
            None)
        self.assertEqual(
            {
                '_id': _id,
                'basket_name': basket_name,
                'basket_revision': basket_rev,
                'name': bundle_name,
                'owner': owner,
                'data': parsed['wordpress-stage'],
                'first_change': None,
                'last_change': None,
                'changes': None,
                'branch_spec': None,
                'promulgated': False,
            },
            self.db.bundles.find_one(_id))

    def test_store_bundles_calls_get_flattened_deployment(self):
        # For every key in the top-level deployment data,
        # get_flattened_deployment is called once.
        deployer_config = dedent("""\
            wordpress-stage:
                series: precise
                services:
                    blog:
                        charm: cs:precise/wordpress
                        constraints: mem=2
                        options:
                            tuning: optimized
                            engine: apache
            wordpress-prod:
                series: precise
                services:
                    blog:
                        charm: cs:precise/wordpress
                        constraints: mem=5
                        options:
                            tuning: optimized
                            engine: apache
        """)
        parsed = yaml.safe_load(deployer_config)
        keys = []

        def get_flattened_deployment(data, key):
            keys.append(key)

        with patch('charmworld.models.get_flattened_deployment',
                   get_flattened_deployment):
            store_bundles(
                self.db.bundles, parsed, 'bac', 'wordpress-basket/5', None,
                None, None, None, None)
        self.assertItemsEqual(['wordpress-stage', 'wordpress-prod'], keys)

    class FauxElasticSearchClient:
        index_bundles_called = False
        called_args = None

        @classmethod
        def from_settings(cls, *args):
            return cls

        @classmethod
        def index_bundles(cls, *args):
            cls.index_bundles_called = True
            cls.called_args = args

    def test_storing_a_bundle_includes_indexing_it(self):
        with patch('charmworld.models.ElasticSearchClient',
                    TestStoreBundles.FauxElasticSearchClient):
            store_bundles(
                self.db.bundles, {}, 'owner', 'wordpress-basket/5', None,
                None, None, None, None)

        self.assertTrue(
            TestStoreBundles.FauxElasticSearchClient.index_bundles_called)

    def test_indexing_a_bundle_removes_some_annotations(self):
        deployer_config = dedent("""\
            wordpress-prod:
                series: precise
                services:
                    blog:
                        charm: cs:precise/wordpress
                        constraints: mem=5
                        annotations:
                            'gui-x': 1
                            'gui-y': 2
                        options:
                            tuning: optimized
                            engine: apache
            wordpress-stage:
                series: precise
                services:
                    blog:
                        charm: cs:precise/wordpress
                        constraints: mem=2
                        options:
                            tuning: optimized
                            engine: apache
                        annotations:
                            'gui-x': 1
                            'gui-y': 2
                            'color': 'purple'
        """)

        parsed = yaml.safe_load(deployer_config)
        with patch('charmworld.models.ElasticSearchClient',
                    TestStoreBundles.FauxElasticSearchClient):
            store_bundles(
                self.db.bundles, parsed, 'owner',
                'wordpress-basket/5', None, None, None, None, None)
        self.assertTrue(
            TestStoreBundles.FauxElasticSearchClient.index_bundles_called)

        called_args = sorted(
            TestStoreBundles.FauxElasticSearchClient.called_args[0],
            key=lambda x: x['_id'])
        for arg in called_args:
            self.assertFalse(
                'annotations' in arg['data']['services']['blog'])


class BundleTestCase(MongoTestBase):
    """Unit tests for the Bundle model that wraps bundle representations."""

    bundle_data = {
        'owner': 'sinzui',
        'basket_name': 'mysql',
        'basket_revision': 2,
        'name': 'tiny',
        'title': 'Tiny bundle',
        'description': 'My Tiny Bundle',
        'data': {
            'services': dict(apache=1),
            'relations': dict(a=1),
            'series': 'series',
        },
        'promulgated': True,
        'branch_deleted': True,
    }

    def test_construct_id_no_revision(self):
        bundle_id = Bundle.construct_id(
            'a', 'b', 'c')
        self.assertEqual('~a/b/c', bundle_id)

    def test_init_with_empty_representation(self):
        bundle_data = {}
        bundle = Bundle(bundle_data)
        self.assertIs(bundle_data, bundle._raw_representation)
        self.assertEqual(bundle._MONGO_FIELDS, bundle._representation)

    def test_init_with_minimal_data(self):
        bundle_data = {
            'owner': 'sinzui',
            'basket_name': 'mysql',
            'basket_revision': 1,
            'changes': None,
            'first_change': None,
            'last_change': None,
            'name': 'tiny',
            'title': 'Tiny bundle',
            'description': 'My Tiny Bundle',
            'data': {
                'services': dict(apache=1),
                'relations': dict(a=1),
                'series': 'series',
            },
            'promulgated': True,
            'branch_deleted': True,
            'is_featured': False,
            'branch_spec': '~sinzui/fake/path',
        }
        bundle = Bundle(bundle_data)
        self.assertIs(bundle_data, bundle._raw_representation)
        self.assertEqual(bundle_data, bundle._representation)

    def test_reject_arbitrary_attributes(self):
        bundle = Bundle({})
        with self.assertRaises(AttributeError):
            bundle.not_a_real_attribute

    def test_is_equal(self):
        # If two bundles have the same permanent_url, they are considered
        # equal, even if their data differ.
        common = {
            'name': 'tiny',
            'owner': 'bac',
            'basket_name': 'apache',
            'basket_revision': 1,
        }
        bundle1 = Bundle(dict(common, title='Tiny Apache'))
        bundle2 = Bundle(dict(common, title='Itty Bitty Apache'))
        self.assertEqual(bundle1, bundle2)

    def test_not_equal(self):
        common = {
            'name': 'tiny',
            'basket_name': 'apache',
            'basket_revision': 4,
        }
        bundle1 = Bundle(dict(common, owner='bac'))
        bundle2 = Bundle(dict(common, owner='abc'))
        self.assertNotEqual(bundle1, bundle2)

    def test_id(self):
        bundle = Bundle(
            {'name': 'tiny',
             'owner': 'bac',
             'basket_name': 'apache',
             'basket_revision': 8,
             })
        self.assertEqual(
            "~bac/apache/8/tiny", bundle.id)

    def test_permanent_url(self):
        bundle = Bundle(
            {'name': 'tiny',
             'owner': 'bac',
             'basket_name': 'apache',
             'basket_revision': 6,
             })
        self.assertEqual(
            "bundle:~bac/apache/6/tiny", bundle.permanent_url)

    def test_basket_name(self):
        bundle = Bundle(
            {'name': 'tiny',
             'owner': 'bac',
             'basket_name': 'apache',
             'basket_revision': 6,
             })
        self.assertEqual(
            "apache", bundle.basket_name)

    def test_basket_name_with_none(self):
        # If a bundle is is not stored because of an ingest error,
        # basket_name will return None.
        bundle = Bundle({})
        self.assertIsNone(bundle.basket_name)

    def test_basket_revision(self):
        bundle = Bundle(
            {'name': 'tiny',
             'owner': 'bac',
             'basket_name': 'apache',
             'basket_revision': 6,
             })
        self.assertEqual(6, bundle.basket_revision)

    def test_basket_revision_no_rev(self):
        bundle = Bundle(
            {'name': 'tiny',
             'owner': 'bac',
             'basket_name': 'apache',
             })
        self.assertIsNone(bundle.basket_revision)

    def test_basket_revision_with_none(self):
        # If a bundle is is not stored because of an ingest error,
        # basket_revision will return None.
        bundle = Bundle({})
        self.assertIsNone(bundle.basket_revision)

    def test_short_url(self):
        bundle = Bundle(
            {'name': 'tiny',
             'owner': 'bac',
             'basket_name': 'apache',
             'basket_revision': 7,
             })
        self.assertEqual(
            "bundle/~bac/apache/tiny", bundle.short_url)

    def test_short_url_without_enough_parts(self):
        # When there is not enough information, the path is an empty string.
        bundle = Bundle({})
        self.assertEqual('', bundle.short_url)

    def test_loading_a_bundle_from_the_database(self):
        # A bundle can be loaded from the database with a query.
        self.db.bundles.save(self.bundle_data)
        bundle = Bundle.from_query({'owner': 'sinzui'}, self.db)
        self.assertIsNotNone(bundle)
        self.assertEqual(bundle.basket_name, 'mysql')
        self.assertEqual(bundle.name, 'tiny')

    def test_loading_a_bundle_from_a_given_collection(self):
        # A bundle can be loaded from a specific collection.
        collection = self.db.create_collection(factory.random_string(10))
        collection.save(self.bundle_data)
        bundle = Bundle.from_query({'owner': 'sinzui'}, collection=collection)
        self.assertIsNotNone(bundle)
        self.assertEqual(bundle.basket_name, 'mysql')
        self.assertEqual(bundle.name, 'tiny')

    def test_loading_a_nonexistent_bundle_returns_none(self):
        # If a query does not match any bundles, None is returned.
        bundle = Bundle.from_query({'owner': 'nunyas'}, self.db)
        self.assertIsNone(bundle)

    def test_multiple_matches_return_highest_revision(self):
        # A bundle can be loaded from the database with a query.
        mod_data = dict(self.bundle_data)
        mod_data['_id'] = 'a'
        self.db.bundles.save(mod_data)
        mod_data['_id'] = 'b'
        mod_data['basket_revision'] = 99
        self.db.bundles.save(mod_data)
        mod_data['_id'] = 'c'
        mod_data['basket_revision'] = 77
        self.db.bundles.save(mod_data)
        bundle = Bundle.from_query({'owner': 'sinzui'}, self.db)
        # If a query matches multiple entries, the one with the latest
        # revision is returned.
        self.assertIsNotNone(bundle)
        self.assertEqual(bundle.basket_name, 'mysql')
        self.assertEqual(bundle.basket_revision, 99)
        self.assertEqual(bundle.name, 'tiny')

    def test_bundles_are_iterable(self):
        # When a bundle is iterated over it generates a series of key, value
        # pairs.  This is convenient for generating a dictionary from a
        # bundle (e.g., dict(bundle)).
        bundle = Bundle({'name': 'bundle-name'})
        self.assertIn(('name', 'bundle-name'), list(bundle))
        # The important properties are also represented in the output.
        bundle_data = dict(bundle)
        self.assertIn('id', bundle_data)
        self.assertIn('permanent_url', bundle_data)

    def test_branch_short_url(self):
        bundle = Bundle(
            {'name': 'tiny',
             'owner': 'bac',
             'basket_name': 'apache',
             'basket_revision': 7,
             })
        self.assertEqual(
            "lp:~bac/charms/bundles/apache/bundle", bundle.branch_short_url)

    def test_branch_url(self):
        bundle = Bundle(
            {'name': 'tiny',
             'owner': 'bac',
             'basket_name': 'apache',
             'basket_revision': 7,
             })
        self.assertEqual(
            "https://code.launchpad.net/~bac/charms/bundles/apache/bundle",
            bundle.branch_url)

    def test_basket_id(self):
        bundle = Bundle(dict(
            owner='bac',
            basket_name='sample_bundle',
            basket_revision=1,
            name='wilma'))
        self.assertEqual(
            '~bac/sample_bundle/1',
            bundle.basket_id)

    def test_uses_provided_series(self):
        """If a series is provided in the data, it is returned."""
        bundle = Bundle(
            {'name': 'tiny',
             'owner': 'bac',
             'basket_name': 'apache',
             'basket_revision': 7,
             'data': {'series': 'edgy'},
             })
        self.assertEqual(
            "edgy", bundle.series)

    def test_default_series(self):
        """If no series is provided in the data, None is returned."""
        bundle = Bundle(
            {'name': 'tiny',
             'owner': 'bac',
             'basket_name': 'apache',
             'basket_revision': 7,
             'data': {},
             })
        self.assertIsNone(bundle.series)


class TestBundledCharmDescription(TestCase):

    def test_charm_resolving_from_bundle_branch(self):
        service_data = {
            'charm': 'mediawiki',
            'branch': 'lp:charms/precise/mediawiki'
        }

        description = BundledCharmDescription('wiki', service_data)

        self.assertEqual(
            '~charmers/charms/precise/mediawiki/trunk',
            description.branch)
        self.assertIsNone(description.revision)
        self.assertTrue(description.assume_latest_revision)

        # And supports a version.
        service_data['branch'] = 'lp:charms/precise/mediawiki@77'
        description = BundledCharmDescription('wiki', service_data)

        self.assertEqual(
            '~charmers/charms/precise/mediawiki/trunk',
            description.branch)
        self.assertEqual(77, description.revision)
        self.assertFalse(description.assume_latest_revision)

    def test_charm_resolving_from_bundle_charm_csurl(self):
        service_data = {
            'charm': 'cs:precise/mediawiki-77'
        }

        description = BundledCharmDescription('wiki', service_data)
        self.assertEqual(
            'cs:precise/mediawiki-77',
            description.store_url)
        self.assertTrue(description.assume_store_url)
        self.assertEqual(77, description.revision)

    def test_charm_resolving_from_charm_store_url(self):
        service_data = {
            'charm_url': 'cs:precise/mediawiki-77'
        }

        description = BundledCharmDescription('wiki', service_data)
        self.assertEqual(
            'cs:precise/mediawiki-77',
            description.store_url)
        self.assertFalse(description.assume_store_url)
        self.assertEqual(77, description.revision)

    def test_charm_resolving_from_bundle_charm_and_series(self):
        service_data = {
            'charm': 'mediawiki'
        }
        series = 'precise'
        description = BundledCharmDescription(
            'wiki', service_data, series=series)
        self.assertEqual(
            'precise',
            description.series)
        self.assertEqual(
            'mediawiki',
            description.charm)
        self.assertTrue(description.assume_latest_revision)
        self.assertTrue(description.assume_promulgated)

    def test_charm_resolving_from_bundle_empty_missing_info(self):
        service_data = {
            'charm': 'mediawiki'
        }
        description = BundledCharmDescription('wiki', service_data)
        self.assertEqual('mediawiki', description.charm)
        self.assertIsNone(description.series)
        self.assertIsNone(description.branch)
        self.assertIsNone(description.store_url)
        self.assertIsNone(description.revision)


class TestMakeBundleDoc(TestCase):

    def test_bundle_doc(self):
        doc = make_bundle_doc(
            {'a': 'b'}, 'foo', 'bar/9', 'baz', None, None, None,
            'fake/branch/spec', promulgated=True)
        self.assertEqual({
            'owner': 'foo',
            'basket_name': 'bar',
            'basket_revision': 9,
            'name': 'baz',
            'data': {'a': 'b'},
            '_id': '~foo/bar/9/baz',
            'first_change': None,
            'last_change': None,
            'changes': None,
            'branch_spec': 'fake/branch/spec',
            'promulgated': True,
        }, doc)

    def test_bundle_doc_with_services_info(self):
        data = {
            'services': {
                'mysql': {
                    'charm': 'mysql',
                },
                'mediawiki': {
                    'branch': 'lp:mediawiki',
                },
            }
        }
        expected_data = {
            'services': {
                'mysql': {
                    'charm': 'cs:precise/mysql',
                },
                'mediawiki': {
                    'branch': 'lp:mediawiki',
                    'charm': 'cs:precise/mediawiki',
                },
            }
        }
        services_info = {
            'mysql': {
                'store_url': 'cs:precise/mysql-1',
            },
            'mediawiki': {
                'store_url': 'cs:precise/mediawiki-1',
            },
        }
        doc = make_bundle_doc(
            data, 'foo', 'bar/9', 'baz', None, None, None,
            'fake/branch/spec', True, services_info)
        self.assertEqual({
            'owner': 'foo',
            'basket_name': 'bar',
            'basket_revision': 9,
            'name': 'baz',
            'data': expected_data,
            '_id': '~foo/bar/9/baz',
            'first_change': None,
            'last_change': None,
            'changes': None,
            'branch_spec': 'fake/branch/spec',
            'promulgated': True,
        }, doc)


class TestSlurpFiles(MongoTestBase):

    def test_slurp_files_saves_all_files_by_default(self):
        with charm_branch() as (branch_dir, revision, path):
            branch = Branch.open(branch_dir)
            tree = branch.repository.revision_tree(revision)
            with read_locked(tree):
                result = slurp_files(self.fs, tree)
        expected_file_paths = set()
        for dirpath, dirnames, filenames in os.walk(path):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                if stat.S_ISLNK(os.lstat(filepath).st_mode):
                    continue
                relpath = filepath[len(path) + 1:]
                expected_file_paths.add(relpath)
                content = open(filepath).read()
                expected_hash = hashlib.sha256(content).hexdigest()
                self.assertEqual(expected_hash, result[relpath])
        self.assertEqual(expected_file_paths, set(result))

    def test_slurp_files_with_identical_content_saved_only_once(self):

        def add_revision_two(cwd, tree):
            src_path = join(cwd, 'branch/trunk/common')
            dst_path = join(cwd, 'branch/trunk/also-common')
            with open(dst_path, 'w') as f:
                f.write(open(src_path).read())
            tree.add(['also-common'])
            return tree.commit('revision 2')

        with charm_branch(extra=[add_revision_two]) as (
                branch_dir, revision, path):
            branch = Branch.open(branch_dir)
            tree = branch.repository.revision_tree(revision)
            with read_locked(tree):
                result = slurp_files(self.fs, tree)
        expected_file_paths = set()
        for dirpath, dirnames, filenames in os.walk(path):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                if stat.S_ISLNK(os.lstat(filepath).st_mode):
                    continue
                relpath = filepath[len(path) + 1:]
                expected_file_paths.add(relpath)
        expected_file_paths.add('also-common')
        self.assertEqual(result['common'], result['also-common'])


class TestBundleFiles(MongoTestBase):

    def setUp(self):
        super(TestBundleFiles, self).setUp()
        with bundle_branch() as (branch_dir, revision, self.path):
            self.branch = Branch.open(branch_dir)
            self.tree = self.branch.repository.revision_tree(revision)
            with read_locked(self.tree):
                self.hashes = slurp_files(self.fs, self.tree)
        basket_data = {'_id': '~bac/sample_bundle/1'}
        basket_data['file_hashes'] = quote_yaml(self.hashes)
        self.db.baskets.save(basket_data)
        self.bundle_data = dict(owner='bac',
                                basket_name='sample_bundle',
                                basket_revision=1,
                                name='wilma')
        self.bundle = Bundle(self.bundle_data)

    def test_get_file(self):
        icon_fn = 'icon.svg'
        self.assertIn(icon_fn, self.hashes)
        fh = self.bundle.get_file(self.db, icon_fn, self.fs)
        content = fh.read()
        real_icon_svg_path = join(self.path, icon_fn)
        with open(real_icon_svg_path) as f:
            real_content = f.read()
        # We cannot assert content and real_content are equal due to
        # viewbox manipulation in slurp_files.
        self.assertIn('mediawiki', content)
        self.assertIn('mediawiki', real_content)

    def test_get_file_list(self):
        filelist = sorted(self.bundle.get_file_list(self.db, self.fs))
        expected = sorted(('icon.svg', 'bundles.yaml', 'README.md'))
        self.assertEqual(expected, filelist)


class TestMassageBundlesYaml(TestCase):

    def test_massage_bundle_file(self):
        """Constraints with comma-separators are converted."""
        comma_constraints = 'mem=2G,cpu-cores=4,arch=i386'
        yaml_template = dedent("""\
            wiki:
              series: precise
              promulgated: True
              services:
                wiki:
                  charm: mediawiki
                  branch: lp:charms/precise/mediawiki
                  constraints: {}
                  num_units: 2
                db:
                  charm: mysql
                  branch: lp:charms/precise/mysql
                  options:
                    tuning-level: fast
        """)
        massaged = make_constraints_space_separated(
            yaml_template.format(comma_constraints))
        expected = yaml.dump(
            yaml.load(yaml_template.format('arch=i386 cpu-cores=4 mem=2G')),
            default_flow_style=False)
        self.assertEqual(expected, massaged)


class TestBundleLoadingCharms(MongoTestBase):

    def setUp(self):
        """Create 3 of the same charms at different revisions"""
        super(TestBundleLoadingCharms, self).setUp()
        charm_args = {
            'name': 'wikipedia',
            'series': 'precise',
            'owner': 'charmers',
            'promulgated': True
        }
        charm_args['revision'] = 1
        charm_args['store_revision'] = 1
        factory.makeCharm(self.db, **charm_args)
        charm_args['revision'] = 2
        charm_args['store_revision'] = 2
        factory.makeCharm(self.db, **charm_args)
        charm_args['revision'] = 3
        charm_args['store_revision'] = 3
        factory.makeCharm(self.db, **charm_args)

    def test_resolve_by_store_url(self):
        data = {
            'charm': 'cs:precise/wikipedia-1'
        }
        charm_description = BundledCharmDescription('wiki', data)
        charm = resolve_charm_from_description(self.db, charm_description)
        self.assertIsNotNone(charm)
        self.assertEqual('~charmers/precise/wikipedia/1', charm['_id'])
        self.assertEqual('wikipedia', charm['name'])
        self.assertEqual(1, charm['store_data']['revision'])
        self.assertEqual(1, charm['revision'])

    def test_resolve_by_store_url_sans_version(self):
        data = {
            'charm': 'cs:precise/wikipedia'
        }
        charm_description = BundledCharmDescription('wiki', data)
        charm = resolve_charm_from_description(self.db, charm_description)
        self.assertIsNotNone(charm)
        self.assertEqual('~charmers/precise/wikipedia/3', charm['_id'])
        self.assertEqual('wikipedia', charm['name'])
        self.assertEqual(3, charm['store_data']['revision'])
        self.assertEqual(3, charm['revision'])

    def test_resolve_by_name_and_series(self):
        data = {
            'charm': 'wikipedia'
        }
        charm_description = BundledCharmDescription(
            'wiki', data, series='precise')
        charm = resolve_charm_from_description(self.db, charm_description)

        self.assertIsNotNone(charm)
        self.assertEqual('wikipedia', charm['name'])
        self.assertEqual(3, charm['store_data']['revision'])
        self.assertEqual(3, charm['revision'])

    def test_resolve_by_branch(self):
        data = {
            'branch': 'lp:charms/precise/wikipedia'
        }
        charm_description = BundledCharmDescription(
            'wiki', data, series='precise')
        charm = resolve_charm_from_description(self.db, charm_description)
        self.assertIsNotNone(charm)
        self.assertEqual('wikipedia', charm['name'])
        self.assertEqual(3, charm['store_data']['revision'])
        self.assertEqual(3, charm['revision'])

    def test_resolve_by_branch_with_revision(self):
        data = {
            'branch': 'lp:charms/precise/wikipedia@2'
        }
        charm_description = BundledCharmDescription('wiki', data)
        charm = resolve_charm_from_description(self.db, charm_description)
        self.assertIsNotNone(charm)
        self.assertEqual('wikipedia', charm['name'])
        self.assertEqual(2, charm['store_data']['revision'])
        self.assertEqual(2, charm['revision'])

    def test_not_enough_info(self):
        data = {
            'name': 'wikipedia'
        }
        charm_description = BundledCharmDescription('wiki', data)
        charm = resolve_charm_from_description(self.db, charm_description)
        self.assertIsNone(charm)


class TestFeaturedSource(MongoTestBase):

    def test_set_and_get_work(self):
        # FeaturedSource instances manage a set of featured charms in a
        # MongoDB collection.
        charm_data_1 = factory.get_charm_json(
            name='name1', owner='owner1', series='series1', promulgated=True)
        charm_data_2 = factory.get_charm_json(
            name='name2', owner='owner2', series='series2', promulgated=True)
        charm_data_3 = factory.get_charm_json(
            name='name3', owner='owner3', series='series3', promulgated=True)
        bundle_data_1 = factory.get_bundle_data(
            name='name4', owner='owner4', basket_with_rev='basket1/1')
        featured_source = FeaturedSource(
            self.db.create_collection(factory.random_string(10)))
        featured_source.set_featured(charm_data_1, CHARM)
        featured_source.set_featured(charm_data_2, CHARM)
        featured_source.set_featured(bundle_data_1, BUNDLE)
        # The first two charms and bundle are featured, but the third is not.
        self.assertTrue(featured_source.is_featured(charm_data_1, CHARM))
        self.assertTrue(featured_source.is_featured(charm_data_2, CHARM))
        self.assertTrue(featured_source.is_featured(bundle_data_1, BUNDLE))
        self.assertFalse(featured_source.is_featured(charm_data_3, CHARM))

    def test_can_create_from_database(self):
        # A convenience constructor is provided that accepts a database.
        charm_data = factory.get_charm_json(
            name='name1', owner='owner1', series='series1')
        featured_source = FeaturedSource.from_db(self.db)
        featured_source.set_featured(charm_data, 'charm')
        self.assertTrue(featured_source.is_featured(charm_data, 'charm'))

    def test_clearing_featured(self):
        # Once featured, an item can be removed from the featured set.
        charm_data = factory.get_charm_json(
            name='name1', owner='owner1', series='series1')
        featured_source = FeaturedSource.from_db(self.db)
        featured_source.set_featured(charm_data, 'charm')
        self.assertTrue(featured_source.is_featured(charm_data, 'charm'))
        # Now we remove the item's featured status and verify that it worked.
        featured_source.clear_featured(charm_data, 'charm')
        self.assertFalse(featured_source.is_featured(charm_data, 'charm'))
        # If the item is cleared again, nothing happens.
        featured_source.clear_featured(charm_data, 'charm')
        self.assertFalse(featured_source.is_featured(charm_data, 'charm'))

    def test_multiple_sets(self):
        # Setting an item as featured more than once will not include it more
        # than once in the set of featured items.
        charm_data = factory.get_charm_json(
            name='name1', owner='owner1', series='series1')
        featured_source = FeaturedSource.from_db(self.db)
        featured_source.set_featured(charm_data, 'charm')
        featured_source.set_featured(charm_data, 'charm')
        featured_source.set_featured(charm_data, 'charm')
        self.assertEqual(len(list(featured_source.collection.find())), 1)

    def test_get_featured_typed_ids_all(self):
        # Retrieve the unversioned ids of the featured items as used by
        # ElasticSearch.
        charm_data_1 = factory.get_charm_json(
            name='name1', owner='owner1', series='series1', promulgated=True)
        charm_data_2 = factory.get_charm_json(
            name='name2', owner='owner2', series='series2', promulgated=True)
        bundle_data_1 = factory.get_bundle_data(
            name='name3', owner='owner3', basket_with_rev='basket1/1')
        featured_source = FeaturedSource.from_db(self.db)
        featured_source.set_featured(charm_data_1, CHARM)
        featured_source.set_featured(charm_data_2, CHARM)
        featured_source.set_featured(bundle_data_1, BUNDLE)
        typed_ids = featured_source.get_featured_typed_ids(doctype=None)
        expected = [
            {'_id': '~owner1/series1/name1', '_type': CHARM},
            {'_id': '~owner2/series2/name2', '_type': CHARM},
            {'_id': '~owner3/basket1/name3', '_type': BUNDLE},
        ]
        self.assertEqual(expected, typed_ids)

    def test_get_featured_typed_ids_for_doctype(self):
        # Retrieve the unversioned ids of the featured doctype as used by
        # ElasticSearch.
        charm_data_1 = factory.get_charm_json(
            name='name1', owner='owner1', series='series1', promulgated=True)
        bundle_data_1 = factory.get_bundle_data(
            name='name3', owner='owner3', basket_with_rev='basket1/1')
        featured_source = FeaturedSource.from_db(self.db)
        featured_source.set_featured(charm_data_1, CHARM)
        featured_source.set_featured(bundle_data_1, BUNDLE)
        typed_ids = featured_source.get_featured_typed_ids(doctype=CHARM)
        expected = [{'_id': '~owner1/series1/name1', '_type': CHARM}]
        self.assertEqual(expected, typed_ids)


class TestDatedMetricApi(TestCase):
    """These are tests of the public API of DatedMetric."""

    def test_instantiation(self):
        # DatedMetric exists.
        DatedMetric()
        # DatedMetric can be instantiated with a starting date.
        DatedMetric(start=date.today())

    def test_fetching_total_count(self):
        # The total number of increments performed on a metric can be
        # retrieved.
        metric = DatedMetric()
        metric.get_total()

    def test_fresh_metric_has_zero_total(self):
        # If a metric has never been incremented, it has a total of zero.
        metric = DatedMetric()
        self.assertEqual(metric.get_total(), 0)

    def test_incrementing(self):
        # A metric can be incremented, which means adding one to a particular
        # day's count.
        metric = DatedMetric()
        total_before_increment = metric.get_total()
        metric.increment(date.today())
        total_after_increment = metric.get_total()
        self.assertEqual(total_before_increment + 1, total_after_increment)

    def test_incrementing_a_new_day(self):
        # A metric from a day more recent than the current starting day can be
        # incremented.  In that case, the starting day will be moved to the
        # more recent day.
        original_starting_day = date(2000, 1, 1)
        metric = DatedMetric(start=original_starting_day)
        self.assertEqual(metric.start, original_starting_day)
        new_starting_day = date(2000, 1, 2)
        metric.increment(new_starting_day)
        self.assertNotEqual(metric.start, original_starting_day)
        self.assertEqual(metric.start, new_starting_day)

    def test_overflow(self):
        # Only a finite number of individual day's records are stored, after
        # that they are put into a single "overflow" bucket.
        original_starting_day = date(2000, 1, 1)
        metric = DatedMetric(start=original_starting_day)
        # No values have been added, so the starting day hasn't changed.
        assert metric.start == original_starting_day
        # Add enough records to fill all the buckets.
        for x in xrange(METRIC_DAYS_TO_KEEP):
            metric.increment(original_starting_day + timedelta(x))
        # The overflow is still empty because up until this point there have
        # been enough buckets to hold all the days.
        self.assertEqual(metric.overflow, 0)
        # However, if we add one more day, the overflow will accumulate.
        metric.increment(metric.start + timedelta(1))
        self.assertEqual(metric.overflow, 1)
        # If we add another day the overflow gets even bigger.
        metric.increment(metric.start + timedelta(1))
        self.assertEqual(metric.overflow, 2)

    def test_total(self):
        # The total number of increments is available.
        metric = DatedMetric()
        # Before any increments happen, the total is zero.
        self.assertEqual(metric.get_total(), 0)
        metric.increment()
        self.assertEqual(metric.get_total(), 1)
        metric.increment()
        self.assertEqual(metric.get_total(), 2)

    def test_total_with_overflow(self):
        # The total will include any values that have overflowed.
        original_starting_day = date(2000, 1, 1)
        metric = DatedMetric(original_starting_day)
        for x in xrange(METRIC_DAYS_TO_KEEP + 10):
            metric.increment(original_starting_day + timedelta(x))
        self.assertEqual(metric.get_total(), METRIC_DAYS_TO_KEEP + 10)

    def test_get_range_total(self):
        # The total number of increments for a particular date range is
        # available.
        original_starting_day = date(2000, 1, 1)
        metric = DatedMetric(start=original_starting_day)
        # No values have been added, so the starting day hasn't changed.
        assert metric.start == original_starting_day
        # Add enough records to fill all the buckets.
        for x in xrange(METRIC_DAYS_TO_KEEP):
            metric.increment(original_starting_day + timedelta(x))
            metric.increment(original_starting_day + timedelta(x))
        # Now that values have been added, the starting day has changed.
        assert metric.start != original_starting_day
        self.assertEqual(
            metric.get_range_total(30, metric.start),
            60)

    def test_casting_to_a_mapping(self):
        # The metric objects can be cast to a mapping which contains the
        # essential details.
        original_starting_day = date(2000, 1, 1)
        metric = DatedMetric(start=original_starting_day)
        self.assertEqual(
            dict(metric),
            {
                'start': metric.start,
                'buckets': metric.buckets,
                'overflow': metric.overflow,
            })

    def test_incrementing_a_far_past_date(self):
        # When incrementing a date far in the past (so long ago there are no
        # buckets for a date that old), the increment goes into the overflow
        # bucket.
        original_starting_day = date(2000, 1, 1)
        metric = DatedMetric(start=original_starting_day)
        # The overflow starts empty.
        assert metric.overflow == 0
        metric.increment(date(1000, 1, 1))
        self.assertEqual(metric.overflow, 1)


class TestDatedMetricIncidentals(TestCase):
    """Herein lie the tests for the internal machinery of DatedMetrics"""

    def test_shifting_buckets_adds_new_bucket_at_head(self):
        # When shifting buckets a new, zero bucket is inserted at the head of
        # the list.
        self.assertEqual(
            DatedMetric._shift_buckets([1, 0, 0], 0),
            ([0, 1, 0], 0))
        self.assertEqual(
            DatedMetric._shift_buckets([0, 1, 0], 0),
            ([0, 0, 1], 0))

    def test_shifting_buckets_acumulates_overflow(self):
        # When shifting buckets a new, zero bucket is inserted at the head of
        # the list and the overflow captures the value of the bucket dropped
        # from the end.
        self.assertEqual(
            DatedMetric._shift_buckets([1, 2, 3], 100),
            ([0, 1, 2], 103))

    def test_filling_in_buckets_accumulates_overflow(self):
        # When adding days to the bucket list via _fill_in_buckets, any
        # buckets pushed off the end of the list will have their values added
        # to the overflow value.
        self.assertEqual(
            DatedMetric._fill_in_buckets(
                date(2000, 1, 2), date(2000, 1, 1), [1, 2, 3, 4], 100),
            (date(2000, 1, 2), [0, 1, 2, 3], 104))
        self.assertEqual(
            DatedMetric._fill_in_buckets(
                date(2000, 1, 4), date(2000, 1, 1), [1, 2, 3, 4], 100),
            (date(2000, 1, 4), [0, 0, 0, 1], 109))
        self.assertEqual(
            DatedMetric._fill_in_buckets(
                date(2099, 1, 1), date(2000, 1, 1), [1, 2, 3, 4], 100),
            (date(2099, 1, 1), [0, 0, 0, 0], 110))

    def test_enough_empty_buckets_are_created(self):
        self.assertEqual(len(DatedMetric().buckets), METRIC_DAYS_TO_KEEP)

    def test_find_day_offset(self):
        # We occasionally need to know which bucket represents a date given
        # the date of the zeroth bucket.
        self.assertEqual(
            DatedMetric._find_day_offset(
                day=date(2000, 1, 1), start=date(2000, 1, 1)),
            0)
        self.assertEqual(
            DatedMetric._find_day_offset(
                day=date(2000, 1, 1), start=date(2000, 1, 10)),
            9)

    def test_getting_date_range_totals(self):
        # We can total up the number of increments over a given date range.
        start = date(2000, 1, 10)   # The day our metrics start.
        buckets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        overflow = 100
        self.assertEqual(
            DatedMetric._get_range_total(5, start, start, buckets, overflow),
            15)

    def test_getting_date_range_totals_that_start_in_the_past(self):
        # We can total up the number of increments over a given date range,
        # even if the day the metrics are to start on is not the current start
        # date.
        day = date(2000, 1, 5)  # The day we want our total to start on.
        start = date(2000, 1, 10)  # The day our metrics start.
        buckets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        overflow = 100
        self.assertEqual(
            DatedMetric._get_range_total(5, day, start, buckets, overflow),
            40)

    def test_getting_date_range_totals_that_start_after_newest_bucket(self):
        # If the total increments are requested for days that includes days
        # that are newer than the start date of the buckets, those days are
        # considered to have no increments and therefore do not contribute to
        # the total.
        day = date(2000, 1, 15)  # The day we want our total to start on.
        start = date(2000, 1, 10)  # The day our metrics start.
        buckets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        overflow = 100
        self.assertEqual(
            DatedMetric._get_range_total(10, day, start, buckets, overflow),
            15)

    def test_getting_date_range_totals_that_overflow(self):
        # If the number of days back requested exceeds the number of days we
        # have, we generate an exception.
        day = date(2000, 1, 5)  # The day we want our total to start on.
        start = date(2000, 1, 10)  # The day our metrics start.
        buckets = [1, 2, 3, 4, 5, 6, 7]
        overflow = 100
        with self.assertRaisesRegexp(ValueError, 'data not available'):
            DatedMetric._get_range_total(5, day, start, buckets, overflow)


class TestDatedMetricSource(MongoTestBase):
    """Verify that storing and retrieving DatedMetrics works."""

    def setUp(self):
        super(TestDatedMetricSource, self).setUp()
        self.collection = self.db.create_collection(factory.random_string(10))
        self.source = DatedMetricSource(self.collection)

    def test_creating_source_from_collection(self):
        # The metrics are stored in a MongoDB collection, so the source
        # constructor requires that collection as an argument.
        collection = self.db.create_collection(factory.random_string(10))
        DatedMetricSource(collection)

    def test_creating_source_from_db(self):
        # The DatedMetricSource can be created from a db, in which case it
        # uses a particular collection.
        source = DatedMetricSource.from_db(self.db)
        self.assertEqual(source.collection.name, 'dated_metrics')

    def test_storing_a_metric(self):
        # Metrics are associated with a given key when stored.
        metric = DatedMetric(start=date(2000, 1, 1))
        self.source.store(metric, 'metric-key')

    def test_retrieving_a_metric(self):
        # Metrics can be retrieved by their associated key.
        metric = DatedMetric(start=date(2000, 1, 1))
        self.source.store(metric, 'metric-key')
        retrieved = self.source.retrieve('metric-key')
        self.assertEqual(retrieved, metric)

    def test_retrieving_a_metric_that_does_not_exist(self):
        # If a key is given that does not have a matching metric, a KeyError
        # is generated.
        with self.assertRaises(KeyError):
            self.source.retrieve('missing-key')

    def test_key_quoting(self):
        # Keys are quoted to make them MongoDB-safe.
        metric = DatedMetric(start=date(2000, 1, 1))
        key = 'very.bad$key%name'

        # We need a simple fake collection for this test.
        real_collection = self.collection
        saved_keys = []
        found_keys = []

        class FauxCollection:

            def save(self, document):
                saved_keys.append(document['_id'])
                real_collection.save(document)

            def find_one(self, spec):
                found_keys.append(spec['_id'])
                return real_collection.find_one(spec)

        self.source.collection = FauxCollection()

        # If a metric is saved with the quote-worthy key...
        self.source.store(metric, key)
        # ...the key is quoted before being written to the collection.
        self.assertEqual(saved_keys, [quote_key(key)])

        # If the metric is then retrieved using the same unquoted key...
        retrieved = self.source.retrieve(key)
        # ...the key is quoted when doing the find, and...
        self.assertEqual(found_keys, [quote_key(key)])
        # ...the correct metric is returned.
        self.assertEqual(retrieved, metric)


def mock_from_buffer(content, mime):
    return 'image/svg+xml'


class TestSetViewBox(TestCase):
    """Test the set_view_box function."""

    def test_mime_type_not_svg(self):
        # If the mime type returned by magic.from_buffer is not an SVG then an
        # error is raised.
        with patch('magic.from_buffer', lambda a, mime: 'image/jpeg'):
            with self.assertRaisesRegexp(BadSVGError,
                                         'File is not an SVG: path'):
                set_view_box('path', 'content')

    @patch('magic.from_buffer', mock_from_buffer)
    def test_viewbox_provided(self):
        # If the mime type is correct and a viewBox is supplied then the
        # contents are unchanged.
        file_content = '<svg viewBox="0 0 1 1"></svg>'
        result = set_view_box('path', file_content)
        self.assertEqual(file_content, result)

    @patch('magic.from_buffer', mock_from_buffer)
    def test_no_viewbox_no_width(self):
        # No viewBox and no width raises an error.
        file_content = '<svg height="10"></svg>'
        with self.assertRaisesRegexp(
                BadSVGError,
                'SVG is malformed: width or height attributes not set'):
            set_view_box('path', file_content)

    @patch('magic.from_buffer', mock_from_buffer)
    def test_no_viewbox_no_height(self):
        # No viewBox and no height raises an error.
        file_content = '<svg width="10"></svg>'
        with self.assertRaisesRegexp(
                BadSVGError,
                'SVG is malformed: width or height attributes not set'):
            set_view_box('path', file_content)

    @patch('magic.from_buffer', mock_from_buffer)
    def test_height_negative(self):
        # Negative height raises an error.
        file_content = '<svg height="-12" width="10"></svg>'
        with self.assertRaisesRegexp(
                BadSVGError,
                'SVG is malformed: width and height must be greater than 0'):
            set_view_box('path', file_content)

    @patch('magic.from_buffer', mock_from_buffer)
    def test_width_negative(self):
        # Negative height raises an error.
        file_content = '<svg height="12" width="-10"></svg>'
        with self.assertRaisesRegexp(
                BadSVGError,
                'SVG is malformed: width and height must be greater than 0'):
            set_view_box('path', file_content)

    @patch('magic.from_buffer', mock_from_buffer)
    def test_viewbox_not_provided_modify_contents(self):
        # If the mime type is correct and a viewBox is supplied then the
        # contents are unchanged.
        file_content = '<svg width="10" height="11"></svg>'
        expected = ElementTree.fromstring(file_content)
        expected.attrib['viewBox'] = "0 0 10 11"
        expected = ElementTree.tostring(expected, encoding='UTF-8')
        result = set_view_box('path', file_content)
        self.assertEqual(expected, result)

    @patch('magic.from_buffer', mock_from_buffer)
    def test_floats_for_width_and_height_are_ok(self):
        # If the mime type is correct and a viewBox is supplied then the
        # contents are unchanged.
        file_content = '<svg width="10.7" height="11.2"></svg>'
        expected = ElementTree.fromstring(file_content)
        expected.attrib['viewBox'] = "0 0 10.7 11.2"
        expected = ElementTree.tostring(expected, encoding='UTF-8')
        result = set_view_box('path', file_content)
        self.assertEqual(expected, result)