summaryrefslogtreecommitdiff
path: root/neutron/tests/unit/test_db_plugin.py
blob: ec624c59fbdb456165a42394558bbd1c40485763 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
# Copyright (c) 2012 OpenStack Foundation.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import contextlib
import copy
import itertools

import mock
from oslo.config import cfg
from testtools import matchers
import webob.exc

import neutron
from neutron.api import api_common
from neutron.api import extensions
from neutron.api.v2 import attributes
from neutron.api.v2 import router
from neutron.common import constants
from neutron.common import exceptions as n_exc
from neutron.common import ipv6_utils
from neutron.common import test_lib
from neutron.common import utils
from neutron import context
from neutron.db import db_base_plugin_v2
from neutron.db import models_v2
from neutron import manager
from neutron.openstack.common import importutils
from neutron.tests import base
from neutron.tests.unit import test_extensions
from neutron.tests.unit import testlib_api
from neutron.tests.unit import testlib_plugin

DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2'


def optional_ctx(obj, fallback):
    if not obj:
        return fallback()

    @contextlib.contextmanager
    def context_wrapper():
        yield obj
    return context_wrapper()


def _fake_get_pagination_helper(self, request):
    return api_common.PaginationEmulatedHelper(request, self._primary_key)


def _fake_get_sorting_helper(self, request):
    return api_common.SortingEmulatedHelper(request, self._attr_info)


class NeutronDbPluginV2TestCase(testlib_api.WebTestCase,
                                testlib_plugin.PluginSetupHelper):
    fmt = 'json'
    resource_prefix_map = {}

    def setUp(self, plugin=None, service_plugins=None,
              ext_mgr=None):

        super(NeutronDbPluginV2TestCase, self).setUp()
        cfg.CONF.set_override('notify_nova_on_port_status_changes', False)
        # Make sure at each test according extensions for the plugin is loaded
        extensions.PluginAwareExtensionManager._instance = None
        # Save the attributes map in case the plugin will alter it
        # loading extensions
        # Note(salvatore-orlando): shallow copy is not good enough in
        # this case, but copy.deepcopy does not seem to work, since it
        # causes test failures
        self._attribute_map_bk = {}
        for item in attributes.RESOURCE_ATTRIBUTE_MAP:
            self._attribute_map_bk[item] = (attributes.
                                            RESOURCE_ATTRIBUTE_MAP[item].
                                            copy())
        self._tenant_id = 'test-tenant'

        if not plugin:
            plugin = DB_PLUGIN_KLASS

        # Update the plugin
        self.setup_coreplugin(plugin)
        cfg.CONF.set_override(
            'service_plugins',
            [test_lib.test_config.get(key, default)
             for key, default in (service_plugins or {}).iteritems()]
        )

        cfg.CONF.set_override('base_mac', "12:34:56:78:90:ab")
        cfg.CONF.set_override('max_dns_nameservers', 2)
        cfg.CONF.set_override('max_subnet_host_routes', 2)
        cfg.CONF.set_override('allow_pagination', True)
        cfg.CONF.set_override('allow_sorting', True)
        self.api = router.APIRouter()
        # Set the defualt status
        self.net_create_status = 'ACTIVE'
        self.port_create_status = 'ACTIVE'

        def _is_native_bulk_supported():
            plugin_obj = manager.NeutronManager.get_plugin()
            native_bulk_attr_name = ("_%s__native_bulk_support"
                                     % plugin_obj.__class__.__name__)
            return getattr(plugin_obj, native_bulk_attr_name, False)

        self._skip_native_bulk = not _is_native_bulk_supported()

        def _is_native_pagination_support():
            native_pagination_attr_name = (
                "_%s__native_pagination_support" %
                manager.NeutronManager.get_plugin().__class__.__name__)
            return (cfg.CONF.allow_pagination and
                    getattr(manager.NeutronManager.get_plugin(),
                            native_pagination_attr_name, False))

        self._skip_native_pagination = not _is_native_pagination_support()

        def _is_native_sorting_support():
            native_sorting_attr_name = (
                "_%s__native_sorting_support" %
                manager.NeutronManager.get_plugin().__class__.__name__)
            return (cfg.CONF.allow_sorting and
                    getattr(manager.NeutronManager.get_plugin(),
                            native_sorting_attr_name, False))

        self._skip_native_sorting = not _is_native_sorting_support()
        if ext_mgr:
            self.ext_api = test_extensions.setup_extensions_middleware(ext_mgr)

    def tearDown(self):
        self.api = None
        self._deserializers = None
        self._skip_native_bulk = None
        self._skip_native_pagination = None
        self._skip_native_sortin = None
        self.ext_api = None
        # Restore the original attribute map
        attributes.RESOURCE_ATTRIBUTE_MAP = self._attribute_map_bk
        super(NeutronDbPluginV2TestCase, self).tearDown()

    def setup_config(self):
        # Create the default configurations
        args = ['--config-file', base.etcdir('neutron.conf.test')]
        # If test_config specifies some config-file, use it, as well
        for config_file in test_lib.test_config.get('config_files', []):
            args.extend(['--config-file', config_file])
        self.config_parse(args=args)

    def _req(self, method, resource, data=None, fmt=None, id=None, params=None,
             action=None, subresource=None, sub_id=None, context=None):
        fmt = fmt or self.fmt

        path = '/%s.%s' % (
            '/'.join(p for p in
                     (resource, id, subresource, sub_id, action) if p),
            fmt
        )

        prefix = self.resource_prefix_map.get(resource)
        if prefix:
            path = prefix + path

        content_type = 'application/%s' % fmt
        body = None
        if data is not None:  # empty dict is valid
            body = self.serialize(data)
        return testlib_api.create_request(path, body, content_type, method,
                                          query_string=params, context=context)

    def new_create_request(self, resource, data, fmt=None, id=None,
                           subresource=None):
        return self._req('POST', resource, data, fmt, id=id,
                         subresource=subresource)

    def new_list_request(self, resource, fmt=None, params=None,
                         subresource=None):
        return self._req(
            'GET', resource, None, fmt, params=params, subresource=subresource
        )

    def new_show_request(self, resource, id, fmt=None,
                         subresource=None, fields=None):
        if fields:
            params = "&".join(["fields=%s" % x for x in fields])
        else:
            params = None
        return self._req('GET', resource, None, fmt, id=id,
                         params=params, subresource=subresource)

    def new_delete_request(self, resource, id, fmt=None, subresource=None,
                           sub_id=None):
        return self._req(
            'DELETE',
            resource,
            None,
            fmt,
            id=id,
            subresource=subresource,
            sub_id=sub_id
        )

    def new_update_request(self, resource, data, id, fmt=None,
                           subresource=None, context=None):
        return self._req(
            'PUT', resource, data, fmt, id=id, subresource=subresource,
            context=context
        )

    def new_action_request(self, resource, data, id, action, fmt=None,
                           subresource=None):
        return self._req(
            'PUT',
            resource,
            data,
            fmt,
            id=id,
            action=action,
            subresource=subresource
        )

    def deserialize(self, content_type, response):
        ctype = 'application/%s' % content_type
        data = self._deserializers[ctype].deserialize(response.body)['body']
        return data

    def _create_bulk_from_list(self, fmt, resource, objects, **kwargs):
        """Creates a bulk request from a list of objects."""
        collection = "%ss" % resource
        req_data = {collection: objects}
        req = self.new_create_request(collection, req_data, fmt)
        if ('set_context' in kwargs and
                kwargs['set_context'] is True and
                'tenant_id' in kwargs):
            # create a specific auth context for this request
            req.environ['neutron.context'] = context.Context(
                '', kwargs['tenant_id'])
        elif 'context' in kwargs:
            req.environ['neutron.context'] = kwargs['context']
        return req.get_response(self.api)

    def _create_bulk(self, fmt, number, resource, data, name='test', **kwargs):
        """Creates a bulk request for any kind of resource."""
        objects = []
        collection = "%ss" % resource
        for i in range(number):
            obj = copy.deepcopy(data)
            obj[resource]['name'] = "%s_%s" % (name, i)
            if 'override' in kwargs and i in kwargs['override']:
                obj[resource].update(kwargs['override'][i])
            objects.append(obj)
        req_data = {collection: objects}
        req = self.new_create_request(collection, req_data, fmt)
        if ('set_context' in kwargs and
                kwargs['set_context'] is True and
                'tenant_id' in kwargs):
            # create a specific auth context for this request
            req.environ['neutron.context'] = context.Context(
                '', kwargs['tenant_id'])
        elif 'context' in kwargs:
            req.environ['neutron.context'] = kwargs['context']
        return req.get_response(self.api)

    def _create_network(self, fmt, name, admin_state_up,
                        arg_list=None, **kwargs):
        data = {'network': {'name': name,
                            'admin_state_up': admin_state_up,
                            'tenant_id': self._tenant_id}}
        for arg in (('admin_state_up', 'tenant_id', 'shared') +
                    (arg_list or ())):
            # Arg must be present
            if arg in kwargs:
                data['network'][arg] = kwargs[arg]
        network_req = self.new_create_request('networks', data, fmt)
        if (kwargs.get('set_context') and 'tenant_id' in kwargs):
            # create a specific auth context for this request
            network_req.environ['neutron.context'] = context.Context(
                '', kwargs['tenant_id'])

        return network_req.get_response(self.api)

    def _create_network_bulk(self, fmt, number, name,
                             admin_state_up, **kwargs):
        base_data = {'network': {'admin_state_up': admin_state_up,
                                 'tenant_id': self._tenant_id}}
        return self._create_bulk(fmt, number, 'network', base_data, **kwargs)

    def _create_subnet(self, fmt, net_id, cidr,
                       expected_res_status=None, **kwargs):
        data = {'subnet': {'network_id': net_id,
                           'cidr': cidr,
                           'ip_version': 4,
                           'tenant_id': self._tenant_id}}
        for arg in ('ip_version', 'tenant_id',
                    'enable_dhcp', 'allocation_pools',
                    'dns_nameservers', 'host_routes',
                    'shared', 'ipv6_ra_mode', 'ipv6_address_mode'):
            # Arg must be present and not null (but can be false)
            if arg in kwargs and kwargs[arg] is not None:
                data['subnet'][arg] = kwargs[arg]

        if ('gateway_ip' in kwargs and
            kwargs['gateway_ip'] is not attributes.ATTR_NOT_SPECIFIED):
            data['subnet']['gateway_ip'] = kwargs['gateway_ip']

        subnet_req = self.new_create_request('subnets', data, fmt)
        if (kwargs.get('set_context') and 'tenant_id' in kwargs):
            # create a specific auth context for this request
            subnet_req.environ['neutron.context'] = context.Context(
                '', kwargs['tenant_id'])

        subnet_res = subnet_req.get_response(self.api)
        if expected_res_status:
            self.assertEqual(subnet_res.status_int, expected_res_status)
        return subnet_res

    def _create_subnet_bulk(self, fmt, number, net_id, name,
                            ip_version=4, **kwargs):
        base_data = {'subnet': {'network_id': net_id,
                                'ip_version': ip_version,
                                'tenant_id': self._tenant_id}}
        # auto-generate cidrs as they should not overlap
        overrides = dict((k, v)
                         for (k, v) in zip(range(number),
                                           [{'cidr': "10.0.%s.0/24" % num}
                                            for num in range(number)]))
        kwargs.update({'override': overrides})
        return self._create_bulk(fmt, number, 'subnet', base_data, **kwargs)

    def _create_port(self, fmt, net_id, expected_res_status=None,
                     arg_list=None, **kwargs):
        data = {'port': {'network_id': net_id,
                         'tenant_id': self._tenant_id}}

        for arg in (('admin_state_up', 'device_id',
                    'mac_address', 'name', 'fixed_ips',
                    'tenant_id', 'device_owner', 'security_groups') +
                    (arg_list or ())):
            # Arg must be present
            if arg in kwargs:
                data['port'][arg] = kwargs[arg]
        # create a dhcp port device id if one hasn't been supplied
        if ('device_owner' in kwargs and
            kwargs['device_owner'] == constants.DEVICE_OWNER_DHCP and
            'host' in kwargs and
            not 'device_id' in kwargs):
            device_id = utils.get_dhcp_agent_device_id(net_id, kwargs['host'])
            data['port']['device_id'] = device_id
        port_req = self.new_create_request('ports', data, fmt)
        if (kwargs.get('set_context') and 'tenant_id' in kwargs):
            # create a specific auth context for this request
            port_req.environ['neutron.context'] = context.Context(
                '', kwargs['tenant_id'])

        port_res = port_req.get_response(self.api)
        if expected_res_status:
            self.assertEqual(port_res.status_int, expected_res_status)
        return port_res

    def _list_ports(self, fmt, expected_res_status=None,
                    net_id=None, **kwargs):
        query_params = []
        if net_id:
            query_params.append("network_id=%s" % net_id)
        if kwargs.get('device_owner'):
            query_params.append("device_owner=%s" % kwargs.get('device_owner'))
        port_req = self.new_list_request('ports', fmt, '&'.join(query_params))
        if ('set_context' in kwargs and
                kwargs['set_context'] is True and
                'tenant_id' in kwargs):
            # create a specific auth context for this request
            port_req.environ['neutron.context'] = context.Context(
                '', kwargs['tenant_id'])

        port_res = port_req.get_response(self.api)
        if expected_res_status:
            self.assertEqual(port_res.status_int, expected_res_status)
        return port_res

    def _create_port_bulk(self, fmt, number, net_id, name,
                          admin_state_up, **kwargs):
        base_data = {'port': {'network_id': net_id,
                              'admin_state_up': admin_state_up,
                              'tenant_id': self._tenant_id}}
        return self._create_bulk(fmt, number, 'port', base_data, **kwargs)

    def _make_network(self, fmt, name, admin_state_up, **kwargs):
        res = self._create_network(fmt, name, admin_state_up, **kwargs)
        # TODO(salvatore-orlando): do exception handling in this test module
        # in a uniform way (we do it differently for ports, subnets, and nets
        # Things can go wrong - raise HTTP exc with res code only
        # so it can be caught by unit tests
        if res.status_int >= webob.exc.HTTPClientError.code:
            raise webob.exc.HTTPClientError(code=res.status_int)
        return self.deserialize(fmt, res)

    def _make_subnet(self, fmt, network, gateway, cidr,
                     allocation_pools=None, ip_version=4, enable_dhcp=True,
                     dns_nameservers=None, host_routes=None, shared=None,
                     ipv6_ra_mode=None, ipv6_address_mode=None):
        res = self._create_subnet(fmt,
                                  net_id=network['network']['id'],
                                  cidr=cidr,
                                  gateway_ip=gateway,
                                  tenant_id=network['network']['tenant_id'],
                                  allocation_pools=allocation_pools,
                                  ip_version=ip_version,
                                  enable_dhcp=enable_dhcp,
                                  dns_nameservers=dns_nameservers,
                                  host_routes=host_routes,
                                  shared=shared,
                                  ipv6_ra_mode=ipv6_ra_mode,
                                  ipv6_address_mode=ipv6_address_mode)
        # Things can go wrong - raise HTTP exc with res code only
        # so it can be caught by unit tests
        if res.status_int >= webob.exc.HTTPClientError.code:
            raise webob.exc.HTTPClientError(code=res.status_int)
        return self.deserialize(fmt, res)

    def _make_port(self, fmt, net_id, expected_res_status=None, **kwargs):
        res = self._create_port(fmt, net_id, expected_res_status, **kwargs)
        # Things can go wrong - raise HTTP exc with res code only
        # so it can be caught by unit tests
        if res.status_int >= webob.exc.HTTPClientError.code:
            raise webob.exc.HTTPClientError(code=res.status_int)
        return self.deserialize(fmt, res)

    def _api_for_resource(self, resource):
        if resource in ['networks', 'subnets', 'ports']:
            return self.api
        else:
            return self.ext_api

    def _delete(self, collection, id,
                expected_code=webob.exc.HTTPNoContent.code,
                neutron_context=None):
        req = self.new_delete_request(collection, id)
        if neutron_context:
            # create a specific auth context for this request
            req.environ['neutron.context'] = neutron_context
        res = req.get_response(self._api_for_resource(collection))
        self.assertEqual(res.status_int, expected_code)

    def _show(self, resource, id,
              expected_code=webob.exc.HTTPOk.code,
              neutron_context=None):
        req = self.new_show_request(resource, id)
        if neutron_context:
            # create a specific auth context for this request
            req.environ['neutron.context'] = neutron_context
        res = req.get_response(self._api_for_resource(resource))
        self.assertEqual(res.status_int, expected_code)
        return self.deserialize(self.fmt, res)

    def _update(self, resource, id, new_data,
                expected_code=webob.exc.HTTPOk.code,
                neutron_context=None):
        req = self.new_update_request(resource, new_data, id)
        if neutron_context:
            # create a specific auth context for this request
            req.environ['neutron.context'] = neutron_context
        res = req.get_response(self._api_for_resource(resource))
        self.assertEqual(res.status_int, expected_code)
        return self.deserialize(self.fmt, res)

    def _list(self, resource, fmt=None, neutron_context=None,
              query_params=None):
        fmt = fmt or self.fmt
        req = self.new_list_request(resource, fmt, query_params)
        if neutron_context:
            req.environ['neutron.context'] = neutron_context
        res = req.get_response(self._api_for_resource(resource))
        self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
        return self.deserialize(fmt, res)

    def _fail_second_call(self, patched_plugin, orig, *args, **kwargs):
        """Invoked by test cases for injecting failures in plugin."""
        def second_call(*args, **kwargs):
            raise n_exc.NeutronException()
        patched_plugin.side_effect = second_call
        return orig(*args, **kwargs)

    def _validate_behavior_on_bulk_failure(
            self, res, collection,
            errcode=webob.exc.HTTPClientError.code):
        self.assertEqual(res.status_int, errcode)
        req = self.new_list_request(collection)
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
        items = self.deserialize(self.fmt, res)
        self.assertEqual(len(items[collection]), 0)

    def _validate_behavior_on_bulk_success(self, res, collection,
                                           names=['test_0', 'test_1']):
        self.assertEqual(res.status_int, webob.exc.HTTPCreated.code)
        items = self.deserialize(self.fmt, res)[collection]
        self.assertEqual(len(items), 2)
        self.assertEqual(items[0]['name'], 'test_0')
        self.assertEqual(items[1]['name'], 'test_1')

    def _test_list_resources(self, resource, items, neutron_context=None,
                             query_params=None):
        res = self._list('%ss' % resource,
                         neutron_context=neutron_context,
                         query_params=query_params)
        resource = resource.replace('-', '_')
        self.assertEqual(sorted([i['id'] for i in res['%ss' % resource]]),
                         sorted([i[resource]['id'] for i in items]))

    @contextlib.contextmanager
    def network(self, name='net1',
                admin_state_up=True,
                fmt=None,
                **kwargs):
        network = self._make_network(fmt or self.fmt, name,
                                     admin_state_up, **kwargs)
        yield network

    @contextlib.contextmanager
    def subnet(self, network=None,
               gateway_ip=attributes.ATTR_NOT_SPECIFIED,
               cidr='10.0.0.0/24',
               fmt=None,
               ip_version=4,
               allocation_pools=None,
               enable_dhcp=True,
               dns_nameservers=None,
               host_routes=None,
               shared=None,
               ipv6_ra_mode=None,
               ipv6_address_mode=None):
        with optional_ctx(network, self.network) as network_to_use:
            subnet = self._make_subnet(fmt or self.fmt,
                                       network_to_use,
                                       gateway_ip,
                                       cidr,
                                       allocation_pools,
                                       ip_version,
                                       enable_dhcp,
                                       dns_nameservers,
                                       host_routes,
                                       shared=shared,
                                       ipv6_ra_mode=ipv6_ra_mode,
                                       ipv6_address_mode=ipv6_address_mode)
            yield subnet

    @contextlib.contextmanager
    def port(self, subnet=None, fmt=None, **kwargs):
        with optional_ctx(subnet, self.subnet) as subnet_to_use:
            net_id = subnet_to_use['subnet']['network_id']
            port = self._make_port(fmt or self.fmt, net_id, **kwargs)
            yield port

    def _test_list_with_sort(self, resource,
                             items, sorts, resources=None, query_params=''):
        query_str = query_params
        for key, direction in sorts:
            query_str = query_str + "&sort_key=%s&sort_dir=%s" % (key,
                                                                  direction)
        if not resources:
            resources = '%ss' % resource
        req = self.new_list_request(resources,
                                    params=query_str)
        api = self._api_for_resource(resources)
        res = self.deserialize(self.fmt, req.get_response(api))
        resource = resource.replace('-', '_')
        resources = resources.replace('-', '_')
        expected_res = [item[resource]['id'] for item in items]
        self.assertEqual(expected_res, [n['id'] for n in res[resources]])

    def _test_list_with_pagination(self, resource, items, sort,
                                   limit, expected_page_num,
                                   resources=None,
                                   query_params='',
                                   verify_key='id'):
        if not resources:
            resources = '%ss' % resource
        query_str = query_params + '&' if query_params else ''
        query_str = query_str + ("limit=%s&sort_key=%s&"
                                 "sort_dir=%s") % (limit, sort[0], sort[1])
        req = self.new_list_request(resources, params=query_str)
        items_res = []
        page_num = 0
        api = self._api_for_resource(resources)
        resource = resource.replace('-', '_')
        resources = resources.replace('-', '_')
        while req:
            page_num = page_num + 1
            res = self.deserialize(self.fmt, req.get_response(api))
            self.assertThat(len(res[resources]),
                            matchers.LessThan(limit + 1))
            items_res = items_res + res[resources]
            req = None
            if '%s_links' % resources in res:
                for link in res['%s_links' % resources]:
                    if link['rel'] == 'next':
                        content_type = 'application/%s' % self.fmt
                        req = testlib_api.create_request(link['href'],
                                                         '', content_type)
                        self.assertEqual(len(res[resources]),
                                         limit)
        self.assertEqual(expected_page_num, page_num)
        self.assertEqual([item[resource][verify_key] for item in items],
                         [n[verify_key] for n in items_res])

    def _test_list_with_pagination_reverse(self, resource, items, sort,
                                           limit, expected_page_num,
                                           resources=None,
                                           query_params=''):
        if not resources:
            resources = '%ss' % resource
        resource = resource.replace('-', '_')
        api = self._api_for_resource(resources)
        marker = items[-1][resource]['id']
        query_str = query_params + '&' if query_params else ''
        query_str = query_str + ("limit=%s&page_reverse=True&"
                                 "sort_key=%s&sort_dir=%s&"
                                 "marker=%s") % (limit, sort[0], sort[1],
                                                 marker)
        req = self.new_list_request(resources, params=query_str)
        item_res = [items[-1][resource]]
        page_num = 0
        resources = resources.replace('-', '_')
        while req:
            page_num = page_num + 1
            res = self.deserialize(self.fmt, req.get_response(api))
            self.assertThat(len(res[resources]),
                            matchers.LessThan(limit + 1))
            res[resources].reverse()
            item_res = item_res + res[resources]
            req = None
            if '%s_links' % resources in res:
                for link in res['%s_links' % resources]:
                    if link['rel'] == 'previous':
                        content_type = 'application/%s' % self.fmt
                        req = testlib_api.create_request(link['href'],
                                                         '', content_type)
                        self.assertEqual(len(res[resources]),
                                         limit)
        self.assertEqual(expected_page_num, page_num)
        expected_res = [item[resource]['id'] for item in items]
        expected_res.reverse()
        self.assertEqual(expected_res, [n['id'] for n in item_res])


class TestBasicGet(NeutronDbPluginV2TestCase):

    def test_single_get_admin(self):
        plugin = neutron.db.db_base_plugin_v2.NeutronDbPluginV2()
        with self.network() as network:
            net_id = network['network']['id']
            ctx = context.get_admin_context()
            n = plugin._get_network(ctx, net_id)
            self.assertEqual(net_id, n.id)

    def test_single_get_tenant(self):
        plugin = neutron.db.db_base_plugin_v2.NeutronDbPluginV2()
        with self.network() as network:
            net_id = network['network']['id']
            ctx = context.get_admin_context()
            n = plugin._get_network(ctx, net_id)
            self.assertEqual(net_id, n.id)


class TestV2HTTPResponse(NeutronDbPluginV2TestCase):
    def test_create_returns_201(self):
        res = self._create_network(self.fmt, 'net2', True)
        self.assertEqual(res.status_int, webob.exc.HTTPCreated.code)

    def test_list_returns_200(self):
        req = self.new_list_request('networks')
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPOk.code)

    def _check_list_with_fields(self, res, field_name):
        self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
        body = self.deserialize(self.fmt, res)
        # further checks: 1 networks
        self.assertEqual(len(body['networks']), 1)
        # 1 field in the network record
        self.assertEqual(len(body['networks'][0]), 1)
        # field is 'name'
        self.assertIn(field_name, body['networks'][0])

    def test_list_with_fields(self):
        self._create_network(self.fmt, 'some_net', True)
        req = self.new_list_request('networks', params="fields=name")
        res = req.get_response(self.api)
        self._check_list_with_fields(res, 'name')

    def test_list_with_fields_noadmin(self):
        tenant_id = 'some_tenant'
        self._create_network(self.fmt,
                             'some_net',
                             True,
                             tenant_id=tenant_id,
                             set_context=True)
        req = self.new_list_request('networks', params="fields=name")
        req.environ['neutron.context'] = context.Context('', tenant_id)
        res = req.get_response(self.api)
        self._check_list_with_fields(res, 'name')

    def test_list_with_fields_noadmin_and_policy_field(self):
        """If a field used by policy is selected, do not duplicate it.

        Verifies that if the field parameter explicitly specifies a field
        which is used by the policy engine, then it is not duplicated
        in the response.

        """
        tenant_id = 'some_tenant'
        self._create_network(self.fmt,
                             'some_net',
                             True,
                             tenant_id=tenant_id,
                             set_context=True)
        req = self.new_list_request('networks', params="fields=tenant_id")
        req.environ['neutron.context'] = context.Context('', tenant_id)
        res = req.get_response(self.api)
        self._check_list_with_fields(res, 'tenant_id')

    def test_show_returns_200(self):
        with self.network() as net:
            req = self.new_show_request('networks', net['network']['id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPOk.code)

    def test_delete_returns_204(self):
        res = self._create_network(self.fmt, 'net1', True)
        net = self.deserialize(self.fmt, res)
        req = self.new_delete_request('networks', net['network']['id'])
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)

    def test_update_returns_200(self):
        with self.network() as net:
            req = self.new_update_request('networks',
                                          {'network': {'name': 'steve'}},
                                          net['network']['id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPOk.code)

    def test_update_invalid_json_400(self):
        with self.network() as net:
            req = self.new_update_request('networks',
                                          '{{"name": "aaa"}}',
                                          net['network']['id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_bad_route_404(self):
        req = self.new_list_request('doohickeys')
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code)


class TestPortsV2(NeutronDbPluginV2TestCase):
    def test_create_port_json(self):
        keys = [('admin_state_up', True), ('status', self.port_create_status)]
        with self.port(name='myname') as port:
            for k, v in keys:
                self.assertEqual(port['port'][k], v)
            self.assertIn('mac_address', port['port'])
            ips = port['port']['fixed_ips']
            self.assertEqual(len(ips), 1)
            self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
            self.assertEqual('myname', port['port']['name'])

    def test_create_port_as_admin(self):
        with self.network() as network:
            self._create_port(self.fmt,
                              network['network']['id'],
                              webob.exc.HTTPCreated.code,
                              tenant_id='bad_tenant_id',
                              device_id='fake_device',
                              device_owner='fake_owner',
                              fixed_ips=[],
                              set_context=False)

    def test_create_port_bad_tenant(self):
        with self.network() as network:
            self._create_port(self.fmt,
                              network['network']['id'],
                              webob.exc.HTTPNotFound.code,
                              tenant_id='bad_tenant_id',
                              device_id='fake_device',
                              device_owner='fake_owner',
                              fixed_ips=[],
                              set_context=True)

    def test_create_port_public_network(self):
        keys = [('admin_state_up', True), ('status', self.port_create_status)]
        with self.network(shared=True) as network:
            port_res = self._create_port(self.fmt,
                                         network['network']['id'],
                                         webob.exc.HTTPCreated.code,
                                         tenant_id='another_tenant',
                                         set_context=True)
            port = self.deserialize(self.fmt, port_res)
            for k, v in keys:
                self.assertEqual(port['port'][k], v)
            self.assertIn('mac_address', port['port'])
            self._delete('ports', port['port']['id'])

    def test_create_port_public_network_with_ip(self):
        with self.network(shared=True) as network:
            with self.subnet(network=network, cidr='10.0.0.0/24') as subnet:
                keys = [('admin_state_up', True),
                        ('status', self.port_create_status),
                        ('fixed_ips', [{'subnet_id': subnet['subnet']['id'],
                                        'ip_address': '10.0.0.2'}])]
                port_res = self._create_port(self.fmt,
                                             network['network']['id'],
                                             webob.exc.HTTPCreated.code,
                                             tenant_id='another_tenant',
                                             set_context=True)
                port = self.deserialize(self.fmt, port_res)
                for k, v in keys:
                    self.assertEqual(port['port'][k], v)
                self.assertIn('mac_address', port['port'])
                self._delete('ports', port['port']['id'])

    def test_create_ports_bulk_native(self):
        if self._skip_native_bulk:
            self.skipTest("Plugin does not support native bulk port create")
        with self.network() as net:
            res = self._create_port_bulk(self.fmt, 2, net['network']['id'],
                                         'test', True)
            self._validate_behavior_on_bulk_success(res, 'ports')
            for p in self.deserialize(self.fmt, res)['ports']:
                self._delete('ports', p['id'])

    def test_create_ports_bulk_emulated(self):
        real_has_attr = hasattr

        #ensures the API choose the emulation code path
        def fakehasattr(item, attr):
            if attr.endswith('__native_bulk_support'):
                return False
            return real_has_attr(item, attr)

        with mock.patch('__builtin__.hasattr',
                        new=fakehasattr):
            with self.network() as net:
                res = self._create_port_bulk(self.fmt, 2, net['network']['id'],
                                             'test', True)
                self._validate_behavior_on_bulk_success(res, 'ports')
                for p in self.deserialize(self.fmt, res)['ports']:
                    self._delete('ports', p['id'])

    def test_create_ports_bulk_wrong_input(self):
        with self.network() as net:
            overrides = {1: {'admin_state_up': 'doh'}}
            res = self._create_port_bulk(self.fmt, 2, net['network']['id'],
                                         'test', True,
                                         override=overrides)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)
            req = self.new_list_request('ports')
            res = req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
            ports = self.deserialize(self.fmt, res)
            self.assertEqual(len(ports['ports']), 0)

    def test_create_ports_bulk_emulated_plugin_failure(self):
        real_has_attr = hasattr

        #ensures the API choose the emulation code path
        def fakehasattr(item, attr):
            if attr.endswith('__native_bulk_support'):
                return False
            return real_has_attr(item, attr)

        with mock.patch('__builtin__.hasattr',
                        new=fakehasattr):
            orig = manager.NeutronManager.get_plugin().create_port
            with mock.patch.object(manager.NeutronManager.get_plugin(),
                                   'create_port') as patched_plugin:

                def side_effect(*args, **kwargs):
                    return self._fail_second_call(patched_plugin, orig,
                                                  *args, **kwargs)

                patched_plugin.side_effect = side_effect
                with self.network() as net:
                    res = self._create_port_bulk(self.fmt, 2,
                                                 net['network']['id'],
                                                 'test',
                                                 True)
                    # We expect a 500 as we injected a fault in the plugin
                    self._validate_behavior_on_bulk_failure(
                        res, 'ports', webob.exc.HTTPServerError.code
                    )

    def test_create_ports_bulk_native_plugin_failure(self):
        if self._skip_native_bulk:
            self.skipTest("Plugin does not support native bulk port create")
        ctx = context.get_admin_context()
        with self.network() as net:
            plugin = manager.NeutronManager.get_plugin()
            orig = plugin.create_port
            with mock.patch.object(plugin, 'create_port') as patched_plugin:

                def side_effect(*args, **kwargs):
                    return self._fail_second_call(patched_plugin, orig,
                                                  *args, **kwargs)

                patched_plugin.side_effect = side_effect
                res = self._create_port_bulk(self.fmt, 2, net['network']['id'],
                                             'test', True, context=ctx)
                # We expect a 500 as we injected a fault in the plugin
                self._validate_behavior_on_bulk_failure(
                    res, 'ports', webob.exc.HTTPServerError.code)

    def test_list_ports(self):
        # for this test we need to enable overlapping ips
        cfg.CONF.set_default('allow_overlapping_ips', True)
        with contextlib.nested(self.port(),
                               self.port(),
                               self.port()) as ports:
            self._test_list_resources('port', ports)

    def test_list_ports_filtered_by_fixed_ip(self):
        # for this test we need to enable overlapping ips
        cfg.CONF.set_default('allow_overlapping_ips', True)
        with contextlib.nested(self.port(), self.port()) as (port1, port2):
            fixed_ips = port1['port']['fixed_ips'][0]
            query_params = """
fixed_ips=ip_address%%3D%s&fixed_ips=ip_address%%3D%s&fixed_ips=subnet_id%%3D%s
""".strip() % (fixed_ips['ip_address'],
               '192.168.126.5',
               fixed_ips['subnet_id'])
            self._test_list_resources('port', [port1],
                                      query_params=query_params)

    def test_list_ports_public_network(self):
        with self.network(shared=True) as network:
            with self.subnet(network) as subnet:
                with contextlib.nested(self.port(subnet, tenant_id='tenant_1'),
                                       self.port(subnet, tenant_id='tenant_2')
                                       ) as (port1, port2):
                    # Admin request - must return both ports
                    self._test_list_resources('port', [port1, port2])
                    # Tenant_1 request - must return single port
                    q_context = context.Context('', 'tenant_1')
                    self._test_list_resources('port', [port1],
                                              neutron_context=q_context)
                    # Tenant_2 request - must return single port
                    q_context = context.Context('', 'tenant_2')
                    self._test_list_resources('port', [port2],
                                              neutron_context=q_context)

    def test_list_ports_with_sort_native(self):
        if self._skip_native_sorting:
            self.skipTest("Skip test for not implemented sorting feature")
        cfg.CONF.set_default('allow_overlapping_ips', True)
        with contextlib.nested(self.port(admin_state_up='True',
                                         mac_address='00:00:00:00:00:01'),
                               self.port(admin_state_up='False',
                                         mac_address='00:00:00:00:00:02'),
                               self.port(admin_state_up='False',
                                         mac_address='00:00:00:00:00:03')
                               ) as (port1, port2, port3):
            self._test_list_with_sort('port', (port3, port2, port1),
                                      [('admin_state_up', 'asc'),
                                       ('mac_address', 'desc')])

    def test_list_ports_with_sort_emulated(self):
        helper_patcher = mock.patch(
            'neutron.api.v2.base.Controller._get_sorting_helper',
            new=_fake_get_sorting_helper)
        helper_patcher.start()
        cfg.CONF.set_default('allow_overlapping_ips', True)
        with contextlib.nested(self.port(admin_state_up='True',
                                         mac_address='00:00:00:00:00:01'),
                               self.port(admin_state_up='False',
                                         mac_address='00:00:00:00:00:02'),
                               self.port(admin_state_up='False',
                                         mac_address='00:00:00:00:00:03')
                               ) as (port1, port2, port3):
            self._test_list_with_sort('port', (port3, port2, port1),
                                      [('admin_state_up', 'asc'),
                                       ('mac_address', 'desc')])

    def test_list_ports_with_pagination_native(self):
        if self._skip_native_pagination:
            self.skipTest("Skip test for not implemented pagination feature")
        cfg.CONF.set_default('allow_overlapping_ips', True)
        with contextlib.nested(self.port(mac_address='00:00:00:00:00:01'),
                               self.port(mac_address='00:00:00:00:00:02'),
                               self.port(mac_address='00:00:00:00:00:03')
                               ) as (port1, port2, port3):
            self._test_list_with_pagination('port',
                                            (port1, port2, port3),
                                            ('mac_address', 'asc'), 2, 2)

    def test_list_ports_with_pagination_emulated(self):
        helper_patcher = mock.patch(
            'neutron.api.v2.base.Controller._get_pagination_helper',
            new=_fake_get_pagination_helper)
        helper_patcher.start()
        cfg.CONF.set_default('allow_overlapping_ips', True)
        with contextlib.nested(self.port(mac_address='00:00:00:00:00:01'),
                               self.port(mac_address='00:00:00:00:00:02'),
                               self.port(mac_address='00:00:00:00:00:03')
                               ) as (port1, port2, port3):
            self._test_list_with_pagination('port',
                                            (port1, port2, port3),
                                            ('mac_address', 'asc'), 2, 2)

    def test_list_ports_with_pagination_reverse_native(self):
        if self._skip_native_pagination:
            self.skipTest("Skip test for not implemented pagination feature")
        cfg.CONF.set_default('allow_overlapping_ips', True)
        with contextlib.nested(self.port(mac_address='00:00:00:00:00:01'),
                               self.port(mac_address='00:00:00:00:00:02'),
                               self.port(mac_address='00:00:00:00:00:03')
                               ) as (port1, port2, port3):
            self._test_list_with_pagination_reverse('port',
                                                    (port1, port2, port3),
                                                    ('mac_address', 'asc'),
                                                    2, 2)

    def test_list_ports_with_pagination_reverse_emulated(self):
        helper_patcher = mock.patch(
            'neutron.api.v2.base.Controller._get_pagination_helper',
            new=_fake_get_pagination_helper)
        helper_patcher.start()
        cfg.CONF.set_default('allow_overlapping_ips', True)
        with contextlib.nested(self.port(mac_address='00:00:00:00:00:01'),
                               self.port(mac_address='00:00:00:00:00:02'),
                               self.port(mac_address='00:00:00:00:00:03')
                               ) as (port1, port2, port3):
            self._test_list_with_pagination_reverse('port',
                                                    (port1, port2, port3),
                                                    ('mac_address', 'asc'),
                                                    2, 2)

    def test_show_port(self):
        with self.port() as port:
            req = self.new_show_request('ports', port['port']['id'], self.fmt)
            sport = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(port['port']['id'], sport['port']['id'])

    def test_delete_port(self):
        with self.port() as port:
            self._delete('ports', port['port']['id'])
            self._show('ports', port['port']['id'],
                       expected_code=webob.exc.HTTPNotFound.code)

    def test_delete_port_public_network(self):
        with self.network(shared=True) as network:
            port_res = self._create_port(self.fmt,
                                         network['network']['id'],
                                         webob.exc.HTTPCreated.code,
                                         tenant_id='another_tenant',
                                         set_context=True)

            port = self.deserialize(self.fmt, port_res)
            self._delete('ports', port['port']['id'])
            self._show('ports', port['port']['id'],
                       expected_code=webob.exc.HTTPNotFound.code)

    def test_update_port(self):
        with self.port() as port:
            data = {'port': {'admin_state_up': False}}
            req = self.new_update_request('ports', data, port['port']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(res['port']['admin_state_up'],
                             data['port']['admin_state_up'])

    def test_update_port_not_admin(self):
        res = self._create_network(self.fmt, 'net1', True,
                                   tenant_id='not_admin',
                                   set_context=True)
        net1 = self.deserialize(self.fmt, res)
        res = self._create_port(self.fmt, net1['network']['id'],
                                tenant_id='not_admin', set_context=True)
        port = self.deserialize(self.fmt, res)
        data = {'port': {'admin_state_up': False}}
        neutron_context = context.Context('', 'not_admin')
        port = self._update('ports', port['port']['id'], data,
                            neutron_context=neutron_context)
        self.assertEqual(port['port']['admin_state_up'], False)

    def test_update_device_id_unchanged(self):
        with self.port() as port:
            data = {'port': {'admin_state_up': True,
                             'device_id': port['port']['device_id']}}
            req = self.new_update_request('ports', data, port['port']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(res['port']['admin_state_up'], True)

    def test_update_device_id_null(self):
        with self.port() as port:
            data = {'port': {'device_id': None}}
            req = self.new_update_request('ports', data, port['port']['id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_delete_network_if_port_exists(self):
        with self.port() as port:
            req = self.new_delete_request('networks',
                                          port['port']['network_id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPConflict.code)

    def test_delete_network_port_exists_owned_by_network(self):
        res = self._create_network(fmt=self.fmt, name='net',
                                   admin_state_up=True)
        network = self.deserialize(self.fmt, res)
        network_id = network['network']['id']
        self._create_port(self.fmt, network_id,
                          device_owner=constants.DEVICE_OWNER_DHCP)
        req = self.new_delete_request('networks', network_id)
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)

    def test_update_port_delete_ip(self):
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                data = {'port': {'admin_state_up': False,
                                 'fixed_ips': []}}
                req = self.new_update_request('ports',
                                              data, port['port']['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                self.assertEqual(res['port']['admin_state_up'],
                                 data['port']['admin_state_up'])
                self.assertEqual(res['port']['fixed_ips'],
                                 data['port']['fixed_ips'])

    def test_no_more_port_exception(self):
        with self.subnet(cidr='10.0.0.0/32', gateway_ip=None) as subnet:
            id = subnet['subnet']['network_id']
            res = self._create_port(self.fmt, id)
            data = self.deserialize(self.fmt, res)
            msg = str(n_exc.IpAddressGenerationFailure(net_id=id))
            self.assertEqual(data['NeutronError']['message'], msg)
            self.assertEqual(res.status_int, webob.exc.HTTPConflict.code)

    def test_update_port_update_ip(self):
        """Test update of port IP.

        Check that a configured IP 10.0.0.2 is replaced by 10.0.0.10.
        """
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                ips = port['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                data = {'port': {'fixed_ips': [{'subnet_id':
                                                subnet['subnet']['id'],
                                                'ip_address': "10.0.0.10"}]}}
                req = self.new_update_request('ports', data,
                                              port['port']['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                ips = res['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.10')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])

    def test_update_port_update_ip_address_only(self):
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                ips = port['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                data = {'port': {'fixed_ips': [{'subnet_id':
                                                subnet['subnet']['id'],
                                                'ip_address': "10.0.0.10"},
                                               {'ip_address': "10.0.0.2"}]}}
                req = self.new_update_request('ports', data,
                                              port['port']['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                ips = res['port']['fixed_ips']
                self.assertEqual(len(ips), 2)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                self.assertEqual(ips[1]['ip_address'], '10.0.0.10')
                self.assertEqual(ips[1]['subnet_id'], subnet['subnet']['id'])

    def test_update_port_update_ips(self):
        """Update IP and associate new IP on port.

        Check a port update with the specified subnet_id's. A IP address
        will be allocated for each subnet_id.
        """
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                data = {'port': {'admin_state_up': False,
                                 'fixed_ips': [{'subnet_id':
                                                subnet['subnet']['id'],
                                                'ip_address': '10.0.0.3'}]}}
                req = self.new_update_request('ports', data,
                                              port['port']['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                self.assertEqual(res['port']['admin_state_up'],
                                 data['port']['admin_state_up'])
                ips = res['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.3')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])

    def test_update_port_add_additional_ip(self):
        """Test update of port with additional IP."""
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                data = {'port': {'admin_state_up': False,
                                 'fixed_ips': [{'subnet_id':
                                                subnet['subnet']['id']},
                                               {'subnet_id':
                                                subnet['subnet']['id']}]}}
                req = self.new_update_request('ports', data,
                                              port['port']['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                self.assertEqual(res['port']['admin_state_up'],
                                 data['port']['admin_state_up'])
                ips = res['port']['fixed_ips']
                self.assertEqual(len(ips), 2)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.3')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                self.assertEqual(ips[1]['ip_address'], '10.0.0.4')
                self.assertEqual(ips[1]['subnet_id'], subnet['subnet']['id'])

    def test_update_port_invalid_fixed_ip_address_v6_slaac(self):
        with self.subnet(
            cidr='2607:f0d0:1002:51::/64',
            ip_version=6,
            ipv6_address_mode=constants.IPV6_SLAAC,
            gateway_ip=attributes.ATTR_NOT_SPECIFIED) as subnet:
            with self.port(subnet=subnet) as port:
                ips = port['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                port_mac = port['port']['mac_address']
                subnet_cidr = subnet['subnet']['cidr']
                eui_addr = str(ipv6_utils.get_ipv6_addr_by_EUI64(subnet_cidr,
                                                                 port_mac))
                self.assertEqual(ips[0]['ip_address'], eui_addr)
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])

                data = {'port': {'fixed_ips': [{'subnet_id':
                                                subnet['subnet']['id'],
                                                'ip_address':
                                                '2607:f0d0:1002:51::5'}]}}
                req = self.new_update_request('ports', data,
                                              port['port']['id'])
                res = req.get_response(self.api)
                err = self.deserialize(self.fmt, res)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)
                self.assertEqual(err['NeutronError']['type'], 'InvalidInput')

    def test_requested_duplicate_mac(self):
        with self.port() as port:
            mac = port['port']['mac_address']
            # check that MAC address matches base MAC
            base_mac = cfg.CONF.base_mac[0:2]
            self.assertTrue(mac.startswith(base_mac))
            kwargs = {"mac_address": mac}
            net_id = port['port']['network_id']
            res = self._create_port(self.fmt, net_id=net_id, **kwargs)
            self.assertEqual(res.status_int, webob.exc.HTTPConflict.code)

    def test_mac_generation(self):
        cfg.CONF.set_override('base_mac', "12:34:56:00:00:00")
        with self.port() as port:
            mac = port['port']['mac_address']
            self.assertTrue(mac.startswith("12:34:56"))

    def test_mac_generation_4octet(self):
        cfg.CONF.set_override('base_mac', "12:34:56:78:00:00")
        with self.port() as port:
            mac = port['port']['mac_address']
            self.assertTrue(mac.startswith("12:34:56:78"))

    def test_bad_mac_format(self):
        cfg.CONF.set_override('base_mac', "bad_mac")
        try:
            self.plugin._check_base_mac_format()
        except Exception:
            return
        self.fail("No exception for illegal base_mac format")

    def test_mac_exhaustion(self):
        # rather than actually consuming all MAC (would take a LONG time)
        # we just raise the exception that would result.
        @staticmethod
        def fake_gen_mac(context, net_id):
            raise n_exc.MacAddressGenerationFailure(net_id=net_id)

        with mock.patch.object(neutron.db.db_base_plugin_v2.NeutronDbPluginV2,
                               '_generate_mac', new=fake_gen_mac):
            res = self._create_network(fmt=self.fmt, name='net1',
                                       admin_state_up=True)
            network = self.deserialize(self.fmt, res)
            net_id = network['network']['id']
            res = self._create_port(self.fmt, net_id=net_id)
            self.assertEqual(res.status_int,
                             webob.exc.HTTPServiceUnavailable.code)

    def test_requested_duplicate_ip(self):
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                ips = port['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                # Check configuring of duplicate IP
                kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'],
                                         'ip_address': ips[0]['ip_address']}]}
                net_id = port['port']['network_id']
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                self.assertEqual(res.status_int, webob.exc.HTTPConflict.code)

    def test_requested_subnet_id(self):
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                ips = port['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                # Request a IP from specific subnet
                kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id']}]}
                net_id = port['port']['network_id']
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                port2 = self.deserialize(self.fmt, res)
                ips = port2['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.3')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                self._delete('ports', port2['port']['id'])

    def test_requested_subnet_id_not_on_network(self):
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                # Create new network
                res = self._create_network(fmt=self.fmt, name='net2',
                                           admin_state_up=True)
                network2 = self.deserialize(self.fmt, res)
                subnet2 = self._make_subnet(self.fmt, network2, "1.1.1.1",
                                            "1.1.1.0/24", ip_version=4)
                net_id = port['port']['network_id']
                # Request a IP from specific subnet
                kwargs = {"fixed_ips": [{'subnet_id':
                                         subnet2['subnet']['id']}]}
                net_id = port['port']['network_id']
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_overlapping_subnets(self):
        with self.subnet() as subnet:
            tenant_id = subnet['subnet']['tenant_id']
            net_id = subnet['subnet']['network_id']
            res = self._create_subnet(self.fmt,
                                      tenant_id=tenant_id,
                                      net_id=net_id,
                                      cidr='10.0.0.225/28',
                                      ip_version=4,
                                      gateway_ip=attributes.ATTR_NOT_SPECIFIED)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_requested_subnet_id_v4_and_v6(self):
        with self.subnet() as subnet:
                # Get a IPv4 and IPv6 address
                tenant_id = subnet['subnet']['tenant_id']
                net_id = subnet['subnet']['network_id']
                res = self._create_subnet(
                    self.fmt,
                    tenant_id=tenant_id,
                    net_id=net_id,
                    cidr='2607:f0d0:1002:51::/124',
                    ip_version=6,
                    gateway_ip=attributes.ATTR_NOT_SPECIFIED)
                subnet2 = self.deserialize(self.fmt, res)
                kwargs = {"fixed_ips":
                          [{'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet2['subnet']['id']}]}
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                port3 = self.deserialize(self.fmt, res)
                ips = port3['port']['fixed_ips']
                self.assertEqual(len(ips), 2)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                self.assertEqual(ips[1]['ip_address'], '2607:f0d0:1002:51::2')
                self.assertEqual(ips[1]['subnet_id'], subnet2['subnet']['id'])
                res = self._create_port(self.fmt, net_id=net_id)
                port4 = self.deserialize(self.fmt, res)
                # Check that a v4 and a v6 address are allocated
                ips = port4['port']['fixed_ips']
                self.assertEqual(len(ips), 2)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.3')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                self.assertEqual(ips[1]['ip_address'], '2607:f0d0:1002:51::3')
                self.assertEqual(ips[1]['subnet_id'], subnet2['subnet']['id'])
                self._delete('ports', port3['port']['id'])
                self._delete('ports', port4['port']['id'])

    def test_requested_invalid_fixed_ip_address_v6_slaac(self):
        with self.subnet(gateway_ip='fe80::1',
                         cidr='2607:f0d0:1002:51::/64',
                         ip_version=6,
                         ipv6_address_mode=constants.IPV6_SLAAC) as subnet:
            kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'],
                                     'ip_address': '2607:f0d0:1002:51::5'}]}
            net_id = subnet['subnet']['network_id']
            res = self._create_port(self.fmt, net_id=net_id, **kwargs)
            self.assertEqual(res.status_int,
                             webob.exc.HTTPClientError.code)

    def test_requested_fixed_ip_address_v6_slaac_router_iface(self):
        with self.subnet(gateway_ip='fe80::1',
                         cidr='fe80::/64',
                         ip_version=6,
                         ipv6_address_mode=constants.IPV6_SLAAC) as subnet:
            kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'],
                                     'ip_address': 'fe80::1'}]}
            net_id = subnet['subnet']['network_id']
            device_owner = constants.DEVICE_OWNER_ROUTER_INTF
            res = self._create_port(self.fmt, net_id=net_id,
                                    device_owner=device_owner, **kwargs)
            port = self.deserialize(self.fmt, res)
            self.assertEqual(len(port['port']['fixed_ips']), 1)
            self.assertEqual(port['port']['fixed_ips'][0]['ip_address'],
                             'fe80::1')

    def test_requested_subnet_id_v6_slaac(self):
        with self.subnet(gateway_ip='fe80::1',
                         cidr='2607:f0d0:1002:51::/64',
                         ip_version=6,
                         ipv6_address_mode=constants.IPV6_SLAAC) as subnet:
            with self.port(subnet,
                           fixed_ips=[{'subnet_id':
                                       subnet['subnet']['id']}]) as port:
                port_mac = port['port']['mac_address']
                subnet_cidr = subnet['subnet']['cidr']
                eui_addr = str(ipv6_utils.get_ipv6_addr_by_EUI64(subnet_cidr,
                                                                 port_mac))
                self.assertEqual(port['port']['fixed_ips'][0]['ip_address'],
                                 eui_addr)

    def test_requested_subnet_id_v4_and_v6_slaac(self):
        with self.network() as network:
            with contextlib.nested(
                self.subnet(network),
                self.subnet(network,
                            cidr='2607:f0d0:1002:51::/64',
                            ip_version=6,
                            gateway_ip='fe80::1',
                            ipv6_address_mode=constants.IPV6_SLAAC)
            ) as (subnet, subnet2):
                with self.port(
                    subnet,
                    fixed_ips=[{'subnet_id': subnet['subnet']['id']},
                               {'subnet_id': subnet2['subnet']['id']}]
                ) as port:
                    ips = port['port']['fixed_ips']
                    self.assertEqual(len(ips), 2)
                    self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
                    port_mac = port['port']['mac_address']
                    subnet_cidr = subnet2['subnet']['cidr']
                    eui_addr = str(ipv6_utils.get_ipv6_addr_by_EUI64(
                            subnet_cidr, port_mac))
                    self.assertEqual(ips[1]['ip_address'], eui_addr)

    def test_ip_allocation_for_ipv6_subnet_slaac_address_mode(self):
        res = self._create_network(fmt=self.fmt, name='net',
                                   admin_state_up=True)
        network = self.deserialize(self.fmt, res)
        v6_subnet = self._make_subnet(self.fmt, network,
                                      gateway='fe80::1',
                                      cidr='fe80::/64',
                                      ip_version=6,
                                      ipv6_ra_mode=None,
                                      ipv6_address_mode=constants.IPV6_SLAAC)
        port = self._make_port(self.fmt, network['network']['id'])
        self.assertEqual(len(port['port']['fixed_ips']), 1)
        port_mac = port['port']['mac_address']
        subnet_cidr = v6_subnet['subnet']['cidr']
        eui_addr = str(ipv6_utils.get_ipv6_addr_by_EUI64(subnet_cidr,
                                                         port_mac))
        self.assertEqual(port['port']['fixed_ips'][0]['ip_address'], eui_addr)

    def test_range_allocation(self):
        with self.subnet(gateway_ip='10.0.0.3',
                         cidr='10.0.0.0/29') as subnet:
                kwargs = {"fixed_ips":
                          [{'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']}]}
                net_id = subnet['subnet']['network_id']
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                port = self.deserialize(self.fmt, res)
                ips = port['port']['fixed_ips']
                self.assertEqual(len(ips), 5)
                alloc = ['10.0.0.1', '10.0.0.2', '10.0.0.4', '10.0.0.5',
                         '10.0.0.6']
                for ip in ips:
                    self.assertIn(ip['ip_address'], alloc)
                    self.assertEqual(ip['subnet_id'],
                                     subnet['subnet']['id'])
                    alloc.remove(ip['ip_address'])
                self.assertEqual(len(alloc), 0)
                self._delete('ports', port['port']['id'])

        with self.subnet(gateway_ip='11.0.0.6',
                         cidr='11.0.0.0/29') as subnet:
                kwargs = {"fixed_ips":
                          [{'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']}]}
                net_id = subnet['subnet']['network_id']
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                port = self.deserialize(self.fmt, res)
                ips = port['port']['fixed_ips']
                self.assertEqual(len(ips), 5)
                alloc = ['11.0.0.1', '11.0.0.2', '11.0.0.3', '11.0.0.4',
                         '11.0.0.5']
                for ip in ips:
                    self.assertIn(ip['ip_address'], alloc)
                    self.assertEqual(ip['subnet_id'],
                                     subnet['subnet']['id'])
                    alloc.remove(ip['ip_address'])
                self.assertEqual(len(alloc), 0)
                self._delete('ports', port['port']['id'])

    def test_requested_invalid_fixed_ips(self):
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                ips = port['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                # Test invalid subnet_id
                kwargs = {"fixed_ips":
                          [{'subnet_id': subnet['subnet']['id']},
                           {'subnet_id':
                            '00000000-ffff-ffff-ffff-000000000000'}]}
                net_id = port['port']['network_id']
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                port2 = self.deserialize(self.fmt, res)
                self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code)

                # Test invalid IP address on specified subnet_id
                kwargs = {"fixed_ips":
                          [{'subnet_id': subnet['subnet']['id'],
                            'ip_address': '1.1.1.1'}]}
                net_id = port['port']['network_id']
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                port2 = self.deserialize(self.fmt, res)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

                # Test invalid addresses - IP's not on subnet or network
                # address or broadcast address
                bad_ips = ['1.1.1.1', '10.0.0.0', '10.0.0.255']
                net_id = port['port']['network_id']
                for ip in bad_ips:
                    kwargs = {"fixed_ips": [{'ip_address': ip}]}
                    res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                    port2 = self.deserialize(self.fmt, res)
                    self.assertEqual(res.status_int,
                                     webob.exc.HTTPClientError.code)

                # Enable allocation of gateway address
                kwargs = {"fixed_ips":
                          [{'subnet_id': subnet['subnet']['id'],
                            'ip_address': '10.0.0.1'}]}
                net_id = port['port']['network_id']
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                port2 = self.deserialize(self.fmt, res)
                ips = port2['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.1')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                self._delete('ports', port2['port']['id'])

    def test_invalid_ip(self):
        with self.subnet() as subnet:
            # Allocate specific IP
            kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'],
                                     'ip_address': '1011.0.0.5'}]}
            net_id = subnet['subnet']['network_id']
            res = self._create_port(self.fmt, net_id=net_id, **kwargs)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_requested_split(self):
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                ports_to_delete = []
                ips = port['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                # Allocate specific IP
                kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'],
                                         'ip_address': '10.0.0.5'}]}
                net_id = port['port']['network_id']
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                port2 = self.deserialize(self.fmt, res)
                ports_to_delete.append(port2)
                ips = port2['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.5')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                # Allocate specific IP's
                allocated = ['10.0.0.3', '10.0.0.4', '10.0.0.6']

                for a in allocated:
                    res = self._create_port(self.fmt, net_id=net_id)
                    port2 = self.deserialize(self.fmt, res)
                    ports_to_delete.append(port2)
                    ips = port2['port']['fixed_ips']
                    self.assertEqual(len(ips), 1)
                    self.assertEqual(ips[0]['ip_address'], a)
                    self.assertEqual(ips[0]['subnet_id'],
                                     subnet['subnet']['id'])

                for p in ports_to_delete:
                    self._delete('ports', p['port']['id'])

    def test_duplicate_ips(self):
        with self.subnet() as subnet:
            # Allocate specific IP
            kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'],
                                     'ip_address': '10.0.0.5'},
                                    {'subnet_id': subnet['subnet']['id'],
                                     'ip_address': '10.0.0.5'}]}
            net_id = subnet['subnet']['network_id']
            res = self._create_port(self.fmt, net_id=net_id, **kwargs)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_fixed_ip_invalid_subnet_id(self):
        with self.subnet() as subnet:
            # Allocate specific IP
            kwargs = {"fixed_ips": [{'subnet_id': 'i am invalid',
                                     'ip_address': '10.0.0.5'}]}
            net_id = subnet['subnet']['network_id']
            res = self._create_port(self.fmt, net_id=net_id, **kwargs)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_fixed_ip_invalid_ip(self):
        with self.subnet() as subnet:
            # Allocate specific IP
            kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'],
                                     'ip_address': '10.0.0.55555'}]}
            net_id = subnet['subnet']['network_id']
            res = self._create_port(self.fmt, net_id=net_id, **kwargs)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_requested_ips_only(self):
        with self.subnet() as subnet:
            with self.port(subnet=subnet) as port:
                ips = port['port']['fixed_ips']
                self.assertEqual(len(ips), 1)
                self.assertEqual(ips[0]['ip_address'], '10.0.0.2')
                self.assertEqual(ips[0]['subnet_id'], subnet['subnet']['id'])
                ips_only = ['10.0.0.18', '10.0.0.20', '10.0.0.22', '10.0.0.21',
                            '10.0.0.3', '10.0.0.17', '10.0.0.19']
                ports_to_delete = []
                for i in ips_only:
                    kwargs = {"fixed_ips": [{'ip_address': i}]}
                    net_id = port['port']['network_id']
                    res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                    port = self.deserialize(self.fmt, res)
                    ports_to_delete.append(port)
                    ips = port['port']['fixed_ips']
                    self.assertEqual(len(ips), 1)
                    self.assertEqual(ips[0]['ip_address'], i)
                    self.assertEqual(ips[0]['subnet_id'],
                                     subnet['subnet']['id'])
                for p in ports_to_delete:
                    self._delete('ports', p['port']['id'])

    def test_invalid_admin_state(self):
        with self.network() as network:
            data = {'port': {'network_id': network['network']['id'],
                             'tenant_id': network['network']['tenant_id'],
                             'admin_state_up': 7,
                             'fixed_ips': []}}
            port_req = self.new_create_request('ports', data)
            res = port_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_invalid_mac_address(self):
        with self.network() as network:
            data = {'port': {'network_id': network['network']['id'],
                             'tenant_id': network['network']['tenant_id'],
                             'admin_state_up': 1,
                             'mac_address': 'mac',
                             'fixed_ips': []}}
            port_req = self.new_create_request('ports', data)
            res = port_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_max_fixed_ips_exceeded(self):
        with self.subnet(gateway_ip='10.0.0.3',
                         cidr='10.0.0.0/24') as subnet:
                kwargs = {"fixed_ips":
                          [{'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']},
                           {'subnet_id': subnet['subnet']['id']}]}
                net_id = subnet['subnet']['network_id']
                res = self._create_port(self.fmt, net_id=net_id, **kwargs)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_update_max_fixed_ips_exceeded(self):
        with self.subnet(gateway_ip='10.0.0.3',
                         cidr='10.0.0.0/24') as subnet:
            with self.port(subnet) as port:
                data = {'port': {'fixed_ips':
                                 [{'subnet_id': subnet['subnet']['id'],
                                   'ip_address': '10.0.0.2'},
                                  {'subnet_id': subnet['subnet']['id'],
                                   'ip_address': '10.0.0.4'},
                                  {'subnet_id': subnet['subnet']['id']},
                                  {'subnet_id': subnet['subnet']['id']},
                                  {'subnet_id': subnet['subnet']['id']},
                                  {'subnet_id': subnet['subnet']['id']}]}}
                req = self.new_update_request('ports', data,
                                              port['port']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_delete_ports_by_device_id(self):
        plugin = manager.NeutronManager.get_plugin()
        ctx = context.get_admin_context()
        with self.subnet() as subnet:
            with contextlib.nested(
                self.port(subnet=subnet, device_id='owner1'),
                self.port(subnet=subnet, device_id='owner1'),
                self.port(subnet=subnet, device_id='owner2'),
            ) as (p1, p2, p3):
                network_id = subnet['subnet']['network_id']
                plugin.delete_ports_by_device_id(ctx, 'owner1',
                                                 network_id)
                self._show('ports', p1['port']['id'],
                           expected_code=webob.exc.HTTPNotFound.code)
                self._show('ports', p2['port']['id'],
                           expected_code=webob.exc.HTTPNotFound.code)
                self._show('ports', p3['port']['id'],
                           expected_code=webob.exc.HTTPOk.code)

    def _test_delete_ports_by_device_id_second_call_failure(self, plugin):
        ctx = context.get_admin_context()
        with self.subnet() as subnet:
            with contextlib.nested(
                self.port(subnet=subnet, device_id='owner1'),
                self.port(subnet=subnet, device_id='owner1'),
                self.port(subnet=subnet, device_id='owner2'),
            ) as (p1, p2, p3):
                orig = plugin.delete_port
                with mock.patch.object(plugin, 'delete_port') as del_port:

                    def side_effect(*args, **kwargs):
                        return self._fail_second_call(del_port, orig,
                                                      *args, **kwargs)

                    del_port.side_effect = side_effect
                    network_id = subnet['subnet']['network_id']
                    self.assertRaises(n_exc.NeutronException,
                                      plugin.delete_ports_by_device_id,
                                      ctx, 'owner1', network_id)
                self._show('ports', p1['port']['id'],
                           expected_code=webob.exc.HTTPNotFound.code)
                self._show('ports', p2['port']['id'],
                           expected_code=webob.exc.HTTPOk.code)
                self._show('ports', p3['port']['id'],
                           expected_code=webob.exc.HTTPOk.code)

    def test_delete_ports_by_device_id_second_call_failure(self):
        plugin = manager.NeutronManager.get_plugin()
        self._test_delete_ports_by_device_id_second_call_failure(plugin)

    def _test_delete_ports_ignores_port_not_found(self, plugin):
        ctx = context.get_admin_context()
        with self.subnet() as subnet:
            with contextlib.nested(
                self.port(subnet=subnet, device_id='owner1'),
                mock.patch.object(plugin, 'delete_port')
            ) as (p, del_port):
                del_port.side_effect = n_exc.PortNotFound(
                    port_id=p['port']['id']
                )
                network_id = subnet['subnet']['network_id']
                try:
                    plugin.delete_ports_by_device_id(ctx, 'owner1',
                                                     network_id)
                except n_exc.PortNotFound:
                    self.fail("delete_ports_by_device_id unexpectedly raised "
                              "a PortNotFound exception. It should ignore "
                              "this exception because it is often called at "
                              "the same time other concurrent operations are "
                              "deleting some of the same ports.")

    def test_delete_ports_ignores_port_not_found(self):
        plugin = manager.NeutronManager.get_plugin()
        self._test_delete_ports_ignores_port_not_found(plugin)


class TestNetworksV2(NeutronDbPluginV2TestCase):
    # NOTE(cerberus): successful network update and delete are
    #                 effectively tested above
    def test_create_network(self):
        name = 'net1'
        keys = [('subnets', []), ('name', name), ('admin_state_up', True),
                ('status', self.net_create_status), ('shared', False)]
        with self.network(name=name) as net:
            for k, v in keys:
                self.assertEqual(net['network'][k], v)

    def test_create_public_network(self):
        name = 'public_net'
        keys = [('subnets', []), ('name', name), ('admin_state_up', True),
                ('status', self.net_create_status), ('shared', True)]
        with self.network(name=name, shared=True) as net:
            for k, v in keys:
                self.assertEqual(net['network'][k], v)

    def test_create_public_network_no_admin_tenant(self):
        name = 'public_net'
        with testlib_api.ExpectedException(
                webob.exc.HTTPClientError) as ctx_manager:
            with self.network(name=name,
                              shared=True,
                              tenant_id="another_tenant",
                              set_context=True):
                pass
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPForbidden.code)

    def test_update_network(self):
        with self.network() as network:
            data = {'network': {'name': 'a_brand_new_name'}}
            req = self.new_update_request('networks',
                                          data,
                                          network['network']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(res['network']['name'],
                             data['network']['name'])

    def test_update_shared_network_noadmin_returns_403(self):
        with self.network(shared=True) as network:
            data = {'network': {'name': 'a_brand_new_name'}}
            req = self.new_update_request('networks',
                                          data,
                                          network['network']['id'])
            req.environ['neutron.context'] = context.Context('', 'somebody')
            res = req.get_response(self.api)
            # The API layer always returns 404 on updates in place of 403
            self.assertEqual(res.status_int, webob.exc.HTTPNotFound.code)

    def test_update_network_set_shared(self):
        with self.network(shared=False) as network:
            data = {'network': {'shared': True}}
            req = self.new_update_request('networks',
                                          data,
                                          network['network']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertTrue(res['network']['shared'])

    def test_update_network_set_shared_owner_returns_403(self):
        with self.network(shared=False) as network:
            net_owner = network['network']['tenant_id']
            data = {'network': {'shared': True}}
            req = self.new_update_request('networks',
                                          data,
                                          network['network']['id'])
            req.environ['neutron.context'] = context.Context('u', net_owner)
            res = req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPForbidden.code)

    def test_update_network_with_subnet_set_shared(self):
        with self.network(shared=False) as network:
            with self.subnet(network=network) as subnet:
                data = {'network': {'shared': True}}
                req = self.new_update_request('networks',
                                              data,
                                              network['network']['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                self.assertTrue(res['network']['shared'])
                # must query db to see whether subnet's shared attribute
                # has been updated or not
                ctx = context.Context('', '', is_admin=True)
                subnet_db = manager.NeutronManager.get_plugin()._get_subnet(
                    ctx, subnet['subnet']['id'])
                self.assertEqual(subnet_db['shared'], True)

    def test_update_network_set_not_shared_single_tenant(self):
        with self.network(shared=True) as network:
            res1 = self._create_port(self.fmt,
                                     network['network']['id'],
                                     webob.exc.HTTPCreated.code,
                                     tenant_id=network['network']['tenant_id'],
                                     set_context=True)
            data = {'network': {'shared': False}}
            req = self.new_update_request('networks',
                                          data,
                                          network['network']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertFalse(res['network']['shared'])
            port1 = self.deserialize(self.fmt, res1)
            self._delete('ports', port1['port']['id'])

    def test_update_network_set_not_shared_other_tenant_returns_409(self):
        with self.network(shared=True) as network:
            res1 = self._create_port(self.fmt,
                                     network['network']['id'],
                                     webob.exc.HTTPCreated.code,
                                     tenant_id='somebody_else',
                                     set_context=True)
            data = {'network': {'shared': False}}
            req = self.new_update_request('networks',
                                          data,
                                          network['network']['id'])
            self.assertEqual(req.get_response(self.api).status_int,
                             webob.exc.HTTPConflict.code)
            port1 = self.deserialize(self.fmt, res1)
            self._delete('ports', port1['port']['id'])

    def test_update_network_set_not_shared_multi_tenants_returns_409(self):
        with self.network(shared=True) as network:
            res1 = self._create_port(self.fmt,
                                     network['network']['id'],
                                     webob.exc.HTTPCreated.code,
                                     tenant_id='somebody_else',
                                     set_context=True)
            res2 = self._create_port(self.fmt,
                                     network['network']['id'],
                                     webob.exc.HTTPCreated.code,
                                     tenant_id=network['network']['tenant_id'],
                                     set_context=True)
            data = {'network': {'shared': False}}
            req = self.new_update_request('networks',
                                          data,
                                          network['network']['id'])
            self.assertEqual(req.get_response(self.api).status_int,
                             webob.exc.HTTPConflict.code)
            port1 = self.deserialize(self.fmt, res1)
            port2 = self.deserialize(self.fmt, res2)
            self._delete('ports', port1['port']['id'])
            self._delete('ports', port2['port']['id'])

    def test_update_network_set_not_shared_multi_tenants2_returns_409(self):
        with self.network(shared=True) as network:
            res1 = self._create_port(self.fmt,
                                     network['network']['id'],
                                     webob.exc.HTTPCreated.code,
                                     tenant_id='somebody_else',
                                     set_context=True)
            self._create_subnet(self.fmt,
                                network['network']['id'],
                                '10.0.0.0/24',
                                webob.exc.HTTPCreated.code,
                                tenant_id=network['network']['tenant_id'],
                                set_context=True)
            data = {'network': {'shared': False}}
            req = self.new_update_request('networks',
                                          data,
                                          network['network']['id'])
            self.assertEqual(req.get_response(self.api).status_int,
                             webob.exc.HTTPConflict.code)

            port1 = self.deserialize(self.fmt, res1)
            self._delete('ports', port1['port']['id'])

    def test_create_networks_bulk_native(self):
        if self._skip_native_bulk:
            self.skipTest("Plugin does not support native bulk network create")
        res = self._create_network_bulk(self.fmt, 2, 'test', True)
        self._validate_behavior_on_bulk_success(res, 'networks')

    def test_create_networks_bulk_native_quotas(self):
        if self._skip_native_bulk:
            self.skipTest("Plugin does not support native bulk network create")
        quota = 4
        cfg.CONF.set_override('quota_network', quota, group='QUOTAS')
        res = self._create_network_bulk(self.fmt, quota + 1, 'test', True)
        self._validate_behavior_on_bulk_failure(
            res, 'networks',
            errcode=webob.exc.HTTPConflict.code)

    def test_create_networks_bulk_tenants_and_quotas(self):
        if self._skip_native_bulk:
            self.skipTest("Plugin does not support native bulk network create")
        quota = 2
        cfg.CONF.set_override('quota_network', quota, group='QUOTAS')
        networks = [{'network': {'name': 'n1',
                                 'tenant_id': self._tenant_id}},
                    {'network': {'name': 'n2',
                                 'tenant_id': self._tenant_id}},
                    {'network': {'name': 'n1',
                                 'tenant_id': 't1'}},
                    {'network': {'name': 'n2',
                                 'tenant_id': 't1'}}]

        res = self._create_bulk_from_list(self.fmt, 'network', networks)
        self.assertEqual(res.status_int, webob.exc.HTTPCreated.code)

    def test_create_networks_bulk_tenants_and_quotas_fail(self):
        if self._skip_native_bulk:
            self.skipTest("Plugin does not support native bulk network create")
        quota = 2
        cfg.CONF.set_override('quota_network', quota, group='QUOTAS')
        networks = [{'network': {'name': 'n1',
                                 'tenant_id': self._tenant_id}},
                    {'network': {'name': 'n2',
                                 'tenant_id': self._tenant_id}},
                    {'network': {'name': 'n1',
                                 'tenant_id': 't1'}},
                    {'network': {'name': 'n3',
                                 'tenant_id': self._tenant_id}},
                    {'network': {'name': 'n2',
                                 'tenant_id': 't1'}}]

        res = self._create_bulk_from_list(self.fmt, 'network', networks)
        self.assertEqual(res.status_int, webob.exc.HTTPConflict.code)

    def test_create_networks_bulk_emulated(self):
        real_has_attr = hasattr

        #ensures the API choose the emulation code path
        def fakehasattr(item, attr):
            if attr.endswith('__native_bulk_support'):
                return False
            return real_has_attr(item, attr)

        with mock.patch('__builtin__.hasattr',
                        new=fakehasattr):
            res = self._create_network_bulk(self.fmt, 2, 'test', True)
            self._validate_behavior_on_bulk_success(res, 'networks')

    def test_create_networks_bulk_wrong_input(self):
        res = self._create_network_bulk(self.fmt, 2, 'test', True,
                                        override={1:
                                                  {'admin_state_up': 'doh'}})
        self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)
        req = self.new_list_request('networks')
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPOk.code)
        nets = self.deserialize(self.fmt, res)
        self.assertEqual(len(nets['networks']), 0)

    def test_create_networks_bulk_emulated_plugin_failure(self):
        real_has_attr = hasattr

        def fakehasattr(item, attr):
            if attr.endswith('__native_bulk_support'):
                return False
            return real_has_attr(item, attr)

        orig = manager.NeutronManager.get_plugin().create_network
        #ensures the API choose the emulation code path
        with mock.patch('__builtin__.hasattr',
                        new=fakehasattr):
            with mock.patch.object(manager.NeutronManager.get_plugin(),
                                   'create_network') as patched_plugin:

                def side_effect(*args, **kwargs):
                    return self._fail_second_call(patched_plugin, orig,
                                                  *args, **kwargs)

                patched_plugin.side_effect = side_effect
                res = self._create_network_bulk(self.fmt, 2, 'test', True)
                # We expect a 500 as we injected a fault in the plugin
                self._validate_behavior_on_bulk_failure(
                    res, 'networks', webob.exc.HTTPServerError.code
                )

    def test_create_networks_bulk_native_plugin_failure(self):
        if self._skip_native_bulk:
            self.skipTest("Plugin does not support native bulk network create")
        orig = manager.NeutronManager.get_plugin().create_network
        with mock.patch.object(manager.NeutronManager.get_plugin(),
                               'create_network') as patched_plugin:

            def side_effect(*args, **kwargs):
                return self._fail_second_call(patched_plugin, orig,
                                              *args, **kwargs)

            patched_plugin.side_effect = side_effect
            res = self._create_network_bulk(self.fmt, 2, 'test', True)
            # We expect a 500 as we injected a fault in the plugin
            self._validate_behavior_on_bulk_failure(
                res, 'networks', webob.exc.HTTPServerError.code
            )

    def test_list_networks(self):
        with contextlib.nested(self.network(),
                               self.network(),
                               self.network()) as networks:
            self._test_list_resources('network', networks)

    def test_list_networks_with_sort_native(self):
        if self._skip_native_sorting:
            self.skipTest("Skip test for not implemented sorting feature")
        with contextlib.nested(self.network(admin_status_up=True,
                                            name='net1'),
                               self.network(admin_status_up=False,
                                            name='net2'),
                               self.network(admin_status_up=False,
                                            name='net3')
                               ) as (net1, net2, net3):
            self._test_list_with_sort('network', (net3, net2, net1),
                                      [('admin_state_up', 'asc'),
                                       ('name', 'desc')])

    def test_list_networks_with_sort_extended_attr_native_returns_400(self):
        if self._skip_native_sorting:
            self.skipTest("Skip test for not implemented sorting feature")
        with contextlib.nested(self.network(admin_status_up=True,
                                            name='net1'),
                               self.network(admin_status_up=False,
                                            name='net2'),
                               self.network(admin_status_up=False,
                                            name='net3')
                               ):
            req = self.new_list_request(
                'networks',
                params='sort_key=provider:segmentation_id&sort_dir=asc')
            res = req.get_response(self.api)
            self.assertEqual(webob.exc.HTTPClientError.code, res.status_int)

    def test_list_networks_with_sort_remote_key_native_returns_400(self):
        if self._skip_native_sorting:
            self.skipTest("Skip test for not implemented sorting feature")
        with contextlib.nested(self.network(admin_status_up=True,
                                            name='net1'),
                               self.network(admin_status_up=False,
                                            name='net2'),
                               self.network(admin_status_up=False,
                                            name='net3')
                               ):
            req = self.new_list_request(
                'networks', params='sort_key=subnets&sort_dir=asc')
            res = req.get_response(self.api)
            self.assertEqual(webob.exc.HTTPClientError.code, res.status_int)

    def test_list_networks_with_sort_emulated(self):
        helper_patcher = mock.patch(
            'neutron.api.v2.base.Controller._get_sorting_helper',
            new=_fake_get_sorting_helper)
        helper_patcher.start()
        with contextlib.nested(self.network(admin_status_up=True,
                                            name='net1'),
                               self.network(admin_status_up=False,
                                            name='net2'),
                               self.network(admin_status_up=False,
                                            name='net3')
                               ) as (net1, net2, net3):
            self._test_list_with_sort('network', (net3, net2, net1),
                                      [('admin_state_up', 'asc'),
                                       ('name', 'desc')])

    def test_list_networks_with_pagination_native(self):
        if self._skip_native_pagination:
            self.skipTest("Skip test for not implemented pagination feature")
        with contextlib.nested(self.network(name='net1'),
                               self.network(name='net2'),
                               self.network(name='net3')
                               ) as (net1, net2, net3):
            self._test_list_with_pagination('network',
                                            (net1, net2, net3),
                                            ('name', 'asc'), 2, 2)

    def test_list_networks_with_pagination_emulated(self):
        helper_patcher = mock.patch(
            'neutron.api.v2.base.Controller._get_pagination_helper',
            new=_fake_get_pagination_helper)
        helper_patcher.start()
        with contextlib.nested(self.network(name='net1'),
                               self.network(name='net2'),
                               self.network(name='net3')
                               ) as (net1, net2, net3):
            self._test_list_with_pagination('network',
                                            (net1, net2, net3),
                                            ('name', 'asc'), 2, 2)

    def test_list_networks_without_pk_in_fields_pagination_emulated(self):
        helper_patcher = mock.patch(
            'neutron.api.v2.base.Controller._get_pagination_helper',
            new=_fake_get_pagination_helper)
        helper_patcher.start()
        with contextlib.nested(self.network(name='net1',
                                            shared=True),
                               self.network(name='net2',
                                            shared=False),
                               self.network(name='net3',
                                            shared=True)
                               ) as (net1, net2, net3):
            self._test_list_with_pagination('network',
                                            (net1, net2, net3),
                                            ('name', 'asc'), 2, 2,
                                            query_params="fields=name",
                                            verify_key='name')

    def test_list_networks_without_pk_in_fields_pagination_native(self):
        if self._skip_native_pagination:
            self.skipTest("Skip test for not implemented pagination feature")
        with contextlib.nested(self.network(name='net1'),
                               self.network(name='net2'),
                               self.network(name='net3')
                               ) as (net1, net2, net3):
            self._test_list_with_pagination('network',
                                            (net1, net2, net3),
                                            ('name', 'asc'), 2, 2,
                                            query_params="fields=shared",
                                            verify_key='shared')

    def test_list_networks_with_pagination_reverse_native(self):
        if self._skip_native_pagination:
            self.skipTest("Skip test for not implemented pagination feature")
        with contextlib.nested(self.network(name='net1'),
                               self.network(name='net2'),
                               self.network(name='net3')
                               ) as (net1, net2, net3):
            self._test_list_with_pagination_reverse('network',
                                                    (net1, net2, net3),
                                                    ('name', 'asc'), 2, 2)

    def test_list_networks_with_pagination_reverse_emulated(self):
        helper_patcher = mock.patch(
            'neutron.api.v2.base.Controller._get_pagination_helper',
            new=_fake_get_pagination_helper)
        helper_patcher.start()
        with contextlib.nested(self.network(name='net1'),
                               self.network(name='net2'),
                               self.network(name='net3')
                               ) as (net1, net2, net3):
            self._test_list_with_pagination_reverse('network',
                                                    (net1, net2, net3),
                                                    ('name', 'asc'), 2, 2)

    def test_list_networks_with_parameters(self):
        with contextlib.nested(self.network(name='net1',
                                            admin_state_up=False),
                               self.network(name='net2')) as (net1, net2):
            query_params = 'admin_state_up=False'
            self._test_list_resources('network', [net1],
                                      query_params=query_params)
            query_params = 'admin_state_up=True'
            self._test_list_resources('network', [net2],
                                      query_params=query_params)

    def test_list_networks_with_fields(self):
        with self.network(name='net1') as net1:
            req = self.new_list_request('networks',
                                        params='fields=name')
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(1, len(res['networks']))
            self.assertEqual(res['networks'][0]['name'],
                             net1['network']['name'])
            self.assertIsNone(res['networks'][0].get('id'))

    def test_list_networks_with_parameters_invalid_values(self):
        with contextlib.nested(self.network(name='net1',
                                            admin_state_up=False),
                               self.network(name='net2')) as (net1, net2):
            req = self.new_list_request('networks',
                                        params='admin_state_up=fake')
            res = req.get_response(self.api)
            self.assertEqual(webob.exc.HTTPClientError.code, res.status_int)

    def test_list_shared_networks_with_non_admin_user(self):
        with contextlib.nested(self.network(shared=False,
                                            name='net1',
                                            tenant_id='tenant1'),
                               self.network(shared=True,
                                            name='net2',
                                            tenant_id='another_tenant'),
                               self.network(shared=False,
                                            name='net3',
                                            tenant_id='another_tenant')
                               ) as (net1, net2, net3):
            ctx = context.Context(user_id='non_admin',
                                  tenant_id='tenant1',
                                  is_admin=False)
            self._test_list_resources('network', (net1, net2), ctx)

    def test_show_network(self):
        with self.network(name='net1') as net:
            req = self.new_show_request('networks', net['network']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(res['network']['name'],
                             net['network']['name'])

    def test_show_network_with_subnet(self):
        with self.network(name='net1') as net:
            with self.subnet(net) as subnet:
                req = self.new_show_request('networks', net['network']['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                self.assertEqual(res['network']['subnets'][0],
                                 subnet['subnet']['id'])

    def test_invalid_admin_status(self):
        value = [[7, False, webob.exc.HTTPClientError.code],
                 [True, True, webob.exc.HTTPCreated.code],
                 ["True", True, webob.exc.HTTPCreated.code],
                 ["true", True, webob.exc.HTTPCreated.code],
                 [1, True, webob.exc.HTTPCreated.code],
                 ["False", False, webob.exc.HTTPCreated.code],
                 [False, False, webob.exc.HTTPCreated.code],
                 ["false", False, webob.exc.HTTPCreated.code],
                 ["7", False, webob.exc.HTTPClientError.code]]
        for v in value:
            data = {'network': {'name': 'net',
                                'admin_state_up': v[0],
                                'tenant_id': self._tenant_id}}
            network_req = self.new_create_request('networks', data)
            req = network_req.get_response(self.api)
            self.assertEqual(req.status_int, v[2])
            if v[2] == webob.exc.HTTPCreated.code:
                res = self.deserialize(self.fmt, req)
                self.assertEqual(res['network']['admin_state_up'], v[1])


class TestSubnetsV2(NeutronDbPluginV2TestCase):

    def _test_create_subnet(self, network=None, expected=None, **kwargs):
        keys = kwargs.copy()
        keys.setdefault('cidr', '10.0.0.0/24')
        keys.setdefault('ip_version', 4)
        keys.setdefault('enable_dhcp', True)
        with self.subnet(network=network, **keys) as subnet:
            # verify the response has each key with the correct value
            for k in keys:
                self.assertIn(k, subnet['subnet'])
                if isinstance(keys[k], list):
                    self.assertEqual(sorted(subnet['subnet'][k]),
                                     sorted(keys[k]))
                else:
                    self.assertEqual(subnet['subnet'][k], keys[k])
            # verify the configured validations are correct
            if expected:
                for k in expected:
                    self.assertIn(k, subnet['subnet'])
                    if isinstance(expected[k], list):
                        self.assertEqual(sorted(subnet['subnet'][k]),
                                         sorted(expected[k]))
                    else:
                        self.assertEqual(subnet['subnet'][k], expected[k])
        self._delete('subnets', subnet['subnet']['id'])
        return subnet

    def test_create_subnet(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        subnet = self._test_create_subnet(gateway_ip=gateway_ip,
                                          cidr=cidr)
        self.assertEqual(4, subnet['subnet']['ip_version'])
        self.assertIn('name', subnet['subnet'])

    def test_create_two_subnets(self):
        gateway_ips = ['10.0.0.1', '10.0.1.1']
        cidrs = ['10.0.0.0/24', '10.0.1.0/24']
        with self.network() as network:
            with self.subnet(network=network,
                             gateway_ip=gateway_ips[0],
                             cidr=cidrs[0]):
                with self.subnet(network=network,
                                 gateway_ip=gateway_ips[1],
                                 cidr=cidrs[1]):
                    net_req = self.new_show_request('networks',
                                                    network['network']['id'])
                    raw_res = net_req.get_response(self.api)
                    net_res = self.deserialize(self.fmt, raw_res)
                    for subnet_id in net_res['network']['subnets']:
                        sub_req = self.new_show_request('subnets', subnet_id)
                        raw_res = sub_req.get_response(self.api)
                        sub_res = self.deserialize(self.fmt, raw_res)
                        self.assertIn(sub_res['subnet']['cidr'], cidrs)
                        self.assertIn(sub_res['subnet']['gateway_ip'],
                                      gateway_ips)

    def test_create_two_subnets_same_cidr_returns_400(self):
        gateway_ip_1 = '10.0.0.1'
        cidr_1 = '10.0.0.0/24'
        gateway_ip_2 = '10.0.0.10'
        cidr_2 = '10.0.0.0/24'
        with self.network() as network:
            with self.subnet(network=network,
                             gateway_ip=gateway_ip_1,
                             cidr=cidr_1):
                with testlib_api.ExpectedException(
                        webob.exc.HTTPClientError) as ctx_manager:
                    with self.subnet(network=network,
                                     gateway_ip=gateway_ip_2,
                                     cidr=cidr_2):
                        pass
                self.assertEqual(ctx_manager.exception.code,
                                 webob.exc.HTTPClientError.code)

    def test_create_subnet_bad_V4_cidr(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                    'cidr': '10.0.2.0',
                    'ip_version': '4',
                    'tenant_id': network['network']['tenant_id'],
                    'gateway_ip': '10.0.2.1'}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_bad_V4_cidr_prefix_len(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                    'cidr': '0.0.0.0/0',
                    'ip_version': '4',
                    'tenant_id': network['network']['tenant_id'],
                    'gateway_ip': '0.0.0.1'}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_bad_V6_cidr(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                    'cidr': 'fe80::',
                    'ip_version': '6',
                    'tenant_id': network['network']['tenant_id'],
                    'gateway_ip': 'fe80::1'}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_V6_slaac_big_prefix(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                    'cidr': '2014::/65',
                    'ip_version': '6',
                    'tenant_id': network['network']['tenant_id'],
                    'gateway_ip': 'fe80::1',
                    'ipv6_address_mode': 'slaac'}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(webob.exc.HTTPClientError.code, res.status_int)

    def test_create_2_subnets_overlapping_cidr_allowed_returns_200(self):
        cidr_1 = '10.0.0.0/23'
        cidr_2 = '10.0.0.0/24'
        cfg.CONF.set_override('allow_overlapping_ips', True)

        with contextlib.nested(self.subnet(cidr=cidr_1),
                               self.subnet(cidr=cidr_2)):
            pass

    def test_create_2_subnets_overlapping_cidr_not_allowed_returns_400(self):
        cidr_1 = '10.0.0.0/23'
        cidr_2 = '10.0.0.0/24'
        cfg.CONF.set_override('allow_overlapping_ips', False)
        with testlib_api.ExpectedException(
                webob.exc.HTTPClientError) as ctx_manager:
            with contextlib.nested(self.subnet(cidr=cidr_1),
                                   self.subnet(cidr=cidr_2)):
                pass
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPClientError.code)

    def test_create_subnets_bulk_native(self):
        if self._skip_native_bulk:
            self.skipTest("Plugin does not support native bulk subnet create")
        with self.network() as net:
            res = self._create_subnet_bulk(self.fmt, 2, net['network']['id'],
                                           'test')
            self._validate_behavior_on_bulk_success(res, 'subnets')

    def test_create_subnets_bulk_emulated(self):
        real_has_attr = hasattr

        #ensures the API choose the emulation code path
        def fakehasattr(item, attr):
            if attr.endswith('__native_bulk_support'):
                return False
            return real_has_attr(item, attr)

        with mock.patch('__builtin__.hasattr',
                        new=fakehasattr):
            with self.network() as net:
                res = self._create_subnet_bulk(self.fmt, 2,
                                               net['network']['id'],
                                               'test')
                self._validate_behavior_on_bulk_success(res, 'subnets')

    def test_create_subnets_bulk_emulated_plugin_failure(self):
        real_has_attr = hasattr

        #ensures the API choose the emulation code path
        def fakehasattr(item, attr):
            if attr.endswith('__native_bulk_support'):
                return False
            return real_has_attr(item, attr)

        with mock.patch('__builtin__.hasattr',
                        new=fakehasattr):
            orig = manager.NeutronManager.get_plugin().create_subnet
            with mock.patch.object(manager.NeutronManager.get_plugin(),
                                   'create_subnet') as patched_plugin:

                def side_effect(*args, **kwargs):
                    self._fail_second_call(patched_plugin, orig,
                                           *args, **kwargs)

                patched_plugin.side_effect = side_effect
                with self.network() as net:
                    res = self._create_subnet_bulk(self.fmt, 2,
                                                   net['network']['id'],
                                                   'test')
                self._delete('networks', net['network']['id'])
                # We expect a 500 as we injected a fault in the plugin
                self._validate_behavior_on_bulk_failure(
                    res, 'subnets', webob.exc.HTTPServerError.code
                )

    def test_create_subnets_bulk_native_plugin_failure(self):
        if self._skip_native_bulk:
            self.skipTest("Plugin does not support native bulk subnet create")
        plugin = manager.NeutronManager.get_plugin()
        orig = plugin.create_subnet
        with mock.patch.object(plugin, 'create_subnet') as patched_plugin:
            def side_effect(*args, **kwargs):
                return self._fail_second_call(patched_plugin, orig,
                                              *args, **kwargs)

            patched_plugin.side_effect = side_effect
            with self.network() as net:
                res = self._create_subnet_bulk(self.fmt, 2,
                                               net['network']['id'],
                                               'test')

                # We expect a 500 as we injected a fault in the plugin
                self._validate_behavior_on_bulk_failure(
                    res, 'subnets', webob.exc.HTTPServerError.code
                )

    def test_delete_subnet(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        # Create new network
        res = self._create_network(fmt=self.fmt, name='net',
                                   admin_state_up=True)
        network = self.deserialize(self.fmt, res)
        subnet = self._make_subnet(self.fmt, network, gateway_ip,
                                   cidr, ip_version=4)
        req = self.new_delete_request('subnets', subnet['subnet']['id'])
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)

    def test_delete_subnet_port_exists_owned_by_network(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        # Create new network
        res = self._create_network(fmt=self.fmt, name='net',
                                   admin_state_up=True)
        network = self.deserialize(self.fmt, res)
        subnet = self._make_subnet(self.fmt, network, gateway_ip,
                                   cidr, ip_version=4)
        self._create_port(self.fmt,
                          network['network']['id'],
                          device_owner=constants.DEVICE_OWNER_DHCP)
        req = self.new_delete_request('subnets', subnet['subnet']['id'])
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)

    def test_delete_subnet_dhcp_port_associated_with_other_subnets(self):
        res = self._create_network(fmt=self.fmt, name='net',
                                   admin_state_up=True)
        network = self.deserialize(self.fmt, res)
        subnet1 = self._make_subnet(self.fmt, network, '10.0.0.1',
                                    '10.0.0.0/24', ip_version=4)
        subnet2 = self._make_subnet(self.fmt, network, '10.0.1.1',
                                    '10.0.1.0/24', ip_version=4)
        res = self._create_port(self.fmt,
                                network['network']['id'],
                                device_owner=constants.DEVICE_OWNER_DHCP,
                                fixed_ips=[
                                    {'subnet_id': subnet1['subnet']['id']},
                                    {'subnet_id': subnet2['subnet']['id']}
                                ])
        port = self.deserialize(self.fmt, res)
        expected_subnets = [subnet1['subnet']['id'], subnet2['subnet']['id']]
        self.assertEqual(expected_subnets,
                         [s['subnet_id'] for s in port['port']['fixed_ips']])
        req = self.new_delete_request('subnets', subnet1['subnet']['id'])
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, 204)
        port = self._show('ports', port['port']['id'])

        expected_subnets = [subnet2['subnet']['id']]
        self.assertEqual(expected_subnets,
                         [s['subnet_id'] for s in port['port']['fixed_ips']])
        req = self.new_delete_request('subnets', subnet2['subnet']['id'])
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, 204)
        port = self._show('ports', port['port']['id'])
        self.assertFalse(port['port']['fixed_ips'])

    def test_delete_subnet_port_exists_owned_by_other(self):
        with self.subnet() as subnet:
            with self.port(subnet=subnet):
                id = subnet['subnet']['id']
                req = self.new_delete_request('subnets', id)
                res = req.get_response(self.api)
                data = self.deserialize(self.fmt, res)
                self.assertEqual(res.status_int, webob.exc.HTTPConflict.code)
                msg = str(n_exc.SubnetInUse(subnet_id=id))
                self.assertEqual(data['NeutronError']['message'], msg)

    def test_delete_subnet_with_other_subnet_on_network_still_in_use(self):
        with self.network() as network:
            with contextlib.nested(
                self.subnet(network=network),
                self.subnet(network=network, cidr='10.0.1.0/24'),
            ) as (subnet1, subnet2):
                subnet1_id = subnet1['subnet']['id']
                subnet2_id = subnet2['subnet']['id']
                with self.port(
                    subnet=subnet1,
                    fixed_ips=[{'subnet_id': subnet1_id}]):
                    req = self.new_delete_request('subnets', subnet2_id)
                    res = req.get_response(self.api)
                    self.assertEqual(res.status_int,
                                     webob.exc.HTTPNoContent.code)

    def test_delete_subnet_ipv6_slaac_port_exists(self):
        """Test IPv6 SLAAC subnet delete when a port is still using subnet."""
        res = self._create_network(fmt=self.fmt, name='net',
                                   admin_state_up=True)
        network = self.deserialize(self.fmt, res)
        # Create an IPv6 SLAAC subnet and a port using that subnet
        subnet = self._make_subnet(self.fmt, network, gateway='fe80::1',
                                   cidr='fe80::/64', ip_version=6,
                                   ipv6_ra_mode=constants.IPV6_SLAAC,
                                   ipv6_address_mode=constants.IPV6_SLAAC)
        res = self._create_port(self.fmt, net_id=network['network']['id'])
        port = self.deserialize(self.fmt, res)
        self.assertEqual(1, len(port['port']['fixed_ips']))

        # The port should have an address from the subnet
        req = self.new_show_request('ports', port['port']['id'], self.fmt)
        res = req.get_response(self.api)
        sport = self.deserialize(self.fmt, req.get_response(self.api))
        self.assertEqual(1, len(sport['port']['fixed_ips']))

        # Delete the subnet
        req = self.new_delete_request('subnets', subnet['subnet']['id'])
        res = req.get_response(self.api)
        self.assertEqual(webob.exc.HTTPNoContent.code, res.status_int)
        # The port should no longer have an address from the deleted subnet
        req = self.new_show_request('ports', port['port']['id'], self.fmt)
        res = req.get_response(self.api)
        sport = self.deserialize(self.fmt, req.get_response(self.api))
        self.assertEqual(0, len(sport['port']['fixed_ips']))

    def test_delete_network(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        # Create new network
        res = self._create_network(fmt=self.fmt, name='net',
                                   admin_state_up=True)
        network = self.deserialize(self.fmt, res)
        self._make_subnet(self.fmt, network, gateway_ip, cidr, ip_version=4)
        req = self.new_delete_request('networks', network['network']['id'])
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)

    def test_create_subnet_bad_tenant(self):
        with self.network() as network:
            self._create_subnet(self.fmt,
                                network['network']['id'],
                                '10.0.2.0/24',
                                webob.exc.HTTPNotFound.code,
                                ip_version=4,
                                tenant_id='bad_tenant_id',
                                gateway_ip='10.0.2.1',
                                device_owner='fake_owner',
                                set_context=True)

    def test_create_subnet_as_admin(self):
        with self.network() as network:
            self._create_subnet(self.fmt,
                                network['network']['id'],
                                '10.0.2.0/24',
                                webob.exc.HTTPCreated.code,
                                ip_version=4,
                                tenant_id='bad_tenant_id',
                                gateway_ip='10.0.2.1',
                                device_owner='fake_owner',
                                set_context=False)

    def test_create_subnet_nonzero_cidr(self):
        with contextlib.nested(
            self.subnet(cidr='10.129.122.5/8'),
            self.subnet(cidr='11.129.122.5/15'),
            self.subnet(cidr='12.129.122.5/16'),
            self.subnet(cidr='13.129.122.5/18'),
            self.subnet(cidr='14.129.122.5/22'),
            self.subnet(cidr='15.129.122.5/24'),
            self.subnet(cidr='16.129.122.5/28'),
            self.subnet(cidr='17.129.122.5/32', gateway_ip=None)
        ) as subs:
            # the API should accept and correct these for users
            self.assertEqual(subs[0]['subnet']['cidr'], '10.0.0.0/8')
            self.assertEqual(subs[1]['subnet']['cidr'], '11.128.0.0/15')
            self.assertEqual(subs[2]['subnet']['cidr'], '12.129.0.0/16')
            self.assertEqual(subs[3]['subnet']['cidr'], '13.129.64.0/18')
            self.assertEqual(subs[4]['subnet']['cidr'], '14.129.120.0/22')
            self.assertEqual(subs[5]['subnet']['cidr'], '15.129.122.0/24')
            self.assertEqual(subs[6]['subnet']['cidr'], '16.129.122.0/28')
            self.assertEqual(subs[7]['subnet']['cidr'], '17.129.122.5/32')

    def test_create_subnet_bad_ip_version(self):
        with self.network() as network:
            # Check bad IP version
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': 'abc',
                               'tenant_id': network['network']['tenant_id'],
                               'gateway_ip': '10.0.2.1'}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_bad_ip_version_null(self):
        with self.network() as network:
            # Check bad IP version
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': None,
                               'tenant_id': network['network']['tenant_id'],
                               'gateway_ip': '10.0.2.1'}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_bad_uuid(self):
        with self.network() as network:
            # Check invalid UUID
            data = {'subnet': {'network_id': None,
                               'cidr': '10.0.2.0/24',
                               'ip_version': 4,
                               'tenant_id': network['network']['tenant_id'],
                               'gateway_ip': '10.0.2.1'}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_bad_boolean(self):
        with self.network() as network:
            # Check invalid boolean
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': '4',
                               'enable_dhcp': None,
                               'tenant_id': network['network']['tenant_id'],
                               'gateway_ip': '10.0.2.1'}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_bad_pools(self):
        with self.network() as network:
            # Check allocation pools
            allocation_pools = [[{'end': '10.0.0.254'}],
                                [{'start': '10.0.0.254'}],
                                [{'start': '1000.0.0.254'}],
                                [{'start': '10.0.0.2', 'end': '10.0.0.254'},
                                 {'end': '10.0.0.254'}],
                                None,
                                [{'start': '10.0.0.2', 'end': '10.0.0.3'},
                                 {'start': '10.0.0.2', 'end': '10.0.0.3'}]]
            tenant_id = network['network']['tenant_id']
            for pool in allocation_pools:
                data = {'subnet': {'network_id': network['network']['id'],
                                   'cidr': '10.0.2.0/24',
                                   'ip_version': '4',
                                   'tenant_id': tenant_id,
                                   'gateway_ip': '10.0.2.1',
                                   'allocation_pools': pool}}
                subnet_req = self.new_create_request('subnets', data)
                res = subnet_req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_create_subnet_bad_nameserver(self):
        with self.network() as network:
            # Check nameservers
            nameserver_pools = [['1100.0.0.2'],
                                ['1.1.1.2', '1.1000.1.3'],
                                ['1.1.1.2', '1.1.1.2']]
            tenant_id = network['network']['tenant_id']
            for nameservers in nameserver_pools:
                data = {'subnet': {'network_id': network['network']['id'],
                                   'cidr': '10.0.2.0/24',
                                   'ip_version': '4',
                                   'tenant_id': tenant_id,
                                   'gateway_ip': '10.0.2.1',
                                   'dns_nameservers': nameservers}}
                subnet_req = self.new_create_request('subnets', data)
                res = subnet_req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_create_subnet_bad_hostroutes(self):
        with self.network() as network:
            # Check hostroutes
            hostroute_pools = [[{'destination': '100.0.0.0/24'}],
                               [{'nexthop': '10.0.2.20'}],
                               [{'nexthop': '10.0.2.20',
                                 'destination': '100.0.0.0/8'},
                                {'nexthop': '10.0.2.20',
                                 'destination': '100.0.0.0/8'}]]
            tenant_id = network['network']['tenant_id']
            for hostroutes in hostroute_pools:
                data = {'subnet': {'network_id': network['network']['id'],
                                   'cidr': '10.0.2.0/24',
                                   'ip_version': '4',
                                   'tenant_id': tenant_id,
                                   'gateway_ip': '10.0.2.1',
                                   'host_routes': hostroutes}}
                subnet_req = self.new_create_request('subnets', data)
                res = subnet_req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_create_subnet_defaults(self):
        gateway = '10.0.0.1'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.254'}]
        enable_dhcp = True
        subnet = self._test_create_subnet()
        # verify cidr & gw have been correctly generated
        self.assertEqual(subnet['subnet']['cidr'], cidr)
        self.assertEqual(subnet['subnet']['gateway_ip'], gateway)
        self.assertEqual(subnet['subnet']['enable_dhcp'], enable_dhcp)
        self.assertEqual(subnet['subnet']['allocation_pools'],
                         allocation_pools)

    def test_create_subnet_gw_values(self):
        cidr = '10.0.0.0/24'
        # Gateway is last IP in range
        gateway = '10.0.0.254'
        allocation_pools = [{'start': '10.0.0.1',
                             'end': '10.0.0.253'}]
        expected = {'gateway_ip': gateway,
                    'cidr': cidr,
                    'allocation_pools': allocation_pools}
        self._test_create_subnet(expected=expected, gateway_ip=gateway)
        # Gateway is first in subnet
        gateway = '10.0.0.1'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.254'}]
        expected = {'gateway_ip': gateway,
                    'cidr': cidr,
                    'allocation_pools': allocation_pools}
        self._test_create_subnet(expected=expected,
                                 gateway_ip=gateway)

    def test_create_subnet_ipv6_gw_values(self):
        cidr = '2001::/64'
        # Gateway is last IP in IPv6 DHCPv6 stateful subnet
        gateway = '2001::ffff:ffff:ffff:fffe'
        allocation_pools = [{'start': '2001::1',
                             'end': '2001::ffff:ffff:ffff:fffd'}]
        expected = {'gateway_ip': gateway,
                    'cidr': cidr,
                    'allocation_pools': allocation_pools}
        self._test_create_subnet(expected=expected, gateway_ip=gateway,
                                 cidr=cidr, ip_version=6,
                                 ipv6_ra_mode=constants.DHCPV6_STATEFUL,
                                 ipv6_address_mode=constants.DHCPV6_STATEFUL)
        # Gateway is first IP in IPv6 DHCPv6 stateful subnet
        gateway = '2001::1'
        allocation_pools = [{'start': '2001::2',
                             'end': '2001::ffff:ffff:ffff:fffe'}]
        expected = {'gateway_ip': gateway,
                    'cidr': cidr,
                    'allocation_pools': allocation_pools}
        self._test_create_subnet(expected=expected, gateway_ip=gateway,
                                 cidr=cidr, ip_version=6,
                                 ipv6_ra_mode=constants.DHCPV6_STATEFUL,
                                 ipv6_address_mode=constants.DHCPV6_STATEFUL)
        # Gateway not specified for IPv6 SLAAC subnet
        expected = {'gateway_ip': None,
                    'cidr': cidr}
        self._test_create_subnet(expected=expected,
                                 cidr=cidr, ip_version=6,
                                 ipv6_ra_mode=constants.IPV6_SLAAC,
                                 ipv6_address_mode=constants.IPV6_SLAAC)

    def test_create_subnet_gw_outside_cidr_returns_400(self):
        with self.network() as network:
            self._create_subnet(self.fmt,
                                network['network']['id'],
                                '10.0.0.0/24',
                                webob.exc.HTTPClientError.code,
                                gateway_ip='100.0.0.1')

    def test_create_subnet_gw_of_network_returns_400(self):
        with self.network() as network:
            self._create_subnet(self.fmt,
                                network['network']['id'],
                                '10.0.0.0/24',
                                webob.exc.HTTPClientError.code,
                                gateway_ip='10.0.0.0')

    def test_create_subnet_gw_bcast_returns_400(self):
        with self.network() as network:
            self._create_subnet(self.fmt,
                                network['network']['id'],
                                '10.0.0.0/24',
                                webob.exc.HTTPClientError.code,
                                gateway_ip='10.0.0.255')

    def test_create_subnet_with_allocation_pool(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.100'}]
        self._test_create_subnet(gateway_ip=gateway_ip,
                                 cidr=cidr,
                                 allocation_pools=allocation_pools)

    def test_create_subnet_with_none_gateway(self):
        cidr = '10.0.0.0/24'
        self._test_create_subnet(gateway_ip=None,
                                 cidr=cidr)

    def test_create_subnet_with_none_gateway_fully_allocated(self):
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.1',
                             'end': '10.0.0.254'}]
        self._test_create_subnet(gateway_ip=None,
                                 cidr=cidr,
                                 allocation_pools=allocation_pools)

    def test_subnet_with_allocation_range(self):
        with self.network() as network:
            net_id = network['network']['id']
            data = {'subnet': {'network_id': net_id,
                               'cidr': '10.0.0.0/24',
                               'ip_version': 4,
                               'gateway_ip': '10.0.0.1',
                               'tenant_id': network['network']['tenant_id'],
                               'allocation_pools': [{'start': '10.0.0.100',
                                                    'end': '10.0.0.120'}]}}
            subnet_req = self.new_create_request('subnets', data)
            subnet = self.deserialize(self.fmt,
                                      subnet_req.get_response(self.api))
            # Check fixed IP not in allocation range
            kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'],
                                     'ip_address': '10.0.0.10'}]}
            res = self._create_port(self.fmt, net_id=net_id, **kwargs)
            self.assertEqual(res.status_int, webob.exc.HTTPCreated.code)
            port = self.deserialize(self.fmt, res)
            # delete the port
            self._delete('ports', port['port']['id'])

            # Check when fixed IP is gateway
            kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'],
                                     'ip_address': '10.0.0.1'}]}
            res = self._create_port(self.fmt, net_id=net_id, **kwargs)
            self.assertEqual(res.status_int, webob.exc.HTTPCreated.code)
            port = self.deserialize(self.fmt, res)
            # delete the port
            self._delete('ports', port['port']['id'])

    def test_create_subnet_with_none_gateway_allocation_pool(self):
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.100'}]
        self._test_create_subnet(gateway_ip=None,
                                 cidr=cidr,
                                 allocation_pools=allocation_pools)

    def test_create_subnet_with_v6_allocation_pool(self):
        gateway_ip = 'fe80::1'
        cidr = 'fe80::/80'
        allocation_pools = [{'start': 'fe80::2',
                             'end': 'fe80::ffff:fffa:ffff'}]
        self._test_create_subnet(gateway_ip=gateway_ip,
                                 cidr=cidr, ip_version=6,
                                 allocation_pools=allocation_pools)

    def test_create_subnet_with_large_allocation_pool(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/8'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.100'},
                            {'start': '10.1.0.0',
                             'end': '10.200.0.100'}]
        self._test_create_subnet(gateway_ip=gateway_ip,
                                 cidr=cidr,
                                 allocation_pools=allocation_pools)

    def test_create_subnet_multiple_allocation_pools(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.100'},
                            {'start': '10.0.0.110',
                             'end': '10.0.0.150'}]
        self._test_create_subnet(gateway_ip=gateway_ip,
                                 cidr=cidr,
                                 allocation_pools=allocation_pools)

    def test_create_subnet_with_dhcp_disabled(self):
        enable_dhcp = False
        self._test_create_subnet(enable_dhcp=enable_dhcp)

    def test_create_subnet_default_gw_conflict_allocation_pool_returns_409(
        self):
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.1',
                             'end': '10.0.0.5'}]
        with testlib_api.ExpectedException(
                webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(cidr=cidr,
                                     allocation_pools=allocation_pools)
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPConflict.code)

    def test_create_subnet_gateway_in_allocation_pool_returns_409(self):
        gateway_ip = '10.0.0.50'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.1',
                             'end': '10.0.0.100'}]
        with testlib_api.ExpectedException(
                webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(gateway_ip=gateway_ip,
                                     cidr=cidr,
                                     allocation_pools=allocation_pools)
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPConflict.code)

    def test_create_subnet_overlapping_allocation_pools_returns_409(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.150'},
                            {'start': '10.0.0.140',
                             'end': '10.0.0.180'}]
        with testlib_api.ExpectedException(
                webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(gateway_ip=gateway_ip,
                                     cidr=cidr,
                                     allocation_pools=allocation_pools)
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPConflict.code)

    def test_create_subnet_invalid_allocation_pool_returns_400(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.256'}]
        with testlib_api.ExpectedException(
                webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(gateway_ip=gateway_ip,
                                     cidr=cidr,
                                     allocation_pools=allocation_pools)
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPClientError.code)

    def test_create_subnet_out_of_range_allocation_pool_returns_400(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.1.6'}]
        with testlib_api.ExpectedException(
                webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(gateway_ip=gateway_ip,
                                     cidr=cidr,
                                     allocation_pools=allocation_pools)
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPClientError.code)

    def test_create_subnet_shared_returns_400(self):
        cidr = '10.0.0.0/24'
        with testlib_api.ExpectedException(
                webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(cidr=cidr,
                                     shared=True)
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPClientError.code)

    def test_create_subnet_inconsistent_ipv6_cidrv4(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': 6,
                               'tenant_id': network['network']['tenant_id']}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_inconsistent_ipv4_cidrv6(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': 'fe80::0/80',
                               'ip_version': 4,
                               'tenant_id': network['network']['tenant_id']}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_inconsistent_ipv4_gatewayv6(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': 4,
                               'gateway_ip': 'fe80::1',
                               'tenant_id': network['network']['tenant_id']}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_inconsistent_ipv6_gatewayv4(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': 'fe80::0/80',
                               'ip_version': 6,
                               'gateway_ip': '192.168.0.1',
                               'tenant_id': network['network']['tenant_id']}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_inconsistent_ipv6_dns_v4(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': 'fe80::0/80',
                               'ip_version': 6,
                               'dns_nameservers': ['192.168.0.1'],
                               'tenant_id': network['network']['tenant_id']}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_inconsistent_ipv4_hostroute_dst_v6(self):
        host_routes = [{'destination': 'fe80::0/48',
                        'nexthop': '10.0.2.20'}]
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': 4,
                               'host_routes': host_routes,
                               'tenant_id': network['network']['tenant_id']}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_inconsistent_ipv4_hostroute_np_v6(self):
        host_routes = [{'destination': '172.16.0.0/24',
                        'nexthop': 'fe80::1'}]
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': 4,
                               'host_routes': host_routes,
                               'tenant_id': network['network']['tenant_id']}}
            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def _test_validate_subnet_ipv6_modes(self, cur_subnet=None,
                                         expect_success=True, **modes):
        plugin = manager.NeutronManager.get_plugin()
        ctx = context.get_admin_context(load_admin_roles=False)
        new_subnet = {'ip_version': 6,
                      'cidr': 'fe80::/64',
                      'enable_dhcp': True}
        for mode, value in modes.items():
            new_subnet[mode] = value
        if expect_success:
            plugin._validate_subnet(ctx, new_subnet, cur_subnet)
        else:
            self.assertRaises(n_exc.InvalidInput, plugin._validate_subnet,
                              ctx, new_subnet, cur_subnet)

    def test_create_subnet_ipv6_ra_modes(self):
        # Test all RA modes with no address mode specified
        for ra_mode in constants.IPV6_MODES:
            self._test_validate_subnet_ipv6_modes(
                ipv6_ra_mode=ra_mode)

    def test_create_subnet_ipv6_addr_modes(self):
        # Test all address modes with no RA mode specified
        for addr_mode in constants.IPV6_MODES:
            self._test_validate_subnet_ipv6_modes(
                ipv6_address_mode=addr_mode)

    def test_create_subnet_ipv6_same_ra_and_addr_modes(self):
        # Test all ipv6 modes with ra_mode==addr_mode
        for ipv6_mode in constants.IPV6_MODES:
            self._test_validate_subnet_ipv6_modes(
                ipv6_ra_mode=ipv6_mode,
                ipv6_address_mode=ipv6_mode)

    def test_create_subnet_ipv6_different_ra_and_addr_modes(self):
        # Test all ipv6 modes with ra_mode!=addr_mode
        for ra_mode, addr_mode in itertools.permutations(
                constants.IPV6_MODES, 2):
            self._test_validate_subnet_ipv6_modes(
                expect_success=not (ra_mode and addr_mode),
                ipv6_ra_mode=ra_mode,
                ipv6_address_mode=addr_mode)

    def test_create_subnet_ipv6_out_of_cidr_global(self):
        gateway_ip = '2000::1'
        cidr = '2001::/64'

        with testlib_api.ExpectedException(
            webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(
                gateway_ip=gateway_ip, cidr=cidr, ip_version=6,
                ipv6_ra_mode=constants.DHCPV6_STATEFUL,
                ipv6_address_mode=constants.DHCPV6_STATEFUL)
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPClientError.code)

    def test_create_subnet_ipv6_out_of_cidr_lla(self):
        gateway_ip = 'fe80::1'
        cidr = '2001::/64'

        self._test_create_subnet(
            gateway_ip=gateway_ip, cidr=cidr, ip_version=6,
            ipv6_ra_mode=constants.IPV6_SLAAC,
            ipv6_address_mode=constants.IPV6_SLAAC)

    def test_create_subnet_ipv6_attributes_no_dhcp_enabled(self):
        gateway_ip = 'fe80::1'
        cidr = 'fe80::/64'
        with testlib_api.ExpectedException(
                webob.exc.HTTPClientError) as ctx_manager:
            for mode in constants.IPV6_MODES:
                self._test_create_subnet(gateway_ip=gateway_ip,
                                         cidr=cidr, ip_version=6,
                                         enable_dhcp=False,
                                         ipv6_ra_mode=mode,
                                         ipv6_address_mode=mode)
                self.assertEqual(ctx_manager.exception.code,
                                 webob.exc.HTTPClientError.code)

    def test_create_subnet_invalid_ipv6_ra_mode(self):
        gateway_ip = 'fe80::1'
        cidr = 'fe80::/80'
        with testlib_api.ExpectedException(
            webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(gateway_ip=gateway_ip,
                                     cidr=cidr, ip_version=6,
                                     ipv6_ra_mode='foo',
                                     ipv6_address_mode='slaac')
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPClientError.code)

    def test_create_subnet_invalid_ipv6_address_mode(self):
        gateway_ip = 'fe80::1'
        cidr = 'fe80::/80'
        with testlib_api.ExpectedException(
            webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(gateway_ip=gateway_ip,
                                     cidr=cidr, ip_version=6,
                                     ipv6_ra_mode='slaac',
                                     ipv6_address_mode='baz')
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPClientError.code)

    def test_create_subnet_ipv6_ra_mode_ip_version_4(self):
        cidr = '10.0.2.0/24'
        with testlib_api.ExpectedException(
            webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(cidr=cidr, ip_version=4,
                                     ipv6_ra_mode=constants.DHCPV6_STATEFUL)
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPClientError.code)

    def test_create_subnet_ipv6_address_mode_ip_version_4(self):
        cidr = '10.0.2.0/24'
        with testlib_api.ExpectedException(
            webob.exc.HTTPClientError) as ctx_manager:
            self._test_create_subnet(
                cidr=cidr, ip_version=4,
                ipv6_address_mode=constants.DHCPV6_STATEFUL)
        self.assertEqual(ctx_manager.exception.code,
                         webob.exc.HTTPClientError.code)

    def test_update_subnet_no_gateway(self):
        with self.subnet() as subnet:
            data = {'subnet': {'gateway_ip': '10.0.0.1'}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(res['subnet']['gateway_ip'],
                             data['subnet']['gateway_ip'])
            data = {'subnet': {'gateway_ip': None}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertIsNone(data['subnet']['gateway_ip'])

    def test_update_subnet(self):
        with self.subnet() as subnet:
            data = {'subnet': {'gateway_ip': '10.0.0.1'}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(res['subnet']['gateway_ip'],
                             data['subnet']['gateway_ip'])

    def test_update_subnet_adding_additional_host_routes_and_dns(self):
        host_routes = [{'destination': '172.16.0.0/24',
                        'nexthop': '10.0.2.2'}]
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': 4,
                               'dns_nameservers': ['192.168.0.1'],
                               'host_routes': host_routes,
                               'tenant_id': network['network']['tenant_id']}}
            subnet_req = self.new_create_request('subnets', data)
            res = self.deserialize(self.fmt, subnet_req.get_response(self.api))

            host_routes = [{'destination': '172.16.0.0/24',
                            'nexthop': '10.0.2.2'},
                           {'destination': '192.168.0.0/24',
                            'nexthop': '10.0.2.3'}]

            dns_nameservers = ['192.168.0.1', '192.168.0.2']
            data = {'subnet': {'host_routes': host_routes,
                               'dns_nameservers': dns_nameservers}}
            req = self.new_update_request('subnets', data,
                                          res['subnet']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(sorted(res['subnet']['host_routes']),
                             sorted(host_routes))
            self.assertEqual(sorted(res['subnet']['dns_nameservers']),
                             sorted(dns_nameservers))

    def test_update_subnet_shared_returns_400(self):
        with self.network(shared=True) as network:
            with self.subnet(network=network) as subnet:
                data = {'subnet': {'shared': True}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_update_subnet_gw_outside_cidr_returns_400(self):
        with self.network() as network:
            with self.subnet(network=network) as subnet:
                data = {'subnet': {'gateway_ip': '100.0.0.1'}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_update_subnet_gw_ip_in_use_returns_409(self):
        with self.network() as network:
            with self.subnet(
                network=network,
                allocation_pools=[{'start': '10.0.0.100',
                                   'end': '10.0.0.253'}]) as subnet:
                subnet_data = subnet['subnet']
                with self.port(
                    subnet=subnet,
                    fixed_ips=[{'subnet_id': subnet_data['id'],
                                'ip_address': subnet_data['gateway_ip']}]):
                    data = {'subnet': {'gateway_ip': '10.0.0.99'}}
                    req = self.new_update_request('subnets', data,
                                                  subnet_data['id'])
                    res = req.get_response(self.api)
                    self.assertEqual(res.status_int, 409)

    def test_update_subnet_inconsistent_ipv4_gatewayv6(self):
        with self.network() as network:
            with self.subnet(network=network) as subnet:
                data = {'subnet': {'gateway_ip': 'fe80::1'}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_update_subnet_inconsistent_ipv6_gatewayv4(self):
        with self.network() as network:
            with self.subnet(network=network,
                             ip_version=6, cidr='fe80::/48') as subnet:
                data = {'subnet': {'gateway_ip': '10.1.1.1'}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_update_subnet_inconsistent_ipv4_dns_v6(self):
        dns_nameservers = ['fe80::1']
        with self.network() as network:
            with self.subnet(network=network) as subnet:
                data = {'subnet': {'dns_nameservers': dns_nameservers}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_update_subnet_inconsistent_ipv6_hostroute_dst_v4(self):
        host_routes = [{'destination': 'fe80::0/48',
                        'nexthop': '10.0.2.20'}]
        with self.network() as network:
            with self.subnet(network=network,
                             ip_version=6, cidr='fe80::/48') as subnet:
                data = {'subnet': {'host_routes': host_routes}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_update_subnet_inconsistent_ipv6_hostroute_np_v4(self):
        host_routes = [{'destination': '172.16.0.0/24',
                        'nexthop': 'fe80::1'}]
        with self.network() as network:
            with self.subnet(network=network,
                             ip_version=6, cidr='fe80::/48') as subnet:
                data = {'subnet': {'host_routes': host_routes}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_update_subnet_gateway_in_allocation_pool_returns_409(self):
        allocation_pools = [{'start': '10.0.0.2', 'end': '10.0.0.254'}]
        with self.network() as network:
            with self.subnet(network=network,
                             allocation_pools=allocation_pools,
                             cidr='10.0.0.0/24') as subnet:
                data = {'subnet': {'gateway_ip': '10.0.0.50'}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPConflict.code)

    def test_update_subnet_ipv6_attributes_fails(self):
        with self.subnet(ip_version=6, cidr='fe80::/64',
                         ipv6_ra_mode=constants.IPV6_SLAAC,
                         ipv6_address_mode=constants.IPV6_SLAAC) as subnet:
            data = {'subnet': {'ipv6_ra_mode': constants.DHCPV6_STATEFUL,
                               'ipv6_address_mode': constants.DHCPV6_STATEFUL}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int,
                             webob.exc.HTTPClientError.code)

    def test_update_subnet_ipv6_ra_mode_fails(self):
        with self.subnet(ip_version=6, cidr='fe80::/64',
                         ipv6_ra_mode=constants.IPV6_SLAAC) as subnet:
            data = {'subnet': {'ipv6_ra_mode': constants.DHCPV6_STATEFUL}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int,
                             webob.exc.HTTPClientError.code)

    def test_update_subnet_ipv6_ra_mode_fails(self):
        with self.subnet(ip_version=6, cidr='fe80::/64',
                         ipv6_address_mode=constants.IPV6_SLAAC) as subnet:
            data = {'subnet': {'ipv6_address_mode': constants.DHCPV6_STATEFUL}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int,
                             webob.exc.HTTPClientError.code)

    def test_update_subnet_ipv6_cannot_disable_dhcp(self):
        with self.subnet(ip_version=6, cidr='fe80::/64',
                         ipv6_ra_mode=constants.IPV6_SLAAC,
                         ipv6_address_mode=constants.IPV6_SLAAC) as subnet:
            data = {'subnet': {'enable_dhcp': False}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int,
                             webob.exc.HTTPClientError.code)

    def test_update_subnet_ipv6_ra_mode_ip_version_4(self):
        with self.network() as network:
            with self.subnet(network=network) as subnet:
                data = {'subnet': {'ipv6_ra_mode':
                                   constants.DHCPV6_STATEFUL}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_update_subnet_ipv6_address_mode_ip_version_4(self):
        with self.network() as network:
            with self.subnet(network=network) as subnet:
                data = {'subnet': {'ipv6_address_mode':
                                   constants.DHCPV6_STATEFUL}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_update_subnet_allocation_pools(self):
        """Test that we can successfully update with sane params.

        This will create a subnet with specified allocation_pools
        Then issue an update (PUT) to update these using correct
        (i.e. non erroneous) params. Finally retrieve the updated
        subnet and verify.
        """
        allocation_pools = [{'start': '192.168.0.2', 'end': '192.168.0.254'}]
        with self.network() as network:
            with self.subnet(network=network,
                             allocation_pools=allocation_pools,
                             cidr='192.168.0.0/24') as subnet:
                data = {'subnet': {'allocation_pools': [
                        {'start': '192.168.0.10', 'end': '192.168.0.20'},
                        {'start': '192.168.0.30', 'end': '192.168.0.40'}]}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                #check res code but then do GET on subnet for verification
                res = req.get_response(self.api)
                self.assertEqual(res.status_code, 200)
                req = self.new_show_request('subnets', subnet['subnet']['id'],
                                            self.fmt)
                res = self.deserialize(self.fmt, req.get_response(self.api))
                self.assertEqual(len(res['subnet']['allocation_pools']), 2)
                res_vals = res['subnet']['allocation_pools'][0].values() +\
                    res['subnet']['allocation_pools'][1].values()
                for pool_val in ['10', '20', '30', '40']:
                    self.assertTrue('192.168.0.%s' % (pool_val) in res_vals)

    #updating alloc pool to something outside subnet.cidr
    def test_update_subnet_allocation_pools_invalid_pool_for_cidr(self):
        """Test update alloc pool to something outside subnet.cidr.

        This makes sure that an erroneous allocation_pool specified
        in a subnet update (outside subnet cidr) will result in an error.
        """
        allocation_pools = [{'start': '192.168.0.2', 'end': '192.168.0.254'}]
        with self.network() as network:
            with self.subnet(network=network,
                             allocation_pools=allocation_pools,
                             cidr='192.168.0.0/24') as subnet:
                data = {'subnet': {'allocation_pools': [
                        {'start': '10.0.0.10', 'end': '10.0.0.20'}]}}
                req = self.new_update_request('subnets', data,
                                              subnet['subnet']['id'])
                res = req.get_response(self.api)
                self.assertEqual(res.status_int,
                                 webob.exc.HTTPClientError.code)

    def test_show_subnet(self):
        with self.network() as network:
            with self.subnet(network=network) as subnet:
                req = self.new_show_request('subnets',
                                            subnet['subnet']['id'])
                res = self.deserialize(self.fmt, req.get_response(self.api))
                self.assertEqual(res['subnet']['id'],
                                 subnet['subnet']['id'])
                self.assertEqual(res['subnet']['network_id'],
                                 network['network']['id'])

    def test_list_subnets(self):
        with self.network() as network:
            with contextlib.nested(self.subnet(network=network,
                                               gateway_ip='10.0.0.1',
                                               cidr='10.0.0.0/24'),
                                   self.subnet(network=network,
                                               gateway_ip='10.0.1.1',
                                               cidr='10.0.1.0/24'),
                                   self.subnet(network=network,
                                               gateway_ip='10.0.2.1',
                                               cidr='10.0.2.0/24')) as subnets:
                self._test_list_resources('subnet', subnets)

    def test_list_subnets_shared(self):
        with self.network(shared=True) as network:
            with self.subnet(network=network, cidr='10.0.0.0/24') as subnet:
                with self.subnet(cidr='10.0.1.0/24') as priv_subnet:
                    # normal user should see only 1 subnet
                    req = self.new_list_request('subnets')
                    req.environ['neutron.context'] = context.Context(
                        '', 'some_tenant')
                    res = self.deserialize(self.fmt,
                                           req.get_response(self.api))
                    self.assertEqual(len(res['subnets']), 1)
                    self.assertEqual(res['subnets'][0]['cidr'],
                                     subnet['subnet']['cidr'])
                    # admin will see both subnets
                    admin_req = self.new_list_request('subnets')
                    admin_res = self.deserialize(
                        self.fmt, admin_req.get_response(self.api))
                    self.assertEqual(len(admin_res['subnets']), 2)
                    cidrs = [sub['cidr'] for sub in admin_res['subnets']]
                    self.assertIn(subnet['subnet']['cidr'], cidrs)
                    self.assertIn(priv_subnet['subnet']['cidr'], cidrs)

    def test_list_subnets_with_parameter(self):
        with self.network() as network:
            with contextlib.nested(self.subnet(network=network,
                                               gateway_ip='10.0.0.1',
                                               cidr='10.0.0.0/24'),
                                   self.subnet(network=network,
                                               gateway_ip='10.0.1.1',
                                               cidr='10.0.1.0/24')
                                   ) as subnets:
                query_params = 'ip_version=4&ip_version=6'
                self._test_list_resources('subnet', subnets,
                                          query_params=query_params)
                query_params = 'ip_version=6'
                self._test_list_resources('subnet', [],
                                          query_params=query_params)

    def test_list_subnets_with_sort_native(self):
        if self._skip_native_sorting:
            self.skipTest("Skip test for not implemented sorting feature")
        with contextlib.nested(self.subnet(enable_dhcp=True,
                                           cidr='10.0.0.0/24'),
                               self.subnet(enable_dhcp=False,
                                           cidr='11.0.0.0/24'),
                               self.subnet(enable_dhcp=False,
                                           cidr='12.0.0.0/24')
                               ) as (subnet1, subnet2, subnet3):
            self._test_list_with_sort('subnet', (subnet3, subnet2, subnet1),
                                      [('enable_dhcp', 'asc'),
                                       ('cidr', 'desc')])

    def test_list_subnets_with_sort_emulated(self):
        helper_patcher = mock.patch(
            'neutron.api.v2.base.Controller._get_sorting_helper',
            new=_fake_get_sorting_helper)
        helper_patcher.start()
        with contextlib.nested(self.subnet(enable_dhcp=True,
                                           cidr='10.0.0.0/24'),
                               self.subnet(enable_dhcp=False,
                                           cidr='11.0.0.0/24'),
                               self.subnet(enable_dhcp=False,
                                           cidr='12.0.0.0/24')
                               ) as (subnet1, subnet2, subnet3):
            self._test_list_with_sort('subnet', (subnet3,
                                                 subnet2,
                                                 subnet1),
                                      [('enable_dhcp', 'asc'),
                                       ('cidr', 'desc')])

    def test_list_subnets_with_pagination_native(self):
        if self._skip_native_pagination:
            self.skipTest("Skip test for not implemented sorting feature")
        with contextlib.nested(self.subnet(cidr='10.0.0.0/24'),
                               self.subnet(cidr='11.0.0.0/24'),
                               self.subnet(cidr='12.0.0.0/24')
                               ) as (subnet1, subnet2, subnet3):
            self._test_list_with_pagination('subnet',
                                            (subnet1, subnet2, subnet3),
                                            ('cidr', 'asc'), 2, 2)

    def test_list_subnets_with_pagination_emulated(self):
        helper_patcher = mock.patch(
            'neutron.api.v2.base.Controller._get_pagination_helper',
            new=_fake_get_pagination_helper)
        helper_patcher.start()
        with contextlib.nested(self.subnet(cidr='10.0.0.0/24'),
                               self.subnet(cidr='11.0.0.0/24'),
                               self.subnet(cidr='12.0.0.0/24')
                               ) as (subnet1, subnet2, subnet3):
            self._test_list_with_pagination('subnet',
                                            (subnet1, subnet2, subnet3),
                                            ('cidr', 'asc'), 2, 2)

    def test_list_subnets_with_pagination_reverse_native(self):
        if self._skip_native_sorting:
            self.skipTest("Skip test for not implemented sorting feature")
        with contextlib.nested(self.subnet(cidr='10.0.0.0/24'),
                               self.subnet(cidr='11.0.0.0/24'),
                               self.subnet(cidr='12.0.0.0/24')
                               ) as (subnet1, subnet2, subnet3):
            self._test_list_with_pagination_reverse('subnet',
                                                    (subnet1, subnet2,
                                                     subnet3),
                                                    ('cidr', 'asc'), 2, 2)

    def test_list_subnets_with_pagination_reverse_emulated(self):
        helper_patcher = mock.patch(
            'neutron.api.v2.base.Controller._get_pagination_helper',
            new=_fake_get_pagination_helper)
        helper_patcher.start()
        with contextlib.nested(self.subnet(cidr='10.0.0.0/24'),
                               self.subnet(cidr='11.0.0.0/24'),
                               self.subnet(cidr='12.0.0.0/24')
                               ) as (subnet1, subnet2, subnet3):
            self._test_list_with_pagination_reverse('subnet',
                                                    (subnet1, subnet2,
                                                     subnet3),
                                                    ('cidr', 'asc'), 2, 2)

    def test_invalid_ip_version(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': 7,
                               'tenant_id': network['network']['tenant_id'],
                               'gateway_ip': '10.0.2.1'}}

            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_invalid_subnet(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': 'invalid',
                               'ip_version': 4,
                               'tenant_id': network['network']['tenant_id'],
                               'gateway_ip': '10.0.2.1'}}

            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_invalid_ip_address(self):
        with self.network() as network:
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': 4,
                               'tenant_id': network['network']['tenant_id'],
                               'gateway_ip': 'ipaddress'}}

            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_invalid_uuid(self):
        with self.network() as network:
            data = {'subnet': {'network_id': 'invalid-uuid',
                               'cidr': '10.0.2.0/24',
                               'ip_version': 4,
                               'tenant_id': network['network']['tenant_id'],
                               'gateway_ip': '10.0.0.1'}}

            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_with_one_dns(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.100'}]
        dns_nameservers = ['1.2.3.4']
        self._test_create_subnet(gateway_ip=gateway_ip,
                                 cidr=cidr,
                                 allocation_pools=allocation_pools,
                                 dns_nameservers=dns_nameservers)

    def test_create_subnet_with_two_dns(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.100'}]
        dns_nameservers = ['1.2.3.4', '4.3.2.1']
        self._test_create_subnet(gateway_ip=gateway_ip,
                                 cidr=cidr,
                                 allocation_pools=allocation_pools,
                                 dns_nameservers=dns_nameservers)

    def test_create_subnet_with_too_many_dns(self):
        with self.network() as network:
            dns_list = ['1.1.1.1', '2.2.2.2', '3.3.3.3']
            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': 4,
                               'tenant_id': network['network']['tenant_id'],
                               'gateway_ip': '10.0.0.1',
                               'dns_nameservers': dns_list}}

            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_create_subnet_with_one_host_route(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.100'}]
        host_routes = [{'destination': '135.207.0.0/16',
                       'nexthop': '1.2.3.4'}]
        self._test_create_subnet(gateway_ip=gateway_ip,
                                 cidr=cidr,
                                 allocation_pools=allocation_pools,
                                 host_routes=host_routes)

    def test_create_subnet_with_two_host_routes(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        allocation_pools = [{'start': '10.0.0.2',
                             'end': '10.0.0.100'}]
        host_routes = [{'destination': '135.207.0.0/16',
                       'nexthop': '1.2.3.4'},
                       {'destination': '12.0.0.0/8',
                        'nexthop': '4.3.2.1'}]

        self._test_create_subnet(gateway_ip=gateway_ip,
                                 cidr=cidr,
                                 allocation_pools=allocation_pools,
                                 host_routes=host_routes)

    def test_create_subnet_with_too_many_routes(self):
        with self.network() as network:
            host_routes = [{'destination': '135.207.0.0/16',
                            'nexthop': '1.2.3.4'},
                           {'destination': '12.0.0.0/8',
                            'nexthop': '4.3.2.1'},
                           {'destination': '141.212.0.0/16',
                            'nexthop': '2.2.2.2'}]

            data = {'subnet': {'network_id': network['network']['id'],
                               'cidr': '10.0.2.0/24',
                               'ip_version': 4,
                               'tenant_id': network['network']['tenant_id'],
                               'gateway_ip': '10.0.0.1',
                               'host_routes': host_routes}}

            subnet_req = self.new_create_request('subnets', data)
            res = subnet_req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_update_subnet_dns(self):
        with self.subnet() as subnet:
            data = {'subnet': {'dns_nameservers': ['11.0.0.1']}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(res['subnet']['dns_nameservers'],
                             data['subnet']['dns_nameservers'])

    def test_update_subnet_dns_to_None(self):
        with self.subnet(dns_nameservers=['11.0.0.1']) as subnet:
            data = {'subnet': {'dns_nameservers': None}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual([], res['subnet']['dns_nameservers'])
            data = {'subnet': {'dns_nameservers': ['11.0.0.3']}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(data['subnet']['dns_nameservers'],
                             res['subnet']['dns_nameservers'])

    def test_update_subnet_dns_with_too_many_entries(self):
        with self.subnet() as subnet:
            dns_list = ['1.1.1.1', '2.2.2.2', '3.3.3.3']
            data = {'subnet': {'dns_nameservers': dns_list}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_update_subnet_route(self):
        with self.subnet() as subnet:
            data = {'subnet': {'host_routes':
                    [{'destination': '12.0.0.0/8', 'nexthop': '1.2.3.4'}]}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(res['subnet']['host_routes'],
                             data['subnet']['host_routes'])

    def test_update_subnet_route_to_None(self):
        with self.subnet(host_routes=[{'destination': '12.0.0.0/8',
                                       'nexthop': '1.2.3.4'}]) as subnet:
            data = {'subnet': {'host_routes': None}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual([], res['subnet']['host_routes'])
            data = {'subnet': {'host_routes': [{'destination': '12.0.0.0/8',
                                                'nexthop': '1.2.3.4'}]}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = self.deserialize(self.fmt, req.get_response(self.api))
            self.assertEqual(data['subnet']['host_routes'],
                             res['subnet']['host_routes'])

    def test_update_subnet_route_with_too_many_entries(self):
        with self.subnet() as subnet:
            data = {'subnet': {'host_routes': [
                    {'destination': '12.0.0.0/8', 'nexthop': '1.2.3.4'},
                    {'destination': '13.0.0.0/8', 'nexthop': '1.2.3.5'},
                    {'destination': '14.0.0.0/8', 'nexthop': '1.2.3.6'}]}}
            req = self.new_update_request('subnets', data,
                                          subnet['subnet']['id'])
            res = req.get_response(self.api)
            self.assertEqual(res.status_int, webob.exc.HTTPClientError.code)

    def test_delete_subnet_with_dns(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        dns_nameservers = ['1.2.3.4']
        # Create new network
        res = self._create_network(fmt=self.fmt, name='net',
                                   admin_state_up=True)
        network = self.deserialize(self.fmt, res)
        subnet = self._make_subnet(self.fmt, network, gateway_ip,
                                   cidr, ip_version=4,
                                   dns_nameservers=dns_nameservers)
        req = self.new_delete_request('subnets', subnet['subnet']['id'])
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)

    def test_delete_subnet_with_route(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        host_routes = [{'destination': '135.207.0.0/16',
                        'nexthop': '1.2.3.4'}]
        # Create new network
        res = self._create_network(fmt=self.fmt, name='net',
                                   admin_state_up=True)
        network = self.deserialize(self.fmt, res)
        subnet = self._make_subnet(self.fmt, network, gateway_ip,
                                   cidr, ip_version=4,
                                   host_routes=host_routes)
        req = self.new_delete_request('subnets', subnet['subnet']['id'])
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)

    def test_delete_subnet_with_dns_and_route(self):
        gateway_ip = '10.0.0.1'
        cidr = '10.0.0.0/24'
        dns_nameservers = ['1.2.3.4']
        host_routes = [{'destination': '135.207.0.0/16',
                        'nexthop': '1.2.3.4'}]
        # Create new network
        res = self._create_network(fmt=self.fmt, name='net',
                                   admin_state_up=True)
        network = self.deserialize(self.fmt, res)
        subnet = self._make_subnet(self.fmt, network, gateway_ip,
                                   cidr, ip_version=4,
                                   dns_nameservers=dns_nameservers,
                                   host_routes=host_routes)
        req = self.new_delete_request('subnets', subnet['subnet']['id'])
        res = req.get_response(self.api)
        self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code)

    def _helper_test_validate_subnet(self, option, exception):
        cfg.CONF.set_override(option, 0)
        with self.network() as network:
            subnet = {'network_id': network['network']['id'],
                      'cidr': '10.0.2.0/24',
                      'ip_version': 4,
                      'tenant_id': network['network']['tenant_id'],
                      'gateway_ip': '10.0.2.1',
                      'dns_nameservers': ['8.8.8.8'],
                      'host_routes': [{'destination': '135.207.0.0/16',
                                       'nexthop': '1.2.3.4'}]}
            plugin = manager.NeutronManager.get_plugin()
            e = self.assertRaises(exception,
                                  plugin._validate_subnet,
                                  context.get_admin_context(
                                      load_admin_roles=False),
                                  subnet)
            self.assertThat(
                str(e),
                matchers.Not(matchers.Contains('built-in function id')))

    def test_validate_subnet_dns_nameservers_exhausted(self):
        self._helper_test_validate_subnet(
            'max_dns_nameservers',
            n_exc.DNSNameServersExhausted)

    def test_validate_subnet_host_routes_exhausted(self):
        self._helper_test_validate_subnet(
            'max_subnet_host_routes',
            n_exc.HostRoutesExhausted)

    def test_port_prevents_network_deletion(self):
        with self.port() as p:
            self._delete('networks', p['port']['network_id'],
                         expected_code=webob.exc.HTTPConflict.code)

    def test_port_prevents_subnet_deletion(self):
        with self.port() as p:
            self._delete('subnets', p['port']['fixed_ips'][0]['subnet_id'],
                         expected_code=webob.exc.HTTPConflict.code)


class DbModelTestCase(base.BaseTestCase):
    """DB model tests."""
    def test_repr(self):
        """testing the string representation of 'model' classes."""
        network = models_v2.Network(name="net_net", status="OK",
                                    admin_state_up=True)
        actual_repr_output = repr(network)
        exp_start_with = "<neutron.db.models_v2.Network"
        exp_middle = "[object at %x]" % id(network)
        exp_end_with = (" {tenant_id=None, id=None, "
                        "name='net_net', status='OK', "
                        "admin_state_up=True, shared=None}>")
        final_exp = exp_start_with + exp_middle + exp_end_with
        self.assertEqual(actual_repr_output, final_exp)


class TestNeutronDbPluginV2(base.BaseTestCase):
    """Unit Tests for NeutronDbPluginV2 IPAM Logic."""

    def test_generate_ip(self):
        with mock.patch.object(db_base_plugin_v2.NeutronDbPluginV2,
                               '_try_generate_ip') as generate:
            with mock.patch.object(db_base_plugin_v2.NeutronDbPluginV2,
                                   '_rebuild_availability_ranges') as rebuild:

                db_base_plugin_v2.NeutronDbPluginV2._generate_ip('c', 's')

        generate.assert_called_once_with('c', 's')
        self.assertEqual(0, rebuild.call_count)

    def test_generate_ip_exhausted_pool(self):
        with mock.patch.object(db_base_plugin_v2.NeutronDbPluginV2,
                               '_try_generate_ip') as generate:
            with mock.patch.object(db_base_plugin_v2.NeutronDbPluginV2,
                                   '_rebuild_availability_ranges') as rebuild:

                exception = n_exc.IpAddressGenerationFailure(net_id='n')
                # fail first call but not second
                generate.side_effect = [exception, None]
                db_base_plugin_v2.NeutronDbPluginV2._generate_ip('c', 's')

        self.assertEqual(2, generate.call_count)
        rebuild.assert_called_once_with('c', 's')

    def test_rebuild_availability_ranges(self):
        pools = [{'id': 'a',
                  'first_ip': '192.168.1.3',
                  'last_ip': '192.168.1.10'},
                 {'id': 'b',
                  'first_ip': '192.168.1.100',
                  'last_ip': '192.168.1.120'}]

        allocations = [{'ip_address': '192.168.1.3'},
                       {'ip_address': '192.168.1.78'},
                       {'ip_address': '192.168.1.7'},
                       {'ip_address': '192.168.1.110'},
                       {'ip_address': '192.168.1.11'},
                       {'ip_address': '192.168.1.4'},
                       {'ip_address': '192.168.1.111'}]

        ip_qry = mock.Mock()
        ip_qry.with_lockmode.return_value = ip_qry
        ip_qry.filter_by.return_value = allocations

        pool_qry = mock.Mock()
        pool_qry.options.return_value = pool_qry
        pool_qry.with_lockmode.return_value = pool_qry
        pool_qry.filter_by.return_value = pools

        def return_queries_side_effect(*args, **kwargs):
            if args[0] == models_v2.IPAllocation:
                return ip_qry
            if args[0] == models_v2.IPAllocationPool:
                return pool_qry

        context = mock.Mock()
        context.session.query.side_effect = return_queries_side_effect
        subnets = [mock.MagicMock()]

        db_base_plugin_v2.NeutronDbPluginV2._rebuild_availability_ranges(
            context, subnets)

        actual = [[args[0].allocation_pool_id,
                   args[0].first_ip, args[0].last_ip]
                  for _name, args, _kwargs in context.session.add.mock_calls]

        self.assertEqual([['a', '192.168.1.5', '192.168.1.6'],
                          ['a', '192.168.1.8', '192.168.1.10'],
                          ['b', '192.168.1.100', '192.168.1.109'],
                          ['b', '192.168.1.112', '192.168.1.120']], actual)


class NeutronDbPluginV2AsMixinTestCase(testlib_api.SqlTestCase):
    """Tests for NeutronDbPluginV2 as Mixin.

    While NeutronDbPluginV2TestCase checks NeutronDbPlugin and all plugins as
    a complete plugin, this test case verifies abilities of NeutronDbPlugin
    which are provided to other plugins (e.g. DB operations). This test case
    may include tests only for NeutronDbPlugin, so this should not be used in
    unit tests for other plugins.
    """

    def setUp(self):
        super(NeutronDbPluginV2AsMixinTestCase, self).setUp()
        self.plugin = importutils.import_object(DB_PLUGIN_KLASS)
        self.context = context.get_admin_context()
        self.net_data = {'network': {'id': 'fake-id',
                                     'name': 'net1',
                                     'admin_state_up': True,
                                     'tenant_id': 'test-tenant',
                                     'shared': False}}

    def test_create_network_with_default_status(self):
        net = self.plugin.create_network(self.context, self.net_data)
        default_net_create_status = 'ACTIVE'
        expected = [('id', 'fake-id'), ('name', 'net1'),
                    ('admin_state_up', True), ('tenant_id', 'test-tenant'),
                    ('shared', False), ('status', default_net_create_status)]
        for k, v in expected:
            self.assertEqual(net[k], v)

    def test_create_network_with_status_BUILD(self):
        self.net_data['network']['status'] = 'BUILD'
        net = self.plugin.create_network(self.context, self.net_data)
        self.assertEqual(net['status'], 'BUILD')


class TestBasicGetXML(TestBasicGet):
    fmt = 'xml'


class TestNetworksV2XML(TestNetworksV2):
    fmt = 'xml'


class TestPortsV2XML(TestPortsV2):
    fmt = 'xml'


class TestSubnetsV2XML(TestSubnetsV2):
    fmt = 'xml'


class TestV2HTTPResponseXML(TestV2HTTPResponse):
    fmt = 'xml'