Skip to content

Commit

Permalink
flake8 linting
Browse files Browse the repository at this point in the history
  • Loading branch information
rthalley committed May 15, 2020
1 parent 6e0857e commit 7142bff
Show file tree
Hide file tree
Showing 18 changed files with 95 additions and 76 deletions.
16 changes: 15 additions & 1 deletion .flake8
Original file line number Diff line number Diff line change
@@ -1,2 +1,16 @@
[flake8]
ignore = E741
ignore =
# Prefer emacs indentation of continued lines
E126,
E129,
# Whitespace round parameter '=' can be excessive
E252,
# Not excited by the "two blank lines" rule
E302,
E305,
# Ambigious variables are ok.
E741,
# Lines ending with binary operators are OK
W504,

max-line-length = 80
2 changes: 1 addition & 1 deletion dns/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,4 @@
'zone',
]

from dns.version import version as __version__
from dns.version import version as __version__ # noqa
9 changes: 6 additions & 3 deletions dns/dnssec.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,8 @@ def _validate_rrsig(rrset, rrsig, keys, origin=None, now=None):
sig = rrsig.signature
elif _is_gost(rrsig.algorithm):
raise UnsupportedAlgorithm(
'algorithm "%s" not supported by dnspython' % algorithm_to_text(rrsig.algorithm))
'algorithm "%s" not supported by dnspython' %
algorithm_to_text(rrsig.algorithm))
else:
raise ValidationFailure('unknown algorithm %u' % rrsig.algorithm)

Expand Down Expand Up @@ -453,8 +454,10 @@ def _validate_rrsig(rrset, rrsig, keys, origin=None, now=None):
# Raise here for code clarity; this won't actually ever happen
# since if the algorithm is really unknown we'd already have
# raised an exception above
raise ValidationFailure('unknown algorithm %u' % rrsig.algorithm)
# If we got here, we successfully verified so we can return without error
raise ValidationFailure('unknown algorithm %u' %
rrsig.algorithm)
# If we got here, we successfully verified so we can return
# without error
return
except InvalidSignature:
# this happens on an individual validation failure
Expand Down
17 changes: 10 additions & 7 deletions dns/edns.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def __init__(self, address, srclen=None, scopelen=0):
self.scopelen = scopelen

addrdata = dns.inet.inet_pton(af, address)
nbytes = int(math.ceil(srclen/8.0))
nbytes = int(math.ceil(srclen / 8.0))

# Truncate to srclen and pad to the end of the last octet needed
# See RFC section 6
Expand All @@ -202,6 +202,7 @@ def __init__(self, address, srclen=None, scopelen=0):
def to_text(self):
return "ECS {}/{} scope/{}".format(self.address, self.srclen,
self.scopelen)

@staticmethod
def from_text(text):
"""Convert a string into a `dns.edns.ECSOption`
Expand Down Expand Up @@ -248,11 +249,13 @@ def from_text(text):
try:
scope = int(scope)
except ValueError:
raise ValueError('invalid scope "{}": scope must be an integer'.format(scope))
raise ValueError('invalid scope ' +
'"{}": scope must be an integer'.format(scope))
try:
srclen = int(srclen)
except ValueError:
raise ValueError('invalid srclen "{}": srclen must be an integer'.format(srclen))
raise ValueError('invalid srclen ' +
'"{}": srclen must be an integer'.format(srclen))
return ECSOption(address, srclen, scope)

def to_wire(self, file):
Expand All @@ -262,17 +265,17 @@ def to_wire(self, file):

@classmethod
def from_wire(cls, otype, wire, cur, olen):
family, src, scope = struct.unpack('!HBB', wire[cur:cur+4])
family, src, scope = struct.unpack('!HBB', wire[cur:cur + 4])
cur += 4

addrlen = int(math.ceil(src/8.0))
addrlen = int(math.ceil(src / 8.0))

if family == 1:
pad = 4 - addrlen
addr = dns.ipv4.inet_ntoa(wire[cur:cur+addrlen] + b'\x00' * pad)
addr = dns.ipv4.inet_ntoa(wire[cur:cur + addrlen] + b'\x00' * pad)
elif family == 2:
pad = 16 - addrlen
addr = dns.ipv6.inet_ntoa(wire[cur:cur+addrlen] + b'\x00' * pad)
addr = dns.ipv6.inet_ntoa(wire[cur:cur + addrlen] + b'\x00' * pad)
else:
raise ValueError('unsupported family')

Expand Down
4 changes: 2 additions & 2 deletions dns/inet.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
try:
AF_INET6 = socket.AF_INET6
except AttributeError:
AF_INET6 = 9999 # type: ignore
AF_INET6 = 9999 # type: ignore


def inet_pton(family, text):
Expand Down Expand Up @@ -96,7 +96,7 @@ def af_for_address(text):
try:
dns.ipv6.inet_aton(text, True)
return AF_INET6
except:
except Exception:
raise ValueError


Expand Down
2 changes: 1 addition & 1 deletion dns/ipv4.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,5 @@ def inet_aton(text):
try:
b = [int(part) for part in parts]
return struct.pack('BBBB', *b)
except:
except Exception:
raise dns.exception.SyntaxError
10 changes: 5 additions & 5 deletions dns/ipv6.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ def inet_ntoa(address):
i = 0
l = len(hex)
while i < l:
chunk = hex[i : i + 4].decode()
chunk = hex[i:i + 4].decode()
# strip leading zeros. we do this with an re instead of
# with lstrip() because lstrip() didn't support chars until
# python 2.2.2
m = _leading_zero.match(chunk)
if not m is None:
if m is not None:
chunk = m.group(1)
chunks.append(chunk)
i += 4
Expand Down Expand Up @@ -127,7 +127,7 @@ def inet_aton(text, ignore_scope=False):
# Get rid of the icky dot-quad syntax if we have it.
#
m = _v4_ending.match(text)
if not m is None:
if m is not None:
b = dns.ipv4.inet_aton(m.group(2))
text = (u"{}:{:02x}{:02x}:{:02x}{:02x}".format(m.group(1).decode(),
b[0], b[1], b[2],
Expand All @@ -137,11 +137,11 @@ def inet_aton(text, ignore_scope=False):
# turn '<whatever>::' into '<whatever>:'
#
m = _colon_colon_start.match(text)
if not m is None:
if m is not None:
text = text[1:]
else:
m = _colon_colon_end.match(text)
if not m is None:
if m is not None:
text = text[:-1]
#
# Now canonicalize into 8 chunks of 4 hex digits each
Expand Down
16 changes: 10 additions & 6 deletions dns/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,20 @@
except ImportError:
have_doh = False


try:
import ssl
except ImportError:
class ssl(object): # type: ignore

class WantReadException(Exception):
pass

class WantWriteException(Exception):
pass

class SSLSocket(object):
pass

def create_default_context(self, *args, **kwargs):
raise Exception('no ssl support')

Expand Down Expand Up @@ -320,7 +323,7 @@ def https(q, where, timeout=None, port=443, af=None, source=None, source_port=0,
})
response = session.post(url, headers=headers, data=wire,
stream=True, timeout=timeout,
verify=verify)
verify=verify)
else:
wire = base64.urlsafe_b64encode(wire).decode('utf-8').strip("=")
url += "?dns={}".format(wire)
Expand Down Expand Up @@ -867,8 +870,9 @@ def xfr(where, zone, rdtype=dns.rdatatype.AXFR, rdclass=dns.rdataclass.IN,
(l,) = struct.unpack("!H", ldata)
wire = _net_read(s, l, mexpiration)
is_ixfr = (rdtype == dns.rdatatype.IXFR)
r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac,
xfr=True, origin=origin, tsig_ctx=tsig_ctx,
r = dns.message.from_wire(wire, keyring=q.keyring,
request_mac=q.mac, xfr=True,
origin=origin, tsig_ctx=tsig_ctx,
multi=True, first=first,
one_rr_per_rrset=is_ixfr)
rcode = r.rcode()
Expand Down Expand Up @@ -911,8 +915,8 @@ def xfr(where, zone, rdtype=dns.rdatatype.AXFR, rdclass=dns.rdataclass.IN,
delete_mode = not delete_mode
#
# If this SOA RRset is equal to the first we saw then we're
# finished. If this is an IXFR we also check that we're seeing
# the record in the expected part of the response.
# finished. If this is an IXFR we also check that we're
# seeing the record in the expected part of the response.
#
if rrset == soa_rrset and \
(rdtype == dns.rdatatype.AXFR or
Expand Down
2 changes: 1 addition & 1 deletion dns/query.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ from requests.sessions import Session
try:
import ssl
except ImportError:
class ssl(object): # type: ignore
class ssl(object): # type: ignore
SSLContext : Dict = {}

have_doh: bool
Expand Down
4 changes: 2 additions & 2 deletions dns/rdatatype.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,8 +274,8 @@ def is_singleton(rdtype):
return True
return False


def register_type(rdtype, rdtype_text, is_singleton=False): # pylint: disable=redefined-outer-name
# pylint: disable=redefined-outer-name
def register_type(rdtype, rdtype_text, is_singleton=False):
"""Dynamically register an rdatatype.
*rdtype*, an ``int``, the rdatatype to register.
Expand Down
2 changes: 1 addition & 1 deletion dns/rdtypes/ANY/AVC.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ class AVC(dns.rdtypes.txtbase.TXTBase):

"""AVC record"""

# See: U{http://www.iana.org/assignments/dns-parameters/AVC/avc-completed-template}
# See: IANA dns parameters for AVC
4 changes: 2 additions & 2 deletions dns/rdtypes/ANY/GPOS.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ def __init__(self, rdclass, rdtype, latitude, longitude, altitude):

def to_text(self, origin=None, relativize=True, **kw):
return '{} {} {}'.format(self.latitude.decode(),
self.longitude.decode(),
self.altitude.decode())
self.longitude.decode(),
self.altitude.decode())

@classmethod
def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True,
Expand Down
2 changes: 1 addition & 1 deletion dns/rdtypes/ANY/ISDN.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def __init__(self, rdclass, rdtype, address, subaddress):
def to_text(self, origin=None, relativize=True, **kw):
if self.subaddress:
return '"{}" "{}"'.format(dns.rdata._escapify(self.address),
dns.rdata._escapify(self.subaddress))
dns.rdata._escapify(self.subaddress))
else:
return '"%s"' % dns.rdata._escapify(self.address)

Expand Down
2 changes: 1 addition & 1 deletion dns/rdtypes/ANY/LOC.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def _float_to_tuple(what):
what *= -1
else:
sign = 1
what = round(what * 3600000) # pylint: disable=round-builtin
what = round(what * 3600000) # pylint: disable=round-builtin
degrees = int(what // 3600000)
what -= degrees * 3600000
minutes = int(what // 60000)
Expand Down
8 changes: 4 additions & 4 deletions dns/rdtypes/CH/A.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ def to_digestable(self, origin=None):

@classmethod
def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin=None):
(domain, cused) = dns.name.from_wire(wire[: current + rdlen-2],
current)
(domain, cused) = dns.name.from_wire(wire[:current + rdlen - 2],
current)
current += cused
(address,) = struct.unpack('!H', wire[current: current + 2])
if cused+2 != rdlen:
(address,) = struct.unpack('!H', wire[current:current + 2])
if cused + 2 != rdlen:
raise dns.exception.FormError
if origin is not None:
domain = domain.relativize(origin)
Expand Down
2 changes: 1 addition & 1 deletion dns/rdtypes/IN/IPSECKEY.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class IPSECKEY(dns.rdata.Rdata):

"""IPSECKEY record"""

#see: RFC 4025
# see: RFC 4025

__slots__ = ['precedence', 'gateway_type', 'algorithm', 'gateway', 'key']

Expand Down
37 changes: 20 additions & 17 deletions dns/resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def __str__(self):
@property
def canonical_name(self):
"""Return the unresolved canonical name."""
if not 'qnames' in self.kwargs:
if 'qnames' not in self.kwargs:
raise TypeError("parametrized exception required")
IN = dns.rdataclass.IN
CNAME = dns.rdatatype.CNAME
Expand Down Expand Up @@ -876,7 +876,7 @@ def resolve(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
all_nxdomain = True
nxdomain_responses = {}
start = time.time()
_qname = None # make pylint happy
_qname = None # make pylint happy
for _qname in qnames_to_try:
if self.cache:
answer = self.cache.get((_qname, rdtype, rdclass))
Expand Down Expand Up @@ -922,21 +922,21 @@ def resolve(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
else:
tcp_attempt = tcp
if tcp:
response = dns.query.tcp(request, nameserver,
timeout=timeout,
port=port,
source=source,
source_port=\
source_port)
response = \
dns.query.tcp(request, nameserver,
timeout=timeout,
port=port,
source=source,
source_port=source_port)
else:
try:
response = dns.query.udp(request,
nameserver,
timeout=timeout,
port=port,
source=source,
source_port=\
source_port)
response = \
dns.query.udp(request,
nameserver,
timeout=timeout,
port=port,
source=source,
source_port=source_port)
except dns.message.Truncated:
# Response truncated; retry with TCP.
tcp_attempt = True
Expand Down Expand Up @@ -1140,7 +1140,7 @@ def nameservers(self, nameservers):
``list``.
"""
if isinstance(nameservers, list):
self._nameservers = nameservers # pylint: disable=attribute-defined-outside-init
self._nameservers = nameservers
else:
raise ValueError('nameservers must be a list'
' (not a {})'.format(type(nameservers)))
Expand Down Expand Up @@ -1288,7 +1288,10 @@ def _getaddrinfo(host=None, service=None, family=socket.AF_UNSPEC, socktype=0,
return _original_getaddrinfo(host, service, family, socktype,
proto, flags)
try:
af = dns.inet.af_for_address(host)
# We don't care about the result of af_for_address(), we're just
# calling it so it raises an exception if host is not an IPv4 or
# IPv6 address.
dns.inet.af_for_address(host)
return _original_getaddrinfo(host, service, family, socktype,
proto, flags)
except Exception:
Expand Down

0 comments on commit 7142bff

Please sign in to comment.