Ticket #5564: 5564.patch

File 5564.patch, 12.5 KB (added by piffey, 4 years ago)
  • twisted/names/test/test_rootresolve.py

     
    1717from twisted.internet.task import Clock
    1818from twisted.internet.address import IPv4Address
    1919from twisted.internet.interfaces import IReactorUDP, IUDPTransport
    20 from twisted.names.root import Resolver, lookupNameservers, lookupAddress
    21 from twisted.names.root import extractAuthority, discoverAuthority, retry
     20from twisted.names.root import Resolver
    2221from twisted.names.dns import IN, HS, A, NS, CNAME, OK, ENAME, Record_CNAME
    2322from twisted.names.dns import Query, Message, RRHeader, Record_A, Record_NS
    2423from twisted.names.error import DNSNameError, ResolverError
     
    558557        return gatherResults([failD, succeedD])
    559558
    560559
    561     def test_discoveredAuthorityDeprecated(self):
    562         """
    563         Calling L{Resolver.discoveredAuthority} produces a deprecation warning.
    564         """
    565         resolver = Resolver([])
    566         d = resolver.discoveredAuthority('127.0.0.1', 'example.com', IN, A, (0,))
    567560
    568         warnings = self.flushWarnings([
    569                 self.test_discoveredAuthorityDeprecated])
    570         self.assertEqual(warnings[0]['category'], DeprecationWarning)
    571         self.assertEqual(
    572             warnings[0]['message'],
    573             'twisted.names.root.Resolver.discoveredAuthority is deprecated since '
    574             'Twisted 10.0.  Use twisted.names.client.Resolver directly, instead.')
    575         self.assertEqual(len(warnings), 1)
    576 
    577         # This will time out quickly, but we need to wait for it because there
    578         # are resources associated with.
    579         d.addErrback(lambda ignored: None)
    580         return d
    581 
    582 
    583 
    584561class StubDNSDatagramProtocol:
    585562    """
    586563    A do-nothing stand-in for L{DNSDatagramProtocol} which can be used to avoid
     
    598575        'Resolver object for retry logic.'))
    599576
    600577
    601 class DiscoveryToolsTests(TestCase):
    602     """
    603     Tests for the free functions in L{twisted.names.root} which help out with
    604     authority discovery.  Since these are mostly deprecated, these are mostly
    605     deprecation tests.
    606     """
    607     def test_lookupNameserversDeprecated(self):
    608         """
    609         Calling L{root.lookupNameservers} produces a deprecation warning.
    610         """
    611         # Don't care about the return value, since it will never have a result,
    612         # since StubDNSDatagramProtocol doesn't actually work.
    613         lookupNameservers('example.com', '127.0.0.1', StubDNSDatagramProtocol())
    614 
    615         warnings = self.flushWarnings([
    616                 self.test_lookupNameserversDeprecated])
    617         self.assertEqual(warnings[0]['category'], DeprecationWarning)
    618         self.assertEqual(
    619             warnings[0]['message'],
    620             'twisted.names.root.lookupNameservers is deprecated since Twisted '
    621             '10.0.  Use twisted.names.root.Resolver.lookupNameservers '
    622             'instead.')
    623         self.assertEqual(len(warnings), 1)
    624     test_lookupNameserversDeprecated.suppress = [_retrySuppression]
    625 
    626 
    627     def test_lookupAddressDeprecated(self):
    628         """
    629         Calling L{root.lookupAddress} produces a deprecation warning.
    630         """
    631         # Don't care about the return value, since it will never have a result,
    632         # since StubDNSDatagramProtocol doesn't actually work.
    633         lookupAddress('example.com', '127.0.0.1', StubDNSDatagramProtocol())
    634 
    635         warnings = self.flushWarnings([
    636                 self.test_lookupAddressDeprecated])
    637         self.assertEqual(warnings[0]['category'], DeprecationWarning)
    638         self.assertEqual(
    639             warnings[0]['message'],
    640             'twisted.names.root.lookupAddress is deprecated since Twisted '
    641             '10.0.  Use twisted.names.root.Resolver.lookupAddress '
    642             'instead.')
    643         self.assertEqual(len(warnings), 1)
    644     test_lookupAddressDeprecated.suppress = [_retrySuppression]
    645 
    646 
    647     def test_extractAuthorityDeprecated(self):
    648         """
    649         Calling L{root.extractAuthority} produces a deprecation warning.
    650         """
    651         extractAuthority(Message(), {})
    652 
    653         warnings = self.flushWarnings([
    654                 self.test_extractAuthorityDeprecated])
    655         self.assertEqual(warnings[0]['category'], DeprecationWarning)
    656         self.assertEqual(
    657             warnings[0]['message'],
    658             'twisted.names.root.extractAuthority is deprecated since Twisted '
    659             '10.0.  Please inspect the Message object directly.')
    660         self.assertEqual(len(warnings), 1)
    661 
    662 
    663     def test_discoverAuthorityDeprecated(self):
    664         """
    665         Calling L{root.discoverAuthority} produces a deprecation warning.
    666         """
    667         discoverAuthority(
    668             'example.com', ['10.0.0.1'], p=StubDNSDatagramProtocol())
    669 
    670         warnings = self.flushWarnings([
    671                 self.test_discoverAuthorityDeprecated])
    672         self.assertEqual(warnings[0]['category'], DeprecationWarning)
    673         self.assertEqual(
    674             warnings[0]['message'],
    675             'twisted.names.root.discoverAuthority is deprecated since Twisted '
    676             '10.0.  Use twisted.names.root.Resolver.lookupNameservers '
    677             'instead.')
    678         self.assertEqual(len(warnings), 1)
    679 
    680     # discoverAuthority is implemented in terms of deprecated functions,
    681     # too.  Ignore those.
    682     test_discoverAuthorityDeprecated.suppress = [
    683         util.suppress(
    684             category=DeprecationWarning,
    685             message=(
    686                 'twisted.names.root.lookupNameservers is deprecated since '
    687                 'Twisted 10.0.  Use '
    688                 'twisted.names.root.Resolver.lookupNameservers instead.')),
    689         _retrySuppression]
    690 
    691 
    692     def test_retryDeprecated(self):
    693         """
    694         Calling L{root.retry} produces a deprecation warning.
    695         """
    696         retry([0], StubDNSDatagramProtocol())
    697 
    698         warnings = self.flushWarnings([
    699                 self.test_retryDeprecated])
    700         self.assertEqual(warnings[0]['category'], DeprecationWarning)
    701         self.assertEqual(
    702             warnings[0]['message'],
    703             'twisted.names.root.retry is deprecated since Twisted '
    704             '10.0.  Use a Resolver object for retry logic.')
    705         self.assertEqual(len(warnings), 1)
  • twisted/names/root.py

     
    2020from twisted.names import dns, common, error
    2121
    2222
    23 def retry(t, p, *args):
    24     """
    25     Issue a query one or more times.
    2623
    27     This function is deprecated.  Use one of the resolver classes for retry
    28     logic, or implement it yourself.
    29     """
    30     warnings.warn(
    31         "twisted.names.root.retry is deprecated since Twisted 10.0.  Use a "
    32         "Resolver object for retry logic.", category=DeprecationWarning,
    33         stacklevel=2)
    34 
    35     assert t, "Timeout is required"
    36     t = list(t)
    37     def errback(failure):
    38         failure.trap(defer.TimeoutError)
    39         if not t:
    40             return failure
    41         return p.query(timeout=t.pop(0), *args
    42             ).addErrback(errback
    43             )
    44     return p.query(timeout=t.pop(0), *args
    45         ).addErrback(errback
    46         )
    47 
    48 
    49 
    5024class _DummyController:
    5125    """
    5226    A do-nothing DNS controller.  This is useful when all messages received
     
    280254                    "Stuck at response without answers or delegation"))
    281255
    282256
    283     def discoveredAuthority(self, auth, name, cls, type, timeout):
    284         warnings.warn(
    285             'twisted.names.root.Resolver.discoveredAuthority is deprecated since '
    286             'Twisted 10.0.  Use twisted.names.client.Resolver directly, instead.',
    287             category=DeprecationWarning, stacklevel=2)
    288         from twisted.names import client
    289         q = dns.Query(name, type, cls)
    290         r = client.Resolver(servers=[(auth, dns.PORT)])
    291         d = r.queryUDP([q], timeout)
    292         d.addCallback(r.filterAnswers)
    293         return d
    294257
    295 
    296 
    297 def lookupNameservers(host, atServer, p=None):
    298     warnings.warn(
    299         'twisted.names.root.lookupNameservers is deprecated since Twisted '
    300         '10.0.  Use twisted.names.root.Resolver.lookupNameservers instead.',
    301         category=DeprecationWarning, stacklevel=2)
    302     # print 'Nameserver lookup for', host, 'at', atServer, 'with', p
    303     if p is None:
    304         p = dns.DNSDatagramProtocol(_DummyController())
    305         p.noisy = False
    306     return retry(
    307         (1, 3, 11, 45),                     # Timeouts
    308         p,                                  # Protocol instance
    309         (atServer, dns.PORT),               # Server to query
    310         [dns.Query(host, dns.NS, dns.IN)]   # Question to ask
    311     )
    312 
    313 def lookupAddress(host, atServer, p=None):
    314     warnings.warn(
    315         'twisted.names.root.lookupAddress is deprecated since Twisted '
    316         '10.0.  Use twisted.names.root.Resolver.lookupAddress instead.',
    317         category=DeprecationWarning, stacklevel=2)
    318     # print 'Address lookup for', host, 'at', atServer, 'with', p
    319     if p is None:
    320         p = dns.DNSDatagramProtocol(_DummyController())
    321         p.noisy = False
    322     return retry(
    323         (1, 3, 11, 45),                     # Timeouts
    324         p,                                  # Protocol instance
    325         (atServer, dns.PORT),               # Server to query
    326         [dns.Query(host, dns.A, dns.IN)]    # Question to ask
    327     )
    328 
    329 def extractAuthority(msg, cache):
    330     warnings.warn(
    331         'twisted.names.root.extractAuthority is deprecated since Twisted '
    332         '10.0.  Please inspect the Message object directly.',
    333         category=DeprecationWarning, stacklevel=2)
    334     records = msg.answers + msg.authority + msg.additional
    335     nameservers = [r for r in records if r.type == dns.NS]
    336 
    337     # print 'Records for', soFar, ':', records
    338     # print 'NS for', soFar, ':', nameservers
    339 
    340     if not nameservers:
    341         return None, nameservers
    342     if not records:
    343         raise IOError("No records")
    344     for r in records:
    345         if r.type == dns.A:
    346             cache[str(r.name)] = r.payload.dottedQuad()
    347     for r in records:
    348         if r.type == dns.NS:
    349             if str(r.payload.name) in cache:
    350                 return cache[str(r.payload.name)], nameservers
    351     for addr in records:
    352         if addr.type == dns.A and addr.name == r.name:
    353             return addr.payload.dottedQuad(), nameservers
    354     return None, nameservers
    355 
    356 def discoverAuthority(host, roots, cache=None, p=None):
    357     warnings.warn(
    358         'twisted.names.root.discoverAuthority is deprecated since Twisted '
    359         '10.0.  Use twisted.names.root.Resolver.lookupNameservers instead.',
    360         category=DeprecationWarning, stacklevel=4)
    361 
    362     if cache is None:
    363         cache = {}
    364 
    365     rootAuths = list(roots)
    366 
    367     parts = host.rstrip('.').split('.')
    368     parts.reverse()
    369 
    370     authority = rootAuths.pop()
    371 
    372     soFar = ''
    373     for part in parts:
    374         soFar = part + '.' + soFar
    375         # print '///////',  soFar, authority, p
    376         msg = defer.waitForDeferred(lookupNameservers(soFar, authority, p))
    377         yield msg
    378         msg = msg.getResult()
    379 
    380         newAuth, nameservers = extractAuthority(msg, cache)
    381 
    382         if newAuth is not None:
    383             # print "newAuth is not None"
    384             authority = newAuth
    385         else:
    386             if nameservers:
    387                 r = str(nameservers[0].payload.name)
    388                 # print 'Recursively discovering authority for', r
    389                 authority = defer.waitForDeferred(discoverAuthority(r, roots, cache, p))
    390                 yield authority
    391                 authority = authority.getResult()
    392                 # print 'Discovered to be', authority, 'for', r
    393 ##            else:
    394 ##                # print 'Doing address lookup for', soFar, 'at', authority
    395 ##                msg = defer.waitForDeferred(lookupAddress(soFar, authority, p))
    396 ##                yield msg
    397 ##                msg = msg.getResult()
    398 ##                records = msg.answers + msg.authority + msg.additional
    399 ##                addresses = [r for r in records if r.type == dns.A]
    400 ##                if addresses:
    401 ##                    authority = addresses[0].payload.dottedQuad()
    402 ##                else:
    403 ##                    raise IOError("Resolution error")
    404     # print "Yielding authority", authority
    405     yield authority
    406 
    407 discoverAuthority = defer.deferredGenerator(discoverAuthority)
    408 
    409258def makePlaceholder(deferred, name):
    410259    def placeholder(*args, **kw):
    411260        deferred.addCallback(lambda r: getattr(r, name)(*args, **kw))