This file is indexed.

/usr/lib/python2.7/dist-packages/twisted/names/test/test_names.py is in python-twisted-names 13.2.0-1ubuntu1.2.

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
# -*- test-case-name: twisted.names.test.test_names -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Test cases for twisted.names.
"""

import socket, operator, copy
from StringIO import StringIO
from functools import partial, reduce

from twisted.trial import unittest

from twisted.internet import reactor, defer, error
from twisted.internet.defer import succeed
from twisted.names import client, server, common, authority, dns
from twisted.names.dns import Message
from twisted.names.error import DomainError
from twisted.names.client import Resolver
from twisted.names.secondary import (
    SecondaryAuthorityService, SecondaryAuthority)

from twisted.test.proto_helpers import StringTransport, MemoryReactorClock

def justPayload(results):
    return [r.payload for r in results[0]]

class NoFileAuthority(authority.FileAuthority):
    def __init__(self, soa, records):
        # Yes, skip FileAuthority
        common.ResolverBase.__init__(self)
        self.soa, self.records = soa, records


soa_record = dns.Record_SOA(
                    mname = 'test-domain.com',
                    rname = 'root.test-domain.com',
                    serial = 100,
                    refresh = 1234,
                    minimum = 7654,
                    expire = 19283784,
                    retry = 15,
                    ttl=1
                )

reverse_soa = dns.Record_SOA(
                     mname = '93.84.28.in-addr.arpa',
                     rname = '93.84.28.in-addr.arpa',
                     serial = 120,
                     refresh = 54321,
                     minimum = 382,
                     expire = 11193983,
                     retry = 30,
                     ttl=3
                )

my_soa = dns.Record_SOA(
    mname = 'my-domain.com',
    rname = 'postmaster.test-domain.com',
    serial = 130,
    refresh = 12345,
    minimum = 1,
    expire = 999999,
    retry = 100,
    )

test_domain_com = NoFileAuthority(
    soa = ('test-domain.com', soa_record),
    records = {
        'test-domain.com': [
            soa_record,
            dns.Record_A('127.0.0.1'),
            dns.Record_NS('39.28.189.39'),
            dns.Record_SPF('v=spf1 mx/30 mx:example.org/30 -all'),
            dns.Record_SPF('v=spf1 +mx a:\0colo', '.example.com/28 -all not valid'),
            dns.Record_MX(10, 'host.test-domain.com'),
            dns.Record_HINFO(os='Linux', cpu='A Fast One, Dontcha know'),
            dns.Record_CNAME('canonical.name.com'),
            dns.Record_MB('mailbox.test-domain.com'),
            dns.Record_MG('mail.group.someplace'),
            dns.Record_TXT('A First piece of Text', 'a SecoNd piece'),
            dns.Record_A6(0, 'ABCD::4321', ''),
            dns.Record_A6(12, '0:0069::0', 'some.network.tld'),
            dns.Record_A6(8, '0:5634:1294:AFCB:56AC:48EF:34C3:01FF', 'tra.la.la.net'),
            dns.Record_TXT('Some more text, haha!  Yes.  \0  Still here?'),
            dns.Record_MR('mail.redirect.or.whatever'),
            dns.Record_MINFO(rmailbx='r mail box', emailbx='e mail box'),
            dns.Record_AFSDB(subtype=1, hostname='afsdb.test-domain.com'),
            dns.Record_RP(mbox='whatever.i.dunno', txt='some.more.text'),
            dns.Record_WKS('12.54.78.12', socket.IPPROTO_TCP,
                           '\x12\x01\x16\xfe\xc1\x00\x01'),
            dns.Record_NAPTR(100, 10, "u", "sip+E2U",
                             "!^.*$!sip:information@domain.tld!"),
            dns.Record_AAAA('AF43:5634:1294:AFCB:56AC:48EF:34C3:01FF')],
        'http.tcp.test-domain.com': [
            dns.Record_SRV(257, 16383, 43690, 'some.other.place.fool')
        ],
        'host.test-domain.com': [
            dns.Record_A('123.242.1.5'),
            dns.Record_A('0.255.0.255'),
        ],
        'host-two.test-domain.com': [
#
#  Python bug
#           dns.Record_A('255.255.255.255'),
#
            dns.Record_A('255.255.255.254'),
            dns.Record_A('0.0.0.0')
        ],
        'cname.test-domain.com': [
            dns.Record_CNAME('test-domain.com')
        ],
        'anothertest-domain.com': [
            dns.Record_A('1.2.3.4')],
    }
)

reverse_domain = NoFileAuthority(
    soa = ('93.84.28.in-addr.arpa', reverse_soa),
    records = {
        '123.93.84.28.in-addr.arpa': [
             dns.Record_PTR('test.host-reverse.lookup.com'),
             reverse_soa
        ]
    }
)


my_domain_com = NoFileAuthority(
    soa = ('my-domain.com', my_soa),
    records = {
        'my-domain.com': [
            my_soa,
            dns.Record_A('1.2.3.4', ttl='1S'),
            dns.Record_NS('ns1.domain', ttl='2M'),
            dns.Record_NS('ns2.domain', ttl='3H'),
            dns.Record_SRV(257, 16383, 43690, 'some.other.place.fool', ttl='4D')
            ]
        }
    )


class ServerDNSTestCase(unittest.TestCase):
    """
    Test cases for DNS server and client.
    """

    def setUp(self):
        self.factory = server.DNSServerFactory([
            test_domain_com, reverse_domain, my_domain_com
        ], verbose=2)

        p = dns.DNSDatagramProtocol(self.factory)

        while 1:
            listenerTCP = reactor.listenTCP(0, self.factory, interface="127.0.0.1")
            # It's simpler to do the stop listening with addCleanup,
            # even though we might not end up using this TCP port in
            # the test (if the listenUDP below fails).  Cleaning up
            # this TCP port sooner than "cleanup time" would mean
            # adding more code to keep track of the Deferred returned
            # by stopListening.
            self.addCleanup(listenerTCP.stopListening)
            port = listenerTCP.getHost().port

            try:
                listenerUDP = reactor.listenUDP(port, p, interface="127.0.0.1")
            except error.CannotListenError:
                pass
            else:
                self.addCleanup(listenerUDP.stopListening)
                break

        self.listenerTCP = listenerTCP
        self.listenerUDP = listenerUDP
        self.resolver = client.Resolver(servers=[('127.0.0.1', port)])


    def tearDown(self):
        """
        Clean up any server connections associated with the
        L{DNSServerFactory} created in L{setUp}
        """
        # It'd be great if DNSServerFactory had a method that
        # encapsulated this task.  At least the necessary data is
        # available, though.
        for conn in self.factory.connections[:]:
            conn.transport.loseConnection()


    def namesTest(self, querying, expectedRecords):
        """
        Assert that the DNS response C{querying} will eventually fire with
        contains exactly a certain collection of records.

        @param querying: A L{Deferred} returned from one of the DNS client
            I{lookup} methods.

        @param expectedRecords: A L{list} of L{IRecord} providers which must be
            in the response or the test will be failed.

        @return: A L{Deferred} that fires when the assertion has been made.  It
            fires with a success result if the assertion succeeds and with a
            L{Failure} if it fails.
        """
        def checkResults(response):
            receivedRecords = justPayload(response)
            self.assertEqual(set(expectedRecords), set(receivedRecords))

        querying.addCallback(checkResults)
        return querying


    def testAddressRecord1(self):
        """Test simple DNS 'A' record queries"""
        return self.namesTest(
            self.resolver.lookupAddress('test-domain.com'),
            [dns.Record_A('127.0.0.1', ttl=19283784)]
        )


    def testAddressRecord2(self):
        """Test DNS 'A' record queries with multiple answers"""
        return self.namesTest(
            self.resolver.lookupAddress('host.test-domain.com'),
            [dns.Record_A('123.242.1.5', ttl=19283784), dns.Record_A('0.255.0.255', ttl=19283784)]
        )


    def testAddressRecord3(self):
        """Test DNS 'A' record queries with edge cases"""
        return self.namesTest(
            self.resolver.lookupAddress('host-two.test-domain.com'),
            [dns.Record_A('255.255.255.254', ttl=19283784), dns.Record_A('0.0.0.0', ttl=19283784)]
        )


    def testAuthority(self):
        """Test DNS 'SOA' record queries"""
        return self.namesTest(
            self.resolver.lookupAuthority('test-domain.com'),
            [soa_record]
        )


    def test_mailExchangeRecord(self):
        """
        The DNS client can issue an MX query and receive a response including
        an MX record as well as any A record hints.
        """
        return self.namesTest(
            self.resolver.lookupMailExchange(b"test-domain.com"),
            [dns.Record_MX(10, b"host.test-domain.com", ttl=19283784),
             dns.Record_A(b"123.242.1.5", ttl=19283784),
             dns.Record_A(b"0.255.0.255", ttl=19283784)])


    def testNameserver(self):
        """Test DNS 'NS' record queries"""
        return self.namesTest(
            self.resolver.lookupNameservers('test-domain.com'),
            [dns.Record_NS('39.28.189.39', ttl=19283784)]
        )


    def testHINFO(self):
        """Test DNS 'HINFO' record queries"""
        return self.namesTest(
            self.resolver.lookupHostInfo('test-domain.com'),
            [dns.Record_HINFO(os='Linux', cpu='A Fast One, Dontcha know', ttl=19283784)]
        )

    def testPTR(self):
        """Test DNS 'PTR' record queries"""
        return self.namesTest(
            self.resolver.lookupPointer('123.93.84.28.in-addr.arpa'),
            [dns.Record_PTR('test.host-reverse.lookup.com', ttl=11193983)]
        )


    def testCNAME(self):
        """Test DNS 'CNAME' record queries"""
        return self.namesTest(
            self.resolver.lookupCanonicalName('test-domain.com'),
            [dns.Record_CNAME('canonical.name.com', ttl=19283784)]
        )

    def testMB(self):
        """Test DNS 'MB' record queries"""
        return self.namesTest(
            self.resolver.lookupMailBox('test-domain.com'),
            [dns.Record_MB('mailbox.test-domain.com', ttl=19283784)]
        )


    def testMG(self):
        """Test DNS 'MG' record queries"""
        return self.namesTest(
            self.resolver.lookupMailGroup('test-domain.com'),
            [dns.Record_MG('mail.group.someplace', ttl=19283784)]
        )


    def testMR(self):
        """Test DNS 'MR' record queries"""
        return self.namesTest(
            self.resolver.lookupMailRename('test-domain.com'),
            [dns.Record_MR('mail.redirect.or.whatever', ttl=19283784)]
        )


    def testMINFO(self):
        """Test DNS 'MINFO' record queries"""
        return self.namesTest(
            self.resolver.lookupMailboxInfo('test-domain.com'),
            [dns.Record_MINFO(rmailbx='r mail box', emailbx='e mail box', ttl=19283784)]
        )


    def testSRV(self):
        """Test DNS 'SRV' record queries"""
        return self.namesTest(
            self.resolver.lookupService('http.tcp.test-domain.com'),
            [dns.Record_SRV(257, 16383, 43690, 'some.other.place.fool', ttl=19283784)]
        )

    def testAFSDB(self):
        """Test DNS 'AFSDB' record queries"""
        return self.namesTest(
            self.resolver.lookupAFSDatabase('test-domain.com'),
            [dns.Record_AFSDB(subtype=1, hostname='afsdb.test-domain.com', ttl=19283784)]
        )


    def testRP(self):
        """Test DNS 'RP' record queries"""
        return self.namesTest(
            self.resolver.lookupResponsibility('test-domain.com'),
            [dns.Record_RP(mbox='whatever.i.dunno', txt='some.more.text', ttl=19283784)]
        )


    def testTXT(self):
        """Test DNS 'TXT' record queries"""
        return self.namesTest(
            self.resolver.lookupText('test-domain.com'),
            [dns.Record_TXT('A First piece of Text', 'a SecoNd piece', ttl=19283784),
             dns.Record_TXT('Some more text, haha!  Yes.  \0  Still here?', ttl=19283784)]
        )


    def test_spf(self):
        """
        L{DNSServerFactory} can serve I{SPF} resource records.
        """
        return self.namesTest(
            self.resolver.lookupSenderPolicy('test-domain.com'),
            [dns.Record_SPF('v=spf1 mx/30 mx:example.org/30 -all', ttl=19283784),
            dns.Record_SPF('v=spf1 +mx a:\0colo', '.example.com/28 -all not valid', ttl=19283784)]
        )


    def testWKS(self):
        """Test DNS 'WKS' record queries"""
        return self.namesTest(
            self.resolver.lookupWellKnownServices('test-domain.com'),
            [dns.Record_WKS('12.54.78.12', socket.IPPROTO_TCP, '\x12\x01\x16\xfe\xc1\x00\x01', ttl=19283784)]
        )


    def testSomeRecordsWithTTLs(self):
        result_soa = copy.copy(my_soa)
        result_soa.ttl = my_soa.expire
        return self.namesTest(
            self.resolver.lookupAllRecords('my-domain.com'),
            [result_soa,
             dns.Record_A('1.2.3.4', ttl='1S'),
             dns.Record_NS('ns1.domain', ttl='2M'),
             dns.Record_NS('ns2.domain', ttl='3H'),
             dns.Record_SRV(257, 16383, 43690, 'some.other.place.fool', ttl='4D')]
            )


    def testAAAA(self):
        """Test DNS 'AAAA' record queries (IPv6)"""
        return self.namesTest(
            self.resolver.lookupIPV6Address('test-domain.com'),
            [dns.Record_AAAA('AF43:5634:1294:AFCB:56AC:48EF:34C3:01FF', ttl=19283784)]
        )

    def testA6(self):
        """Test DNS 'A6' record queries (IPv6)"""
        return self.namesTest(
            self.resolver.lookupAddress6('test-domain.com'),
            [dns.Record_A6(0, 'ABCD::4321', '', ttl=19283784),
             dns.Record_A6(12, '0:0069::0', 'some.network.tld', ttl=19283784),
             dns.Record_A6(8, '0:5634:1294:AFCB:56AC:48EF:34C3:01FF', 'tra.la.la.net', ttl=19283784)]
         )


    def test_zoneTransfer(self):
        """
        Test DNS 'AXFR' queries (Zone transfer)
        """
        default_ttl = soa_record.expire
        results = [copy.copy(r) for r in reduce(operator.add, test_domain_com.records.values())]
        for r in results:
            if r.ttl is None:
                r.ttl = default_ttl
        return self.namesTest(
            self.resolver.lookupZone('test-domain.com').addCallback(lambda r: (r[0][:-1],)),
            results
        )


    def testSimilarZonesDontInterfere(self):
        """Tests that unrelated zones don't mess with each other."""
        return self.namesTest(
            self.resolver.lookupAddress("anothertest-domain.com"),
            [dns.Record_A('1.2.3.4', ttl=19283784)]
        )


    def test_NAPTR(self):
        """
        Test DNS 'NAPTR' record queries.
        """
        return self.namesTest(
            self.resolver.lookupNamingAuthorityPointer('test-domain.com'),
            [dns.Record_NAPTR(100, 10, "u", "sip+E2U",
                              "!^.*$!sip:information@domain.tld!",
                              ttl=19283784)])



class DNSServerFactoryTests(unittest.TestCase):
    """
    Tests for L{server.DNSServerFactory}.
    """
    def _messageReceivedTest(self, methodName, message):
        """
        Assert that the named method is called with the given message when
        it is passed to L{DNSServerFactory.messageReceived}.
        """
        # Make it appear to have some queries so that
        # DNSServerFactory.allowQuery allows it.
        message.queries = [None]

        receivedMessages = []
        def fakeHandler(message, protocol, address):
            receivedMessages.append((message, protocol, address))

        class FakeProtocol(object):
            def writeMessage(self, message):
                pass

        protocol = FakeProtocol()
        factory = server.DNSServerFactory(None)
        setattr(factory, methodName, fakeHandler)
        factory.messageReceived(message, protocol)
        self.assertEqual(receivedMessages, [(message, protocol, None)])


    def test_notifyMessageReceived(self):
        """
        L{DNSServerFactory.messageReceived} passes messages with an opcode
        of C{OP_NOTIFY} on to L{DNSServerFactory.handleNotify}.
        """
        # RFC 1996, section 4.5
        opCode = 4
        self._messageReceivedTest('handleNotify', Message(opCode=opCode))


    def test_updateMessageReceived(self):
        """
        L{DNSServerFactory.messageReceived} passes messages with an opcode
        of C{OP_UPDATE} on to L{DNSServerFactory.handleOther}.

        This may change if the implementation ever covers update messages.
        """
        # RFC 2136, section 1.3
        opCode = 5
        self._messageReceivedTest('handleOther', Message(opCode=opCode))


    def test_connectionTracking(self):
        """
        The C{connectionMade} and C{connectionLost} methods of
        L{DNSServerFactory} cooperate to keep track of all
        L{DNSProtocol} objects created by a factory which are
        connected.
        """
        protoA, protoB = object(), object()
        factory = server.DNSServerFactory()
        factory.connectionMade(protoA)
        self.assertEqual(factory.connections, [protoA])
        factory.connectionMade(protoB)
        self.assertEqual(factory.connections, [protoA, protoB])
        factory.connectionLost(protoA)
        self.assertEqual(factory.connections, [protoB])
        factory.connectionLost(protoB)
        self.assertEqual(factory.connections, [])


class HelperTestCase(unittest.TestCase):
    def testSerialGenerator(self):
        f = self.mktemp()
        a = authority.getSerial(f)
        for i in range(20):
            b = authority.getSerial(f)
            self.failUnless(a < b)
            a = b


class AXFRTest(unittest.TestCase):
    def setUp(self):
        self.results = None
        self.d = defer.Deferred()
        self.d.addCallback(self._gotResults)
        self.controller = client.AXFRController('fooby.com', self.d)

        self.soa = dns.RRHeader(name='fooby.com', type=dns.SOA, cls=dns.IN, ttl=86400, auth=False,
                                payload=dns.Record_SOA(mname='fooby.com',
                                                       rname='hooj.fooby.com',
                                                       serial=100,
                                                       refresh=200,
                                                       retry=300,
                                                       expire=400,
                                                       minimum=500,
                                                       ttl=600))

        self.records = [
            self.soa,
            dns.RRHeader(name='fooby.com', type=dns.NS, cls=dns.IN, ttl=700, auth=False,
                         payload=dns.Record_NS(name='ns.twistedmatrix.com', ttl=700)),

            dns.RRHeader(name='fooby.com', type=dns.MX, cls=dns.IN, ttl=700, auth=False,
                         payload=dns.Record_MX(preference=10, exchange='mail.mv3d.com', ttl=700)),

            dns.RRHeader(name='fooby.com', type=dns.A, cls=dns.IN, ttl=700, auth=False,
                         payload=dns.Record_A(address='64.123.27.105', ttl=700)),
            self.soa
            ]

    def _makeMessage(self):
        # hooray they all have the same message format
        return dns.Message(id=999, answer=1, opCode=0, recDes=0, recAv=1, auth=1, rCode=0, trunc=0, maxSize=0)

    def testBindAndTNamesStyle(self):
        # Bind style = One big single message
        m = self._makeMessage()
        m.queries = [dns.Query('fooby.com', dns.AXFR, dns.IN)]
        m.answers = self.records
        self.controller.messageReceived(m, None)
        self.assertEqual(self.results, self.records)

    def _gotResults(self, result):
        self.results = result

    def testDJBStyle(self):
        # DJB style = message per record
        records = self.records[:]
        while records:
            m = self._makeMessage()
            m.queries = [] # DJB *doesn't* specify any queries.. hmm..
            m.answers = [records.pop(0)]
            self.controller.messageReceived(m, None)
        self.assertEqual(self.results, self.records)



class ResolvConfHandling(unittest.TestCase):
    def testMissing(self):
        resolvConf = self.mktemp()
        r = client.Resolver(resolv=resolvConf)
        self.assertEqual(r.dynServers, [('127.0.0.1', 53)])
        r._parseCall.cancel()

    def testEmpty(self):
        resolvConf = self.mktemp()
        fObj = file(resolvConf, 'w')
        fObj.close()
        r = client.Resolver(resolv=resolvConf)
        self.assertEqual(r.dynServers, [('127.0.0.1', 53)])
        r._parseCall.cancel()



class AuthorityTests(unittest.TestCase):
    """
    Tests for the basic response record selection code in L{FileAuthority}
    (independent of its fileness).
    """

    def test_domainErrorForNameWithCommonSuffix(self):
        """
        L{FileAuthority} lookup methods errback with L{DomainError} if
        the requested C{name} shares a common suffix with its zone but
        is not actually a descendant of its zone, in terms of its
        sequence of DNS name labels. eg www.the-example.com has
        nothing to do with the zone example.com.
        """
        testDomain = test_domain_com
        testDomainName = 'nonexistent.prefix-' + testDomain.soa[0]
        f = self.failureResultOf(testDomain.lookupAddress(testDomainName))
        self.assertIsInstance(f.value, DomainError)


    def test_recordMissing(self):
        """
        If a L{FileAuthority} has a zone which includes an I{NS} record for a
        particular name and that authority is asked for another record for the
        same name which does not exist, the I{NS} record is not included in the
        authority section of the response.
        """
        authority = NoFileAuthority(
            soa=(str(soa_record.mname), soa_record),
            records={
                str(soa_record.mname): [
                    soa_record,
                    dns.Record_NS('1.2.3.4'),
                    ]})
        d = authority.lookupAddress(str(soa_record.mname))
        result = []
        d.addCallback(result.append)
        answer, authority, additional = result[0]
        self.assertEqual(answer, [])
        self.assertEqual(
            authority, [
                dns.RRHeader(
                    str(soa_record.mname), soa_record.TYPE,
                    ttl=soa_record.expire, payload=soa_record,
                    auth=True)])
        self.assertEqual(additional, [])


    def _referralTest(self, method):
        """
        Create an authority and make a request against it.  Then verify that the
        result is a referral, including no records in the answers or additional
        sections, but with an I{NS} record in the authority section.
        """
        subdomain = 'example.' + str(soa_record.mname)
        nameserver = dns.Record_NS('1.2.3.4')
        authority = NoFileAuthority(
            soa=(str(soa_record.mname), soa_record),
            records={
                subdomain: [
                    nameserver,
                    ]})
        d = getattr(authority, method)(subdomain)
        answer, authority, additional = self.successResultOf(d)
        self.assertEqual(answer, [])
        self.assertEqual(
            authority, [dns.RRHeader(
                    subdomain, dns.NS, ttl=soa_record.expire,
                    payload=nameserver, auth=False)])
        self.assertEqual(additional, [])


    def test_referral(self):
        """
        When an I{NS} record is found for a child zone, it is included in the
        authority section of the response.  It is marked as non-authoritative if
        the authority is not also authoritative for the child zone (RFC 2181,
        section 6.1).
        """
        self._referralTest('lookupAddress')


    def test_allRecordsReferral(self):
        """
        A referral is also generated for a request of type C{ALL_RECORDS}.
        """
        self._referralTest('lookupAllRecords')



class AdditionalProcessingTests(unittest.TestCase):
    """
    Tests for L{FileAuthority}'s additional processing for those record types
    which require it (MX, CNAME, etc).
    """
    _A = dns.Record_A(b"10.0.0.1")
    _AAAA = dns.Record_AAAA(b"f080::1")

    def _lookupSomeRecords(self, method, soa, makeRecord, target, addresses):
        """
        Perform a DNS lookup against a L{FileAuthority} configured with records
        as defined by C{makeRecord} and C{addresses}.

        @param method: The name of the lookup method to use; for example,
            C{"lookupNameservers"}.
        @type method: L{str}

        @param soa: A L{Record_SOA} for the zone for which the L{FileAuthority}
            is authoritative.

        @param makeRecord: A one-argument callable which accepts a name and
            returns an L{IRecord} provider.  L{FileAuthority} is constructed
            with this record.  The L{FileAuthority} is queried for a record of
            the resulting type with the given name.

        @param target: The extra name which the record returned by
            C{makeRecord} will be pointed at; this is the name which might
            require extra processing by the server so that all the available,
            useful information is returned.  For example, this is the target of
            a CNAME record or the mail exchange host pointed to by an MX record.
        @type target: L{bytes}

        @param addresses: A L{list} of records giving addresses of C{target}.

        @return: A L{Deferred} that fires with the result of the resolver
            method give by C{method}.
        """
        authority = NoFileAuthority(
            soa=(soa.mname.name, soa),
            records={
                soa.mname.name: [makeRecord(target)],
                target: addresses,
                },
            )
        return getattr(authority, method)(soa_record.mname.name)


    def assertRecordsMatch(self, expected, computed):
        """
        Assert that the L{RRHeader} instances given by C{expected} and
        C{computed} carry all the same information but without requiring the
        records appear in the same order.

        @param expected: A L{list} of L{RRHeader} instances giving the expected
            records.

        @param computed: A L{list} of L{RRHeader} instances giving the records
            computed by the scenario under test.

        @raise self.failureException: If the two collections of records disagree.
        """
        # RRHeader instances aren't inherently ordered.  Impose an ordering
        # that's good enough for the purposes of these tests - in which we
        # never have more than one record of a particular type.
        key = lambda rr: rr.type
        self.assertEqual(sorted(expected, key=key), sorted(computed, key=key))


    def _additionalTest(self, method, makeRecord, addresses):
        """
        Verify that certain address records are included in the I{additional}
        section of a response generated by L{FileAuthority}.

        @param method: See L{_lookupSomeRecords}

        @param makeRecord: See L{_lookupSomeRecords}

        @param addresses: A L{list} of L{IRecord} providers which the
            I{additional} section of the response is required to match
            (ignoring order).

        @raise self.failureException: If the I{additional} section of the
            response consists of different records than those given by
            C{addresses}.
        """
        target = b"mail." + soa_record.mname.name
        d = self._lookupSomeRecords(
            method, soa_record, makeRecord, target, addresses)
        answer, authority, additional = self.successResultOf(d)

        self.assertRecordsMatch(
            [dns.RRHeader(
                    target, address.TYPE, ttl=soa_record.expire, payload=address,
                    auth=True)
             for address in addresses],
            additional)


    def _additionalMXTest(self, addresses):
        """
        Verify that a response to an MX query has certain records in the
        I{additional} section.

        @param addresses: See C{_additionalTest}
        """
        self._additionalTest(
            "lookupMailExchange", partial(dns.Record_MX, 10), addresses)


    def test_mailExchangeAdditionalA(self):
        """
        If the name of the MX response has A records, they are included in the
        additional section of the response.
        """
        self._additionalMXTest([self._A])


    def test_mailExchangeAdditionalAAAA(self):
        """
        If the name of the MX response has AAAA records, they are included in
        the additional section of the response.
        """
        self._additionalMXTest([self._AAAA])


    def test_mailExchangeAdditionalBoth(self):
        """
        If the name of the MX response has both A and AAAA records, they are
        all included in the additional section of the response.
        """
        self._additionalMXTest([self._A, self._AAAA])


    def _additionalNSTest(self, addresses):
        """
        Verify that a response to an NS query has certain records in the
        I{additional} section.

        @param addresses: See C{_additionalTest}
        """
        self._additionalTest(
            "lookupNameservers", dns.Record_NS, addresses)


    def test_nameserverAdditionalA(self):
        """
        If the name of the NS response has A records, they are included in the
        additional section of the response.
        """
        self._additionalNSTest([self._A])


    def test_nameserverAdditionalAAAA(self):
        """
        If the name of the NS response has AAAA records, they are included in
        the additional section of the response.
        """
        self._additionalNSTest([self._AAAA])


    def test_nameserverAdditionalBoth(self):
        """
        If the name of the NS response has both A and AAAA records, they are
        all included in the additional section of the response.
        """
        self._additionalNSTest([self._A, self._AAAA])


    def _answerCNAMETest(self, addresses):
        """
        Verify that a response to a CNAME query has certain records in the
        I{answer} section.

        @param addresses: See C{_additionalTest}
        """
        target = b"www." + soa_record.mname.name
        d = self._lookupSomeRecords(
            "lookupCanonicalName", soa_record, dns.Record_CNAME, target,
            addresses)
        answer, authority, additional = self.successResultOf(d)

        alias = dns.RRHeader(
            soa_record.mname.name, dns.CNAME, ttl=soa_record.expire,
            payload=dns.Record_CNAME(target), auth=True)
        self.assertRecordsMatch(
            [dns.RRHeader(
                    target, address.TYPE, ttl=soa_record.expire, payload=address,
                    auth=True)
             for address in addresses] + [alias],
            answer)


    def test_canonicalNameAnswerA(self):
        """
        If the name of the CNAME response has A records, they are included in
        the answer section of the response.
        """
        self._answerCNAMETest([self._A])


    def test_canonicalNameAnswerAAAA(self):
        """
        If the name of the CNAME response has AAAA records, they are included
        in the answer section of the response.
        """
        self._answerCNAMETest([self._AAAA])


    def test_canonicalNameAnswerBoth(self):
        """
        If the name of the CNAME response has both A and AAAA records, they are
        all included in the answer section of the response.
        """
        self._answerCNAMETest([self._A, self._AAAA])



class NoInitialResponseTestCase(unittest.TestCase):

    def test_no_answer(self):
        """
        If a request returns a L{dns.NS} response, but we can't connect to the
        given server, the request fails with the error returned at connection.
        """

        def query(self, *args):
            # Pop from the message list, so that it blows up if more queries
            # are run than expected.
            return succeed(messages.pop(0))

        def queryProtocol(self, *args, **kwargs):
            return defer.fail(socket.gaierror("Couldn't connect"))

        resolver = Resolver(servers=[('0.0.0.0', 0)])
        resolver._query = query
        messages = []
        # Let's patch dns.DNSDatagramProtocol.query, as there is no easy way to
        # customize it.
        self.patch(dns.DNSDatagramProtocol, "query", queryProtocol)

        records = [
            dns.RRHeader(name='fooba.com', type=dns.NS, cls=dns.IN, ttl=700,
                         auth=False,
                         payload=dns.Record_NS(name='ns.twistedmatrix.com',
                         ttl=700))]
        m = dns.Message(id=999, answer=1, opCode=0, recDes=0, recAv=1, auth=1,
                        rCode=0, trunc=0, maxSize=0)
        m.answers = records
        messages.append(m)
        return self.assertFailure(
            resolver.getHostByName("fooby.com"), socket.gaierror)



class SecondaryAuthorityServiceTests(unittest.TestCase):
    """
    Tests for L{SecondaryAuthorityService}, a service which keeps one or more
    authorities up to date by doing zone transfers from a master.
    """

    def test_constructAuthorityFromHost(self):
        """
        L{SecondaryAuthorityService} can be constructed with a C{str} giving a
        master server address and several domains, causing the creation of a
        secondary authority for each domain and that master server address and
        the default DNS port.
        """
        primary = '192.168.1.2'
        service = SecondaryAuthorityService(
            primary, ['example.com', 'example.org'])
        self.assertEqual(service.primary, primary)
        self.assertEqual(service._port, 53)

        self.assertEqual(service.domains[0].primary, primary)
        self.assertEqual(service.domains[0]._port, 53)
        self.assertEqual(service.domains[0].domain, 'example.com')

        self.assertEqual(service.domains[1].primary, primary)
        self.assertEqual(service.domains[1]._port, 53)
        self.assertEqual(service.domains[1].domain, 'example.org')


    def test_constructAuthorityFromHostAndPort(self):
        """
        L{SecondaryAuthorityService.fromServerAddressAndDomains} constructs a
        new L{SecondaryAuthorityService} from a C{str} giving a master server
        address and DNS port and several domains, causing the creation of a secondary
        authority for each domain and that master server address and the given
        DNS port.
        """
        primary = '192.168.1.3'
        port = 5335
        service = SecondaryAuthorityService.fromServerAddressAndDomains(
            (primary, port), ['example.net', 'example.edu'])
        self.assertEqual(service.primary, primary)
        self.assertEqual(service._port, 5335)

        self.assertEqual(service.domains[0].primary, primary)
        self.assertEqual(service.domains[0]._port, port)
        self.assertEqual(service.domains[0].domain, 'example.net')

        self.assertEqual(service.domains[1].primary, primary)
        self.assertEqual(service.domains[1]._port, port)
        self.assertEqual(service.domains[1].domain, 'example.edu')



class SecondaryAuthorityTests(unittest.TestCase):
    """
    L{twisted.names.secondary.SecondaryAuthority} correctly constructs objects
    with a specified IP address and optionally specified DNS port.
    """

    def test_defaultPort(self):
        """
        When constructed using L{SecondaryAuthority.__init__}, the default port
        of 53 is used.
        """
        secondary = SecondaryAuthority('192.168.1.1', 'inside.com')
        self.assertEqual(secondary.primary, '192.168.1.1')
        self.assertEqual(secondary._port, 53)
        self.assertEqual(secondary.domain, 'inside.com')


    def test_explicitPort(self):
        """
        When constructed using L{SecondaryAuthority.fromServerAddressAndDomain},
        the specified port is used.
        """
        secondary = SecondaryAuthority.fromServerAddressAndDomain(
            ('192.168.1.1', 5353), 'inside.com')
        self.assertEqual(secondary.primary, '192.168.1.1')
        self.assertEqual(secondary._port, 5353)
        self.assertEqual(secondary.domain, 'inside.com')


    def test_transfer(self):
        """
        An attempt is made to transfer the zone for the domain the
        L{SecondaryAuthority} was constructed with from the server address it
        was constructed with when L{SecondaryAuthority.transfer} is called.
        """
        secondary = SecondaryAuthority.fromServerAddressAndDomain(
            ('192.168.1.2', 1234), 'example.com')
        secondary._reactor = reactor = MemoryReactorClock()

        secondary.transfer()

        # Verify a connection attempt to the server address above
        host, port, factory, timeout, bindAddress = reactor.tcpClients.pop(0)
        self.assertEqual(host, '192.168.1.2')
        self.assertEqual(port, 1234)

        # See if a zone transfer query is issued.
        proto = factory.buildProtocol((host, port))
        transport = StringTransport()
        proto.makeConnection(transport)

        msg = Message()
        # DNSProtocol.writeMessage length encodes the message by prepending a
        # 2 byte message length to the buffered value.
        msg.decode(StringIO(transport.value()[2:]))

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