This file is indexed.

/usr/lib/python2.7/dist-packages/twisted/names/test/test_dns.py is in python-twisted-names 14.0.2-3.

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

The actual contents of the file can be viewed below.

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

"""
Tests for twisted.names.dns.
"""

from __future__ import division, absolute_import

from io import BytesIO

import struct

from zope.interface.verify import verifyClass

from twisted.python.failure import Failure
from twisted.python.util import FancyEqMixin, FancyStrMixin
from twisted.internet import address, task
from twisted.internet.error import CannotListenError, ConnectionDone
from twisted.trial import unittest
from twisted.names import dns

from twisted.test import proto_helpers
from twisted.test.testutils import ComparisonTestsMixin

RECORD_TYPES = [
    dns.Record_NS, dns.Record_MD, dns.Record_MF, dns.Record_CNAME,
    dns.Record_MB, dns.Record_MG, dns.Record_MR, dns.Record_PTR,
    dns.Record_DNAME, dns.Record_A, dns.Record_SOA, dns.Record_NULL,
    dns.Record_WKS, dns.Record_SRV, dns.Record_AFSDB, dns.Record_RP,
    dns.Record_HINFO, dns.Record_MINFO, dns.Record_MX, dns.Record_TXT,
    dns.Record_AAAA, dns.Record_A6, dns.Record_NAPTR, dns.UnknownRecord,
    ]


class Ord2ByteTests(unittest.TestCase):
    """
    Tests for L{dns._ord2bytes}.
    """
    def test_ord2byte(self):
        """
        L{dns._ord2byte} accepts an integer and returns a byte string of length
        one with an ordinal value equal to the given integer.
        """
        self.assertEqual(b'\x10', dns._ord2bytes(0x10))



class Str2TimeTests(unittest.TestCase):
    """
    Tests for L{dns.str2name}.
    """
    def test_nonString(self):
        """
        When passed a non-string object, L{dns.str2name} returns it unmodified.
        """
        time = object()
        self.assertIs(time, dns.str2time(time))


    def test_seconds(self):
        """
        Passed a string giving a number of seconds, L{dns.str2time} returns the
        number of seconds represented.  For example, C{"10S"} represents C{10}
        seconds.
        """
        self.assertEqual(10, dns.str2time("10S"))


    def test_minutes(self):
        """
        Like C{test_seconds}, but for the C{"M"} suffix which multiplies the
        time value by C{60} (the number of seconds in a minute!).
        """
        self.assertEqual(2 * 60, dns.str2time("2M"))


    def test_hours(self):
        """
        Like C{test_seconds}, but for the C{"H"} suffix which multiplies the
        time value by C{3600}, the number of seconds in an hour.
        """
        self.assertEqual(3 * 3600, dns.str2time("3H"))


    def test_days(self):
        """
        Like L{test_seconds}, but for the C{"D"} suffix which multiplies the
        time value by C{86400}, the number of seconds in a day.
        """
        self.assertEqual(4 * 86400, dns.str2time("4D"))


    def test_weeks(self):
        """
        Like L{test_seconds}, but for the C{"W"} suffix which multiplies the
        time value by C{604800}, the number of seconds in a week.
        """
        self.assertEqual(5 * 604800, dns.str2time("5W"))


    def test_years(self):
        """
        Like L{test_seconds}, but for the C{"Y"} suffix which multiplies the
        time value by C{31536000}, the number of seconds in a year.
        """
        self.assertEqual(6 * 31536000, dns.str2time("6Y"))


    def test_invalidPrefix(self):
        """
        If a non-integer prefix is given, L{dns.str2time} raises L{ValueError}.
        """
        self.assertRaises(ValueError, dns.str2time, "fooS")



class NameTests(unittest.TestCase):
    """
    Tests for L{Name}, the representation of a single domain name with support
    for encoding into and decoding from DNS message format.
    """
    def test_nonStringName(self):
        """
        When constructed with a name which is neither C{bytes} nor C{str},
        L{Name} raises L{TypeError}.
        """
        self.assertRaises(TypeError, dns.Name, 123)
        self.assertRaises(TypeError, dns.Name, object())
        self.assertRaises(TypeError, dns.Name, [])


    def test_unicodeName(self):
        """
        L{dns.Name} automatically encodes unicode domain name using C{idna}
        encoding.
        """
        name = dns.Name(u'\u00e9chec.example.org')
        self.assertIsInstance(name.name, bytes)
        self.assertEqual(b'xn--chec-9oa.example.org', name.name)


    def test_decode(self):
        """
        L{Name.decode} populates the L{Name} instance with name information read
        from the file-like object passed to it.
        """
        n = dns.Name()
        n.decode(BytesIO(b"\x07example\x03com\x00"))
        self.assertEqual(n.name, b"example.com")


    def test_encode(self):
        """
        L{Name.encode} encodes its name information and writes it to the
        file-like object passed to it.
        """
        name = dns.Name(b"foo.example.com")
        stream = BytesIO()
        name.encode(stream)
        self.assertEqual(stream.getvalue(), b"\x03foo\x07example\x03com\x00")


    def test_encodeWithCompression(self):
        """
        If a compression dictionary is passed to it, L{Name.encode} uses offset
        information from it to encode its name with references to existing
        labels in the stream instead of including another copy of them in the
        output.  It also updates the compression dictionary with the location of
        the name it writes to the stream.
        """
        name = dns.Name(b"foo.example.com")
        compression = {b"example.com": 0x17}

        # Some bytes already encoded into the stream for this message
        previous = b"some prefix to change .tell()"
        stream = BytesIO()
        stream.write(previous)

        # The position at which the encoded form of this new name will appear in
        # the stream.
        expected = len(previous) + dns.Message.headerSize
        name.encode(stream, compression)
        self.assertEqual(
            b"\x03foo\xc0\x17",
            stream.getvalue()[len(previous):])
        self.assertEqual(
            {b"example.com": 0x17, b"foo.example.com": expected},
            compression)


    def test_unknown(self):
        """
        A resource record of unknown type and class is parsed into an
        L{UnknownRecord} instance with its data preserved, and an
        L{UnknownRecord} instance is serialized to a string equal to the one it
        was parsed from.
        """
        wire = (
            b'\x01\x00' # Message ID
            b'\x00' # answer bit, opCode nibble, auth bit, trunc bit, recursive
                    # bit
            b'\x00' # recursion bit, empty bit, authenticData bit,
                    # checkingDisabled bit, response code nibble
            b'\x00\x01' # number of queries
            b'\x00\x01' # number of answers
            b'\x00\x00' # number of authorities
            b'\x00\x01' # number of additionals

            # query
            b'\x03foo\x03bar\x00'    # foo.bar
            b'\xde\xad'              # type=0xdead
            b'\xbe\xef'              # cls=0xbeef

            # 1st answer
            b'\xc0\x0c'              # foo.bar - compressed
            b'\xde\xad'              # type=0xdead
            b'\xbe\xef'              # cls=0xbeef
            b'\x00\x00\x01\x01'      # ttl=257
            b'\x00\x08somedata'      # some payload data

            # 1st additional
            b'\x03baz\x03ban\x00'    # baz.ban
            b'\x00\x01'              # type=A
            b'\x00\x01'              # cls=IN
            b'\x00\x00\x01\x01'      # ttl=257
            b'\x00\x04'              # len=4
            b'\x01\x02\x03\x04'      # 1.2.3.4
            )

        msg = dns.Message()
        msg.fromStr(wire)

        self.assertEqual(msg.queries, [
                dns.Query(b'foo.bar', type=0xdead, cls=0xbeef),
                ])
        self.assertEqual(msg.answers, [
                dns.RRHeader(b'foo.bar', type=0xdead, cls=0xbeef, ttl=257,
                             payload=dns.UnknownRecord(b'somedata', ttl=257)),
                ])
        self.assertEqual(msg.additional, [
                dns.RRHeader(b'baz.ban', type=dns.A, cls=dns.IN, ttl=257,
                             payload=dns.Record_A('1.2.3.4', ttl=257)),
                ])

        enc = msg.toStr()

        self.assertEqual(enc, wire)


    def test_decodeWithCompression(self):
        """
        If the leading byte of an encoded label (in bytes read from a stream
        passed to L{Name.decode}) has its two high bits set, the next byte is
        treated as a pointer to another label in the stream and that label is
        included in the name being decoded.
        """
        # Slightly modified version of the example from RFC 1035, section 4.1.4.
        stream = BytesIO(
            b"x" * 20 +
            b"\x01f\x03isi\x04arpa\x00"
            b"\x03foo\xc0\x14"
            b"\x03bar\xc0\x20")
        stream.seek(20)
        name = dns.Name()
        name.decode(stream)
        # Verify we found the first name in the stream and that the stream
        # position is left at the first byte after the decoded name.
        self.assertEqual(b"f.isi.arpa", name.name)
        self.assertEqual(32, stream.tell())

        # Get the second name from the stream and make the same assertions.
        name.decode(stream)
        self.assertEqual(name.name, b"foo.f.isi.arpa")
        self.assertEqual(38, stream.tell())

        # Get the third and final name
        name.decode(stream)
        self.assertEqual(name.name, b"bar.foo.f.isi.arpa")
        self.assertEqual(44, stream.tell())


    def test_rejectCompressionLoop(self):
        """
        L{Name.decode} raises L{ValueError} if the stream passed to it includes
        a compression pointer which forms a loop, causing the name to be
        undecodable.
        """
        name = dns.Name()
        stream = BytesIO(b"\xc0\x00")
        self.assertRaises(ValueError, name.decode, stream)



class RoundtripDNSTestCase(unittest.TestCase):
    """
    Encoding and then decoding various objects.
    """

    names = [b"example.org", b"go-away.fish.tv", b"23strikesback.net"]

    def testName(self):
        for n in self.names:
            # encode the name
            f = BytesIO()
            dns.Name(n).encode(f)

            # decode the name
            f.seek(0, 0)
            result = dns.Name()
            result.decode(f)
            self.assertEqual(result.name, n)

    def test_query(self):
        """
        L{dns.Query.encode} returns a byte string representing the fields of the
        query which can be decoded into a new L{dns.Query} instance using
        L{dns.Query.decode}.
        """
        for n in self.names:
            for dnstype in range(1, 17):
                for dnscls in range(1, 5):
                    # encode the query
                    f = BytesIO()
                    dns.Query(n, dnstype, dnscls).encode(f)

                    # decode the result
                    f.seek(0, 0)
                    result = dns.Query()
                    result.decode(f)
                    self.assertEqual(result.name.name, n)
                    self.assertEqual(result.type, dnstype)
                    self.assertEqual(result.cls, dnscls)

    def test_resourceRecordHeader(self):
        """
        L{dns.RRHeader.encode} encodes the record header's information and
        writes it to the file-like object passed to it and
        L{dns.RRHeader.decode} reads from a file-like object to re-construct a
        L{dns.RRHeader} instance.
        """
        # encode the RR
        f = BytesIO()
        dns.RRHeader(b"test.org", 3, 4, 17).encode(f)

        # decode the result
        f.seek(0, 0)
        result = dns.RRHeader()
        result.decode(f)
        self.assertEqual(result.name, dns.Name(b"test.org"))
        self.assertEqual(result.type, 3)
        self.assertEqual(result.cls, 4)
        self.assertEqual(result.ttl, 17)


    def test_resources(self):
        """
        L{dns.SimpleRecord.encode} encodes the record's name information and
        writes it to the file-like object passed to it and
        L{dns.SimpleRecord.decode} reads from a file-like object to re-construct
        a L{dns.SimpleRecord} instance.
        """
        names = (
            b"this.are.test.name",
            b"will.compress.will.this.will.name.will.hopefully",
            b"test.CASE.preSErVatIOn.YeAH",
            b"a.s.h.o.r.t.c.a.s.e.t.o.t.e.s.t",
            b"singleton"
        )
        for s in names:
            f = BytesIO()
            dns.SimpleRecord(s).encode(f)
            f.seek(0, 0)
            result = dns.SimpleRecord()
            result.decode(f)
            self.assertEqual(result.name, dns.Name(s))


    def test_hashable(self):
        """
        Instances of all record types are hashable.
        """
        for k in RECORD_TYPES:
            k1, k2 = k(), k()
            hk1 = hash(k1)
            hk2 = hash(k2)
            self.assertEqual(hk1, hk2, "%s != %s (for %s)" % (hk1,hk2,k))


    def test_Charstr(self):
        """
        Test L{dns.Charstr} encode and decode.
        """
        for n in self.names:
            # encode the name
            f = BytesIO()
            dns.Charstr(n).encode(f)

            # decode the name
            f.seek(0, 0)
            result = dns.Charstr()
            result.decode(f)
            self.assertEqual(result.string, n)


    def _recordRoundtripTest(self, record):
        """
        Assert that encoding C{record} and then decoding the resulting bytes
        creates a record which compares equal to C{record}.
        """
        stream = BytesIO()
        record.encode(stream)

        length = stream.tell()
        stream.seek(0, 0)
        replica = record.__class__()
        replica.decode(stream, length)
        self.assertEqual(record, replica)


    def test_SOA(self):
        """
        The byte stream written by L{dns.Record_SOA.encode} can be used by
        L{dns.Record_SOA.decode} to reconstruct the state of the original
        L{dns.Record_SOA} instance.
        """
        self._recordRoundtripTest(
            dns.Record_SOA(
                mname=b'foo', rname=b'bar', serial=12, refresh=34,
                retry=56, expire=78, minimum=90))


    def test_A(self):
        """
        The byte stream written by L{dns.Record_A.encode} can be used by
        L{dns.Record_A.decode} to reconstruct the state of the original
        L{dns.Record_A} instance.
        """
        self._recordRoundtripTest(dns.Record_A('1.2.3.4'))


    def test_NULL(self):
        """
        The byte stream written by L{dns.Record_NULL.encode} can be used by
        L{dns.Record_NULL.decode} to reconstruct the state of the original
        L{dns.Record_NULL} instance.
        """
        self._recordRoundtripTest(dns.Record_NULL(b'foo bar'))


    def test_WKS(self):
        """
        The byte stream written by L{dns.Record_WKS.encode} can be used by
        L{dns.Record_WKS.decode} to reconstruct the state of the original
        L{dns.Record_WKS} instance.
        """
        self._recordRoundtripTest(dns.Record_WKS('1.2.3.4', 3, b'xyz'))


    def test_AAAA(self):
        """
        The byte stream written by L{dns.Record_AAAA.encode} can be used by
        L{dns.Record_AAAA.decode} to reconstruct the state of the original
        L{dns.Record_AAAA} instance.
        """
        self._recordRoundtripTest(dns.Record_AAAA('::1'))


    def test_A6(self):
        """
        The byte stream written by L{dns.Record_A6.encode} can be used by
        L{dns.Record_A6.decode} to reconstruct the state of the original
        L{dns.Record_A6} instance.
        """
        self._recordRoundtripTest(dns.Record_A6(8, '::1:2', b'foo'))


    def test_SRV(self):
        """
        The byte stream written by L{dns.Record_SRV.encode} can be used by
        L{dns.Record_SRV.decode} to reconstruct the state of the original
        L{dns.Record_SRV} instance.
        """
        self._recordRoundtripTest(dns.Record_SRV(
                priority=1, weight=2, port=3, target=b'example.com'))


    def test_NAPTR(self):
        """
        Test L{dns.Record_NAPTR} encode and decode.
        """
        naptrs = [
            (100, 10, b"u", b"sip+E2U",
             b"!^.*$!sip:information@domain.tld!", b""),
            (100, 50, b"s", b"http+I2L+I2C+I2R",
             b"", b"_http._tcp.gatech.edu")]

        for (order, preference, flags, service, regexp, replacement) in naptrs:
            rin = dns.Record_NAPTR(order, preference, flags, service, regexp,
                                   replacement)
            e = BytesIO()
            rin.encode(e)
            e.seek(0, 0)
            rout = dns.Record_NAPTR()
            rout.decode(e)
            self.assertEqual(rin.order, rout.order)
            self.assertEqual(rin.preference, rout.preference)
            self.assertEqual(rin.flags, rout.flags)
            self.assertEqual(rin.service, rout.service)
            self.assertEqual(rin.regexp, rout.regexp)
            self.assertEqual(rin.replacement.name, rout.replacement.name)
            self.assertEqual(rin.ttl, rout.ttl)


    def test_AFSDB(self):
        """
        The byte stream written by L{dns.Record_AFSDB.encode} can be used by
        L{dns.Record_AFSDB.decode} to reconstruct the state of the original
        L{dns.Record_AFSDB} instance.
        """
        self._recordRoundtripTest(dns.Record_AFSDB(
                subtype=3, hostname=b'example.com'))


    def test_RP(self):
        """
        The byte stream written by L{dns.Record_RP.encode} can be used by
        L{dns.Record_RP.decode} to reconstruct the state of the original
        L{dns.Record_RP} instance.
        """
        self._recordRoundtripTest(dns.Record_RP(
                mbox=b'alice.example.com', txt=b'example.com'))


    def test_HINFO(self):
        """
        The byte stream written by L{dns.Record_HINFO.encode} can be used by
        L{dns.Record_HINFO.decode} to reconstruct the state of the original
        L{dns.Record_HINFO} instance.
        """
        self._recordRoundtripTest(dns.Record_HINFO(cpu=b'fast', os=b'great'))


    def test_MINFO(self):
        """
        The byte stream written by L{dns.Record_MINFO.encode} can be used by
        L{dns.Record_MINFO.decode} to reconstruct the state of the original
        L{dns.Record_MINFO} instance.
        """
        self._recordRoundtripTest(dns.Record_MINFO(
                rmailbx=b'foo', emailbx=b'bar'))


    def test_MX(self):
        """
        The byte stream written by L{dns.Record_MX.encode} can be used by
        L{dns.Record_MX.decode} to reconstruct the state of the original
        L{dns.Record_MX} instance.
        """
        self._recordRoundtripTest(dns.Record_MX(
                preference=1, name=b'example.com'))


    def test_TXT(self):
        """
        The byte stream written by L{dns.Record_TXT.encode} can be used by
        L{dns.Record_TXT.decode} to reconstruct the state of the original
        L{dns.Record_TXT} instance.
        """
        self._recordRoundtripTest(dns.Record_TXT(b'foo', b'bar'))



MESSAGE_AUTHENTIC_DATA_BYTES = (
    b'\x00\x00' # ID
    b'\x00' #
    b'\x20' # RA, Z, AD=1, CD, RCODE
    b'\x00\x00' # Query count
    b'\x00\x00' # Answer count
    b'\x00\x00' # Authority count
    b'\x00\x00' # Additional count
)



MESSAGE_CHECKING_DISABLED_BYTES = (
    b'\x00\x00' # ID
    b'\x00' #
    b'\x10' # RA, Z, AD, CD=1, RCODE
    b'\x00\x00' # Query count
    b'\x00\x00' # Answer count
    b'\x00\x00' # Authority count
    b'\x00\x00' # Additional count
)



class MessageTestCase(unittest.SynchronousTestCase):
    """
    Tests for L{twisted.names.dns.Message}.
    """

    def test_authenticDataDefault(self):
        """
        L{dns.Message.authenticData} has default value 0.
        """
        self.assertEqual(dns.Message().authenticData, 0)


    def test_authenticDataOverride(self):
        """
        L{dns.Message.__init__} accepts a C{authenticData} argument which
        is assigned to L{dns.Message.authenticData}.
        """
        self.assertEqual(dns.Message(authenticData=1).authenticData, 1)


    def test_authenticDataEncode(self):
        """
        L{dns.Message.toStr} encodes L{dns.Message.authenticData} into
        byte4 of the byte string.
        """
        self.assertEqual(
            dns.Message(authenticData=1).toStr(),
            MESSAGE_AUTHENTIC_DATA_BYTES
        )


    def test_authenticDataDecode(self):
        """
        L{dns.Message.fromStr} decodes byte4 and assigns bit3 to
        L{dns.Message.authenticData}.
        """
        m = dns.Message()
        m.fromStr(MESSAGE_AUTHENTIC_DATA_BYTES)

        self.assertEqual(m.authenticData, 1)


    def test_checkingDisabledDefault(self):
        """
        L{dns.Message.checkingDisabled} has default value 0.
        """
        self.assertEqual(dns.Message().checkingDisabled, 0)


    def test_checkingDisabledOverride(self):
        """
        L{dns.Message.__init__} accepts a C{checkingDisabled} argument which
        is assigned to L{dns.Message.checkingDisabled}.
        """
        self.assertEqual(
            dns.Message(checkingDisabled=1).checkingDisabled, 1)


    def test_checkingDisabledEncode(self):
        """
        L{dns.Message.toStr} encodes L{dns.Message.checkingDisabled} into
        byte4 of the byte string.
        """
        self.assertEqual(
            dns.Message(checkingDisabled=1).toStr(),
            MESSAGE_CHECKING_DISABLED_BYTES
        )


    def test_checkingDisabledDecode(self):
        """
        L{dns.Message.fromStr} decodes byte4 and assigns bit4 to
        L{dns.Message.checkingDisabled}.
        """
        m = dns.Message()
        m.fromStr(MESSAGE_CHECKING_DISABLED_BYTES)

        self.assertEqual(m.checkingDisabled, 1)


    def test_reprDefaults(self):
        """
        L{dns.Message.__repr__} omits field values and sections which are
        identical to their defaults. The id field value is always shown.
        """
        self.assertEqual(
            '<Message id=0>',
            repr(dns.Message())
        )


    def test_reprFlagsIfSet(self):
        """
        L{dns.Message.__repr__} displays flags if they are L{True}.
        """
        m = dns.Message(answer=True, auth=True, trunc=True, recDes=True,
                        recAv=True, authenticData=True, checkingDisabled=True)
        self.assertEqual(
            '<Message '
            'id=0 '
            'flags=answer,auth,trunc,recDes,recAv,authenticData,'
            'checkingDisabled'
            '>',
            repr(m),
        )


    def test_reprNonDefautFields(self):
        """
        L{dns.Message.__repr__} displays field values if they differ from their
        defaults.
        """
        m = dns.Message(id=10, opCode=20, rCode=30, maxSize=40)
        self.assertEqual(
            '<Message '
            'id=10 '
            'opCode=20 '
            'rCode=30 '
            'maxSize=40'
            '>',
            repr(m),
        )


    def test_reprNonDefaultSections(self):
        """
        L{dns.Message.__repr__} displays sections which differ from their
        defaults.
        """
        m = dns.Message()
        m.queries = [1, 2, 3]
        m.answers = [4, 5, 6]
        m.authority = [7, 8, 9]
        m.additional = [10, 11, 12]
        self.assertEqual(
            '<Message '
            'id=0 '
            'queries=[1, 2, 3] '
            'answers=[4, 5, 6] '
            'authority=[7, 8, 9] '
            'additional=[10, 11, 12]'
            '>',
            repr(m),
        )


    def testEmptyMessage(self):
        """
        Test that a message which has been truncated causes an EOFError to
        be raised when it is parsed.
        """
        msg = dns.Message()
        self.assertRaises(EOFError, msg.fromStr, b'')


    def test_emptyQuery(self):
        """
        Test that bytes representing an empty query message can be decoded
        as such.
        """
        msg = dns.Message()
        msg.fromStr(
            b'\x01\x00' # Message ID
            b'\x00' # answer bit, opCode nibble, auth bit, trunc bit, recursive bit
            b'\x00' # recursion bit, empty bit, authenticData bit,
                    # checkingDisabled bit, response code nibble
            b'\x00\x00' # number of queries
            b'\x00\x00' # number of answers
            b'\x00\x00' # number of authorities
            b'\x00\x00' # number of additionals
            )
        self.assertEqual(msg.id, 256)
        self.assertFalse(
            msg.answer, "Message was not supposed to be an answer.")
        self.assertEqual(msg.opCode, dns.OP_QUERY)
        self.assertFalse(
            msg.auth, "Message was not supposed to be authoritative.")
        self.assertFalse(
            msg.trunc, "Message was not supposed to be truncated.")
        self.assertEqual(msg.queries, [])
        self.assertEqual(msg.answers, [])
        self.assertEqual(msg.authority, [])
        self.assertEqual(msg.additional, [])


    def test_NULL(self):
        """
        A I{NULL} record with an arbitrary payload can be encoded and decoded as
        part of a L{dns.Message}.
        """
        bytes = b''.join([dns._ord2bytes(i) for i in range(256)])
        rec = dns.Record_NULL(bytes)
        rr = dns.RRHeader(b'testname', dns.NULL, payload=rec)
        msg1 = dns.Message()
        msg1.answers.append(rr)
        s = BytesIO()
        msg1.encode(s)
        s.seek(0, 0)
        msg2 = dns.Message()
        msg2.decode(s)

        self.assertIsInstance(msg2.answers[0].payload, dns.Record_NULL)
        self.assertEqual(msg2.answers[0].payload.payload, bytes)


    def test_lookupRecordTypeDefault(self):
        """
        L{Message.lookupRecordType} returns C{dns.UnknownRecord} if it is
        called with an integer which doesn't correspond to any known record
        type.
        """
        # 65280 is the first value in the range reserved for private
        # use, so it shouldn't ever conflict with an officially
        # allocated value.
        self.assertIs(dns.Message().lookupRecordType(65280), dns.UnknownRecord)


    def test_nonAuthoritativeMessage(self):
        """
        The L{RRHeader} instances created by L{Message} from a non-authoritative
        message are marked as not authoritative.
        """
        buf = BytesIO()
        answer = dns.RRHeader(payload=dns.Record_A('1.2.3.4', ttl=0))
        answer.encode(buf)
        message = dns.Message()
        message.fromStr(
            b'\x01\x00' # Message ID
            # answer bit, opCode nibble, auth bit, trunc bit, recursive bit
            b'\x00'
            # recursion bit, empty bit, authenticData bit,
            # checkingDisabled bit, response code nibble
            b'\x00'
            b'\x00\x00' # number of queries
            b'\x00\x01' # number of answers
            b'\x00\x00' # number of authorities
            b'\x00\x00' # number of additionals
            + buf.getvalue()
            )
        self.assertEqual(message.answers, [answer])
        self.assertFalse(message.answers[0].auth)


    def test_authoritativeMessage(self):
        """
        The L{RRHeader} instances created by L{Message} from an authoritative
        message are marked as authoritative.
        """
        buf = BytesIO()
        answer = dns.RRHeader(payload=dns.Record_A('1.2.3.4', ttl=0))
        answer.encode(buf)
        message = dns.Message()
        message.fromStr(
            b'\x01\x00' # Message ID
            # answer bit, opCode nibble, auth bit, trunc bit, recursive bit
            b'\x04'
            # recursion bit, empty bit, authenticData bit,
            # checkingDisabled bit, response code nibble
            b'\x00'
            b'\x00\x00' # number of queries
            b'\x00\x01' # number of answers
            b'\x00\x00' # number of authorities
            b'\x00\x00' # number of additionals
            + buf.getvalue()
            )
        answer.auth = True
        self.assertEqual(message.answers, [answer])
        self.assertTrue(message.answers[0].auth)



class MessageComparisonTests(ComparisonTestsMixin,
                             unittest.SynchronousTestCase):
    """
    Tests for the rich comparison of L{dns.Message} instances.
    """
    def messageFactory(self, *args, **kwargs):
        """
        Create a L{dns.Message}.

        The L{dns.Message} constructor doesn't accept C{queries}, C{answers},
        C{authority}, C{additional} arguments, so we extract them from the
        kwargs supplied to this factory function and assign them to the message.

        @param args: Positional arguments.
        @param kwargs: Keyword arguments.
        @return: A L{dns.Message} instance.
        """
        queries = kwargs.pop('queries', [])
        answers = kwargs.pop('answers', [])
        authority = kwargs.pop('authority', [])
        additional = kwargs.pop('additional', [])
        m = dns.Message(**kwargs)
        if queries:
            m.queries = queries
        if answers:
            m.answers = answers
        if authority:
            m.authority = authority
        if additional:
            m.additional = additional
        return m


    def test_id(self):
        """
        Two L{dns.Message} instances compare equal if they have the same id
        value.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(id=10),
            self.messageFactory(id=10),
            self.messageFactory(id=20),
        )


    def test_answer(self):
        """
        Two L{dns.Message} instances compare equal if they have the same answer
        flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(answer=1),
            self.messageFactory(answer=1),
            self.messageFactory(answer=0),
        )


    def test_opCode(self):
        """
        Two L{dns.Message} instances compare equal if they have the same opCode
        value.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(opCode=10),
            self.messageFactory(opCode=10),
            self.messageFactory(opCode=20),
        )


    def test_recDes(self):
        """
        Two L{dns.Message} instances compare equal if they have the same recDes
        flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(recDes=1),
            self.messageFactory(recDes=1),
            self.messageFactory(recDes=0),
        )


    def test_recAv(self):
        """
        Two L{dns.Message} instances compare equal if they have the same recAv
        flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(recAv=1),
            self.messageFactory(recAv=1),
            self.messageFactory(recAv=0),
        )


    def test_auth(self):
        """
        Two L{dns.Message} instances compare equal if they have the same auth
        flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(auth=1),
            self.messageFactory(auth=1),
            self.messageFactory(auth=0),
        )


    def test_rCode(self):
        """
        Two L{dns.Message} instances compare equal if they have the same rCode
        value.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(rCode=10),
            self.messageFactory(rCode=10),
            self.messageFactory(rCode=20),
        )


    def test_trunc(self):
        """
        Two L{dns.Message} instances compare equal if they have the same trunc
        flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(trunc=1),
            self.messageFactory(trunc=1),
            self.messageFactory(trunc=0),
        )


    def test_maxSize(self):
        """
        Two L{dns.Message} instances compare equal if they have the same
        maxSize value.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(maxSize=10),
            self.messageFactory(maxSize=10),
            self.messageFactory(maxSize=20),
        )


    def test_authenticData(self):
        """
        Two L{dns.Message} instances compare equal if they have the same
        authenticData flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(authenticData=1),
            self.messageFactory(authenticData=1),
            self.messageFactory(authenticData=0),
        )


    def test_checkingDisabled(self):
        """
        Two L{dns.Message} instances compare equal if they have the same
        checkingDisabled flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(checkingDisabled=1),
            self.messageFactory(checkingDisabled=1),
            self.messageFactory(checkingDisabled=0),
        )


    def test_queries(self):
        """
        Two L{dns.Message} instances compare equal if they have the same
        queries.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(queries=[dns.Query(b'example.com')]),
            self.messageFactory(queries=[dns.Query(b'example.com')]),
            self.messageFactory(queries=[dns.Query(b'example.org')]),
            )


    def test_answers(self):
        """
        Two L{dns.Message} instances compare equal if they have the same
        answers.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(answers=[dns.RRHeader(
                        b'example.com', payload=dns.Record_A('1.2.3.4'))]),
            self.messageFactory(answers=[dns.RRHeader(
                        b'example.com', payload=dns.Record_A('1.2.3.4'))]),
            self.messageFactory(answers=[dns.RRHeader(
                        b'example.org', payload=dns.Record_A('4.3.2.1'))]),
            )


    def test_authority(self):
        """
        Two L{dns.Message} instances compare equal if they have the same
        authority records.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(authority=[dns.RRHeader(
                        b'example.com',
                        type=dns.SOA, payload=dns.Record_SOA())]),
            self.messageFactory(authority=[dns.RRHeader(
                        b'example.com',
                        type=dns.SOA, payload=dns.Record_SOA())]),
            self.messageFactory(authority=[dns.RRHeader(
                        b'example.org',
                        type=dns.SOA, payload=dns.Record_SOA())]),
            )


    def test_additional(self):
        """
        Two L{dns.Message} instances compare equal if they have the same
        additional records.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(additional=[dns.RRHeader(
                        b'example.com', payload=dns.Record_A('1.2.3.4'))]),
            self.messageFactory(additional=[dns.RRHeader(
                        b'example.com', payload=dns.Record_A('1.2.3.4'))]),
            self.messageFactory(additional=[dns.RRHeader(
                        b'example.org', payload=dns.Record_A('1.2.3.4'))]),
            )



class TestController(object):
    """
    Pretend to be a DNS query processor for a DNSDatagramProtocol.

    @ivar messages: the list of received messages.
    @type messages: C{list} of (msg, protocol, address)
    """

    def __init__(self):
        """
        Initialize the controller: create a list of messages.
        """
        self.messages = []


    def messageReceived(self, msg, proto, addr=None):
        """
        Save the message so that it can be checked during the tests.
        """
        self.messages.append((msg, proto, addr))



class DatagramProtocolTestCase(unittest.TestCase):
    """
    Test various aspects of L{dns.DNSDatagramProtocol}.
    """

    def setUp(self):
        """
        Create a L{dns.DNSDatagramProtocol} with a deterministic clock.
        """
        self.clock = task.Clock()
        self.controller = TestController()
        self.proto = dns.DNSDatagramProtocol(self.controller)
        transport = proto_helpers.FakeDatagramTransport()
        self.proto.makeConnection(transport)
        self.proto.callLater = self.clock.callLater


    def test_truncatedPacket(self):
        """
        Test that when a short datagram is received, datagramReceived does
        not raise an exception while processing it.
        """
        self.proto.datagramReceived(
            b'', address.IPv4Address('UDP', '127.0.0.1', 12345))
        self.assertEqual(self.controller.messages, [])


    def test_simpleQuery(self):
        """
        Test content received after a query.
        """
        d = self.proto.query(('127.0.0.1', 21345), [dns.Query(b'foo')])
        self.assertEqual(len(self.proto.liveMessages.keys()), 1)
        m = dns.Message()
        m.id = next(iter(self.proto.liveMessages.keys()))
        m.answers = [dns.RRHeader(payload=dns.Record_A(address='1.2.3.4'))]
        def cb(result):
            self.assertEqual(result.answers[0].payload.dottedQuad(), '1.2.3.4')
        d.addCallback(cb)
        self.proto.datagramReceived(m.toStr(), ('127.0.0.1', 21345))
        return d


    def test_queryTimeout(self):
        """
        Test that query timeouts after some seconds.
        """
        d = self.proto.query(('127.0.0.1', 21345), [dns.Query(b'foo')])
        self.assertEqual(len(self.proto.liveMessages), 1)
        self.clock.advance(10)
        self.assertFailure(d, dns.DNSQueryTimeoutError)
        self.assertEqual(len(self.proto.liveMessages), 0)
        return d


    def test_writeError(self):
        """
        Exceptions raised by the transport's write method should be turned into
        C{Failure}s passed to errbacks of the C{Deferred} returned by
        L{DNSDatagramProtocol.query}.
        """
        def writeError(message, addr):
            raise RuntimeError("bar")
        self.proto.transport.write = writeError

        d = self.proto.query(('127.0.0.1', 21345), [dns.Query(b'foo')])
        return self.assertFailure(d, RuntimeError)


    def test_listenError(self):
        """
        Exception L{CannotListenError} raised by C{listenUDP} should be turned
        into a C{Failure} passed to errback of the C{Deferred} returned by
        L{DNSDatagramProtocol.query}.
        """
        def startListeningError():
            raise CannotListenError(None, None, None)
        self.proto.startListening = startListeningError
        # Clean up transport so that the protocol calls startListening again
        self.proto.transport = None

        d = self.proto.query(('127.0.0.1', 21345), [dns.Query(b'foo')])
        return self.assertFailure(d, CannotListenError)


    def test_receiveMessageNotInLiveMessages(self):
        """
        When receiving a message whose id is not in
        L{DNSDatagramProtocol.liveMessages} or L{DNSDatagramProtocol.resends},
        the message will be received by L{DNSDatagramProtocol.controller}.
        """
        message = dns.Message()
        message.id = 1
        message.answers = [dns.RRHeader(
            payload=dns.Record_A(address='1.2.3.4'))]
        self.proto.datagramReceived(message.toStr(), ('127.0.0.1', 21345))
        self.assertEqual(self.controller.messages[-1][0].toStr(),
                         message.toStr())



class TestTCPController(TestController):
    """
    Pretend to be a DNS query processor for a DNSProtocol.

    @ivar connections: A list of L{DNSProtocol} instances which have
        notified this controller that they are connected and have not
        yet notified it that their connection has been lost.
    """
    def __init__(self):
        TestController.__init__(self)
        self.connections = []


    def connectionMade(self, proto):
        self.connections.append(proto)


    def connectionLost(self, proto):
        self.connections.remove(proto)



class DNSProtocolTestCase(unittest.TestCase):
    """
    Test various aspects of L{dns.DNSProtocol}.
    """

    def setUp(self):
        """
        Create a L{dns.DNSProtocol} with a deterministic clock.
        """
        self.clock = task.Clock()
        self.controller = TestTCPController()
        self.proto = dns.DNSProtocol(self.controller)
        self.proto.makeConnection(proto_helpers.StringTransport())
        self.proto.callLater = self.clock.callLater


    def test_connectionTracking(self):
        """
        L{dns.DNSProtocol} calls its controller's C{connectionMade}
        method with itself when it is connected to a transport and its
        controller's C{connectionLost} method when it is disconnected.
        """
        self.assertEqual(self.controller.connections, [self.proto])
        self.proto.connectionLost(
            Failure(ConnectionDone("Fake Connection Done")))
        self.assertEqual(self.controller.connections, [])


    def test_queryTimeout(self):
        """
        Test that query timeouts after some seconds.
        """
        d = self.proto.query([dns.Query(b'foo')])
        self.assertEqual(len(self.proto.liveMessages), 1)
        self.clock.advance(60)
        self.assertFailure(d, dns.DNSQueryTimeoutError)
        self.assertEqual(len(self.proto.liveMessages), 0)
        return d


    def test_simpleQuery(self):
        """
        Test content received after a query.
        """
        d = self.proto.query([dns.Query(b'foo')])
        self.assertEqual(len(self.proto.liveMessages.keys()), 1)
        m = dns.Message()
        m.id = next(iter(self.proto.liveMessages.keys()))
        m.answers = [dns.RRHeader(payload=dns.Record_A(address='1.2.3.4'))]
        def cb(result):
            self.assertEqual(result.answers[0].payload.dottedQuad(), '1.2.3.4')
        d.addCallback(cb)
        s = m.toStr()
        s = struct.pack('!H', len(s)) + s
        self.proto.dataReceived(s)
        return d


    def test_writeError(self):
        """
        Exceptions raised by the transport's write method should be turned into
        C{Failure}s passed to errbacks of the C{Deferred} returned by
        L{DNSProtocol.query}.
        """
        def writeError(message):
            raise RuntimeError("bar")
        self.proto.transport.write = writeError

        d = self.proto.query([dns.Query(b'foo')])
        return self.assertFailure(d, RuntimeError)


    def test_receiveMessageNotInLiveMessages(self):
        """
        When receiving a message whose id is not in L{DNSProtocol.liveMessages}
        the message will be received by L{DNSProtocol.controller}.
        """
        message = dns.Message()
        message.id = 1
        message.answers = [dns.RRHeader(
            payload=dns.Record_A(address='1.2.3.4'))]
        string = message.toStr()
        string = struct.pack('!H', len(string)) + string
        self.proto.dataReceived(string)
        self.assertEqual(self.controller.messages[-1][0].toStr(),
                         message.toStr())



class ReprTests(unittest.TestCase):
    """
    Tests for the C{__repr__} implementation of record classes.
    """
    def test_ns(self):
        """
        The repr of a L{dns.Record_NS} instance includes the name of the
        nameserver and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_NS(b'example.com', 4321)),
            "<NS name=example.com ttl=4321>")


    def test_md(self):
        """
        The repr of a L{dns.Record_MD} instance includes the name of the
        mail destination and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_MD(b'example.com', 4321)),
            "<MD name=example.com ttl=4321>")


    def test_mf(self):
        """
        The repr of a L{dns.Record_MF} instance includes the name of the
        mail forwarder and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_MF(b'example.com', 4321)),
            "<MF name=example.com ttl=4321>")


    def test_cname(self):
        """
        The repr of a L{dns.Record_CNAME} instance includes the name of the
        mail forwarder and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_CNAME(b'example.com', 4321)),
            "<CNAME name=example.com ttl=4321>")


    def test_mb(self):
        """
        The repr of a L{dns.Record_MB} instance includes the name of the
        mailbox and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_MB(b'example.com', 4321)),
            "<MB name=example.com ttl=4321>")


    def test_mg(self):
        """
        The repr of a L{dns.Record_MG} instance includes the name of the
        mail group memeber and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_MG(b'example.com', 4321)),
            "<MG name=example.com ttl=4321>")


    def test_mr(self):
        """
        The repr of a L{dns.Record_MR} instance includes the name of the
        mail rename domain and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_MR(b'example.com', 4321)),
            "<MR name=example.com ttl=4321>")


    def test_ptr(self):
        """
        The repr of a L{dns.Record_PTR} instance includes the name of the
        pointer and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_PTR(b'example.com', 4321)),
            "<PTR name=example.com ttl=4321>")


    def test_dname(self):
        """
        The repr of a L{dns.Record_DNAME} instance includes the name of the
        non-terminal DNS name redirection and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_DNAME(b'example.com', 4321)),
            "<DNAME name=example.com ttl=4321>")


    def test_a(self):
        """
        The repr of a L{dns.Record_A} instance includes the dotted-quad
        string representation of the address it is for and the TTL of the
        record.
        """
        self.assertEqual(
            repr(dns.Record_A('1.2.3.4', 567)),
            '<A address=1.2.3.4 ttl=567>')


    def test_soa(self):
        """
        The repr of a L{dns.Record_SOA} instance includes all of the
        authority fields.
        """
        self.assertEqual(
            repr(dns.Record_SOA(mname=b'mName', rname=b'rName', serial=123,
                                refresh=456, retry=789, expire=10,
                                minimum=11, ttl=12)),
            "<SOA mname=mName rname=rName serial=123 refresh=456 "
            "retry=789 expire=10 minimum=11 ttl=12>")


    def test_null(self):
        """
        The repr of a L{dns.Record_NULL} instance includes the repr of its
        payload and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_NULL(b'abcd', 123)),
            "<NULL payload='abcd' ttl=123>")


    def test_wks(self):
        """
        The repr of a L{dns.Record_WKS} instance includes the dotted-quad
        string representation of the address it is for, the IP protocol
        number it is for, and the TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_WKS('2.3.4.5', 7, ttl=8)),
            "<WKS address=2.3.4.5 protocol=7 ttl=8>")


    def test_aaaa(self):
        """
        The repr of a L{dns.Record_AAAA} instance includes the colon-separated
        hex string representation of the address it is for and the TTL of the
        record.
        """
        self.assertEqual(
            repr(dns.Record_AAAA('8765::1234', ttl=10)),
            "<AAAA address=8765::1234 ttl=10>")


    def test_a6(self):
        """
        The repr of a L{dns.Record_A6} instance includes the colon-separated
        hex string representation of the address it is for and the TTL of the
        record.
        """
        self.assertEqual(
            repr(dns.Record_A6(0, '1234::5678', b'foo.bar', ttl=10)),
            "<A6 suffix=1234::5678 prefix=foo.bar ttl=10>")


    def test_srv(self):
        """
        The repr of a L{dns.Record_SRV} instance includes the name and port of
        the target and the priority, weight, and TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_SRV(1, 2, 3, b'example.org', 4)),
            "<SRV priority=1 weight=2 target=example.org port=3 ttl=4>")


    def test_naptr(self):
        """
        The repr of a L{dns.Record_NAPTR} instance includes the order,
        preference, flags, service, regular expression, replacement, and TTL of
        the record.
        """
        record = dns.Record_NAPTR(
            5, 9, b"S", b"http", b"/foo/bar/i", b"baz", 3)
        self.assertEqual(
            repr(record),
            "<NAPTR order=5 preference=9 flags=S service=http "
            "regexp=/foo/bar/i replacement=baz ttl=3>")


    def test_afsdb(self):
        """
        The repr of a L{dns.Record_AFSDB} instance includes the subtype,
        hostname, and TTL of the record.
        """
        self.assertEqual(
            repr(dns.Record_AFSDB(3, b'example.org', 5)),
            "<AFSDB subtype=3 hostname=example.org ttl=5>")


    def test_rp(self):
        """
        The repr of a L{dns.Record_RP} instance includes the mbox, txt, and TTL
        fields of the record.
        """
        self.assertEqual(
            repr(dns.Record_RP(b'alice.example.com', b'admin.example.com', 3)),
            "<RP mbox=alice.example.com txt=admin.example.com ttl=3>")


    def test_hinfo(self):
        """
        The repr of a L{dns.Record_HINFO} instance includes the cpu, os, and
        TTL fields of the record.
        """
        self.assertEqual(
            repr(dns.Record_HINFO(b'sparc', b'minix', 12)),
            "<HINFO cpu='sparc' os='minix' ttl=12>")


    def test_minfo(self):
        """
        The repr of a L{dns.Record_MINFO} instance includes the rmailbx,
        emailbx, and TTL fields of the record.
        """
        record = dns.Record_MINFO(
            b'alice.example.com', b'bob.example.com', 15)
        self.assertEqual(
            repr(record),
            "<MINFO responsibility=alice.example.com "
            "errors=bob.example.com ttl=15>")


    def test_mx(self):
        """
        The repr of a L{dns.Record_MX} instance includes the preference, name,
        and TTL fields of the record.
        """
        self.assertEqual(
            repr(dns.Record_MX(13, b'mx.example.com', 2)),
            "<MX preference=13 name=mx.example.com ttl=2>")


    def test_txt(self):
        """
        The repr of a L{dns.Record_TXT} instance includes the data and ttl
        fields of the record.
        """
        self.assertEqual(
            repr(dns.Record_TXT(b"foo", b"bar", ttl=15)),
            "<TXT data=['foo', 'bar'] ttl=15>")


    def test_spf(self):
        """
        The repr of a L{dns.Record_SPF} instance includes the data and ttl
        fields of the record.
        """
        self.assertEqual(
            repr(dns.Record_SPF(b"foo", b"bar", ttl=15)),
            "<SPF data=['foo', 'bar'] ttl=15>")


    def test_unknown(self):
        """
        The repr of a L{dns.UnknownRecord} instance includes the data and ttl
        fields of the record.
        """
        self.assertEqual(
            repr(dns.UnknownRecord(b"foo\x1fbar", 12)),
            "<UNKNOWN data='foo\\x1fbar' ttl=12>")



class EqualityTests(ComparisonTestsMixin, unittest.TestCase):
    """
    Tests for the equality and non-equality behavior of record classes.
    """
    def _equalityTest(self, firstValueOne, secondValueOne, valueTwo):
        return self.assertNormalEqualityImplementation(
            firstValueOne, secondValueOne, valueTwo)


    def test_charstr(self):
        """
        Two L{dns.Charstr} instances compare equal if and only if they have the
        same string value.
        """
        self._equalityTest(
            dns.Charstr(b'abc'), dns.Charstr(b'abc'), dns.Charstr(b'def'))


    def test_name(self):
        """
        Two L{dns.Name} instances compare equal if and only if they have the
        same name value.
        """
        self._equalityTest(
            dns.Name(b'abc'), dns.Name(b'abc'), dns.Name(b'def'))


    def _simpleEqualityTest(self, cls):
        """
        Assert that instances of C{cls} with the same attributes compare equal
        to each other and instances with different attributes compare as not
        equal.

        @param cls: A L{dns.SimpleRecord} subclass.
        """
        # Vary the TTL
        self._equalityTest(
            cls(b'example.com', 123),
            cls(b'example.com', 123),
            cls(b'example.com', 321))
        # Vary the name
        self._equalityTest(
            cls(b'example.com', 123),
            cls(b'example.com', 123),
            cls(b'example.org', 123))


    def test_rrheader(self):
        """
        Two L{dns.RRHeader} instances compare equal if and only if they have
        the same name, type, class, time to live, payload, and authoritative
        bit.
        """
        # Vary the name
        self._equalityTest(
            dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4')),
            dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4')),
            dns.RRHeader(b'example.org', payload=dns.Record_A('1.2.3.4')))

        # Vary the payload
        self._equalityTest(
            dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4')),
            dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4')),
            dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.5')))

        # Vary the type.  Leave the payload as None so that we don't have to
        # provide non-equal values.
        self._equalityTest(
            dns.RRHeader(b'example.com', dns.A),
            dns.RRHeader(b'example.com', dns.A),
            dns.RRHeader(b'example.com', dns.MX))

        # Probably not likely to come up.  Most people use the internet.
        self._equalityTest(
            dns.RRHeader(b'example.com', cls=dns.IN, payload=dns.Record_A('1.2.3.4')),
            dns.RRHeader(b'example.com', cls=dns.IN, payload=dns.Record_A('1.2.3.4')),
            dns.RRHeader(b'example.com', cls=dns.CS, payload=dns.Record_A('1.2.3.4')))

        # Vary the ttl
        self._equalityTest(
            dns.RRHeader(b'example.com', ttl=60, payload=dns.Record_A('1.2.3.4')),
            dns.RRHeader(b'example.com', ttl=60, payload=dns.Record_A('1.2.3.4')),
            dns.RRHeader(b'example.com', ttl=120, payload=dns.Record_A('1.2.3.4')))

        # Vary the auth bit
        self._equalityTest(
            dns.RRHeader(b'example.com', auth=1, payload=dns.Record_A('1.2.3.4')),
            dns.RRHeader(b'example.com', auth=1, payload=dns.Record_A('1.2.3.4')),
            dns.RRHeader(b'example.com', auth=0, payload=dns.Record_A('1.2.3.4')))


    def test_ns(self):
        """
        Two L{dns.Record_NS} instances compare equal if and only if they have
        the same name and TTL.
        """
        self._simpleEqualityTest(dns.Record_NS)


    def test_md(self):
        """
        Two L{dns.Record_MD} instances compare equal if and only if they have
        the same name and TTL.
        """
        self._simpleEqualityTest(dns.Record_MD)


    def test_mf(self):
        """
        Two L{dns.Record_MF} instances compare equal if and only if they have
        the same name and TTL.
        """
        self._simpleEqualityTest(dns.Record_MF)


    def test_cname(self):
        """
        Two L{dns.Record_CNAME} instances compare equal if and only if they
        have the same name and TTL.
        """
        self._simpleEqualityTest(dns.Record_CNAME)


    def test_mb(self):
        """
        Two L{dns.Record_MB} instances compare equal if and only if they have
        the same name and TTL.
        """
        self._simpleEqualityTest(dns.Record_MB)


    def test_mg(self):
        """
        Two L{dns.Record_MG} instances compare equal if and only if they have
        the same name and TTL.
        """
        self._simpleEqualityTest(dns.Record_MG)


    def test_mr(self):
        """
        Two L{dns.Record_MR} instances compare equal if and only if they have
        the same name and TTL.
        """
        self._simpleEqualityTest(dns.Record_MR)


    def test_ptr(self):
        """
        Two L{dns.Record_PTR} instances compare equal if and only if they have
        the same name and TTL.
        """
        self._simpleEqualityTest(dns.Record_PTR)


    def test_dname(self):
        """
        Two L{dns.Record_MD} instances compare equal if and only if they have
        the same name and TTL.
        """
        self._simpleEqualityTest(dns.Record_DNAME)


    def test_a(self):
        """
        Two L{dns.Record_A} instances compare equal if and only if they have
        the same address and TTL.
        """
        # Vary the TTL
        self._equalityTest(
            dns.Record_A('1.2.3.4', 5),
            dns.Record_A('1.2.3.4', 5),
            dns.Record_A('1.2.3.4', 6))
        # Vary the address
        self._equalityTest(
            dns.Record_A('1.2.3.4', 5),
            dns.Record_A('1.2.3.4', 5),
            dns.Record_A('1.2.3.5', 5))


    def test_soa(self):
        """
        Two L{dns.Record_SOA} instances compare equal if and only if they have
        the same mname, rname, serial, refresh, minimum, expire, retry, and
        ttl.
        """
        # Vary the mname
        self._equalityTest(
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'xname', b'rname', 123, 456, 789, 10, 20, 30))
        # Vary the rname
        self._equalityTest(
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'xname', 123, 456, 789, 10, 20, 30))
        # Vary the serial
        self._equalityTest(
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 1, 456, 789, 10, 20, 30))
        # Vary the refresh
        self._equalityTest(
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 1, 789, 10, 20, 30))
        # Vary the minimum
        self._equalityTest(
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 1, 10, 20, 30))
        # Vary the expire
        self._equalityTest(
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 1, 20, 30))
        # Vary the retry
        self._equalityTest(
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 1, 30))
        # Vary the ttl
        self._equalityTest(
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'rname', 123, 456, 789, 10, 20, 30),
            dns.Record_SOA(b'mname', b'xname', 123, 456, 789, 10, 20, 1))


    def test_null(self):
        """
        Two L{dns.Record_NULL} instances compare equal if and only if they have
        the same payload and ttl.
        """
        # Vary the payload
        self._equalityTest(
            dns.Record_NULL('foo bar', 10),
            dns.Record_NULL('foo bar', 10),
            dns.Record_NULL('bar foo', 10))
        # Vary the ttl
        self._equalityTest(
            dns.Record_NULL('foo bar', 10),
            dns.Record_NULL('foo bar', 10),
            dns.Record_NULL('foo bar', 100))


    def test_wks(self):
        """
        Two L{dns.Record_WKS} instances compare equal if and only if they have
        the same address, protocol, map, and ttl.
        """
        # Vary the address
        self._equalityTest(
            dns.Record_WKS('1.2.3.4', 1, 'foo', 2),
            dns.Record_WKS('1.2.3.4', 1, 'foo', 2),
            dns.Record_WKS('4.3.2.1', 1, 'foo', 2))
        # Vary the protocol
        self._equalityTest(
            dns.Record_WKS('1.2.3.4', 1, 'foo', 2),
            dns.Record_WKS('1.2.3.4', 1, 'foo', 2),
            dns.Record_WKS('1.2.3.4', 100, 'foo', 2))
        # Vary the map
        self._equalityTest(
            dns.Record_WKS('1.2.3.4', 1, 'foo', 2),
            dns.Record_WKS('1.2.3.4', 1, 'foo', 2),
            dns.Record_WKS('1.2.3.4', 1, 'bar', 2))
        # Vary the ttl
        self._equalityTest(
            dns.Record_WKS('1.2.3.4', 1, 'foo', 2),
            dns.Record_WKS('1.2.3.4', 1, 'foo', 2),
            dns.Record_WKS('1.2.3.4', 1, 'foo', 200))


    def test_aaaa(self):
        """
        Two L{dns.Record_AAAA} instances compare equal if and only if they have
        the same address and ttl.
        """
        # Vary the address
        self._equalityTest(
            dns.Record_AAAA('1::2', 1),
            dns.Record_AAAA('1::2', 1),
            dns.Record_AAAA('2::1', 1))
        # Vary the ttl
        self._equalityTest(
            dns.Record_AAAA('1::2', 1),
            dns.Record_AAAA('1::2', 1),
            dns.Record_AAAA('1::2', 10))


    def test_a6(self):
        """
        Two L{dns.Record_A6} instances compare equal if and only if they have
        the same prefix, prefix length, suffix, and ttl.
        """
        # Note, A6 is crazy, I'm not sure these values are actually legal.
        # Hopefully that doesn't matter for this test. -exarkun

        # Vary the prefix length
        self._equalityTest(
            dns.Record_A6(16, '::abcd', b'example.com', 10),
            dns.Record_A6(16, '::abcd', b'example.com', 10),
            dns.Record_A6(32, '::abcd', b'example.com', 10))
        # Vary the suffix
        self._equalityTest(
            dns.Record_A6(16, '::abcd', b'example.com', 10),
            dns.Record_A6(16, '::abcd', b'example.com', 10),
            dns.Record_A6(16, '::abcd:0', b'example.com', 10))
        # Vary the prefix
        self._equalityTest(
            dns.Record_A6(16, '::abcd', b'example.com', 10),
            dns.Record_A6(16, '::abcd', b'example.com', 10),
            dns.Record_A6(16, '::abcd', b'example.org', 10))
        # Vary the ttl
        self._equalityTest(
            dns.Record_A6(16, '::abcd', b'example.com', 10),
            dns.Record_A6(16, '::abcd', b'example.com', 10),
            dns.Record_A6(16, '::abcd', b'example.com', 100))


    def test_srv(self):
        """
        Two L{dns.Record_SRV} instances compare equal if and only if they have
        the same priority, weight, port, target, and ttl.
        """
        # Vary the priority
        self._equalityTest(
            dns.Record_SRV(10, 20, 30, b'example.com', 40),
            dns.Record_SRV(10, 20, 30, b'example.com', 40),
            dns.Record_SRV(100, 20, 30, b'example.com', 40))
        # Vary the weight
        self._equalityTest(
            dns.Record_SRV(10, 20, 30, b'example.com', 40),
            dns.Record_SRV(10, 20, 30, b'example.com', 40),
            dns.Record_SRV(10, 200, 30, b'example.com', 40))
        # Vary the port
        self._equalityTest(
            dns.Record_SRV(10, 20, 30, b'example.com', 40),
            dns.Record_SRV(10, 20, 30, b'example.com', 40),
            dns.Record_SRV(10, 20, 300, b'example.com', 40))
        # Vary the target
        self._equalityTest(
            dns.Record_SRV(10, 20, 30, b'example.com', 40),
            dns.Record_SRV(10, 20, 30, b'example.com', 40),
            dns.Record_SRV(10, 20, 30, b'example.org', 40))
        # Vary the ttl
        self._equalityTest(
            dns.Record_SRV(10, 20, 30, b'example.com', 40),
            dns.Record_SRV(10, 20, 30, b'example.com', 40),
            dns.Record_SRV(10, 20, 30, b'example.com', 400))


    def test_naptr(self):
        """
        Two L{dns.Record_NAPTR} instances compare equal if and only if they
        have the same order, preference, flags, service, regexp, replacement,
        and ttl.
        """
        # Vary the order
        self._equalityTest(
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(2, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12))
        # Vary the preference
        self._equalityTest(
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 3, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12))
        # Vary the flags
        self._equalityTest(
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"p", b"sip+E2U", b"/foo/bar/", b"baz", 12))
        # Vary the service
        self._equalityTest(
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"http", b"/foo/bar/", b"baz", 12))
        # Vary the regexp
        self._equalityTest(
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/bar/foo/", b"baz", 12))
        # Vary the replacement
        self._equalityTest(
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/bar/foo/", b"quux", 12))
        # Vary the ttl
        self._equalityTest(
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/foo/bar/", b"baz", 12),
            dns.Record_NAPTR(1, 2, b"u", b"sip+E2U", b"/bar/foo/", b"baz", 5))


    def test_afsdb(self):
        """
        Two L{dns.Record_AFSDB} instances compare equal if and only if they
        have the same subtype, hostname, and ttl.
        """
        # Vary the subtype
        self._equalityTest(
            dns.Record_AFSDB(1, b'example.com', 2),
            dns.Record_AFSDB(1, b'example.com', 2),
            dns.Record_AFSDB(2, b'example.com', 2))
        # Vary the hostname
        self._equalityTest(
            dns.Record_AFSDB(1, b'example.com', 2),
            dns.Record_AFSDB(1, b'example.com', 2),
            dns.Record_AFSDB(1, b'example.org', 2))
        # Vary the ttl
        self._equalityTest(
            dns.Record_AFSDB(1, b'example.com', 2),
            dns.Record_AFSDB(1, b'example.com', 2),
            dns.Record_AFSDB(1, b'example.com', 3))


    def test_rp(self):
        """
        Two L{Record_RP} instances compare equal if and only if they have the
        same mbox, txt, and ttl.
        """
        # Vary the mbox
        self._equalityTest(
            dns.Record_RP(b'alice.example.com', b'alice is nice', 10),
            dns.Record_RP(b'alice.example.com', b'alice is nice', 10),
            dns.Record_RP(b'bob.example.com', b'alice is nice', 10))
        # Vary the txt
        self._equalityTest(
            dns.Record_RP(b'alice.example.com', b'alice is nice', 10),
            dns.Record_RP(b'alice.example.com', b'alice is nice', 10),
            dns.Record_RP(b'alice.example.com', b'alice is not nice', 10))
        # Vary the ttl
        self._equalityTest(
            dns.Record_RP(b'alice.example.com', b'alice is nice', 10),
            dns.Record_RP(b'alice.example.com', b'alice is nice', 10),
            dns.Record_RP(b'alice.example.com', b'alice is nice', 100))


    def test_hinfo(self):
        """
        Two L{dns.Record_HINFO} instances compare equal if and only if they
        have the same cpu, os, and ttl.
        """
        # Vary the cpu
        self._equalityTest(
            dns.Record_HINFO('x86-64', 'plan9', 10),
            dns.Record_HINFO('x86-64', 'plan9', 10),
            dns.Record_HINFO('i386', 'plan9', 10))
        # Vary the os
        self._equalityTest(
            dns.Record_HINFO('x86-64', 'plan9', 10),
            dns.Record_HINFO('x86-64', 'plan9', 10),
            dns.Record_HINFO('x86-64', 'plan11', 10))
        # Vary the ttl
        self._equalityTest(
            dns.Record_HINFO('x86-64', 'plan9', 10),
            dns.Record_HINFO('x86-64', 'plan9', 10),
            dns.Record_HINFO('x86-64', 'plan9', 100))


    def test_minfo(self):
        """
        Two L{dns.Record_MINFO} instances compare equal if and only if they
        have the same rmailbx, emailbx, and ttl.
        """
        # Vary the rmailbx
        self._equalityTest(
            dns.Record_MINFO(b'rmailbox', b'emailbox', 10),
            dns.Record_MINFO(b'rmailbox', b'emailbox', 10),
            dns.Record_MINFO(b'someplace', b'emailbox', 10))
        # Vary the emailbx
        self._equalityTest(
            dns.Record_MINFO(b'rmailbox', b'emailbox', 10),
            dns.Record_MINFO(b'rmailbox', b'emailbox', 10),
            dns.Record_MINFO(b'rmailbox', b'something', 10))
        # Vary the ttl
        self._equalityTest(
            dns.Record_MINFO(b'rmailbox', b'emailbox', 10),
            dns.Record_MINFO(b'rmailbox', b'emailbox', 10),
            dns.Record_MINFO(b'rmailbox', b'emailbox', 100))


    def test_mx(self):
        """
        Two L{dns.Record_MX} instances compare equal if and only if they have
        the same preference, name, and ttl.
        """
        # Vary the preference
        self._equalityTest(
            dns.Record_MX(10, b'example.org', 20),
            dns.Record_MX(10, b'example.org', 20),
            dns.Record_MX(100, b'example.org', 20))
        # Vary the name
        self._equalityTest(
            dns.Record_MX(10, b'example.org', 20),
            dns.Record_MX(10, b'example.org', 20),
            dns.Record_MX(10, b'example.net', 20))
        # Vary the ttl
        self._equalityTest(
            dns.Record_MX(10, b'example.org', 20),
            dns.Record_MX(10, b'example.org', 20),
            dns.Record_MX(10, b'example.org', 200))


    def test_txt(self):
        """
        Two L{dns.Record_TXT} instances compare equal if and only if they have
        the same data and ttl.
        """
        # Vary the length of the data
        self._equalityTest(
            dns.Record_TXT('foo', 'bar', ttl=10),
            dns.Record_TXT('foo', 'bar', ttl=10),
            dns.Record_TXT('foo', 'bar', 'baz', ttl=10))
        # Vary the value of the data
        self._equalityTest(
            dns.Record_TXT('foo', 'bar', ttl=10),
            dns.Record_TXT('foo', 'bar', ttl=10),
            dns.Record_TXT('bar', 'foo', ttl=10))
        # Vary the ttl
        self._equalityTest(
            dns.Record_TXT('foo', 'bar', ttl=10),
            dns.Record_TXT('foo', 'bar', ttl=10),
            dns.Record_TXT('foo', 'bar', ttl=100))


    def test_spf(self):
        """
        L{dns.Record_SPF} instances compare equal if and only if they have the
        same data and ttl.
        """
        # Vary the length of the data
        self._equalityTest(
            dns.Record_SPF('foo', 'bar', ttl=10),
            dns.Record_SPF('foo', 'bar', ttl=10),
            dns.Record_SPF('foo', 'bar', 'baz', ttl=10))
        # Vary the value of the data
        self._equalityTest(
            dns.Record_SPF('foo', 'bar', ttl=10),
            dns.Record_SPF('foo', 'bar', ttl=10),
            dns.Record_SPF('bar', 'foo', ttl=10))
        # Vary the ttl
        self._equalityTest(
            dns.Record_SPF('foo', 'bar', ttl=10),
            dns.Record_SPF('foo', 'bar', ttl=10),
            dns.Record_SPF('foo', 'bar', ttl=100))


    def test_unknown(self):
        """
        L{dns.UnknownRecord} instances compare equal if and only if they have
        the same data and ttl.
        """
        # Vary the length of the data
        self._equalityTest(
            dns.UnknownRecord('foo', ttl=10),
            dns.UnknownRecord('foo', ttl=10),
            dns.UnknownRecord('foobar', ttl=10))
        # Vary the value of the data
        self._equalityTest(
            dns.UnknownRecord('foo', ttl=10),
            dns.UnknownRecord('foo', ttl=10),
            dns.UnknownRecord('bar', ttl=10))
        # Vary the ttl
        self._equalityTest(
            dns.UnknownRecord('foo', ttl=10),
            dns.UnknownRecord('foo', ttl=10),
            dns.UnknownRecord('foo', ttl=100))



class RRHeaderTests(unittest.TestCase):
    """
    Tests for L{twisted.names.dns.RRHeader}.
    """

    def test_negativeTTL(self):
        """
        Attempting to create a L{dns.RRHeader} instance with a negative TTL
        causes L{ValueError} to be raised.
        """
        self.assertRaises(
            ValueError, dns.RRHeader, "example.com", dns.A,
            dns.IN, -1, dns.Record_A("127.0.0.1"))



class NameToLabelsTests(unittest.SynchronousTestCase):
    """
    Tests for L{twisted.names.dns._nameToLabels}.
    """

    def test_empty(self):
        """
        L{dns._nameToLabels} returns a list containing a single
        empty label for an empty name.
        """
        self.assertEqual(dns._nameToLabels(b''), [b''])


    def test_onlyDot(self):
        """
        L{dns._nameToLabels} returns a list containing a single
        empty label for a name containing only a dot.
        """
        self.assertEqual(dns._nameToLabels(b'.'), [b''])


    def test_withoutTrailingDot(self):
        """
        L{dns._nameToLabels} returns a list ending with an empty
        label for a name without a trailing dot.
        """
        self.assertEqual(dns._nameToLabels(b'com'), [b'com', b''])


    def test_withTrailingDot(self):
        """
        L{dns._nameToLabels} returns a list ending with an empty
        label for a name with a trailing dot.
        """
        self.assertEqual(dns._nameToLabels(b'com.'), [b'com', b''])


    def test_subdomain(self):
        """
        L{dns._nameToLabels} returns a list containing entries
        for all labels in a subdomain name.
        """
        self.assertEqual(
            dns._nameToLabels(b'foo.bar.baz.example.com.'),
            [b'foo', b'bar', b'baz', b'example', b'com', b''])


    def test_casePreservation(self):
        """
        L{dns._nameToLabels} preserves the case of ascii
        characters in labels.
        """
        self.assertEqual(
            dns._nameToLabels(b'EXAMPLE.COM'),
            [b'EXAMPLE', b'COM', b''])



def assertIsSubdomainOf(testCase, descendant, ancestor):
    """
    Assert that C{descendant} *is* a subdomain of C{ancestor}.

    @type testCase: L{unittest.SynchronousTestCase}
    @param testCase: The test case on which to run the assertions.

    @type descendant: C{str}
    @param descendant: The subdomain name to test.

    @type ancestor: C{str}
    @param ancestor: The superdomain name to test.
    """
    testCase.assertTrue(
        dns._isSubdomainOf(descendant, ancestor),
        '%r is not a subdomain of %r' % (descendant, ancestor))



def assertIsNotSubdomainOf(testCase, descendant, ancestor):
    """
    Assert that C{descendant} *is not* a subdomain of C{ancestor}.

    @type testCase: L{unittest.SynchronousTestCase}
    @param testCase: The test case on which to run the assertions.

    @type descendant: C{str}
    @param descendant: The subdomain name to test.

    @type ancestor: C{str}
    @param ancestor: The superdomain name to test.
    """
    testCase.assertFalse(
        dns._isSubdomainOf(descendant, ancestor),
        '%r is a subdomain of %r' % (descendant, ancestor))



class IsSubdomainOfTests(unittest.SynchronousTestCase):
    """
    Tests for L{twisted.names.dns._isSubdomainOf}.
    """

    def test_identical(self):
        """
        L{dns._isSubdomainOf} returns C{True} for identical
        domain names.
        """
        assertIsSubdomainOf(self, b'example.com', b'example.com')


    def test_parent(self):
        """
        L{dns._isSubdomainOf} returns C{True} when the first
        name is an immediate descendant of the second name.
        """
        assertIsSubdomainOf(self, b'foo.example.com', b'example.com')


    def test_distantAncestor(self):
        """
        L{dns._isSubdomainOf} returns C{True} when the first
        name is a distant descendant of the second name.
        """
        assertIsSubdomainOf(self, b'foo.bar.baz.example.com', b'com')


    def test_superdomain(self):
        """
        L{dns._isSubdomainOf} returns C{False} when the first
        name is an ancestor of the second name.
        """
        assertIsNotSubdomainOf(self, b'example.com', b'foo.example.com')


    def test_sibling(self):
        """
        L{dns._isSubdomainOf} returns C{False} if the first name
        is a sibling of the second name.
        """
        assertIsNotSubdomainOf(self, b'foo.example.com', b'bar.example.com')


    def test_unrelatedCommonSuffix(self):
        """
        L{dns._isSubdomainOf} returns C{False} even when domain
        names happen to share a common suffix.
        """
        assertIsNotSubdomainOf(self, b'foo.myexample.com', b'example.com')


    def test_subdomainWithTrailingDot(self):
        """
        L{dns._isSubdomainOf} returns C{True} if the first name
        is a subdomain of the second name but the first name has a
        trailing ".".
        """
        assertIsSubdomainOf(self, b'foo.example.com.', b'example.com')


    def test_superdomainWithTrailingDot(self):
        """
        L{dns._isSubdomainOf} returns C{True} if the first name
        is a subdomain of the second name but the second name has a
        trailing ".".
        """
        assertIsSubdomainOf(self, b'foo.example.com', b'example.com.')


    def test_bothWithTrailingDot(self):
        """
        L{dns._isSubdomainOf} returns C{True} if the first name
        is a subdomain of the second name and both names have a
        trailing ".".
        """
        assertIsSubdomainOf(self, b'foo.example.com.', b'example.com.')


    def test_emptySubdomain(self):
        """
        L{dns._isSubdomainOf} returns C{False} if the first name
        is empty and the second name is not.
        """
        assertIsNotSubdomainOf(self, b'', b'example.com')


    def test_emptySuperdomain(self):
        """
        L{dns._isSubdomainOf} returns C{True} if the second name
        is empty and the first name is not.
        """
        assertIsSubdomainOf(self, b'foo.example.com', b'')


    def test_caseInsensitiveComparison(self):
        """
        L{dns._isSubdomainOf} does case-insensitive comparison
        of name labels.
        """
        assertIsSubdomainOf(self, b'foo.example.com', b'EXAMPLE.COM')

        assertIsSubdomainOf(self, b'FOO.EXAMPLE.COM', b'example.com')



class OPTNonStandardAttributes(object):
    """
    Generate byte and instance representations of an L{dns._OPTHeader}
    where all attributes are set to non-default values.

    For testing whether attributes have really been read from the byte
    string during decoding.
    """
    @classmethod
    def bytes(cls, excludeName=False, excludeOptions=False):
        """
        Return L{bytes} representing an encoded OPT record.

        @param excludeName: A flag that controls whether to exclude
            the name field. This allows a non-standard name to be
            prepended during the test.
        @type excludeName: L{bool}

        @param excludeOptions: A flag that controls whether to exclude
            the RDLEN field. This allows encoded variable options to be
            appended during the test.
        @type excludeOptions: L{bool}

        @return: L{bytes} representing the encoded OPT record returned
            by L{object}.
        """
        rdlen = b'\x00\x00' # RDLEN 0
        if excludeOptions:
            rdlen = b''

        return (
            b'\x00' # 0 root zone
            b'\x00\x29' # type 41
            b'\x02\x00' # udpPayloadsize 512
            b'\x03' # extendedRCODE 3
            b'\x04' # version 4
            b'\x80\x00' # DNSSEC OK 1 + Z
            ) + rdlen


    @classmethod
    def object(cls):
        """
        Return a new L{dns._OPTHeader} instance.

        @return: A L{dns._OPTHeader} instance with attributes that
            match the encoded record returned by L{bytes}.
        """
        return dns._OPTHeader(
            udpPayloadSize=512,
            extendedRCODE=3,
            version=4,
            dnssecOK=True)



class OPTHeaderTests(ComparisonTestsMixin, unittest.TestCase):
    """
    Tests for L{twisted.names.dns._OPTHeader}.
    """
    def test_interface(self):
        """
        L{dns._OPTHeader} implements L{dns.IEncodable}.
        """
        verifyClass(dns.IEncodable, dns._OPTHeader)


    def test_name(self):
        """
        L{dns._OPTHeader.name} is a instance attribute whose value is
        fixed as the root domain
        """
        self.assertEqual(dns._OPTHeader().name, dns.Name(b''))


    def test_nameReadonly(self):
        """
        L{dns._OPTHeader.name} is readonly.
        """
        h = dns._OPTHeader()
        self.assertRaises(
            AttributeError, setattr, h, 'name', dns.Name(b'example.com'))


    def test_type(self):
        """
        L{dns._OPTHeader.type} is an instance attribute with fixed value
        41.
        """
        self.assertEqual(dns._OPTHeader().type, 41)


    def test_typeReadonly(self):
        """
        L{dns._OPTHeader.type} is readonly.
        """
        h = dns._OPTHeader()
        self.assertRaises(
            AttributeError, setattr, h, 'type', dns.A)


    def test_udpPayloadSize(self):
        """
        L{dns._OPTHeader.udpPayloadSize} defaults to 4096 as
        recommended in rfc6891 section-6.2.5.
        """
        self.assertEqual(dns._OPTHeader().udpPayloadSize, 4096)


    def test_udpPayloadSizeOverride(self):
        """
        L{dns._OPTHeader.udpPayloadSize} can be overridden in the
        constructor.
        """
        self.assertEqual(dns._OPTHeader(udpPayloadSize=512).udpPayloadSize, 512)


    def test_extendedRCODE(self):
        """
        L{dns._OPTHeader.extendedRCODE} defaults to 0.
        """
        self.assertEqual(dns._OPTHeader().extendedRCODE, 0)


    def test_extendedRCODEOverride(self):
        """
        L{dns._OPTHeader.extendedRCODE} can be overridden in the
        constructor.
        """
        self.assertEqual(dns._OPTHeader(extendedRCODE=1).extendedRCODE, 1)


    def test_version(self):
        """
        L{dns._OPTHeader.version} defaults to 0.
        """
        self.assertEqual(dns._OPTHeader().version, 0)


    def test_versionOverride(self):
        """
        L{dns._OPTHeader.version} can be overridden in the
        constructor.
        """
        self.assertEqual(dns._OPTHeader(version=1).version, 1)


    def test_dnssecOK(self):
        """
        L{dns._OPTHeader.dnssecOK} defaults to False.
        """
        self.assertEqual(dns._OPTHeader().dnssecOK, False)


    def test_dnssecOKOverride(self):
        """
        L{dns._OPTHeader.dnssecOK} can be overridden in the
        constructor.
        """
        self.assertEqual(dns._OPTHeader(dnssecOK=True).dnssecOK, True)


    def test_options(self):
        """
        L{dns._OPTHeader.options} defaults to empty list.
        """
        self.assertEqual(dns._OPTHeader().options, [])


    def test_optionsOverride(self):
        """
        L{dns._OPTHeader.options} can be overridden in the
        constructor.
        """
        h = dns._OPTHeader(options=[(1, 1, b'\x00')])
        self.assertEqual(h.options, [(1, 1, b'\x00')])


    def test_encode(self):
        """
        L{dns._OPTHeader.encode} packs the header fields and writes
        them to a file like object passed in as an argument.
        """
        b = BytesIO()

        OPTNonStandardAttributes.object().encode(b)
        self.assertEqual(
            b.getvalue(),
            OPTNonStandardAttributes.bytes()
            )


    def test_encodeWithOptions(self):
        """
        L{dns._OPTHeader.options} is a list of L{dns._OPTVariableOption}
        instances which are packed into the rdata area of the header.
        """
        h = OPTNonStandardAttributes.object()
        h.options = [
            dns._OPTVariableOption(1, b'foobarbaz'),
            dns._OPTVariableOption(2, b'qux'),
            ]
        b = BytesIO()

        h.encode(b)
        self.assertEqual(
            b.getvalue(),

            OPTNonStandardAttributes.bytes(excludeOptions=True) + (
                b'\x00\x14' # RDLEN 20

                b'\x00\x01' # OPTION-CODE
                b'\x00\x09' # OPTION-LENGTH
                b'foobarbaz' # OPTION-DATA

                b'\x00\x02' # OPTION-CODE
                b'\x00\x03' # OPTION-LENGTH
                b'qux' # OPTION-DATA
                ))


    def test_decode(self):
        """
        L{dns._OPTHeader.decode} unpacks the header fields from a file
        like object and populates the attributes of an existing
        L{dns._OPTHeader} instance.
        """
        decodedHeader = dns._OPTHeader()
        decodedHeader.decode(BytesIO(OPTNonStandardAttributes.bytes()))

        self.assertEqual(
            decodedHeader,
            OPTNonStandardAttributes.object())


    def test_decodeAllExpectedBytes(self):
        """
        L{dns._OPTHeader.decode} reads all the bytes of the record
        that is being decoded.
        """
        # Check that all the input data has been consumed.
        b = BytesIO(OPTNonStandardAttributes.bytes())

        decodedHeader = dns._OPTHeader()
        decodedHeader.decode(b)

        self.assertEqual(b.tell(), len(b.getvalue()))


    def test_decodeOnlyExpectedBytes(self):
        """
        L{dns._OPTHeader.decode} reads only the bytes from the current
        file position to the end of the record that is being
        decoded. Trailing bytes are not consumed.
        """
        b = BytesIO(OPTNonStandardAttributes.bytes()
                    + b'xxxx') # Trailing bytes

        decodedHeader = dns._OPTHeader()
        decodedHeader.decode(b)

        self.assertEqual(b.tell(), len(b.getvalue())-len(b'xxxx'))


    def test_decodeDiscardsName(self):
        """
        L{dns._OPTHeader.decode} discards the name which is encoded in
        the supplied bytes. The name attribute of the resulting
        L{dns._OPTHeader} instance will always be L{dns.Name(b'')}.
        """
        b = BytesIO(OPTNonStandardAttributes.bytes(excludeName=True)
                    + b'\x07example\x03com\x00')

        h = dns._OPTHeader()
        h.decode(b)
        self.assertEqual(h.name, dns.Name(b''))


    def test_decodeRdlengthTooShort(self):
        """
        L{dns._OPTHeader.decode} raises an exception if the supplied
        RDLEN is too short.
        """
        b = BytesIO(
            OPTNonStandardAttributes.bytes(excludeOptions=True) + (
                b'\x00\x05' # RDLEN 5 Too short - should be 6

                b'\x00\x01' # OPTION-CODE
                b'\x00\x02' # OPTION-LENGTH
                b'\x00\x00' # OPTION-DATA
                ))
        h = dns._OPTHeader()
        self.assertRaises(EOFError, h.decode, b)


    def test_decodeRdlengthTooLong(self):
        """
        L{dns._OPTHeader.decode} raises an exception if the supplied
        RDLEN is too long.
        """
        b = BytesIO(
            OPTNonStandardAttributes.bytes(excludeOptions=True) + (

                b'\x00\x07' # RDLEN 7 Too long - should be 6

                b'\x00\x01' # OPTION-CODE
                b'\x00\x02' # OPTION-LENGTH
                b'\x00\x00' # OPTION-DATA
                ))
        h = dns._OPTHeader()
        self.assertRaises(EOFError, h.decode, b)


    def test_decodeWithOptions(self):
        """
        If the OPT bytes contain variable options,
        L{dns._OPTHeader.decode} will populate a list
        L{dns._OPTHeader.options} with L{dns._OPTVariableOption}
        instances.
        """

        b = BytesIO(
            OPTNonStandardAttributes.bytes(excludeOptions=True) + (

                b'\x00\x14' # RDLEN 20

                b'\x00\x01' # OPTION-CODE
                b'\x00\x09' # OPTION-LENGTH
                b'foobarbaz' # OPTION-DATA

                b'\x00\x02' # OPTION-CODE
                b'\x00\x03' # OPTION-LENGTH
                b'qux' # OPTION-DATA
                ))

        h = dns._OPTHeader()
        h.decode(b)
        self.assertEqual(
            h.options,
            [dns._OPTVariableOption(1, b'foobarbaz'),
             dns._OPTVariableOption(2, b'qux'),]
            )


    def test_fromRRHeader(self):
        """
        L{_OPTHeader.fromRRHeader} accepts an L{RRHeader} instance and
        returns an L{_OPTHeader} instance whose attribute values have
        been derived from the C{cls}, C{ttl} and C{payload} attributes
        of the original header.
        """
        genericHeader = dns.RRHeader(
            b'example.com',
            type=dns.OPT,
            cls=0xffff,
            ttl=(0xfe << 24
                 | 0xfd << 16
                 | True << 15),
            payload=dns.UnknownRecord(b'\xff\xff\x00\x03abc'))

        decodedOptHeader = dns._OPTHeader.fromRRHeader(genericHeader)

        expectedOptHeader = dns._OPTHeader(
            udpPayloadSize=0xffff,
            extendedRCODE=0xfe,
            version=0xfd,
            dnssecOK=True,
            options=[dns._OPTVariableOption(code=0xffff, data=b'abc')])

        self.assertEqual(decodedOptHeader, expectedOptHeader)


    def test_repr(self):
        """
        L{dns._OPTHeader.__repr__} displays the name and type and all
        the fixed and extended header values of the OPT record.
        """
        self.assertEqual(
            repr(dns._OPTHeader()),
            '<_OPTHeader '
            'name= '
            'type=41 '
            'udpPayloadSize=4096 '
            'extendedRCODE=0 '
            'version=0 '
            'dnssecOK=False '
            'options=[]>')


    def test_equalityUdpPayloadSize(self):
        """
        Two L{OPTHeader} instances compare equal if they have the same
        udpPayloadSize.
        """
        self.assertNormalEqualityImplementation(
            dns._OPTHeader(udpPayloadSize=512),
            dns._OPTHeader(udpPayloadSize=512),
            dns._OPTHeader(udpPayloadSize=4096))


    def test_equalityExtendedRCODE(self):
        """
        Two L{OPTHeader} instances compare equal if they have the same
        extendedRCODE.
        """
        self.assertNormalEqualityImplementation(
            dns._OPTHeader(extendedRCODE=1),
            dns._OPTHeader(extendedRCODE=1),
            dns._OPTHeader(extendedRCODE=2))


    def test_equalityVersion(self):
        """
        Two L{OPTHeader} instances compare equal if they have the same
        version.
        """
        self.assertNormalEqualityImplementation(
            dns._OPTHeader(version=1),
            dns._OPTHeader(version=1),
            dns._OPTHeader(version=2))


    def test_equalityDnssecOK(self):
        """
        Two L{OPTHeader} instances compare equal if they have the same
        dnssecOK flags.
        """
        self.assertNormalEqualityImplementation(
            dns._OPTHeader(dnssecOK=True),
            dns._OPTHeader(dnssecOK=True),
            dns._OPTHeader(dnssecOK=False))


    def test_equalityOptions(self):
        """
        Two L{OPTHeader} instances compare equal if they have the same
        options.
        """
        self.assertNormalEqualityImplementation(
            dns._OPTHeader(options=[dns._OPTVariableOption(1, b'x')]),
            dns._OPTHeader(options=[dns._OPTVariableOption(1, b'x')]),
            dns._OPTHeader(options=[dns._OPTVariableOption(2, b'y')]))



class OPTVariableOptionTests(ComparisonTestsMixin, unittest.TestCase):
    """
    Tests for L{dns._OPTVariableOption}.
    """
    def test_interface(self):
        """
        L{dns._OPTVariableOption} implements L{dns.IEncodable}.
        """
        verifyClass(dns.IEncodable, dns._OPTVariableOption)


    def test_constructorArguments(self):
        """
        L{dns._OPTVariableOption.__init__} requires code and data
        arguments which are saved as public instance attributes.
        """
        h = dns._OPTVariableOption(1, b'x')
        self.assertEqual(h.code, 1)
        self.assertEqual(h.data, b'x')


    def test_repr(self):
        """
        L{dns._OPTVariableOption.__repr__} displays the code and data
        of the option.
        """
        self.assertEqual(
            repr(dns._OPTVariableOption(1, b'x')),
            '<_OPTVariableOption '
            'code=1 '
            "data=x"
            '>')


    def test_equality(self):
        """
        Two OPTVariableOption instances compare equal if they have the same
        code and data values.
        """
        self.assertNormalEqualityImplementation(
            dns._OPTVariableOption(1, b'x'),
            dns._OPTVariableOption(1, b'x'),
            dns._OPTVariableOption(2, b'x'))

        self.assertNormalEqualityImplementation(
            dns._OPTVariableOption(1, b'x'),
            dns._OPTVariableOption(1, b'x'),
            dns._OPTVariableOption(1, b'y'))


    def test_encode(self):
        """
        L{dns._OPTVariableOption.encode} encodes the code and data
        instance attributes to a byte string which also includes the
        data length.
        """
        o = dns._OPTVariableOption(1, b'foobar')
        b = BytesIO()
        o.encode(b)
        self.assertEqual(
            b.getvalue(),
            b'\x00\x01' # OPTION-CODE 1
            b'\x00\x06' # OPTION-LENGTH 6
            b'foobar' # OPTION-DATA
            )


    def test_decode(self):
        """
        L{dns._OPTVariableOption.decode} is a classmethod that decodes
        a byte string and returns a L{dns._OPTVariableOption} instance.
        """
        b = BytesIO(
            b'\x00\x01' # OPTION-CODE 1
            b'\x00\x06' # OPTION-LENGTH 6
            b'foobar' # OPTION-DATA
            )

        o = dns._OPTVariableOption()
        o.decode(b)
        self.assertEqual(o.code, 1)
        self.assertEqual(o.data, b'foobar')



class RaisedArgs(Exception):
    """
    An exception which can be raised by fakes to test that the fake is called
    with expected arguments.
    """
    def __init__(self, args, kwargs):
        """
        Store the positional and keyword arguments as attributes.

        @param args: The positional args.
        @param kwargs: The keyword args.
        """
        self.args = args
        self.kwargs = kwargs



class MessageEmpty(object):
    """
    Generate byte string and constructor arguments for an empty
    L{dns._EDNSMessage}.
    """
    @classmethod
    def bytes(cls):
        """
        Bytes which are expected when encoding an instance constructed using
        C{kwargs} and which are expected to result in an identical instance when
        decoded.

        @return: The L{bytes} of a wire encoded message.
        """
        return (
            b'\x01\x00' # id: 256
            b'\x97' # QR: 1, OPCODE: 2, AA: 0, TC: 0, RD: 1
            b'\x8f' # RA: 1, Z, RCODE: 15
            b'\x00\x00' # number of queries
            b'\x00\x00' # number of answers
            b'\x00\x00' # number of authorities
            b'\x00\x00' # number of additionals
        )


    @classmethod
    def kwargs(cls):
        """
        Keyword constructor arguments which are expected to result in an
        instance which returns C{bytes} when encoded.

        @return: A L{dict} of keyword arguments.
        """
        return dict(
            id=256,
            answer=True,
            opCode=dns.OP_STATUS,
            auth=True,
            trunc=True,
            recDes=True,
            recAv=True,
            rCode=15,
            ednsVersion=None,
        )



class MessageTruncated(object):
    """
    An empty response message whose TR bit is set to 1.
    """
    @classmethod
    def bytes(cls):
        """
        Bytes which are expected when encoding an instance constructed using
        C{kwargs} and which are expected to result in an identical instance when
        decoded.

        @return: The L{bytes} of a wire encoded message.
        """
        return (
            b'\x01\x00' # ID: 256
            b'\x82' # QR: 1, OPCODE: 0, AA: 0, TC: 1, RD: 0
            b'\x00' # RA: 0, Z, RCODE: 0
            b'\x00\x00' # Number of queries
            b'\x00\x00' # Number of answers
            b'\x00\x00' # Number of authorities
            b'\x00\x00' # Number of additionals
        )


    @classmethod
    def kwargs(cls):
        """
        Keyword constructor arguments which are expected to result in an
        instance which returns C{bytes} when encoded.

        @return: A L{dict} of keyword arguments.
        """
        return dict(
            id=256,
            answer=1,
            opCode=0,
            auth=0,
            trunc=1,
            recDes=0,
            recAv=0,
            rCode=0,
            ednsVersion=None,)



class MessageNonAuthoritative(object):
    """
    A minimal non-authoritative message.
    """
    @classmethod
    def bytes(cls):
        """
        Bytes which are expected when encoding an instance constructed using
        C{kwargs} and which are expected to result in an identical instance when
        decoded.

        @return: The L{bytes} of a wire encoded message.
        """
        return (
            b'\x01\x00' # ID 256
            b'\x00' # QR: 0, OPCODE: 0, AA: 0, TC: 0, RD: 0
            b'\x00' # RA: 0, Z, RCODE: 0
            b'\x00\x00' # Query count
            b'\x00\x01' # Answer count
            b'\x00\x00' # Authorities count
            b'\x00\x00' # Additionals count
            # Answer
            b'\x00' # RR NAME (root)
            b'\x00\x01' # RR TYPE 1 (A)
            b'\x00\x01' # RR CLASS 1 (IN)
            b'\x00\x00\x00\x00' # RR TTL
            b'\x00\x04' # RDLENGTH 4
            b'\x01\x02\x03\x04' # IPv4 1.2.3.4
        )


    @classmethod
    def kwargs(cls):
        """
        Keyword constructor arguments which are expected to result in an
        instance which returns C{bytes} when encoded.

        @return: A L{dict} of keyword arguments.
        """
        return dict(
            id=256,
            auth=0,
            ednsVersion=None,
            answers=[
                dns.RRHeader(
                    b'',
                    payload=dns.Record_A('1.2.3.4', ttl=0),
                    auth=False)])



class MessageAuthoritative(object):
    """
    A minimal authoritative message.
    """
    @classmethod
    def bytes(cls):
        """
        Bytes which are expected when encoding an instance constructed using
        C{kwargs} and which are expected to result in an identical instance when
        decoded.

        @return: The L{bytes} of a wire encoded message.
        """
        return (
            b'\x01\x00' # ID: 256
            b'\x04' # QR: 0, OPCODE: 0, AA: 1, TC: 0, RD: 0
            b'\x00' # RA: 0, Z, RCODE: 0
            b'\x00\x00' # Query count
            b'\x00\x01' # Answer count
            b'\x00\x00' # Authorities count
            b'\x00\x00' # Additionals count
            # Answer
            b'\x00' # RR NAME (root)
            b'\x00\x01' # RR TYPE 1 (A)
            b'\x00\x01' # RR CLASS 1 (IN)
            b'\x00\x00\x00\x00' # RR TTL
            b'\x00\x04' # RDLENGTH 4
            b'\x01\x02\x03\x04' # IPv4 1.2.3.4
        )


    @classmethod
    def kwargs(cls):
        """
        Keyword constructor arguments which are expected to result in an
        instance which returns C{bytes} when encoded.

        @return: A L{dict} of keyword arguments.
        """
        return dict(
            id=256,
            auth=1,
            ednsVersion=None,
            answers=[
                dns.RRHeader(
                    b'',
                    payload=dns.Record_A('1.2.3.4', ttl=0),
                    auth=True)])



class MessageComplete:
    """
    An example of a fully populated non-edns response message.

    Contains name compression, answers, authority, and additional records.
    """
    @classmethod
    def bytes(cls):
        """
        Bytes which are expected when encoding an instance constructed using
        C{kwargs} and which are expected to result in an identical instance when
        decoded.

        @return: The L{bytes} of a wire encoded message.
        """
        return (
            b'\x01\x00' # ID: 256
            b'\x95' # QR: 1, OPCODE: 2, AA: 1, TC: 0, RD: 1
            b'\x8f' # RA: 1, Z, RCODE: 15
            b'\x00\x01' # Query count
            b'\x00\x01' # Answer count
            b'\x00\x01' # Authorities count
            b'\x00\x01' # Additionals count

            # Query begins at Byte 12
            b'\x07example\x03com\x00' # QNAME
            b'\x00\x06' # QTYPE 6 (SOA)
            b'\x00\x01' # QCLASS 1 (IN)

            # Answers
            b'\xc0\x0c' # RR NAME (compression ref b12)
            b'\x00\x06' # RR TYPE 6 (SOA)
            b'\x00\x01' # RR CLASS 1 (IN)
            b'\xff\xff\xff\xff' # RR TTL
            b'\x00\x27' # RDLENGTH 39
            b'\x03ns1\xc0\x0c' # Mname (ns1.example.com (compression ref b15)
            b'\x0ahostmaster\xc0\x0c' # rname (hostmaster.example.com)
            b'\xff\xff\xff\xfe' # Serial
            b'\x7f\xff\xff\xfd' # Refresh
            b'\x7f\xff\xff\xfc' # Retry
            b'\x7f\xff\xff\xfb' # Expire
            b'\xff\xff\xff\xfa' # Minimum

            # Authority
            b'\xc0\x0c' # RR NAME (example.com compression ref b12)
            b'\x00\x02' # RR TYPE 2 (NS)
            b'\x00\x01' # RR CLASS 1 (IN)
            b'\xff\xff\xff\xff' # RR TTL
            b'\x00\x02' # RDLENGTH
            b'\xc0\x29' # RDATA (ns1.example.com (compression ref b41)

            # Additional
            b'\xc0\x29' # RR NAME (ns1.example.com compression ref b41)
            b'\x00\x01' # RR TYPE 1 (A)
            b'\x00\x01' # RR CLASS 1 (IN)
            b'\xff\xff\xff\xff' # RR TTL
            b'\x00\x04' # RDLENGTH
            b'\x05\x06\x07\x08' # RDATA 5.6.7.8
        )


    @classmethod
    def kwargs(cls):
        """
        Keyword constructor arguments which are expected to result in an
        instance which returns C{bytes} when encoded.

        @return: A L{dict} of keyword arguments.
        """
        return dict(
            id=256,
            answer=1,
            opCode=dns.OP_STATUS,
            auth=1,
            recDes=1,
            recAv=1,
            rCode=15,
            ednsVersion=None,
            queries=[dns.Query(b'example.com', dns.SOA)],
            answers=[
                dns.RRHeader(
                    b'example.com',
                    type=dns.SOA,
                    ttl=0xffffffff,
                    auth=True,
                    payload=dns.Record_SOA(
                        ttl=0xffffffff,
                        mname=b'ns1.example.com',
                        rname=b'hostmaster.example.com',
                        serial=0xfffffffe,
                        refresh=0x7ffffffd,
                        retry=0x7ffffffc,
                        expire=0x7ffffffb,
                        minimum=0xfffffffa,
                        ))],
            authority=[
                dns.RRHeader(
                    b'example.com',
                    type=dns.NS,
                    ttl=0xffffffff,
                    auth=True,
                    payload=dns.Record_NS(
                        'ns1.example.com', ttl=0xffffffff))],
            additional=[
                dns.RRHeader(
                    b'ns1.example.com',
                    type=dns.A,
                    ttl=0xffffffff,
                    auth=True,
                    payload=dns.Record_A(
                        '5.6.7.8', ttl=0xffffffff))])



class MessageEDNSQuery(object):
    """
    A minimal EDNS query message.
    """
    @classmethod
    def bytes(cls):
        """
        Bytes which are expected when encoding an instance constructed using
        C{kwargs} and which are expected to result in an identical instance when
        decoded.

        @return: The L{bytes} of a wire encoded message.
        """
        return (
            b'\x00\x00' # ID: 0
            b'\x00' # QR: 0, OPCODE: 0, AA: 0, TC: 0, RD: 0
            b'\x00' # RA: 0, Z, RCODE: 0
            b'\x00\x01' # Queries count
            b'\x00\x00' # Anwers count
            b'\x00\x00' # Authority count
            b'\x00\x01' # Additionals count

            # Queries
            b'\x03www\x07example\x03com\x00' # QNAME
            b'\x00\x01' # QTYPE (A)
            b'\x00\x01' # QCLASS (IN)

            # Additional OPT record
            b'\x00' # NAME (.)
            b'\x00\x29' # TYPE (OPT 41)
            b'\x10\x00' # UDP Payload Size (4096)
            b'\x00' # Extended RCODE
            b'\x03' # EDNS version
            b'\x00\x00' # DO: False + Z
            b'\x00\x00' # RDLENGTH
        )


    @classmethod
    def kwargs(cls):
        """
        Keyword constructor arguments which are expected to result in an
        instance which returns C{bytes} when encoded.

        @return: A L{dict} of keyword arguments.
        """
        return dict(
            id=0,
            answer=0,
            opCode=dns.OP_QUERY,
            auth=0,
            recDes=0,
            recAv=0,
            rCode=0,
            ednsVersion=3,
            dnssecOK=False,
            queries=[dns.Query(b'www.example.com', dns.A)],
            additional=[])



class MessageEDNSComplete(object):
    """
    An example of a fully populated edns response message.

    Contains name compression, answers, authority, and additional records.
    """
    @classmethod
    def bytes(cls):
        """
        Bytes which are expected when encoding an instance constructed using
        C{kwargs} and which are expected to result in an identical instance when
        decoded.

        @return: The L{bytes} of a wire encoded message.
        """
        return (
            b'\x01\x00' # ID: 256
            b'\x95' # QR: 1, OPCODE: 2, AA: 1, TC: 0, RD: 1
            b'\xbf' # RA: 1, AD: 1, RCODE: 15
            b'\x00\x01' # Query count
            b'\x00\x01' # Answer count
            b'\x00\x01' # Authorities count
            b'\x00\x02' # Additionals count

            # Query begins at Byte 12
            b'\x07example\x03com\x00' # QNAME
            b'\x00\x06' # QTYPE 6 (SOA)
            b'\x00\x01' # QCLASS 1 (IN)

            # Answers
            b'\xc0\x0c' # RR NAME (compression ref b12)
            b'\x00\x06' # RR TYPE 6 (SOA)
            b'\x00\x01' # RR CLASS 1 (IN)
            b'\xff\xff\xff\xff' # RR TTL
            b'\x00\x27' # RDLENGTH 39
            b'\x03ns1\xc0\x0c' # mname (ns1.example.com (compression ref b15)
            b'\x0ahostmaster\xc0\x0c' # rname (hostmaster.example.com)
            b'\xff\xff\xff\xfe' # Serial
            b'\x7f\xff\xff\xfd' # Refresh
            b'\x7f\xff\xff\xfc' # Retry
            b'\x7f\xff\xff\xfb' # Expire
            b'\xff\xff\xff\xfa' # Minimum

            # Authority
            b'\xc0\x0c' # RR NAME (example.com compression ref b12)
            b'\x00\x02' # RR TYPE 2 (NS)
            b'\x00\x01' # RR CLASS 1 (IN)
            b'\xff\xff\xff\xff' # RR TTL
            b'\x00\x02' # RDLENGTH
            b'\xc0\x29' # RDATA (ns1.example.com (compression ref b41)

            # Additional
            b'\xc0\x29' # RR NAME (ns1.example.com compression ref b41)
            b'\x00\x01' # RR TYPE 1 (A)
            b'\x00\x01' # RR CLASS 1 (IN)
            b'\xff\xff\xff\xff' # RR TTL
            b'\x00\x04' # RDLENGTH
            b'\x05\x06\x07\x08' # RDATA 5.6.7.8

            # Additional OPT record
            b'\x00' # NAME (.)
            b'\x00\x29' # TYPE (OPT 41)
            b'\x04\x00' # UDP Payload Size (1024)
            b'\x00' # Extended RCODE
            b'\x03' # EDNS version
            b'\x80\x00' # DO: True + Z
            b'\x00\x00' # RDLENGTH
        )


    @classmethod
    def kwargs(cls):
        """
        Keyword constructor arguments which are expected to result in an
        instance which returns C{bytes} when encoded.

        @return: A L{dict} of keyword arguments.
        """
        return dict(
            id=256,
            answer=1,
            opCode=dns.OP_STATUS,
            auth=1,
            trunc=0,
            recDes=1,
            recAv=1,
            rCode=15,
            ednsVersion=3,
            dnssecOK=True,
            authenticData=True,
            checkingDisabled=True,
            maxSize=1024,
            queries=[dns.Query(b'example.com', dns.SOA)],
            answers=[
                dns.RRHeader(
                    b'example.com',
                    type=dns.SOA,
                    ttl=0xffffffff,
                    auth=True,
                    payload=dns.Record_SOA(
                        ttl=0xffffffff,
                        mname=b'ns1.example.com',
                        rname=b'hostmaster.example.com',
                        serial=0xfffffffe,
                        refresh=0x7ffffffd,
                        retry=0x7ffffffc,
                        expire=0x7ffffffb,
                        minimum=0xfffffffa,
                        ))],
            authority=[
                dns.RRHeader(
                    b'example.com',
                    type=dns.NS,
                    ttl=0xffffffff,
                    auth=True,
                    payload=dns.Record_NS(
                        'ns1.example.com', ttl=0xffffffff))],
            additional=[
                dns.RRHeader(
                    b'ns1.example.com',
                    type=dns.A,
                    ttl=0xffffffff,
                    auth=True,
                    payload=dns.Record_A(
                        '5.6.7.8', ttl=0xffffffff))])



class MessageEDNSExtendedRCODE(object):
    """
    An example of an EDNS message with an extended RCODE.
    """
    @classmethod
    def bytes(cls):
        """
        Bytes which are expected when encoding an instance constructed using
        C{kwargs} and which are expected to result in an identical instance when
        decoded.

        @return: The L{bytes} of a wire encoded message.
        """
        return (
            b'\x00\x00'
            b'\x00'
            b'\x0c' # RA: 0, Z, RCODE: 12
            b'\x00\x00'
            b'\x00\x00'
            b'\x00\x00'
            b'\x00\x01' # 1 additionals

            # Additional OPT record
            b'\x00'
            b'\x00\x29'
            b'\x10\x00'
            b'\xab' # Extended RCODE: 171
            b'\x00'
            b'\x00\x00'
            b'\x00\x00'
        )


    @classmethod
    def kwargs(cls):
        """
        Keyword constructor arguments which are expected to result in an
        instance which returns C{bytes} when encoded.

        @return: A L{dict} of keyword arguments.
        """
        return dict(
            id=0,
            answer=False,
            opCode=dns.OP_QUERY,
            auth=False,
            trunc=False,
            recDes=False,
            recAv=False,
            rCode=0xabc, # Combined OPT extended RCODE + Message RCODE
            ednsVersion=0,
            dnssecOK=False,
            maxSize=4096,
            queries=[],
            answers=[],
            authority=[],
            additional=[],
        )



class MessageComparable(FancyEqMixin, FancyStrMixin, object):
    """
    A wrapper around L{dns.Message} which is comparable so that it can be tested
    using some of the L{dns._EDNSMessage} tests.
    """
    showAttributes = compareAttributes = (
        'id', 'answer', 'opCode', 'auth', 'trunc',
        'recDes', 'recAv', 'rCode',
        'queries', 'answers', 'authority', 'additional')

    def __init__(self, original):
        self.original = original


    def __getattr__(self, key):
        return getattr(self.original, key)



def verifyConstructorArgument(testCase, cls, argName, defaultVal, altVal,
                              attrName=None):
    """
    Verify that an attribute has the expected default value and that a
    corresponding argument passed to a constructor is assigned to that
    attribute.

    @param testCase: The L{TestCase} whose assert methods will be
        called.
    @type testCase: L{unittest.TestCase}

    @param cls: The constructor under test.
    @type cls: L{type}

    @param argName: The name of the constructor argument under test.
    @type argName: L{str}

    @param defaultVal: The expected default value of C{attrName} /
        C{argName}
    @type defaultVal: L{object}

    @param altVal: A value which is different from the default. Used to
        test that supplied constructor arguments are actually assigned to the
        correct attribute.
    @type altVal: L{object}

    @param attrName: The name of the attribute under test if different
        from C{argName}. Defaults to C{argName}
    @type attrName: L{str}
    """
    if attrName is None:
        attrName = argName

    actual = {}
    expected = {'defaultVal': defaultVal, 'altVal': altVal}

    o = cls()
    actual['defaultVal'] = getattr(o, attrName)

    o = cls(**{argName: altVal})
    actual['altVal'] = getattr(o, attrName)

    testCase.assertEqual(expected, actual)



class ConstructorTestsMixin(object):
    """
    Helper methods for verifying default attribute values and corresponding
    constructor arguments.
    """
    def _verifyConstructorArgument(self, argName, defaultVal, altVal):
        """
        Wrap L{verifyConstructorArgument} to provide simpler interface for
        testing Message and _EDNSMessage constructor arguments.

        @param argName: The name of the constructor argument.
        @param defaultVal: The expected default value.
        @param altVal: An alternative value which is expected to be assigned to
            a correspondingly named attribute.
        """
        verifyConstructorArgument(testCase=self, cls=self.messageFactory,
                                  argName=argName, defaultVal=defaultVal,
                                  altVal=altVal)


    def _verifyConstructorFlag(self, argName, defaultVal):
        """
        Wrap L{verifyConstructorArgument} to provide simpler interface for
        testing  _EDNSMessage constructor flags.

        @param argName: The name of the constructor flag argument
        @param defaultVal: The expected default value of the flag
        """
        assert defaultVal in (True, False)
        verifyConstructorArgument(testCase=self, cls=self.messageFactory,
                                  argName=argName, defaultVal=defaultVal,
                                  altVal=not defaultVal,)



class CommonConstructorTestsMixin(object):
    """
    Tests for constructor arguments and their associated attributes that are
    common to both L{twisted.names.dns._EDNSMessage} and L{dns.Message}.

    TestCase classes that use this mixin must provide a C{messageFactory} method
    which accepts any argment supported by L{dns.Message.__init__}.

    TestCases must also mixin ConstructorTestsMixin which provides some custom
    assertions for testing constructor arguments.
    """
    def test_id(self):
        """
        L{dns._EDNSMessage.id} defaults to C{0} and can be overridden in
        the constructor.
        """
        self._verifyConstructorArgument('id', defaultVal=0, altVal=1)


    def test_answer(self):
        """
        L{dns._EDNSMessage.answer} defaults to C{False} and can be overridden in
        the constructor.
        """
        self._verifyConstructorFlag('answer', defaultVal=False)


    def test_opCode(self):
        """
        L{dns._EDNSMessage.opCode} defaults to L{dns.OP_QUERY} and can be
        overridden in the constructor.
        """
        self._verifyConstructorArgument(
            'opCode', defaultVal=dns.OP_QUERY, altVal=dns.OP_STATUS)


    def test_auth(self):
        """
        L{dns._EDNSMessage.auth} defaults to C{False} and can be overridden in
        the constructor.
        """
        self._verifyConstructorFlag('auth', defaultVal=False)


    def test_trunc(self):
        """
        L{dns._EDNSMessage.trunc} defaults to C{False} and can be overridden in
        the constructor.
        """
        self._verifyConstructorFlag('trunc', defaultVal=False)


    def test_recDes(self):
        """
        L{dns._EDNSMessage.recDes} defaults to C{False} and can be overridden in
        the constructor.
        """
        self._verifyConstructorFlag('recDes', defaultVal=False)


    def test_recAv(self):
        """
        L{dns._EDNSMessage.recAv} defaults to C{False} and can be overridden in
        the constructor.
        """
        self._verifyConstructorFlag('recAv', defaultVal=False)


    def test_rCode(self):
        """
        L{dns._EDNSMessage.rCode} defaults to C{0} and can be overridden in the
        constructor.
        """
        self._verifyConstructorArgument('rCode', defaultVal=0, altVal=123)


    def test_maxSize(self):
        """
        L{dns._EDNSMessage.maxSize} defaults to C{512} and can be overridden in
        the constructor.
        """
        self._verifyConstructorArgument('maxSize', defaultVal=512, altVal=1024)


    def test_queries(self):
        """
        L{dns._EDNSMessage.queries} defaults to C{[]}.
        """
        self.assertEqual(self.messageFactory().queries, [])


    def test_answers(self):
        """
        L{dns._EDNSMessage.answers} defaults to C{[]}.
        """
        self.assertEqual(self.messageFactory().answers, [])


    def test_authority(self):
        """
        L{dns._EDNSMessage.authority} defaults to C{[]}.
        """
        self.assertEqual(self.messageFactory().authority, [])


    def test_additional(self):
        """
        L{dns._EDNSMessage.additional} defaults to C{[]}.
        """
        self.assertEqual(self.messageFactory().additional, [])



class EDNSMessageConstructorTests(ConstructorTestsMixin,
                                  CommonConstructorTestsMixin,
                                  unittest.SynchronousTestCase):
    """
    Tests for L{twisted.names.dns._EDNSMessage} constructor arguments that are
    shared with L{dns.Message}.
    """
    messageFactory = dns._EDNSMessage



class MessageConstructorTests(ConstructorTestsMixin,
                               CommonConstructorTestsMixin,
                               unittest.SynchronousTestCase):
    """
    Tests for L{twisted.names.dns.Message} constructor arguments that are shared
    with L{dns._EDNSMessage}.
    """
    messageFactory = dns.Message



class EDNSMessageSpecificsTestCase(ConstructorTestsMixin,
                                   unittest.SynchronousTestCase):
    """
    Tests for L{dns._EDNSMessage}.

    These tests are for L{dns._EDNSMessage} APIs which are not shared with
    L{dns.Message}.
    """
    messageFactory = dns._EDNSMessage

    def test_ednsVersion(self):
        """
        L{dns._EDNSMessage.ednsVersion} defaults to C{0} and can be overridden
        in the constructor.
        """
        self._verifyConstructorArgument(
            'ednsVersion', defaultVal=0, altVal=None)


    def test_dnssecOK(self):
        """
        L{dns._EDNSMessage.dnssecOK} defaults to C{False} and can be overridden
        in the constructor.
        """
        self._verifyConstructorFlag('dnssecOK', defaultVal=False)


    def test_authenticData(self):
        """
        L{dns._EDNSMessage.authenticData} defaults to C{False} and can be
        overridden in the constructor.
        """
        self._verifyConstructorFlag('authenticData', defaultVal=False)


    def test_checkingDisabled(self):
        """
        L{dns._EDNSMessage.checkingDisabled} defaults to C{False} and can be
        overridden in the constructor.
        """
        self._verifyConstructorFlag('checkingDisabled', defaultVal=False)


    def test_queriesOverride(self):
        """
        L{dns._EDNSMessage.queries} can be overridden in the constructor.
        """
        msg = self.messageFactory(queries=[dns.Query(b'example.com')])

        self.assertEqual(
            msg.queries,
            [dns.Query(b'example.com')])


    def test_answersOverride(self):
        """
        L{dns._EDNSMessage.answers} can be overridden in the constructor.
        """
        msg = self.messageFactory(
            answers=[
                dns.RRHeader(
                    b'example.com',
                    payload=dns.Record_A('1.2.3.4'))])

        self.assertEqual(
            msg.answers,
            [dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4'))])


    def test_authorityOverride(self):
        """
        L{dns._EDNSMessage.authority} can be overridden in the constructor.
        """
        msg = self.messageFactory(
            authority=[
                dns.RRHeader(
                    b'example.com',
                    type=dns.SOA,
                    payload=dns.Record_SOA())])

        self.assertEqual(
            msg.authority,
            [dns.RRHeader(b'example.com', type=dns.SOA,
                          payload=dns.Record_SOA())])


    def test_additionalOverride(self):
        """
        L{dns._EDNSMessage.authority} can be overridden in the constructor.
        """
        msg = self.messageFactory(
            additional=[
                dns.RRHeader(
                    b'example.com',
                    payload=dns.Record_A('1.2.3.4'))])

        self.assertEqual(
            msg.additional,
            [dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4'))])


    def test_reprDefaults(self):
        """
        L{dns._EDNSMessage.__repr__} omits field values and sections which are
        identical to their defaults. The id field value is always shown.
        """
        self.assertEqual(
            '<_EDNSMessage id=0>',
            repr(self.messageFactory())
        )


    def test_reprFlagsIfSet(self):
        """
        L{dns._EDNSMessage.__repr__} displays flags if they are L{True}.
        """
        m = self.messageFactory(answer=True, auth=True, trunc=True, recDes=True,
                                recAv=True, authenticData=True,
                                checkingDisabled=True, dnssecOK=True)
        self.assertEqual(
            '<_EDNSMessage '
            'id=0 '
            'flags=answer,auth,trunc,recDes,recAv,authenticData,'
            'checkingDisabled,dnssecOK'
            '>',
            repr(m),
        )


    def test_reprNonDefautFields(self):
        """
        L{dns._EDNSMessage.__repr__} displays field values if they differ from
        their defaults.
        """
        m = self.messageFactory(id=10, opCode=20, rCode=30, maxSize=40,
                                ednsVersion=50)
        self.assertEqual(
            '<_EDNSMessage '
            'id=10 '
            'opCode=20 '
            'rCode=30 '
            'maxSize=40 '
            'ednsVersion=50'
            '>',
            repr(m),
        )


    def test_reprNonDefaultSections(self):
        """
        L{dns.Message.__repr__} displays sections which differ from their
        defaults.
        """
        m = self.messageFactory()
        m.queries = [1, 2, 3]
        m.answers = [4, 5, 6]
        m.authority = [7, 8, 9]
        m.additional = [10, 11, 12]
        self.assertEqual(
            '<_EDNSMessage '
            'id=0 '
            'queries=[1, 2, 3] '
            'answers=[4, 5, 6] '
            'authority=[7, 8, 9] '
            'additional=[10, 11, 12]'
            '>',
            repr(m),
        )


    def test_fromStrCallsMessageFactory(self):
        """
        L{dns._EDNSMessage.fromString} calls L{dns._EDNSMessage._messageFactory}
        to create a new L{dns.Message} instance which is used to decode the
        supplied bytes.
        """
        class FakeMessageFactory(object):
            """
            Fake message factory.
            """
            def fromStr(self, *args, **kwargs):
                """
                Fake fromStr method which raises the arguments it was passed.

                @param args: positional arguments
                @param kwargs: keyword arguments
                """
                raise RaisedArgs(args, kwargs)

        m = dns._EDNSMessage()
        m._messageFactory = FakeMessageFactory
        dummyBytes = object()
        e = self.assertRaises(RaisedArgs, m.fromStr, dummyBytes)
        self.assertEqual(
            ((dummyBytes,), {}),
            (e.args, e.kwargs)
        )


    def test_fromStrCallsFromMessage(self):
        """
        L{dns._EDNSMessage.fromString} calls L{dns._EDNSMessage._fromMessage}
        with a L{dns.Message} instance
        """
        m = dns._EDNSMessage()
        class FakeMessageFactory():
            """
            Fake message factory.
            """
            def fromStr(self, bytes):
                """
                A noop fake version of fromStr

                @param bytes: the bytes to be decoded
                """

        fakeMessage = FakeMessageFactory()
        m._messageFactory = lambda: fakeMessage

        def fakeFromMessage(*args, **kwargs):
            raise RaisedArgs(args, kwargs)
        m._fromMessage = fakeFromMessage
        e = self.assertRaises(RaisedArgs, m.fromStr, b'')
        self.assertEqual(
            ((fakeMessage,), {}),
            (e.args, e.kwargs)
        )


    def test_toStrCallsToMessage(self):
        """
        L{dns._EDNSMessage.toStr} calls L{dns._EDNSMessage._toMessage}
        """
        m = dns._EDNSMessage()
        def fakeToMessage(*args, **kwargs):
            raise RaisedArgs(args, kwargs)
        m._toMessage = fakeToMessage
        e = self.assertRaises(RaisedArgs, m.toStr)
        self.assertEqual(
            ((), {}),
            (e.args, e.kwargs)
        )


    def test_toStrCallsToMessageToStr(self):
        """
        L{dns._EDNSMessage.toStr} calls C{toStr} on the message returned by
        L{dns._EDNSMessage._toMessage}.
        """
        m = dns._EDNSMessage()
        dummyBytes = object()
        class FakeMessage(object):
            """
            Fake Message
            """
            def toStr(self):
                """
                Fake toStr which returns dummyBytes.

                @return: dummyBytes
                """
                return dummyBytes

        def fakeToMessage(*args, **kwargs):
            return FakeMessage()
        m._toMessage = fakeToMessage

        self.assertEqual(
            dummyBytes,
            m.toStr()
        )



class EDNSMessageEqualityTests(ComparisonTestsMixin, unittest.SynchronousTestCase):
    """
    Tests for equality between L(dns._EDNSMessage} instances.

    These tests will not work with L{dns.Message} because it does not use
    L{twisted.python.util.FancyEqMixin}.
    """

    messageFactory = dns._EDNSMessage

    def test_id(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        id.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(id=1),
            self.messageFactory(id=1),
            self.messageFactory(id=2),
            )


    def test_answer(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        answer flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(answer=True),
            self.messageFactory(answer=True),
            self.messageFactory(answer=False),
            )


    def test_opCode(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        opCode.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(opCode=dns.OP_STATUS),
            self.messageFactory(opCode=dns.OP_STATUS),
            self.messageFactory(opCode=dns.OP_INVERSE),
            )


    def test_auth(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        auth flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(auth=True),
            self.messageFactory(auth=True),
            self.messageFactory(auth=False),
            )


    def test_trunc(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        trunc flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(trunc=True),
            self.messageFactory(trunc=True),
            self.messageFactory(trunc=False),
            )


    def test_recDes(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        recDes flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(recDes=True),
            self.messageFactory(recDes=True),
            self.messageFactory(recDes=False),
            )


    def test_recAv(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        recAv flag.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(recAv=True),
            self.messageFactory(recAv=True),
            self.messageFactory(recAv=False),
            )


    def test_rCode(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        rCode.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(rCode=16),
            self.messageFactory(rCode=16),
            self.messageFactory(rCode=15),
            )


    def test_ednsVersion(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        ednsVersion.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(ednsVersion=1),
            self.messageFactory(ednsVersion=1),
            self.messageFactory(ednsVersion=None),
            )


    def test_dnssecOK(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        dnssecOK.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(dnssecOK=True),
            self.messageFactory(dnssecOK=True),
            self.messageFactory(dnssecOK=False),
            )


    def test_authenticData(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        authenticData flags.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(authenticData=True),
            self.messageFactory(authenticData=True),
            self.messageFactory(authenticData=False),
            )


    def test_checkingDisabled(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        checkingDisabled flags.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(checkingDisabled=True),
            self.messageFactory(checkingDisabled=True),
            self.messageFactory(checkingDisabled=False),
            )


    def test_maxSize(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        maxSize.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(maxSize=2048),
            self.messageFactory(maxSize=2048),
            self.messageFactory(maxSize=1024),
            )


    def test_queries(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        queries.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(queries=[dns.Query(b'example.com')]),
            self.messageFactory(queries=[dns.Query(b'example.com')]),
            self.messageFactory(queries=[dns.Query(b'example.org')]),
            )


    def test_answers(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        answers.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(answers=[dns.RRHeader(
                        b'example.com', payload=dns.Record_A('1.2.3.4'))]),
            self.messageFactory(answers=[dns.RRHeader(
                        b'example.com', payload=dns.Record_A('1.2.3.4'))]),
            self.messageFactory(answers=[dns.RRHeader(
                        b'example.org', payload=dns.Record_A('4.3.2.1'))]),
            )


    def test_authority(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        authority records.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(authority=[dns.RRHeader(
                        b'example.com',
                        type=dns.SOA, payload=dns.Record_SOA())]),
            self.messageFactory(authority=[dns.RRHeader(
                        b'example.com',
                        type=dns.SOA, payload=dns.Record_SOA())]),
            self.messageFactory(authority=[dns.RRHeader(
                        b'example.org',
                        type=dns.SOA, payload=dns.Record_SOA())]),
            )


    def test_additional(self):
        """
        Two L{dns._EDNSMessage} instances compare equal if they have the same
        additional records.
        """
        self.assertNormalEqualityImplementation(
            self.messageFactory(additional=[dns.RRHeader(
                        b'example.com', payload=dns.Record_A('1.2.3.4'))]),
            self.messageFactory(additional=[dns.RRHeader(
                        b'example.com', payload=dns.Record_A('1.2.3.4'))]),
            self.messageFactory(additional=[dns.RRHeader(
                        b'example.org', payload=dns.Record_A('1.2.3.4'))]),
            )



class StandardEncodingTestsMixin(object):
    """
    Tests for the encoding and decoding of various standard (not EDNS) messages.

    These tests should work with both L{dns._EDNSMessage} and L{dns.Message}.

    TestCase classes that use this mixin must provide a C{messageFactory} method
    which accepts any argment supported by L{dns._EDNSMessage.__init__}.

    EDNS specific arguments may be discarded if not supported by the message
    class under construction.
    """
    def test_emptyMessageEncode(self):
        """
        An empty message can be encoded.
        """
        self.assertEqual(
            self.messageFactory(**MessageEmpty.kwargs()).toStr(),
            MessageEmpty.bytes())


    def test_emptyMessageDecode(self):
        """
        An empty message byte sequence can be decoded.
        """
        m = self.messageFactory()
        m.fromStr(MessageEmpty.bytes())

        self.assertEqual(m, self.messageFactory(**MessageEmpty.kwargs()))


    def test_completeQueryEncode(self):
        """
        A fully populated query message can be encoded.
        """
        self.assertEqual(
            self.messageFactory(**MessageComplete.kwargs()).toStr(),
            MessageComplete.bytes())


    def test_completeQueryDecode(self):
        """
        A fully populated message byte string can be decoded.
        """
        m = self.messageFactory()
        m.fromStr(MessageComplete.bytes()),

        self.assertEqual(m, self.messageFactory(**MessageComplete.kwargs()))


    def test_NULL(self):
        """
        A I{NULL} record with an arbitrary payload can be encoded and decoded as
        part of a message.
        """
        bytes = b''.join([dns._ord2bytes(i) for i in range(256)])
        rec = dns.Record_NULL(bytes)
        rr = dns.RRHeader(b'testname', dns.NULL, payload=rec)
        msg1 = self.messageFactory()
        msg1.answers.append(rr)
        s = msg1.toStr()

        msg2 = self.messageFactory()
        msg2.fromStr(s)

        self.assertIsInstance(msg2.answers[0].payload, dns.Record_NULL)
        self.assertEqual(msg2.answers[0].payload.payload, bytes)


    def test_nonAuthoritativeMessageEncode(self):
        """
        If the message C{authoritative} attribute is set to 0, the encoded bytes
        will have AA bit 0.
        """
        self.assertEqual(
            self.messageFactory(**MessageNonAuthoritative.kwargs()).toStr(),
            MessageNonAuthoritative.bytes())


    def test_nonAuthoritativeMessageDecode(self):
        """
        The L{dns.RRHeader} instances created by a message from a
        non-authoritative message byte string are marked as not authoritative.
        """
        m = self.messageFactory()
        m.fromStr(MessageNonAuthoritative.bytes())

        self.assertEqual(
            m, self.messageFactory(**MessageNonAuthoritative.kwargs()))


    def test_authoritativeMessageEncode(self):
        """
        If the message C{authoritative} attribute is set to 1, the encoded bytes
        will have AA bit 1.
        """
        self.assertEqual(
            self.messageFactory(**MessageAuthoritative.kwargs()).toStr(),
            MessageAuthoritative.bytes())


    def test_authoritativeMessageDecode(self):
        """
        The message and its L{dns.RRHeader} instances created by C{decode} from
        an authoritative message byte string, are marked as authoritative.
        """
        m = self.messageFactory()
        m.fromStr(MessageAuthoritative.bytes())

        self.assertEqual(
            m, self.messageFactory(**MessageAuthoritative.kwargs()))


    def test_truncatedMessageEncode(self):
        """
        If the message C{trunc} attribute is set to 1 the encoded bytes will
        have TR bit 1.
        """
        self.assertEqual(
            self.messageFactory(**MessageTruncated.kwargs()).toStr(),
            MessageTruncated.bytes())


    def test_truncatedMessageDecode(self):
        """
        The message instance created by decoding a truncated message is marked
        as truncated.
        """
        m = self.messageFactory()
        m.fromStr(MessageTruncated.bytes())

        self.assertEqual(m, self.messageFactory(**MessageTruncated.kwargs()))



class EDNSMessageStandardEncodingTests(StandardEncodingTestsMixin,
                                       unittest.SynchronousTestCase):
    """
    Tests for the encoding and decoding of various standard (non-EDNS) messages
    by L{dns._EDNSMessage}.
    """
    messageFactory = dns._EDNSMessage



class MessageStandardEncodingTests(StandardEncodingTestsMixin,
                                   unittest.SynchronousTestCase):
    """
    Tests for the encoding and decoding of various standard (non-EDNS) messages
    by L{dns.Message}.
    """
    @staticmethod
    def messageFactory(**kwargs):
        """
        This function adapts constructor arguments expected by
        _EDNSMessage.__init__ to arguments suitable for use with the
        Message.__init__.

        Also handles the fact that unlike L{dns._EDNSMessage},
        L{dns.Message.__init__} does not accept queries, answers etc as
        arguments.

        Also removes any L{dns._EDNSMessage} specific arguments.

        @param args: The positional arguments which will be passed to
            L{dns.Message.__init__}.

        @param kwargs: The keyword arguments which will be stripped of EDNS
            specific arguments before being passed to L{dns.Message.__init__}.

        @return: An L{dns.Message} instance.
        """
        queries = kwargs.pop('queries', [])
        answers = kwargs.pop('answers', [])
        authority = kwargs.pop('authority', [])
        additional = kwargs.pop('additional', [])

        kwargs.pop('ednsVersion', None)

        m = dns.Message(**kwargs)
        m.queries = queries
        m.answers = answers
        m.authority = authority
        m.additional = additional
        return MessageComparable(m)



class EDNSMessageEDNSEncodingTests(unittest.SynchronousTestCase):
    """
    Tests for the encoding and decoding of various EDNS messages.

    These test will not work with L{dns.Message}.
    """
    messageFactory = dns._EDNSMessage

    def test_ednsMessageDecodeStripsOptRecords(self):
        """
        The L(_EDNSMessage} instance created by L{dns._EDNSMessage.decode} from
        an EDNS query never includes OPT records in the additional section.
        """
        m = self.messageFactory()
        m.fromStr(MessageEDNSQuery.bytes())

        self.assertEqual(m.additional, [])


    def test_ednsMessageDecodeMultipleOptRecords(self):
        """
        An L(_EDNSMessage} instance created from a byte string containing
        multiple I{OPT} records will discard all the C{OPT} records.

        C{ednsVersion} will be set to C{None}.

        @see: U{https://tools.ietf.org/html/rfc6891#section-6.1.1}
        """
        m = dns.Message()
        m.additional = [
            dns._OPTHeader(version=2),
            dns._OPTHeader(version=3)]

        ednsMessage = dns._EDNSMessage()
        ednsMessage.fromStr(m.toStr())

        self.assertEqual(ednsMessage.ednsVersion, None)


    def test_fromMessageCopiesSections(self):
        """
        L{dns._EDNSMessage._fromMessage} returns an L{_EDNSMessage} instance
        whose queries, answers, authority and additional lists are copies (not
        references to) the original message lists.
        """
        standardMessage = dns.Message()
        standardMessage.fromStr(MessageEDNSQuery.bytes())

        ednsMessage = dns._EDNSMessage._fromMessage(standardMessage)

        duplicates = []
        for attrName in ('queries', 'answers', 'authority', 'additional'):
            if (getattr(standardMessage, attrName)
                is getattr(ednsMessage, attrName)):
                duplicates.append(attrName)

        if duplicates:
            self.fail(
                'Message and _EDNSMessage shared references to the following '
                'section lists after decoding: %s' % (duplicates,))


    def test_toMessageCopiesSections(self):
        """
        L{dns._EDNSMessage.toStr} makes no in place changes to the message
        instance.
        """
        ednsMessage = dns._EDNSMessage(ednsVersion=1)
        ednsMessage.toStr()
        self.assertEqual(ednsMessage.additional, [])


    def test_optHeaderPosition(self):
        """
        L{dns._EDNSMessage} can decode OPT records, regardless of their position
        in the additional records section.

        "The OPT RR MAY be placed anywhere within the additional data section."

        @see: U{https://tools.ietf.org/html/rfc6891#section-6.1.1}
        """
        # XXX: We need an _OPTHeader.toRRHeader method. See #6779.
        b = BytesIO()
        optRecord = dns._OPTHeader(version=1)
        optRecord.encode(b)
        optRRHeader = dns.RRHeader()
        b.seek(0)
        optRRHeader.decode(b)
        m = dns.Message()
        m.additional = [optRRHeader]

        actualMessages = []
        actualMessages.append(dns._EDNSMessage._fromMessage(m).ednsVersion)

        m.additional.append(dns.RRHeader(type=dns.A))
        actualMessages.append(
            dns._EDNSMessage._fromMessage(m).ednsVersion)

        m.additional.insert(0, dns.RRHeader(type=dns.A))
        actualMessages.append(
            dns._EDNSMessage._fromMessage(m).ednsVersion)

        self.assertEqual(
            [1] * 3,
            actualMessages
        )


    def test_ednsDecode(self):
        """
        The L(_EDNSMessage} instance created by L{dns._EDNSMessage.fromStr}
        derives its edns specific values (C{ednsVersion}, etc) from the supplied
        OPT record.
        """
        m = self.messageFactory()
        m.fromStr(MessageEDNSComplete.bytes())

        self.assertEqual(m, self.messageFactory(**MessageEDNSComplete.kwargs()))


    def test_ednsEncode(self):
        """
        The L(_EDNSMessage} instance created by L{dns._EDNSMessage.toStr}
        encodes its edns specific values (C{ednsVersion}, etc) into an OPT
        record added to the additional section.
        """
        self.assertEqual(
            self.messageFactory(**MessageEDNSComplete.kwargs()).toStr(),
            MessageEDNSComplete.bytes())


    def test_extendedRcodeEncode(self):
        """
        The L(_EDNSMessage.toStr} encodes the extended I{RCODE} (>=16) by
        assigning the lower 4bits to the message RCODE field and the upper 4bits
        to the OPT pseudo record.
        """
        self.assertEqual(
            self.messageFactory(**MessageEDNSExtendedRCODE.kwargs()).toStr(),
            MessageEDNSExtendedRCODE.bytes())


    def test_extendedRcodeDecode(self):
        """
        The L(_EDNSMessage} instance created by L{dns._EDNSMessage.fromStr}
        derives RCODE from the supplied OPT record.
        """
        m = self.messageFactory()
        m.fromStr(MessageEDNSExtendedRCODE.bytes())

        self.assertEqual(
            m, self.messageFactory(**MessageEDNSExtendedRCODE.kwargs()))


    def test_extendedRcodeZero(self):
        """
        Note that EXTENDED-RCODE value 0 indicates that an unextended RCODE is
        in use (values 0 through 15).

        https://tools.ietf.org/html/rfc6891#section-6.1.3
        """
        ednsMessage = self.messageFactory(rCode=15, ednsVersion=0)
        standardMessage = ednsMessage._toMessage()

        self.assertEqual(
            (15, 0),
            (standardMessage.rCode, standardMessage.additional[0].extendedRCODE)
        )



class ResponseFromMessageTests(unittest.SynchronousTestCase):
    """
    Tests for L{dns._responseFromMessage}.
    """
    def test_responseFromMessageResponseType(self):
        """
        L{dns.Message._responseFromMessage} is a constructor function which
        generates a new I{answer} message from an existing L{dns.Message} like
        instance.
        """
        request = dns.Message()
        response = dns._responseFromMessage(responseConstructor=dns.Message,
                                            message=request)
        self.assertIsNot(request, response)


    def test_responseType(self):
        """
        L{dns._responseFromMessage} returns a new instance of C{cls}
        """
        class SuppliedClass(object):
            id = 1
            queries = []

        expectedClass = dns.Message

        self.assertIsInstance(
            dns._responseFromMessage(responseConstructor=expectedClass,
                                     message=SuppliedClass()),
            expectedClass
        )


    def test_responseId(self):
        """
        L{dns._responseFromMessage} copies the C{id} attribute of the original
        message.
        """
        self.assertEqual(
            1234,
            dns._responseFromMessage(responseConstructor=dns.Message,
                                     message=dns.Message(id=1234)).id
        )


    def test_responseAnswer(self):
        """
        L{dns._responseFromMessage} sets the C{answer} flag to L{True}
        """
        request = dns.Message()
        response = dns._responseFromMessage(responseConstructor=dns.Message,
                                            message=request)
        self.assertEqual(
            (False, True),
            (request.answer, response.answer)
        )


    def test_responseQueries(self):
        """
        L{dns._responseFromMessage} copies the C{queries} attribute of the
        original message.
        """
        request = dns.Message()
        expectedQueries = [object(), object(), object()]
        request.queries = expectedQueries[:]

        self.assertEqual(
            expectedQueries,
            dns._responseFromMessage(responseConstructor=dns.Message,
                                     message=request).queries
        )


    def test_responseKwargs(self):
        """
        L{dns._responseFromMessage} accepts other C{kwargs} which are assigned
        to the new message before it is returned.
        """
        self.assertEqual(
            123,
            dns._responseFromMessage(
                responseConstructor=dns.Message, message=dns.Message(),
                rCode=123).rCode
        )



class Foo(object):
    """
    An example class for use in L{dns._compactRepr} tests.
    It follows the pattern of initialiser settable flags, fields and sections
    found in L{dns.Message} and L{dns._EDNSMessage}.
    """
    def __init__(self,
                 field1=1, field2=2, alwaysShowField='AS',
                 flagTrue=True, flagFalse=False, section1=None):
        """
        Set some flags, fields and sections as public attributes.
        """
        self.field1 = field1
        self.field2 = field2
        self.alwaysShowField = alwaysShowField
        self.flagTrue = flagTrue
        self.flagFalse = flagFalse

        if section1 is None:
            section1 = []
        self.section1 = section1


    def __repr__(self):
        """
        Call L{dns._compactRepr} to generate a string representation.
        """
        return dns._compactRepr(
            self,
            alwaysShow='alwaysShowField'.split(),
            fieldNames='field1 field2 alwaysShowField'.split(),
            flagNames='flagTrue flagFalse'.split(),
            sectionNames='section1 section2'.split()
        )



class CompactReprTests(unittest.SynchronousTestCase):
    """
    Tests for L[dns._compactRepr}.
    """
    messageFactory = Foo
    def test_defaults(self):
        """
        L{dns._compactRepr} omits field values and sections which have the
        default value. Flags which are True are always shown.
        """
        self.assertEqual(
            "<Foo alwaysShowField='AS' flags=flagTrue>",
            repr(self.messageFactory())
        )


    def test_flagsIfSet(self):
        """
        L{dns._compactRepr} displays flags if they have a non-default value.
        """
        m = self.messageFactory(flagTrue=True, flagFalse=True)
        self.assertEqual(
            '<Foo '
            "alwaysShowField='AS' "
            'flags=flagTrue,flagFalse'
            '>',
            repr(m),
        )


    def test_nonDefautFields(self):
        """
        L{dns._compactRepr} displays field values if they differ from their
        defaults.
        """
        m = self.messageFactory(field1=10, field2=20)
        self.assertEqual(
            '<Foo '
            'field1=10 '
            'field2=20 '
            "alwaysShowField='AS' "
            'flags=flagTrue'
            '>',
            repr(m),
        )


    def test_nonDefaultSections(self):
        """
        L{dns._compactRepr} displays sections which differ from their defaults.
        """
        m = self.messageFactory()
        m.section1 = [1, 1, 1]
        m.section2 = [2, 2, 2]
        self.assertEqual(
            '<Foo '
            "alwaysShowField='AS' "
            'flags=flagTrue '
            'section1=[1, 1, 1] '
            'section2=[2, 2, 2]'
            '>',
            repr(m),
        )