async def fake_resolve_(qname): try: addr = fake_hosts[qname] except KeyError: raise DNSException(f"unknown test host: {qname}") else: return [dns.rdtypes.IN.A.A("IN", "A", addr)]
def test_update_dns_error(self, mock_tsigkeyring, mock_update, mock_query): record = 'update' sa_version = '3.4.1' config = dict(dns_key='6e2347bc-278e-42f6-a84b-fa1766140cbd') mock_query.tcp.side_effect = DNSException('permission denied') with self.assertRaises(SaChannelUpdateError): update_dns(config, record, sa_version)
def import_records(self): answer = dns.resolver.query(self.zone, "NS") for rdata in answer: try: ns = str(rdata) dns_zone = dns.zone.from_xfr(dns.query.xfr(ns, self.zone)) except DNSException as exc: exc = DNSException(f"{str(exc)} ({self.zone})") raise exc except Exception as exc: exc = RuntimeError(f"{str(exc)} ({self.zone})") raise exc records = list() for name, node in dns_zone.nodes.items(): todict = {} for rdataset in node.rdatasets: for rdata in rdataset: if rdataset.rdtype in ( dns.rdatatype.A, dns.rdatatype.CNAME, dns.rdatatype.MX, ): todict["zone"] = self.zone todict["name"] = str(name) todict["content"] = rdata.to_text() todict["rtype"] = dns.rdatatype.to_text( rdataset.rdtype) todict["ttl"] = rdataset.ttl todict["representation"] = str(rdataset) if not todict: continue records.append(todict) return records
def test_rejects_domain_without_mx_record(self, fake_query): """Reject email address for a domain without an MX record.""" fake_query.side_effect = DNSException() form = EmailForm(data={'email': '*****@*****.**'}) self.assertFalse(form.is_valid()) # Enure dns.resolver.query() was actually called. fake_query.assert_called_once_with('thecut.net.au', 'MX')
def test_rejects_domain_without_mx_record(self, fake_query): """Reject email address for a domain without an MX record.""" fake_query.side_effect = DNSException() model = EmailModel(email='*****@*****.**') with self.assertRaises(ValidationError): model.full_clean() # Enure dns.resolver.query() was actually called. fake_query.assert_called_once_with('thecut.net.au', 'MX')
def dns_query(name, _): if '-server' not in name or '-ssl' in name: return [] if name == '_etcd-server._tcp.blabla': return [] elif name == '_etcd-server._tcp.exception': raise DNSException() srv = Mock() srv.port = 2380 srv.target.to_text.return_value = 'localhost' if name == '_etcd-server._tcp.foobar' else '127.0.0.1' return [srv]
def test_nothing_submitted_if_no_pool_servers(self): config = MockConfig(pool=['127.0.0.1']) with dns_query([]) as dns_resolver: dns_resolver.side_effect = raise_exception( DNSException('Some DNS problem')) self.plugin(config).read() self.collectd.Values.assert_has_calls([])
def __init__(self, domain): self.resolver = resolver.Resolver() self.resolver.timeout = 1 self.resolver.lifetime = 1 #Validate the domain. if valid_domain(domain): self.domain = domain else: raise DNSException('Could not validate domain') # Get name server self.name_servers = self._get_name_servers() if len(self.name_servers) < 1: raise DNSException('Could not get authoritative name servers.') # Get the DNS baseline self.baseline = self._get_baseline()
def naptr(fqdn, service_type, name_server): try: # request the ONS recursive name server naptr = dns.message.make_query(fqdn, dns.rdatatype.from_text('NAPTR')) msg = dns.query.udp(naptr, name_server) # test returned code if msg.rcode() != dns.rcode.NOERROR: raise DNSException(dns.rcode._by_value[msg.rcode()]) # show the result of the query for rr_set in msg.answer: # detect any redirection by DNAME (generate a CNAME - switch to another ONS root) if rr_set.rdtype == dns.rdatatype.CNAME: (str1, sep, str2) = rr_set.to_text().partition('CNAME ') print_info("=> FQDN modification (redirection occurred): " + str2) # NAPTR response if rr_set.rdtype == dns.rdatatype.NAPTR: selected_answers = [] # filter : keep only desired service and valid flags for rdata in rr_set: # print rdata if ((rdata.order == 0) and ((service_type.lower() == rdata.service.lower() and rdata.flags == 'u') or (rdata.service.lower() == "" and rdata.flags == ""))): selected_answers.append(rdata) # select the best answser (NAPTR algorithm) if len(selected_answers) >= 1: selected_answers.sort(lambda x, y: cmp( x.preference, y.preference)) # order by preference rdata = selected_answers[ 0] # take only the first item (lower preference) print_info("=> ONS response: NAPTR " + rdata.to_text()) elements = re.match(re.compile("!(.*)!(.*)!"), rdata.regexp) # retrive url rewriting return (rdata.flags, elements.group(1), elements.group(2)) else: print "==> No appropriate service found for this product ! \n" return (None, "", "") except DNSException, e: # print "*** ONS report : ", e.__class__, e print e.__class__, e print return (None, "", "")
def _get_baseline(self): """ Create a baseline records set """ res = {} base = False for name_server in self.name_servers: if base: if set(self._get_record_set(name_server)) == base: continue else: raise DNSException( 'Authoritative Name Servers do not agree.') else: base = self._get_record_set(name_server) return base
def query(self, domain, data_type): if data_type != TXT: raise NoAnswer dparts = domain.split('.') if len(dparts) < 3: raise NXDOMAIN if len(dparts) > 3: raise NoAnswer if dparts[0] != '_dmarc': raise NoAnswer if dparts[2] == 'info': raise DNSException('no internet') if dparts[1] != 'example' or dparts[2] != 'biz': raise NXDOMAIN self.response = Answer() return self
def fake_srv_(qname, rdtype): try: ans = fake_hosts[qname, rdtype] except KeyError: raise DNSException(f"unknown test host: {qname} {rdtype}") rv: List[Union[A, SRV]] = [] if rdtype == "A": for entry in ans: rv.append(A("IN", "A", entry)) else: for entry in ans: pri, w, port, target = entry.split() rv.append(SRV("IN", "SRV", int(pri), int(w), int(port), target)) return rv
def test_implicit_message(self): try: raise DNSException() except DNSException as ex: self.assertEqual(ex.__class__.__doc__, str(ex))
def test_custom_message(self): msg = "this is a custom message" try: raise DNSException(msg) except DNSException as ex: self.assertEqual(str(ex), msg)
import pytest from srvresolver.srv_resolver import SRVRecord # type: ignore from unittest import mock from yapapi.package import Package, PackageException from yapapi.package.vm import resolve_repo_srv, _FALLBACK_REPO_URL _MOCK_HOST = "non.existent.domain" _MOCK_PORT = 9999 @mock.patch( "yapapi.package.vm.SRVResolver.resolve_random", mock.Mock(return_value=SRVRecord( host=_MOCK_HOST, port=_MOCK_PORT, weight=1, priority=1)), ) def test_resolve_srv(): assert resolve_repo_srv("") == f"http://{_MOCK_HOST}:{_MOCK_PORT}" @mock.patch("yapapi.package.vm.SRVResolver.resolve_random", mock.Mock(side_effect=DNSException())) def test_resolve_srv_exception(): # should be: # with pytest.raises(DNSException): # assert resolve_repo_srv("") # temporary work-around: assert resolve_repo_srv("") == _FALLBACK_REPO_URL
def dns_query(name, type): if name == '_etcd-server._tcp.blabla': return [] elif name == '_etcd-server._tcp.exception': raise DNSException() return [MockSRV()]