Ticket #6862: deprecate-message-6862.patch

File deprecate-message-6862.patch, 64.4 KB (added by Richard Wall, 4 years ago)

Introduce a new "StandardMessage" class with meaningful constructor args and attribute names. Deprecate dns.Message.

  • twisted/names/client.py

    === modified file 'twisted/names/client.py'
     
    368368        Otherwise, return a three-tuple of lists containing the results from
    369369        the answers section, the authority section, and the additional section.
    370370        """
    371         if message.trunc:
     371        if message.truncated:
    372372            return self.queryTCP(message.queries).addCallback(self.filterAnswers)
    373         if message.rCode != dns.OK:
    374             return failure.Failure(self.exceptionForCode(message.rCode)(message))
     373        if message.responseCode != dns.OK:
     374            return failure.Failure(self.exceptionForCode(message.responseCode)(message))
    375375        return (message.answers, message.authority, message.additional)
    376376
    377377
     
    451451
    452452    def connectionMade(self, protocol):
    453453        # dig saids recursion-desired to 0, so I will too
    454         message = dns.Message(protocol.pickID(), recDes=0)
     454        message = dns.StandardMessage(protocol.pickID(), recursionDesired=0)
    455455        message.queries = [dns.Query(self.name, dns.AXFR, dns.IN)]
    456456        protocol.writeMessage(message)
    457457
  • twisted/names/dns.py

    === modified file 'twisted/names/dns.py'
     
    19111911
    19121912
    19131913
    1914 class Message(tputil.FancyEqMixin):
     1914class _Message(tputil.FancyEqMixin):
    19151915    """
    19161916    L{Message} contains all the information represented by a single
    19171917    DNS request or response.
     
    20872087
    20882088
    20892089    def decode(self, strio, length=None):
    2090         self.maxSize = 0
     2090#        self.maxSize = 0
    20912091        header = readPrecisely(strio, self.headerSize)
    20922092        r = struct.unpack(self.headerFmt, header)
    20932093        self.id, byte3, byte4, nqueries, nans, nns, nadd = r
     
    21892189
    21902190
    21912191
     2192class Message(_Message):
     2193    """
     2194    Placeholder for the deprecated Message
     2195    """
     2196
     2197
     2198
     2199from twisted.python.util import Version
     2200from twisted.python.deprecate import deprecatedModuleAttribute
     2201deprecatedModuleAttribute(
     2202    Version("Twisted", 14, 0, 0),
     2203    "Use StandardMessage instead.",
     2204    "twisted.names.dns",
     2205    "Message")
     2206
     2207
     2208
     2209class StandardMessage(tputil.FancyStrMixin, tputil.FancyEqMixin, object):
     2210
     2211    showAttributes = (
     2212        'id', 'answer', 'opCode', 'authoritativeAnswer', 'truncated',
     2213        'recursionDesired', 'recursionAvailable', 'responseCode',
     2214        'authenticData', 'checkingDisabled', 'maxSize',
     2215        'queries', 'answers', 'authority', 'additional')
     2216
     2217    compareAttributes = showAttributes
     2218
     2219    def __init__(self, id=0, answer=False, opCode=OP_QUERY,
     2220                 authoritativeAnswer=False, truncated=False,
     2221                 recursionDesired=False, recursionAvailable=False,
     2222                 responseCode=0,
     2223                 authenticData=False, checkingDisabled=False, maxSize=512,
     2224                 queries=None, answers=None, authority=None, additional=None):
     2225        """
     2226        Construct a new L{StandardMessage}.
     2227
     2228        @see U{RFC1035 section-4.1.1<https://tools.ietf.org/html/rfc1035#section-4.1.1>}
     2229        @see U{RFC2535 section-6.1<https://tools.ietf.org/html/rfc2535#section-6.1>}
     2230        @see U{RFC3225 section-3<https://tools.ietf.org/html/rfc3225#section-3>}
     2231        @see U{RFC6891 section-6.1.3<https://tools.ietf.org/html/rfc6891#section-6.1.3>}
     2232
     2233        @param id: A 16 bit identifier assigned by the program that generates
     2234            any kind of query.  This identifier is copied the corresponding
     2235            reply and can be used by the requester to match up replies to
     2236            outstanding queries.
     2237        @type id: L{int}
     2238
     2239        @param answer: A one bit field that specifies whether this message is a
     2240            query (0), or a response (1).
     2241        @type answer: L{bool}
     2242
     2243        @param opCode: A four bit field that specifies kind of query in this
     2244            message.  This value is set by the originator of a query and copied
     2245            into the response.
     2246        @type opCode: L{int}
     2247
     2248        @param authoritativeAnswer: Authoritative Answer - this bit is valid in
     2249            responses, and specifies that the responding name server is an
     2250            authority for the domain name in question section.
     2251        @type authoritativeAnswer: L{bool}
     2252
     2253        @param truncated: Truncation - specifies that this message was truncated due
     2254            to length greater than that permitted on the transmission channel.
     2255        @type truncated: L{bool}
     2256
     2257        @param recursionDesired: Recursion Desired - this bit may be set in a
     2258            query and is copied into the response.  If set, it directs the name
     2259            server to pursue the query recursively. Recursive query support is
     2260            optional.
     2261        @type recursionDesired: L{bool}
     2262
     2263        @param recursionAvailable: Recursion Available - this bit is set or
     2264            cleared in a response, and denotes whether recursive query support
     2265            is available in the name server.
     2266        @type recursionAvailable: L{bool}
     2267
     2268        @param responseCode: Extended 12-bit RCODE. Derived from the 4 bits
     2269            defined in U{RFC1035
     2270            4.1.1<https://tools.ietf.org/html/rfc1035#section-4.1.1>} and the
     2271            upper 8bits defined in U{RFC6891
     2272            6.1.3<https://tools.ietf.org/html/rfc6891#section-6.1.3>}.
     2273        @type responseCode: L{int}
     2274
     2275        @param authenticData: A flag indicating in a response that all the data
     2276            included in the answer and authority portion of the response has
     2277            been authenticated by the server according to the policies of that
     2278            server.
     2279            See U{RFC2535 section-6.1<https://tools.ietf.org/html/rfc2535#section-6.1>}.
     2280        @type authenticData: L{bool}
     2281
     2282        @param checkingDisabled: A flag indicating in a query that pending
     2283            (non-authenticated) data is acceptable to the resolver sending the
     2284            query.
     2285            See U{RFC2535 section-6.1<https://tools.ietf.org/html/rfc2535#section-6.1>}.
     2286        @type authenticData: L{bool}
     2287
     2288        @param maxSize: The requestor's UDP payload size is the number of octets
     2289            of the largest UDP payload that can be reassembled and delivered in
     2290            the requestor's network stack.
     2291        @type maxSize: L{int}
     2292
     2293        @param queries: The L{list} of L{Query} associated with this message.
     2294        @type queries: L{list} of L{Query}
     2295
     2296        @param answers: The L{list} of answers associated with this message.
     2297        @type answers: L{list} of L{RRHeader}
     2298
     2299        @param authority: The L{list} of authority records associated with this
     2300            message.
     2301        @type authority: L{list} of L{RRHeader}
     2302
     2303        @param additional: The L{list} of additional records associated with
     2304            this message.
     2305        @type additional: L{list} of L{RRHeader}
     2306        """
     2307        self.id = id
     2308        self.answer = answer
     2309        self.opCode = opCode
     2310        self.authoritativeAnswer = authoritativeAnswer
     2311        self.truncated = truncated
     2312        self.recursionDesired = recursionDesired
     2313        self.recursionAvailable = recursionAvailable
     2314        self.responseCode = responseCode
     2315        self.authenticData = authenticData
     2316        self.checkingDisabled = checkingDisabled
     2317        self.maxSize = maxSize
     2318
     2319        if queries is None:
     2320            queries = []
     2321        self.queries = queries
     2322
     2323        if answers is None:
     2324            answers = []
     2325        self.answers = answers
     2326
     2327        if authority is None:
     2328            authority = []
     2329        self.authority = authority
     2330
     2331        if additional is None:
     2332            additional = []
     2333        self.additional = additional
     2334
     2335
     2336    def addQuery(self, name, type=ALL_RECORDS, cls=IN):
     2337        """
     2338        Add another query to this Message.
     2339
     2340        @type name: C{bytes}
     2341        @param name: The name to query.
     2342
     2343        @type type: C{int}
     2344        @param type: Query type
     2345
     2346        @type cls: C{int}
     2347        @param cls: Query class
     2348        """
     2349        self.queries.append(Query(name, type, cls))
     2350
     2351
     2352    def toStr(self):
     2353        """
     2354        Encode this L{StandardMessage} into a byte string in the format
     2355        described by RFC 1035.
     2356
     2357        @rtype: C{bytes}
     2358        """
     2359        strio = BytesIO()
     2360        m = _Message(
     2361            id=self.id,
     2362            answer=self.answer,
     2363            opCode=self.opCode,
     2364            recDes=self.recursionDesired,
     2365            recAv=self.recursionAvailable,
     2366            auth=self.authoritativeAnswer,
     2367            rCode=self.responseCode,
     2368            trunc=self.truncated,
     2369            maxSize=self.maxSize,
     2370            authenticData=self.authenticData,
     2371            checkingDisabled=self.checkingDisabled,
     2372        )
     2373        m.queries = self.queries
     2374        m.answers = self.answers
     2375        m.authority = self.authority
     2376        m.additional = self.additional
     2377        m.encode(strio)
     2378        return strio.getvalue()
     2379
     2380
     2381    @classmethod
     2382    def fromStr(cls, str):
     2383        """
     2384        Decode a byte string in the format described by RFC 1035 into this
     2385        L{StandardMessage}.
     2386
     2387        @param str: L{bytes}
     2388        """
     2389        strio = BytesIO(str)
     2390        m = _Message()
     2391        m.decode(strio)
     2392        return cls(
     2393            id=m.id,
     2394            answer=m.answer,
     2395            opCode=m.opCode,
     2396            recursionDesired=m.recDes,
     2397            recursionAvailable=m.recAv,
     2398            authoritativeAnswer=m.auth,
     2399            responseCode=m.rCode,
     2400            truncated=m.trunc,
     2401            maxSize=m.maxSize,
     2402            authenticData=m.authenticData,
     2403            checkingDisabled=m.checkingDisabled,
     2404            queries=m.queries,
     2405            answers=m.answers,
     2406            authority=m.authority,
     2407            additional=m.additional,
     2408        )
     2409
     2410
     2411
    21922412class _EDNSMessage(tputil.FancyStrMixin, tputil.FancyEqMixin, object):
    21932413    """
    21942414    An I{EDNS} message.
     
    24782698        return newMessage
    24792699
    24802700
    2481     def fromStr(self, bytes):
     2701    @classmethod
     2702    def fromStr(cls, bytes):
    24822703        """
    24832704        Decode from wire format, saving flags, values and records to this
    24842705        L{_EDNSMessage} instance in place.
     
    24862707        @param bytes: The full byte string to be decoded.
    24872708        @type bytes: L{bytes}
    24882709        """
    2489         m = self._messageFactory()
     2710        m = cls._messageFactory()
    24902711        m.fromStr(bytes)
    2491 
    2492         ednsMessage = self._fromMessage(m)
    2493         for attrName in self.compareAttributes:
    2494             setattr(self, attrName, getattr(ednsMessage, attrName))
     2712        return cls._fromMessage(m)
    24952713
    24962714
    24972715
     
    25512769            query, or errbacked with any errors that could happen (exceptions
    25522770            during writing of the query, timeout errors, ...).
    25532771        """
    2554         m = Message(id, recDes=1)
     2772        m = StandardMessage(id, recursionDesired=1)
    25552773        m.queries = queries
    25562774
    25572775        try:
     
    26132831        Read a datagram, extract the message in it and trigger the associated
    26142832        Deferred.
    26152833        """
    2616         m = Message()
    26172834        try:
    2618             m.fromStr(data)
     2835            m = StandardMessage.fromStr(data)
    26192836        except EOFError:
    26202837            log.msg("Truncated packet (%d bytes) from %s" % (len(data), addr))
    26212838            return
  • twisted/names/root.py

    === modified file 'twisted/names/root.py'
     
    184184            lists of L{RRHeaders} giving the response to C{query} or a
    185185            L{Deferred} which will fire with one of those.
    186186        """
    187         if response.rCode != dns.OK:
    188             return Failure(self.exceptionForCode(response.rCode)(response))
     187        if response.responseCode != dns.OK:
     188            return Failure(self.exceptionForCode(response.responseCode)(response))
    189189
    190190        # Turn the answers into a structure that's a little easier to work with.
    191191        records = {}
  • twisted/names/test/test_client.py

    === modified file 'twisted/names/test/test_client.py'
     
    379379        # The response to the first query should be sent in response to both
    380380        # queries.
    381381        answer = object()
    382         response = dns.Message()
     382        response = dns.StandardMessage()
    383383        response.answers.append(answer)
    384384        queries.pop()[-1].callback(response)
    385385
     
    438438        self.assertEqual(len(queries), 1)
    439439
    440440        # Deliver the response.
    441         queries.pop()[-1].callback(dns.Message())
     441        queries.pop()[-1].callback(dns.StandardMessage())
    442442
    443443        # Repeating the first query should touch the protocol again.
    444444        resolver.query(query)
     
    518518
    519519            def query(self, address, query, timeout=10, id=None):
    520520                protocols.append(self)
    521                 return defer.succeed(dns.Message())
     521                return defer.succeed(dns.StandardMessage())
    522522
    523523        resolver._connectedProtocol = FakeProtocol
    524524        resolver.query(dns.Query(b'foo.example.com'))
     
    554554        resolver = client.Resolver(servers=[('example.com', 53)])
    555555        protocols = []
    556556        results = [defer.fail(failure.Failure(DNSQueryTimeoutError(None))),
    557                    defer.succeed(dns.Message())]
     557                   defer.succeed(dns.StandardMessage())]
    558558
    559559        class FakeProtocol(object):
    560560            def __init__(self):
     
    591591        resolver.query(dns.Query(b'foo.example.com'))
    592592
    593593        self.assertFalse(protocols[0].transport.disconnected)
    594         result.callback(dns.Message())
     594        result.callback(dns.StandardMessage())
    595595        self.assertTrue(protocols[0].transport.disconnected)
    596596
    597597
     
    619619        resolver.query(dns.Query(b'foo.example.com'))
    620620
    621621        self.assertFalse(protocols[1].transport.disconnected)
    622         result.callback(dns.Message())
     622        result.callback(dns.StandardMessage())
    623623        self.assertTrue(protocols[1].transport.disconnected)
    624624
    625625
     
    10561056        Test that a truncated message results in an equivalent request made via
    10571057        TCP.
    10581058        """
    1059         m = dns.Message(trunc=True)
    1060         m.addQuery(b'example.com')
     1059        m = dns.StandardMessage(
     1060            truncated=True,
     1061            queries=[dns.Query(b'example.com')]
     1062        )
    10611063
    10621064        def queryTCP(queries):
    10631065            self.assertEqual(queries, m.queries)
    1064             response = dns.Message()
    1065             response.answers = ['answer']
    1066             response.authority = ['authority']
    1067             response.additional = ['additional']
     1066            response = dns.StandardMessage(
     1067                answers=['answer'],
     1068                authority=['authority'],
     1069                additional=['additional']
     1070            )
    10681071            return defer.succeed(response)
    10691072        self.resolver.queryTCP = queryTCP
    10701073        d = self.resolver.filterAnswers(m)
     
    10741077
    10751078
    10761079    def _rcodeTest(self, rcode, exc):
    1077         m = dns.Message(rCode=rcode)
     1080        m = dns.StandardMessage(responseCode=rcode)
    10781081        err = self.resolver.filterAnswers(m)
    10791082        err.trap(exc)
    10801083
  • twisted/names/test/test_dns.py

    === modified file 'twisted/names/test/test_dns.py'
     
    180180
    181181        # The position at which the encoded form of this new name will appear in
    182182        # the stream.
    183         expected = len(previous) + dns.Message.headerSize
     183        expected = len(previous) + dns._Message.headerSize
    184184        name.encode(stream, compression)
    185185        self.assertEqual(
    186186            b"\x03foo\xc0\x17",
     
    229229            b'\x01\x02\x03\x04'      # 1.2.3.4
    230230            )
    231231
    232         msg = dns.Message()
     232        msg = dns._Message()
    233233        msg.fromStr(wire)
    234234
    235235        self.assertEqual(msg.queries, [
     
    598598
    599599class MessageTestCase(unittest.SynchronousTestCase):
    600600    """
    601     Tests for L{twisted.names.dns.Message}.
     601    Tests for L{twisted.names.dns._Message}.
    602602    """
    603603
    604604    def test_authenticDataDefault(self):
    605605        """
    606         L{dns.Message.authenticData} has default value 0.
     606        L{dns._Message.authenticData} has default value 0.
    607607        """
    608         self.assertEqual(dns.Message().authenticData, 0)
     608        self.assertEqual(dns._Message().authenticData, 0)
    609609
    610610
    611611    def test_authenticDataOverride(self):
    612612        """
    613         L{dns.Message.__init__} accepts a C{authenticData} argument which
    614         is assigned to L{dns.Message.authenticData}.
     613        L{dns._Message.__init__} accepts a C{authenticData} argument which
     614        is assigned to L{dns._Message.authenticData}.
    615615        """
    616         self.assertEqual(dns.Message(authenticData=1).authenticData, 1)
     616        self.assertEqual(dns._Message(authenticData=1).authenticData, 1)
    617617
    618618
    619619    def test_authenticDataEncode(self):
    620620        """
    621         L{dns.Message.toStr} encodes L{dns.Message.authenticData} into
     621        L{dns._Message.toStr} encodes L{dns._Message.authenticData} into
    622622        byte4 of the byte string.
    623623        """
    624624        self.assertEqual(
    625             dns.Message(authenticData=1).toStr(),
     625            dns._Message(authenticData=1).toStr(),
    626626            MESSAGE_AUTHENTIC_DATA_BYTES
    627627        )
    628628
    629629
    630630    def test_authenticDataDecode(self):
    631631        """
    632         L{dns.Message.fromStr} decodes byte4 and assigns bit3 to
    633         L{dns.Message.authenticData}.
     632        L{dns._Message.fromStr} decodes byte4 and assigns bit3 to
     633        L{dns._Message.authenticData}.
    634634        """
    635         m = dns.Message()
     635        m = dns._Message()
    636636        m.fromStr(MESSAGE_AUTHENTIC_DATA_BYTES)
    637637
    638638        self.assertEqual(m.authenticData, 1)
     
    640640
    641641    def test_checkingDisabledDefault(self):
    642642        """
    643         L{dns.Message.checkingDisabled} has default value 0.
     643        L{dns._Message.checkingDisabled} has default value 0.
    644644        """
    645         self.assertEqual(dns.Message().checkingDisabled, 0)
     645        self.assertEqual(dns._Message().checkingDisabled, 0)
    646646
    647647
    648648    def test_checkingDisabledOverride(self):
    649649        """
    650         L{dns.Message.__init__} accepts a C{checkingDisabled} argument which
    651         is assigned to L{dns.Message.checkingDisabled}.
     650        L{dns._Message.__init__} accepts a C{checkingDisabled} argument which
     651        is assigned to L{dns._Message.checkingDisabled}.
    652652        """
    653653        self.assertEqual(
    654             dns.Message(checkingDisabled=1).checkingDisabled, 1)
     654            dns._Message(checkingDisabled=1).checkingDisabled, 1)
    655655
    656656
    657657    def test_checkingDisabledEncode(self):
    658658        """
    659         L{dns.Message.toStr} encodes L{dns.Message.checkingDisabled} into
     659        L{dns._Message.toStr} encodes L{dns._Message.checkingDisabled} into
    660660        byte4 of the byte string.
    661661        """
    662662        self.assertEqual(
    663             dns.Message(checkingDisabled=1).toStr(),
     663            dns._Message(checkingDisabled=1).toStr(),
    664664            MESSAGE_CHECKING_DISABLED_BYTES
    665665        )
    666666
    667667
    668668    def test_checkingDisabledDecode(self):
    669669        """
    670         L{dns.Message.fromStr} decodes byte4 and assigns bit4 to
    671         L{dns.Message.checkingDisabled}.
     670        L{dns._Message.fromStr} decodes byte4 and assigns bit4 to
     671        L{dns._Message.checkingDisabled}.
    672672        """
    673         m = dns.Message()
     673        m = dns._Message()
    674674        m.fromStr(MESSAGE_CHECKING_DISABLED_BYTES)
    675675
    676676        self.assertEqual(m.checkingDisabled, 1)
     
    681681        Test that a message which has been truncated causes an EOFError to
    682682        be raised when it is parsed.
    683683        """
    684         msg = dns.Message()
     684        msg = dns._Message()
    685685        self.assertRaises(EOFError, msg.fromStr, b'')
    686686
    687687
     
    690690        Test that bytes representing an empty query message can be decoded
    691691        as such.
    692692        """
    693         msg = dns.Message()
     693        msg = dns._Message()
    694694        msg.fromStr(
    695695            b'\x01\x00' # Message ID
    696696            b'\x00' # answer bit, opCode nibble, auth bit, trunc bit, recursive bit
     
    718718    def test_NULL(self):
    719719        """
    720720        A I{NULL} record with an arbitrary payload can be encoded and decoded as
    721         part of a L{dns.Message}.
     721        part of a L{dns._Message}.
    722722        """
    723723        bytes = b''.join([dns._ord2bytes(i) for i in range(256)])
    724724        rec = dns.Record_NULL(bytes)
    725725        rr = dns.RRHeader(b'testname', dns.NULL, payload=rec)
    726         msg1 = dns.Message()
     726        msg1 = dns._Message()
    727727        msg1.answers.append(rr)
    728728        s = BytesIO()
    729729        msg1.encode(s)
    730730        s.seek(0, 0)
    731         msg2 = dns.Message()
     731        msg2 = dns._Message()
    732732        msg2.decode(s)
    733733
    734734        self.assertIsInstance(msg2.answers[0].payload, dns.Record_NULL)
     
    744744        # 65280 is the first value in the range reserved for private
    745745        # use, so it shouldn't ever conflict with an officially
    746746        # allocated value.
    747         self.assertIs(dns.Message().lookupRecordType(65280), dns.UnknownRecord)
     747        self.assertIs(dns._Message().lookupRecordType(65280), dns.UnknownRecord)
    748748
    749749
    750750    def test_nonAuthoritativeMessage(self):
     
    755755        buf = BytesIO()
    756756        answer = dns.RRHeader(payload=dns.Record_A('1.2.3.4', ttl=0))
    757757        answer.encode(buf)
    758         message = dns.Message()
     758        message = dns._Message()
    759759        message.fromStr(
    760760            b'\x01\x00' # Message ID
    761761            # answer bit, opCode nibble, auth bit, trunc bit, recursive bit
     
    781781        buf = BytesIO()
    782782        answer = dns.RRHeader(payload=dns.Record_A('1.2.3.4', ttl=0))
    783783        answer.encode(buf)
    784         message = dns.Message()
     784        message = dns._Message()
    785785        message.fromStr(
    786786            b'\x01\x00' # Message ID
    787787            # answer bit, opCode nibble, auth bit, trunc bit, recursive bit
     
    804804class MessageComparisonTests(ComparisonTestsMixin,
    805805                             unittest.SynchronousTestCase):
    806806    """
    807     Tests for the rich comparison of L{dns.Message} instances.
     807    Tests for the rich comparison of L{dns._Message} instances.
    808808    """
    809809    def messageFactory(self, *args, **kwargs):
    810810        """
    811         Create a L{dns.Message}.
     811        Create a L{dns._Message}.
    812812
    813         The L{dns.Message} constructor doesn't accept C{queries}, C{answers},
     813        The L{dns._Message} constructor doesn't accept C{queries}, C{answers},
    814814        C{authority}, C{additional} arguments, so we extract them from the
    815815        kwargs supplied to this factory function and assign them to the message.
    816816
    817817        @param args: Positional arguments.
    818818        @param kwargs: Keyword arguments.
    819         @return: A L{dns.Message} instance.
     819        @return: A L{dns._Message} instance.
    820820        """
    821821        queries = kwargs.pop('queries', [])
    822822        answers = kwargs.pop('answers', [])
    823823        authority = kwargs.pop('authority', [])
    824824        additional = kwargs.pop('additional', [])
    825         m = dns.Message(**kwargs)
     825        m = dns._Message(**kwargs)
    826826        if queries:
    827827            m.queries = queries
    828828        if answers:
     
    836836
    837837    def test_id(self):
    838838        """
    839         Two L{dns.Message} instances compare equal if they have the same id
     839        Two L{dns._Message} instances compare equal if they have the same id
    840840        value.
    841841        """
    842842        self.assertNormalEqualityImplementation(
     
    848848
    849849    def test_answer(self):
    850850        """
    851         Two L{dns.Message} instances compare equal if they have the same answer
     851        Two L{dns._Message} instances compare equal if they have the same answer
    852852        flag.
    853853        """
    854854        self.assertNormalEqualityImplementation(
     
    860860
    861861    def test_opCode(self):
    862862        """
    863         Two L{dns.Message} instances compare equal if they have the same opCode
     863        Two L{dns._Message} instances compare equal if they have the same opCode
    864864        value.
    865865        """
    866866        self.assertNormalEqualityImplementation(
     
    872872
    873873    def test_recDes(self):
    874874        """
    875         Two L{dns.Message} instances compare equal if they have the same recDes
     875        Two L{dns._Message} instances compare equal if they have the same recDes
    876876        flag.
    877877        """
    878878        self.assertNormalEqualityImplementation(
     
    884884
    885885    def test_recAv(self):
    886886        """
    887         Two L{dns.Message} instances compare equal if they have the same recAv
     887        Two L{dns._Message} instances compare equal if they have the same recAv
    888888        flag.
    889889        """
    890890        self.assertNormalEqualityImplementation(
     
    896896
    897897    def test_auth(self):
    898898        """
    899         Two L{dns.Message} instances compare equal if they have the same auth
     899        Two L{dns._Message} instances compare equal if they have the same auth
    900900        flag.
    901901        """
    902902        self.assertNormalEqualityImplementation(
     
    908908
    909909    def test_rCode(self):
    910910        """
    911         Two L{dns.Message} instances compare equal if they have the same rCode
     911        Two L{dns._Message} instances compare equal if they have the same rCode
    912912        value.
    913913        """
    914914        self.assertNormalEqualityImplementation(
     
    920920
    921921    def test_trunc(self):
    922922        """
    923         Two L{dns.Message} instances compare equal if they have the same trunc
     923        Two L{dns._Message} instances compare equal if they have the same trunc
    924924        flag.
    925925        """
    926926        self.assertNormalEqualityImplementation(
     
    932932
    933933    def test_maxSize(self):
    934934        """
    935         Two L{dns.Message} instances compare equal if they have the same
     935        Two L{dns._Message} instances compare equal if they have the same
    936936        maxSize value.
    937937        """
    938938        self.assertNormalEqualityImplementation(
     
    944944
    945945    def test_authenticData(self):
    946946        """
    947         Two L{dns.Message} instances compare equal if they have the same
     947        Two L{dns._Message} instances compare equal if they have the same
    948948        authenticData flag.
    949949        """
    950950        self.assertNormalEqualityImplementation(
     
    956956
    957957    def test_checkingDisabled(self):
    958958        """
    959         Two L{dns.Message} instances compare equal if they have the same
     959        Two L{dns._Message} instances compare equal if they have the same
    960960        checkingDisabled flag.
    961961        """
    962962        self.assertNormalEqualityImplementation(
     
    968968
    969969    def test_queries(self):
    970970        """
    971         Two L{dns.Message} instances compare equal if they have the same
     971        Two L{dns._Message} instances compare equal if they have the same
    972972        queries.
    973973        """
    974974        self.assertNormalEqualityImplementation(
     
    980980
    981981    def test_answers(self):
    982982        """
    983         Two L{dns.Message} instances compare equal if they have the same
     983        Two L{dns._Message} instances compare equal if they have the same
    984984        answers.
    985985        """
    986986        self.assertNormalEqualityImplementation(
     
    995995
    996996    def test_authority(self):
    997997        """
    998         Two L{dns.Message} instances compare equal if they have the same
     998        Two L{dns._Message} instances compare equal if they have the same
    999999        authority records.
    10001000        """
    10011001        self.assertNormalEqualityImplementation(
     
    10131013
    10141014    def test_additional(self):
    10151015        """
    1016         Two L{dns.Message} instances compare equal if they have the same
     1016        Two L{dns._Message} instances compare equal if they have the same
    10171017        additional records.
    10181018        """
    10191019        self.assertNormalEqualityImplementation(
     
    10831083        """
    10841084        d = self.proto.query(('127.0.0.1', 21345), [dns.Query(b'foo')])
    10851085        self.assertEqual(len(self.proto.liveMessages.keys()), 1)
    1086         m = dns.Message()
     1086        m = dns._Message()
    10871087        m.id = next(iter(self.proto.liveMessages.keys()))
    10881088        m.answers = [dns.RRHeader(payload=dns.Record_A(address='1.2.3.4'))]
    10891089        def cb(result):
     
    11411141        L{DNSDatagramProtocol.liveMessages} or L{DNSDatagramProtocol.resends},
    11421142        the message will be received by L{DNSDatagramProtocol.controller}.
    11431143        """
    1144         message = dns.Message()
     1144        message = dns._Message()
    11451145        message.id = 1
    11461146        message.answers = [dns.RRHeader(
    11471147            payload=dns.Record_A(address='1.2.3.4'))]
     
    12191219        """
    12201220        d = self.proto.query([dns.Query(b'foo')])
    12211221        self.assertEqual(len(self.proto.liveMessages.keys()), 1)
    1222         m = dns.Message()
     1222        m = dns._Message()
    12231223        m.id = next(iter(self.proto.liveMessages.keys()))
    12241224        m.answers = [dns.RRHeader(payload=dns.Record_A(address='1.2.3.4'))]
    12251225        def cb(result):
     
    12501250        When receiving a message whose id is not in L{DNSProtocol.liveMessages}
    12511251        the message will be received by L{DNSProtocol.controller}.
    12521252        """
    1253         message = dns.Message()
     1253        message = dns._Message()
    12541254        message.id = 1
    12551255        message.answers = [dns.RRHeader(
    12561256            payload=dns.Record_A(address='1.2.3.4'))]
     
    34283428
    34293429class MessageComparable(FancyEqMixin, FancyStrMixin, object):
    34303430    """
    3431     A wrapper around L{dns.Message} which is comparable so that it can be tested
     3431    A wrapper around L{dns._Message} which is comparable so that it can be tested
    34323432    using some of the L{dns._EDNSMessage} tests.
    34333433    """
    34343434    showAttributes = compareAttributes = (
     
    35293529class CommonConstructorTestsMixin(object):
    35303530    """
    35313531    Tests for constructor arguments and their associated attributes that are
    3532     common to both L{twisted.names.dns._EDNSMessage} and L{dns.Message}.
     3532    common to both L{twisted.names.dns._EDNSMessage} and L{dns._Message}.
    35333533
    35343534    TestCase classes that use this mixin must provide a C{messageFactory} method
    3535     which accepts any argment supported by L{dns.Message.__init__}.
     3535    which accepts any argment supported by L{dns._Message.__init__}.
    35363536
    35373537    TestCases must also mixin ConstructorTestsMixin which provides some custom
    35383538    assertions for testing constructor arguments.
     
    35703570        self._verifyConstructorArgument('maxSize', defaultVal=512, altVal=1024)
    35713571
    35723572
     3573    def test_authenticData(self):
     3574        """
     3575        L{dns._EDNSMessage.authenticData} defaults to C{False} and can be
     3576        overridden in the constructor.
     3577        """
     3578        self._verifyConstructorFlag('authenticData', defaultVal=False)
     3579
     3580
     3581    def test_checkingDisabled(self):
     3582        """
     3583        L{dns._EDNSMessage.checkingDisabled} defaults to C{False} and can be
     3584        overridden in the constructor.
     3585        """
     3586        self._verifyConstructorFlag('checkingDisabled', defaultVal=False)
     3587
     3588
    35733589    def test_queries(self):
    35743590        """
    35753591        L{dns._EDNSMessage.queries} defaults to C{[]}.
     
    35993615
    36003616
    36013617
    3602 class EDNSMessageConstructorTests(ConstructorTestsMixin,
    3603                                   CommonConstructorTestsMixin,
    3604                                   unittest.SynchronousTestCase):
    3605     """
    3606     Tests for L{twisted.names.dns._EDNSMessage} constructor arguments that are
    3607     shared with L{dns.Message}.
    3608     """
    3609     messageFactory = dns._EDNSMessage
    3610 
    3611 
    3612 
    3613 class MessageConstructorTests(ConstructorTestsMixin,
    3614                               CommonConstructorTestsMixin,
    3615                               unittest.SynchronousTestCase):
    3616     """
    3617     Tests for L{twisted.names.dns.Message} constructor arguments that are shared
    3618     with L{dns._EDNSMessage}.
    3619     """
    3620     messageFactory = dns.Message
    3621 
    3622 
    3623 
    3624 class MessageSpecificsTestCase(ConstructorTestsMixin,
    3625                                unittest.SynchronousTestCase):
    3626     """
    3627     Tests for L{dns.Message}.
    3628 
    3629     These tests are for L{dns.Message} APIs which are not shared with
    3630     L{dns._EDNSMessage}.
    3631     """
    3632     messageFactory = dns.Message
    3633 
    3634     def test_auth(self):
    3635         """
    3636         L{dns.Message.auth} defaults to C{False} and can be overridden in the
    3637         constructor.
    3638         """
    3639         self._verifyConstructorFlag('auth', defaultVal=False)
    3640 
    3641 
    3642     def test_recDes(self):
    3643         """
    3644         L{dns.Message.recDes} defaults to C{False} and can be overridden in the
    3645         constructor.
    3646         """
    3647         self._verifyConstructorFlag('recDes', defaultVal=False)
    3648 
    3649 
    3650     def test_recAv(self):
    3651         """
    3652         L{dns.Message.recAv} defaults to C{False} and can be overridden in the
    3653         constructor.
    3654         """
    3655         self._verifyConstructorFlag('recAv', defaultVal=False)
    3656 
    3657 
    3658     def test_responseCode(self):
    3659         """
    3660         L{dns.Message.rCode} defaults to C{0} and can be overridden in the
    3661         constructor.
    3662         """
    3663         self._verifyConstructorArgument('rCode', defaultVal=0, altVal=123)
    3664 
    3665 
    3666     def test_trunc(self):
    3667         """
    3668         L{dns.Message.trunc} defaults to C{False} and can be overridden in the
    3669         constructor.
    3670         """
    3671         self._verifyConstructorFlag('trunc', defaultVal=False)
    3672 
    3673 
    3674 
    3675 class EDNSMessageSpecificsTestCase(ConstructorTestsMixin,
    3676                                    unittest.SynchronousTestCase):
    3677     """
    3678     Tests for L{dns._EDNSMessage}.
    3679 
    3680     These tests are for L{dns._EDNSMessage} APIs which are not shared with
    3681     L{dns.Message}.
    3682     """
    3683     messageFactory = dns._EDNSMessage
    3684 
     3618class NewStyleConstructorTestsMixin(object):
     3619    """
     3620    Tests for the new meaningful constructor arguments and attribute names which
     3621    were introduced with L{_EDNSMessage} and L{StandardMessage}.
     3622    """
    36853623    def test_authoritativeAnswer(self):
    36863624        """
    36873625        L{dns._EDNSMessage.authoritativeAnswer} defaults to C{False} and can be
     
    37223660        """
    37233661        self._verifyConstructorFlag('truncated', defaultVal=False)
    37243662
    3725 
    3726     def test_ednsVersion(self):
    3727         """
    3728         L{dns._EDNSMessage.ednsVersion} defaults to C{0} and can be overridden
    3729         in the constructor.
    3730         """
    3731         self._verifyConstructorArgument(
    3732             'ednsVersion', defaultVal=0, altVal=None)
    3733 
    3734 
    3735     def test_dnssecOK(self):
    3736         """
    3737         L{dns._EDNSMessage.dnssecOK} defaults to C{False} and can be overridden
    3738         in the constructor.
    3739         """
    3740         self._verifyConstructorFlag('dnssecOK', defaultVal=False)
    3741 
    3742 
    3743     def test_authenticData(self):
    3744         """
    3745         L{dns._EDNSMessage.authenticData} defaults to C{False} and can be
    3746         overridden in the constructor.
    3747         """
    3748         self._verifyConstructorFlag('authenticData', defaultVal=False)
    3749 
    3750 
    3751     def test_checkingDisabled(self):
    3752         """
    3753         L{dns._EDNSMessage.checkingDisabled} defaults to C{False} and can be
    3754         overridden in the constructor.
    3755         """
    3756         self._verifyConstructorFlag('checkingDisabled', defaultVal=False)
    3757 
    3758 
    37593663    def test_queriesOverride(self):
    37603664        """
    37613665        L{dns._EDNSMessage.queries} can be overridden in the constructor.
     
    38143718            [dns.RRHeader(b'example.com', payload=dns.Record_A('1.2.3.4'))])
    38153719
    38163720
     3721
     3722class EDNSMessageConstructorTests(ConstructorTestsMixin,
     3723                                  CommonConstructorTestsMixin,
     3724                                  NewStyleConstructorTestsMixin,
     3725                                  unittest.SynchronousTestCase):
     3726    """
     3727    Tests for L{twisted.names.dns._EDNSMessage} constructor arguments that are
     3728    shared with L{dns._Message}.
     3729    """
     3730    messageFactory = dns._EDNSMessage
     3731
     3732
     3733
     3734class StandardMessageConstructorTests(ConstructorTestsMixin,
     3735                                      CommonConstructorTestsMixin,
     3736                                      NewStyleConstructorTestsMixin,
     3737                                      unittest.SynchronousTestCase):
     3738    """
     3739    Tests for L{twisted.names.dns.StandardMessage} constructor arguments that
     3740    are shared with L{dns._EDNSMessage}.
     3741    """
     3742    messageFactory = dns.StandardMessage
     3743
     3744
     3745
     3746class MessageConstructorTests(ConstructorTestsMixin,
     3747                              CommonConstructorTestsMixin,
     3748                              unittest.SynchronousTestCase):
     3749    """
     3750    Tests for L{twisted.names.dns._Message} constructor arguments that are shared
     3751    with L{dns._EDNSMessage}.
     3752    """
     3753    messageFactory = dns._Message
     3754
     3755
     3756
     3757class MessageSpecificsTestCase(ConstructorTestsMixin,
     3758                               unittest.SynchronousTestCase):
     3759    """
     3760    Tests for L{dns._Message}.
     3761
     3762    These tests are for L{dns._Message} APIs which are not shared with
     3763    L{dns._EDNSMessage}.
     3764    """
     3765    messageFactory = dns._Message
     3766
     3767    def test_auth(self):
     3768        """
     3769        L{dns._Message.auth} defaults to C{False} and can be overridden in the
     3770        constructor.
     3771        """
     3772        self._verifyConstructorFlag('auth', defaultVal=False)
     3773
     3774
     3775    def test_recDes(self):
     3776        """
     3777        L{dns._Message.recDes} defaults to C{False} and can be overridden in the
     3778        constructor.
     3779        """
     3780        self._verifyConstructorFlag('recDes', defaultVal=False)
     3781
     3782
     3783    def test_recAv(self):
     3784        """
     3785        L{dns._Message.recAv} defaults to C{False} and can be overridden in the
     3786        constructor.
     3787        """
     3788        self._verifyConstructorFlag('recAv', defaultVal=False)
     3789
     3790
     3791    def test_rCode(self):
     3792        """
     3793        L{dns._Message.rCode} defaults to C{0} and can be overridden in the
     3794        constructor.
     3795        """
     3796        self._verifyConstructorArgument('rCode', defaultVal=0, altVal=123)
     3797
     3798
     3799    def test_trunc(self):
     3800        """
     3801        L{dns._Message.trunc} defaults to C{False} and can be overridden in the
     3802        constructor.
     3803        """
     3804        self._verifyConstructorFlag('trunc', defaultVal=False)
     3805
     3806
     3807
     3808class EDNSMessageSpecificsTestCase(ConstructorTestsMixin,
     3809                                   unittest.SynchronousTestCase):
     3810    """
     3811    Tests for L{dns._EDNSMessage}.
     3812
     3813    These tests are for L{dns._EDNSMessage} APIs which are not shared with
     3814    L{dns._Message}.
     3815    """
     3816    messageFactory = dns._EDNSMessage
     3817
     3818    def test_ednsVersion(self):
     3819        """
     3820        L{dns._EDNSMessage.ednsVersion} defaults to C{0} and can be overridden
     3821        in the constructor.
     3822        """
     3823        self._verifyConstructorArgument(
     3824            'ednsVersion', defaultVal=0, altVal=None)
     3825
     3826
     3827    def test_dnssecOK(self):
     3828        """
     3829        L{dns._EDNSMessage.dnssecOK} defaults to C{False} and can be overridden
     3830        in the constructor.
     3831        """
     3832        self._verifyConstructorFlag('dnssecOK', defaultVal=False)
     3833
     3834
    38173835    def test_repr(self):
    38183836        """
    38193837        L{dns._EDNSMessage.__repr__} displays the id, answer, opCode,
     
    38463864    def test_fromStrCallsMessageFactory(self):
    38473865        """
    38483866        L{dns._EDNSMessage.fromString} calls L{dns._EDNSMessage._messageFactory}
    3849         to create a new L{dns.Message} instance which is used to decode the
     3867        to create a new L{dns._Message} instance which is used to decode the
    38503868        supplied bytes.
    38513869        """
    38523870        class FakeMessageFactory(object):
     
    38623880                """
    38633881                raise RaisedArgs(args, kwargs)
    38643882
    3865         m = dns._EDNSMessage()
    3866         m._messageFactory = FakeMessageFactory
     3883        class RaisingEdnsMessage(dns._EDNSMessage):
     3884            _messageFactory = FakeMessageFactory
    38673885        dummyBytes = object()
    3868         e = self.assertRaises(RaisedArgs, m.fromStr, dummyBytes)
     3886        e = self.assertRaises(RaisedArgs, RaisingEdnsMessage.fromStr, dummyBytes)
    38693887        self.assertEqual(
    38703888            ((dummyBytes,), {}),
    38713889            (e.args, e.kwargs)
     
    38753893    def test_fromStrCallsFromMessage(self):
    38763894        """
    38773895        L{dns._EDNSMessage.fromString} calls L{dns._EDNSMessage._fromMessage}
    3878         with a L{dns.Message} instance
     3896        with a L{dns._Message} instance
    38793897        """
    38803898        m = dns._EDNSMessage()
    38813899        class FakeMessageFactory():
     
    38903908                """
    38913909
    38923910        fakeMessage = FakeMessageFactory()
    3893         m._messageFactory = lambda: fakeMessage
    3894 
    3895         def fakeFromMessage(*args, **kwargs):
    3896             raise RaisedArgs(args, kwargs)
    3897         m._fromMessage = fakeFromMessage
    3898         e = self.assertRaises(RaisedArgs, m.fromStr, b'')
     3911
     3912        class TestableEDNSMessage(dns._EDNSMessage):
     3913            @staticmethod
     3914            def _messageFactory():
     3915                return fakeMessage
     3916
     3917            @classmethod
     3918            def _fromMessage(cls, *args, **kwargs):
     3919                raise RaisedArgs(args, kwargs)
     3920
     3921        e = self.assertRaises(RaisedArgs, TestableEDNSMessage.fromStr, b'')
    38993922        self.assertEqual(
    39003923            ((fakeMessage,), {}),
    39013924            (e.args, e.kwargs)
     
    39513974    """
    39523975    Tests for equality between L(dns._EDNSMessage} instances.
    39533976
    3954     These tests will not work with L{dns.Message} because it does not use
     3977    These tests will not work with L{dns._Message} because it does not use
    39553978    L{twisted.python.util.FancyEqMixin}.
    39563979    """
    39573980
     
    41784201    """
    41794202    Tests for the encoding and decoding of various standard (not EDNS) messages.
    41804203
    4181     These tests should work with both L{dns._EDNSMessage} and L{dns.Message}.
     4204    These tests should work with both L{dns._EDNSMessage} and L{dns._Message}.
    41824205
    41834206    TestCase classes that use this mixin must provide a C{messageFactory} method
    41844207    which accepts any argment supported by L{dns._EDNSMessage.__init__}.
     
    41994222        """
    42004223        An empty message byte sequence can be decoded.
    42014224        """
    4202         m = self.messageFactory()
    4203         m.fromStr(MessageEmpty.bytes())
    4204 
    4205         self.assertEqual(m, self.messageFactory(**MessageEmpty.kwargs()))
     4225        self.assertEqual(
     4226            self.messageFactory(**MessageEmpty.kwargs()),
     4227            self.messageFactory.fromStr(MessageEmpty.bytes())
     4228        )
    42064229
    42074230
    42084231    def test_completeQueryEncode(self):
     
    42184241        """
    42194242        A fully populated message byte string can be decoded.
    42204243        """
    4221         m = self.messageFactory()
    4222         m.fromStr(MessageComplete.bytes()),
    4223 
    4224         self.assertEqual(m, self.messageFactory(**MessageComplete.kwargs()))
     4244        self.assertEqual(
     4245            self.messageFactory(**MessageComplete.kwargs()),
     4246            self.messageFactory.fromStr(MessageComplete.bytes())
     4247        )
    42254248
    42264249
    42274250    def test_NULL(self):
     
    42364259        msg1.answers.append(rr)
    42374260        s = msg1.toStr()
    42384261
    4239         msg2 = self.messageFactory()
    4240         msg2.fromStr(s)
     4262        msg2 = self.messageFactory.fromStr(s)
    42414263
    42424264        self.assertIsInstance(msg2.answers[0].payload, dns.Record_NULL)
    42434265        self.assertEqual(msg2.answers[0].payload.payload, bytes)
     
    42584280        The L{dns.RRHeader} instances created by a message from a
    42594281        non-authoritative message byte string are marked as not authoritative.
    42604282        """
    4261         m = self.messageFactory()
    4262         m.fromStr(MessageNonAuthoritative.bytes())
    4263 
    42644283        self.assertEqual(
    4265             m, self.messageFactory(**MessageNonAuthoritative.kwargs()))
     4284            self.messageFactory(**MessageNonAuthoritative.kwargs()),
     4285            self.messageFactory.fromStr(MessageNonAuthoritative.bytes())
     4286        )
    42664287
    42674288
    42684289    def test_authoritativeMessageEncode(self):
     
    42804301        The message and its L{dns.RRHeader} instances created by C{decode} from
    42814302        an authoritative message byte string, are marked as authoritative.
    42824303        """
    4283         m = self.messageFactory()
    4284         m.fromStr(MessageAuthoritative.bytes())
    4285 
    42864304        self.assertEqual(
    4287             m, self.messageFactory(**MessageAuthoritative.kwargs()))
     4305            self.messageFactory(**MessageAuthoritative.kwargs()),
     4306            self.messageFactory.fromStr(MessageAuthoritative.bytes())
     4307        )
    42884308
    42894309
    42904310    def test_truncatedMessageEncode(self):
     
    43024322        The message instance created by decoding a truncated message is marked
    43034323        as truncated.
    43044324        """
    4305         m = self.messageFactory()
    4306         m.fromStr(MessageTruncated.bytes())
    4307 
    4308         self.assertEqual(m, self.messageFactory(**MessageTruncated.kwargs()))
     4325        self.assertEqual(
     4326            self.messageFactory(**MessageTruncated.kwargs()),
     4327            self.messageFactory.fromStr(MessageTruncated.bytes())
     4328        )
    43094329
    43104330
    43114331
     
    43184338    messageFactory = dns._EDNSMessage
    43194339
    43204340
    4321 
    4322 class MessageStandardEncodingTests(StandardEncodingTestsMixin,
    4323                                    unittest.SynchronousTestCase):
     4341class StandardMessageAdaptor(object):
     4342    def __new__(cls, **kwargs):
     4343        """
     4344        This function adapts constructor arguments expected by
     4345        _EDNSMessage.__init__ to arguments suitable for use with the
     4346        StandardMessage.__init__.
     4347
     4348        Removes any L{dns._EDNSMessage} specific arguments.
     4349
     4350        @param kwargs: The keyword arguments which will be stripped of EDNS
     4351            specific arguments before being passed to
     4352            L{dns.StandardMessage.__init__}.
     4353
     4354        @return: An L{dns.StandardMessage} instance.
     4355        """
     4356        kwargs.pop('ednsVersion', None)
     4357        return dns.StandardMessage(**kwargs)
     4358
     4359
     4360    @classmethod
     4361    def fromStr(cls, bytes):
     4362        return dns.StandardMessage.fromStr(bytes)
     4363
     4364
     4365
     4366class StandardMessageStandardEncodingTests(StandardEncodingTestsMixin,
     4367                                           unittest.SynchronousTestCase):
    43244368    """
    43254369    Tests for the encoding and decoding of various standard (non-EDNS) messages
    4326     by L{dns.Message}.
     4370    by L{dns.StandardMessage}.
    43274371    """
    4328     @staticmethod
    4329     def messageFactory(**kwargs):
     4372    messageFactory = StandardMessageAdaptor
     4373
     4374
     4375
     4376class LegacyMessageAdaptor(object):
     4377    def __new__(cls, **kwargs):
    43304378        """
    43314379        This function adapts constructor arguments expected by
    43324380        _EDNSMessage.__init__ to arguments suitable for use with the
    43334381        Message.__init__.
    43344382
    43354383        Also handles the fact that unlike L{dns._EDNSMessage},
    4336         L{dns.Message.__init__} does not accept queries, answers etc as
     4384        L{dns._Message.__init__} does not accept queries, answers etc as
    43374385        arguments.
    43384386
    43394387        Also removes any L{dns._EDNSMessage} specific arguments.
    43404388
    43414389        @param args: The positional arguments which will be passed to
    4342             L{dns.Message.__init__}.
     4390            L{dns._Message.__init__}.
    43434391
    43444392        @param kwargs: The keyword arguments which will be stripped of EDNS
    4345             specific arguments before being passed to L{dns.Message.__init__}.
     4393            specific arguments before being passed to L{dns._Message.__init__}.
    43464394
    4347         @return: An L{dns.Message} instance.
     4395        @return: An L{dns._Message} instance.
    43484396        """
    43494397        kwargs['auth'] = kwargs.pop('authoritativeAnswer', False)
    43504398        kwargs['recDes'] = kwargs.pop('recursionDesired', False)
     
    43594407
    43604408        kwargs.pop('ednsVersion', None)
    43614409
    4362         m = dns.Message(**kwargs)
     4410        m = dns._Message(**kwargs)
    43634411        m.queries = queries
    43644412        m.answers = answers
    43654413        m.authority = authority
    43664414        m.additional = additional
    4367         return MessageComparable(m)
     4415        return m
     4416
     4417
     4418    @classmethod
     4419    def fromStr(cls, bytes):
     4420        m = dns._Message()
     4421        m.fromStr(bytes)
     4422        return m
     4423
     4424
     4425
     4426class MessageStandardEncodingTests(StandardEncodingTestsMixin,
     4427                                   unittest.SynchronousTestCase):
     4428    """
     4429    Tests for the encoding and decoding of various standard (non-EDNS) messages
     4430    by L{dns._Message}.
     4431    """
     4432    messageFactory = LegacyMessageAdaptor
    43684433
    43694434
    43704435
     
    43724437    """
    43734438    Tests for the encoding and decoding of various EDNS messages.
    43744439
    4375     These test will not work with L{dns.Message}.
     4440    These test will not work with L{dns._Message}.
    43764441    """
    43774442    messageFactory = dns._EDNSMessage
    43784443
     
    43814446        The L(_EDNSMessage} instance created by L{dns._EDNSMessage.decode} from
    43824447        an EDNS query never includes OPT records in the additional section.
    43834448        """
    4384         m = self.messageFactory()
    4385         m.fromStr(MessageEDNSQuery.bytes())
    4386 
    4387         self.assertEqual(m.additional, [])
     4449        self.assertEqual(
     4450            self.messageFactory.fromStr(MessageEDNSQuery.bytes()).additional,
     4451            []
     4452        )
    43884453
    43894454
    43904455    def test_ednsMessageDecodeMultipleOptRecords(self):
     
    43964461
    43974462        @see: U{https://tools.ietf.org/html/rfc6891#section-6.1.1}
    43984463        """
    4399         m = dns.Message()
     4464        m = dns._Message()
    44004465        m.additional = [
    44014466            dns._OPTHeader(version=2),
    44024467            dns._OPTHeader(version=3)]
    44034468
    4404         ednsMessage = dns._EDNSMessage()
    4405         ednsMessage.fromStr(m.toStr())
    4406 
    4407         self.assertEqual(ednsMessage.ednsVersion, None)
     4469        self.assertEqual(
     4470            None,
     4471            dns._EDNSMessage.fromStr(m.toStr()).ednsVersion
     4472        )
    44084473
    44094474
    44104475    def test_fromMessageCopiesSections(self):
     
    44134478        whose queries, answers, authority and additional lists are copies (not
    44144479        references to) the original message lists.
    44154480        """
    4416         standardMessage = dns.Message()
     4481        standardMessage = dns._Message()
    44174482        standardMessage.fromStr(MessageEDNSQuery.bytes())
    44184483
    44194484        ednsMessage = dns._EDNSMessage._fromMessage(standardMessage)
     
    44564521        optRRHeader = dns.RRHeader()
    44574522        b.seek(0)
    44584523        optRRHeader.decode(b)
    4459         m = dns.Message()
     4524        m = dns._Message()
    44604525        m.additional = [optRRHeader]
    44614526
    44624527        actualMessages = []
     
    44824547        derives its edns specific values (C{ednsVersion}, etc) from the supplied
    44834548        OPT record.
    44844549        """
    4485         m = self.messageFactory()
    4486         m.fromStr(MessageEDNSComplete.bytes())
    4487 
    4488         self.assertEqual(m, self.messageFactory(**MessageEDNSComplete.kwargs()))
     4550        self.assertEqual(
     4551            self.messageFactory(**MessageEDNSComplete.kwargs()),
     4552            self.messageFactory.fromStr(MessageEDNSComplete.bytes())
     4553        )
    44894554
    44904555
    44914556    def test_ednsEncode(self):
     
    45154580        The L(_EDNSMessage} instance created by L{dns._EDNSMessage.fromStr}
    45164581        derives RCODE from the supplied OPT record.
    45174582        """
    4518         m = self.messageFactory()
    4519         m.fromStr(MessageEDNSExtendedRCODE.bytes())
    4520 
    45214583        self.assertEqual(
    4522             m, self.messageFactory(**MessageEDNSExtendedRCODE.kwargs()))
     4584            self.messageFactory(**MessageEDNSExtendedRCODE.kwargs()),
     4585            self.messageFactory.fromStr(MessageEDNSExtendedRCODE.bytes())
     4586        )
    45234587
    45244588
    45254589    def test_extendedRcodeZero(self):
  • twisted/names/test/test_names.py

    === modified file 'twisted/names/test/test_names.py'
     
    475475
    476476    def _makeMessage(self):
    477477        # hooray they all have the same message format
    478         return dns.Message(id=999, answer=1, opCode=0, recDes=0, recAv=1, auth=1, rCode=0, trunc=0, maxSize=0)
     478        return dns.StandardMessage(
     479            id=999,
     480            answer=1,
     481            opCode=0,
     482            recursionDesired=0,
     483            recursionAvailable=1,
     484            authoritativeAnswer=1,
     485            responseCode=0,
     486            truncated=0,
     487            maxSize=0
     488        )
    479489
    480490    def testBindAndTNamesStyle(self):
    481491        # Bind style = One big single message
     
    852862                         auth=False,
    853863                         payload=dns.Record_NS(name='ns.twistedmatrix.com',
    854864                         ttl=700))]
    855         m = dns.Message(id=999, answer=1, opCode=0, recDes=0, recAv=1, auth=1,
    856                         rCode=0, trunc=0, maxSize=0)
     865        m = dns.StandardMessage(
     866            id=999,
     867            answer=1,
     868            opCode=0,
     869            recursionDesired=0,
     870            recursionAvailable=1,
     871            authoritativeAnswer=1,
     872            responseCode=0,
     873            truncated=0,
     874            maxSize=0
     875        )
    857876        m.answers = records
    858877        messages.append(m)
    859878        return self.assertFailure(
  • twisted/names/test/test_rootresolve.py

    === modified file 'twisted/names/test/test_rootresolve.py'
     
    2121from twisted.names.root import Resolver
    2222from twisted.names.dns import (
    2323    IN, HS, A, NS, CNAME, OK, ENAME, Record_CNAME,
    24     Name, Query, Message, RRHeader, Record_A, Record_NS)
     24    Name, Query, StandardMessage, RRHeader, Record_A, Record_NS)
    2525from twisted.names.error import DNSNameError, ResolverError
    2626
    2727
     
    172172        # And a DNS packet sent.
    173173        [(packet, address)] = transport._sentPackets
    174174
    175         msg = Message()
    176         msg.fromStr(packet)
     175        msg = StandardMessage.fromStr(packet)
    177176
    178177        # It should be a query with the parameters used above.
    179178        self.assertEqual(msg.queries, [Query(b'foo.example.com', A, IN)])
     
    215214        L{Message} instance.
    216215        """
    217216        message = self._queryTest(False)
    218         self.assertIsInstance(message, Message)
     217        self.assertIsInstance(message, StandardMessage)
    219218        self.assertEqual(message.queries, [])
    220219        self.assertEqual(
    221220            message.answers,
     
    226225
    227226    def _respond(self, answers=[], authority=[], additional=[], rCode=OK):
    228227        """
    229         Create a L{Message} suitable for use as a response to a query.
     228        Create a L{StandardMessage} suitable for use as a response to a query.
    230229
    231230        @param answers: A C{list} of two-tuples giving data for the answers
    232231            section of the message.  The first element of each tuple is a name
     
    237236            additional section of the response.
    238237        @param rCode: The response code the message will be created with.
    239238
    240         @return: A new L{Message} initialized with the given values.
     239        @return: A new L{StandardMessage} initialized with the given values.
    241240        """
    242         response = Message(rCode=rCode)
     241        response = StandardMessage(responseCode=rCode)
    243242        for (section, data) in [(response.answers, answers),
    244243                                (response.authority, authority),
    245244                                (response.additional, additional)]:
  • twisted/names/test/test_server.py

    === modified file 'twisted/names/test/test_server.py'
     
    417417        L{server.DNSServerFactory.messageReceived} logs about an empty query if
    418418        the message had no queries and C{verbose} is C{>0}.
    419419        """
    420         m = dns.Message()
     420        m = dns.StandardMessage()
    421421        f = NoResponseDNSServerFactory(verbose=1)
    422422
    423423        assertLogMessage(
     
    432432        L{server.DNSServerFactory.messageReceived} logs the query types of all
    433433        queries in the message if C{verbose} is set to C{1}.
    434434        """
    435         m = dns.Message()
     435        m = dns.StandardMessage()
    436436        m.addQuery(name='example.com', type=dns.MX)
    437437        m.addQuery(name='example.com', type=dns.AAAA)
    438438        f = NoResponseDNSServerFactory(verbose=1)
     
    449449        L{server.DNSServerFactory.messageReceived} logs the repr of all queries
    450450        in the message if C{verbose} is set to C{2}.
    451451        """
    452         m = dns.Message()
     452        m = dns.StandardMessage()
    453453        m.addQuery(name='example.com', type=dns.MX)
    454454        m.addQuery(name='example.com', type=dns.AAAA)
    455455        f = NoResponseDNSServerFactory(verbose=2)
     
    467467        L{server.DNSServerFactory.messageReceived} assigns a unix timestamp to
    468468        the received message.
    469469        """
    470         m = dns.Message()
     470        m = dns.StandardMessage()
    471471        f = NoResponseDNSServerFactory()
    472472        t = object()
    473473        self.patch(server.time, 'time', lambda: t)
     
    482482        L{server.DNSServerFactory.allowQuery} along with the receiving protocol
    483483        and origin address.
    484484        """
    485         message = dns.Message()
     485        message = dns.StandardMessage()
    486486        dummyProtocol = object()
    487487        dummyAddress = object()
    488488
     
    516516        e = self.assertRaises(
    517517            SendReplyException,
    518518            f.messageReceived,
    519             message=dns.Message(), proto=None, address=None)
     519            message=dns.StandardMessage(), proto=None, address=None)
    520520        (proto, message, address), kwargs = e.args
    521521
    522522        self.assertEqual(message.rCode, dns.EREFUSED)
     
    533533
    534534        @param message: The message which is expected to be passed to the
    535535            C{methodName} method.
    536         @type message: L{dns.Message}
     536        @type message: L{dns.StandardMessage}
    537537        """
    538538        # Make it appear to have some queries so that
    539539        # DNSServerFactory.allowQuery allows it.
     
    556556        C{OP_QUERY} on to L{DNSServerFactory.handleQuery}.
    557557        """
    558558        self._messageReceivedTest(
    559             'handleQuery', dns.Message(opCode=dns.OP_QUERY))
     559            'handleQuery', dns.StandardMessage(opCode=dns.OP_QUERY))
    560560
    561561
    562562    def test_inverseQueryMessageReceived(self):
     
    565565        C{OP_INVERSE} on to L{DNSServerFactory.handleInverseQuery}.
    566566        """
    567567        self._messageReceivedTest(
    568             'handleInverseQuery', dns.Message(opCode=dns.OP_INVERSE))
     568            'handleInverseQuery', dns.StandardMessage(opCode=dns.OP_INVERSE))
    569569
    570570
    571571    def test_statusMessageReceived(self):
     
    574574        C{OP_STATUS} on to L{DNSServerFactory.handleStatus}.
    575575        """
    576576        self._messageReceivedTest(
    577             'handleStatus', dns.Message(opCode=dns.OP_STATUS))
     577            'handleStatus', dns.StandardMessage(opCode=dns.OP_STATUS))
    578578
    579579
    580580    def test_notifyMessageReceived(self):
     
    583583        C{OP_NOTIFY} on to L{DNSServerFactory.handleNotify}.
    584584        """
    585585        self._messageReceivedTest(
    586             'handleNotify', dns.Message(opCode=dns.OP_NOTIFY))
     586            'handleNotify', dns.StandardMessage(opCode=dns.OP_NOTIFY))
    587587
    588588
    589589    def test_updateMessageReceived(self):
     
    594594        This may change if the implementation ever covers update messages.
    595595        """
    596596        self._messageReceivedTest(
    597             'handleOther', dns.Message(opCode=dns.OP_UPDATE))
     597            'handleOther', dns.StandardMessage(opCode=dns.OP_UPDATE))
    598598
    599599
    600600    def test_connectionTracking(self):
     
    621621        supplied message and dispatches it to
    622622        L{server.DNSServerFactory.resolver.query}.
    623623        """
    624         m = dns.Message()
     624        m = dns.StandardMessage()
    625625        m.addQuery(b'one.example.com')
    626626        m.addQuery(b'two.example.com')
    627627        f = server.DNSServerFactory()
     
    656656            gotResolverResponseArgs.append((args, kwargs))
    657657        f.gotResolverResponse = fakeGotResolverResponse
    658658
    659         m = dns.Message()
     659        m = dns.StandardMessage()
    660660        m.addQuery(b'one.example.com')
    661661        stubProtocol = NoopProtocol()
    662662        dummyAddress = object()
     
    692692            gotResolverErrorArgs.append((args, kwargs))
    693693        f.gotResolverError = fakeGotResolverError
    694694
    695         m = dns.Message()
     695        m = dns.StandardMessage()
    696696        m.addQuery(b'one.example.com')
    697697        stubProtocol = NoopProtocol()
    698698        dummyAddress = object()
     
    721721            RaisingProtocol.WriteMessageArguments,
    722722            f.gotResolverResponse,
    723723            (answers, authority, additional),
    724             protocol=RaisingProtocol(), message=dns.Message(), address=None)
     724            protocol=RaisingProtocol(), message=dns.StandardMessage(), address=None)
    725725        (message,), kwargs = e.args
    726726
    727727        self.assertIs(message.answers, answers)
     
    742742            RaisingProtocol.WriteMessageArguments,
    743743            f.gotResolverResponse,
    744744            (answers, authority, additional),
    745             protocol=RaisingProtocol(), message=dns.Message(), address=None)
     745            protocol=RaisingProtocol(), message=dns.StandardMessage(), address=None)
    746746        (message,), kwargs = e.args
    747747
    748748        self.assertTrue(
     
    765765            ["Lookup found 3 records"],
    766766            f.gotResolverResponse,
    767767            (answers, authority, additional),
    768             protocol=NoopProtocol(), message=dns.Message(), address=None)
     768            protocol=NoopProtocol(), message=dns.StandardMessage(), address=None)
    769769
    770770
    771771    def test_gotResolverResponseCaching(self):
     
    775775        """
    776776        f = NoResponseDNSServerFactory(caches=[RaisingCache()])
    777777
    778         m = dns.Message()
     778        m = dns.StandardMessage()
    779779        m.addQuery(b'example.com')
    780780        expectedAnswers = [dns.RRHeader()]
    781781        expectedAuthority = []
     
    815815            RaisingProtocol.WriteMessageArguments,
    816816            f.gotResolverError,
    817817            failure.Failure(responseError),
    818             protocol=RaisingProtocol(), message=dns.Message(), address=None)
     818            protocol=RaisingProtocol(), message=dns.StandardMessage(), address=None)
    819819        (message,), kwargs = e.args
    820820
    821821        self.assertEqual(message.rCode, expectedMessageCode)
     
    860860            ["Lookup failed"],
    861861            f.gotResolverError,
    862862            failure.Failure(error.DomainError()),
    863             protocol=NoopProtocol(), message=dns.Message(), address=None)
     863            protocol=NoopProtocol(), message=dns.StandardMessage(), address=None)
    864864
    865865
    866866    def test_sendReplyWithAddress(self):
     
    869869        *and* an address tuple it will supply that address to
    870870        C{protocol.writeMessage}.
    871871        """
    872         m = dns.Message()
     872        m = dns.StandardMessage()
    873873        dummyAddress = object()
    874874        f = server.DNSServerFactory()
    875875        e = self.assertRaises(
     
    889889        no address tuple it will supply only a message to
    890890        C{protocol.writeMessage}.
    891891        """
    892         m = dns.Message()
     892        m = dns.StandardMessage()
    893893        f = server.DNSServerFactory()
    894894        e = self.assertRaises(
    895895            RaisingProtocol.WriteMessageArguments,
     
    908908        the supplied message has no answers.
    909909        """
    910910        self.patch(server.time, 'time', lambda: 2)
    911         m = dns.Message()
     911        m = dns.StandardMessage()
    912912        m.timeReceived = 1
    913913        f = server.DNSServerFactory(verbose=2)
    914914        assertLogMessage(
     
    927927        those sections.
    928928        """
    929929        self.patch(server.time, 'time', lambda: 2)
    930         m = dns.Message()
     930        m = dns.StandardMessage()
    931931        m.answers.append(dns.RRHeader(payload=dns.Record_A('127.0.0.1')))
    932932        m.authority.append(dns.RRHeader(payload=dns.Record_A('127.0.0.1')))
    933933        m.additional.append(dns.RRHeader(payload=dns.Record_A('127.0.0.1')))
     
    954954        e = self.assertRaises(
    955955            RaisingProtocol.WriteMessageArguments,
    956956            f.handleInverseQuery,
    957             message=dns.Message(), protocol=RaisingProtocol(), address=None)
     957            message=dns.StandardMessage(), protocol=RaisingProtocol(), address=None)
    958958        (message,), kwargs = e.args
    959959
    960960        self.assertEqual(message.rCode, dns.ENOTIMP)
     
    970970            self,
    971971            ["Inverse query from ('::1', 53)"],
    972972            f.handleInverseQuery,
    973             message=dns.Message(),
     973            message=dns.StandardMessage(),
    974974            protocol=NoopProtocol(),
    975975            address=('::1', 53))
    976976
     
    984984        e = self.assertRaises(
    985985            RaisingProtocol.WriteMessageArguments,
    986986            f.handleStatus,
    987             message=dns.Message(), protocol=RaisingProtocol(), address=None)
     987            message=dns.StandardMessage(), protocol=RaisingProtocol(), address=None)
    988988        (message,), kwargs = e.args
    989989
    990990        self.assertEqual(message.rCode, dns.ENOTIMP)
     
    10001000            self,
    10011001            ["Status request from ('::1', 53)"],
    10021002            f.handleStatus,
    1003             message=dns.Message(),
     1003            message=dns.StandardMessage(),
    10041004            protocol=NoopProtocol(),
    10051005            address=('::1', 53))
    10061006
     
    10141014        e = self.assertRaises(
    10151015            RaisingProtocol.WriteMessageArguments,
    10161016            f.handleNotify,
    1017             message=dns.Message(), protocol=RaisingProtocol(), address=None)
     1017            message=dns.StandardMessage(), protocol=RaisingProtocol(), address=None)
    10181018        (message,), kwargs = e.args
    10191019
    10201020        self.assertEqual(message.rCode, dns.ENOTIMP)
     
    10301030            self,
    10311031            ["Notify message from ('::1', 53)"],
    10321032            f.handleNotify,
    1033             message=dns.Message(),
     1033            message=dns.StandardMessage(),
    10341034            protocol=NoopProtocol(),
    10351035            address=('::1', 53))
    10361036
     
    10441044        e = self.assertRaises(
    10451045            RaisingProtocol.WriteMessageArguments,
    10461046            f.handleOther,
    1047             message=dns.Message(), protocol=RaisingProtocol(), address=None)
     1047            message=dns.StandardMessage(), protocol=RaisingProtocol(), address=None)
    10481048        (message,), kwargs = e.args
    10491049
    10501050        self.assertEqual(message.rCode, dns.ENOTIMP)
     
    10601060            self,
    10611061            ["Unknown op code (0) from ('::1', 53)"],
    10621062            f.handleOther,
    1063             message=dns.Message(),
     1063            message=dns.StandardMessage(),
    10641064            protocol=NoopProtocol(),
    10651065            address=('::1', 53))