pep8 letsencrypt

This commit is contained in:
Jakub Warmuz 2015-09-06 09:20:11 +00:00
parent 89c99a1f34
commit 83185e5553
No known key found for this signature in database
GPG key ID: 2A7BAD3A489B52EA
26 changed files with 59 additions and 48 deletions

View file

@ -244,7 +244,7 @@ class AuthHandler(object):
"""
for authzr_challb in authzr.body.challenges:
if type(authzr_challb.chall) is type(achall.challb.chall):
if type(authzr_challb.chall) is type(achall.challb.chall): # noqa
return authzr_challb
raise errors.AuthorizationError(
"Target challenge not found in authorization resource")
@ -512,7 +512,8 @@ _ERROR_HELP = {
"to date TLS configuration that allows the server to communicate with "
"the Let's Encrypt client.",
"unauthorized": _ERROR_HELP_COMMON,
"unknownHost": _ERROR_HELP_COMMON,}
"unknownHost": _ERROR_HELP_COMMON,
}
def _report_failed_challs(failed_achalls):

View file

@ -69,7 +69,7 @@ Choice of server for authentication/installation:
More detailed help:
-h, --help [topic] print this message, or detailed help on a topic;
-h, --help [topic] print this message, or detailed help on a topic;
the available topics are:
all, apache, automation, nginx, paths, security, testing, or any of the
@ -334,6 +334,7 @@ class SilentParser(object): # pylint: disable=too-few-public-methods
"""
def __init__(self, parser):
self.parser = parser
def add_argument(self, *args, **kwargs):
"""Wrap, but silence help"""
kwargs["help"] = argparse.SUPPRESS
@ -362,14 +363,14 @@ class HelpfulArgumentParser(object):
default_config_files=flag_default("config_files"))
# This is the only way to turn off overly verbose config flag documentation
self.parser._add_config_file_help = False # pylint: disable=protected-access
self.parser._add_config_file_help = False # pylint: disable=protected-access
self.silent_parser = SilentParser(self.parser)
help1 = self.prescan_for_flag("-h", self.help_topics)
help2 = self.prescan_for_flag("--help", self.help_topics)
assert max(True, "a") == "a", "Gravity changed direction"
help_arg = max(help1, help2)
if help_arg == True:
if help_arg:
# just --help with no topic; avoid argparse altogether
print USAGE
sys.exit(0)
@ -546,6 +547,7 @@ def create_parser(plugins, args):
def _create_subparsers(helpful):
subparsers = helpful.parser.add_subparsers(metavar="SUBCOMMAND")
def add_subparser(name, func): # pylint: disable=missing-docstring
subparser = subparsers.add_parser(
name, help=func.__doc__.splitlines()[0], description=func.__doc__)
@ -701,7 +703,7 @@ def _handle_exception(exc_type, exc_value, trace, args):
with open(logfile, "w") as logfd:
traceback.print_exception(
exc_type, exc_value, trace, file=logfd)
except: # pylint: disable=bare-except
except: # pylint: disable=bare-except
sys.exit("".join(
traceback.format_exception(exc_type, exc_value, trace)))

View file

@ -279,8 +279,8 @@ class Client(object):
:param .RenewableCert cert: Newly issued certificate
"""
if ("autorenew" not in cert.configuration
or cert.configuration.as_bool("autorenew")):
if ("autorenew" not in cert.configuration or
cert.configuration.as_bool("autorenew")):
if ("autodeploy" not in cert.configuration or
cert.configuration.as_bool("autodeploy")):
msg = "Automatic renewal and deployment has "

View file

@ -45,7 +45,7 @@ class NamespaceConfig(object):
return (parsed.netloc + parsed.path).replace('/', os.path.sep)
@property
def accounts_dir(self): #pylint: disable=missing-docstring
def accounts_dir(self): # pylint: disable=missing-docstring
return os.path.join(
self.namespace.config_dir, constants.ACCOUNTS_DIR, self.server_path)

View file

@ -205,6 +205,7 @@ def _pyopenssl_load(data, method, types=(
raise errors.Error("Unable to load: {0}".format(",".join(
str(error) for error in openssl_errors)))
def pyopenssl_load_certificate(data):
"""Load PEM/DER certificate.

View file

@ -25,8 +25,8 @@ def choose_plugin(prepared, question):
:rtype: `~.PluginEntryPoint`
"""
opts = [plugin_ep.description_with_name
+ (" [Misconfigured]" if plugin_ep.misconfigured else "")
opts = [plugin_ep.description_with_name +
(" [Misconfigured]" if plugin_ep.misconfigured else "")
for plugin_ep in prepared]
while True:

View file

@ -76,7 +76,7 @@ class NcursesDisplay(object):
"help_label": help_label,
"width": self.width,
"height": self.height,
"menu_height": self.height-6,
"menu_height": self.height - 6,
}
# Can accept either tuples or just the actual choices
@ -315,7 +315,7 @@ class FileDisplay(object):
if index < 1 or index > len(tags):
return []
# Transform indices to appropriate tags
return [tags[index-1] for index in indices]
return [tags[index - 1] for index in indices]
def _print_menu(self, message, choices):
"""Print a menu on the screen.

View file

@ -73,6 +73,7 @@ class NoInstallationError(PluginError):
class MisconfigurationError(PluginError):
"""Let's Encrypt Misconfiguration error."""
class NotSupportedError(PluginError):
"""Let's Encrypt Plugin function not supported error."""

View file

@ -440,7 +440,6 @@ class IValidator(zope.interface.Interface):
"""
def hsts(name):
"""Verify HSTS header is enabled

View file

@ -196,6 +196,8 @@ def safely_remove(path):
# start with a period or have two consecutive periods <- this needs to
# be done in addition to the regex
EMAIL_REGEX = re.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+$")
def safe_email(email):
"""Scrub email address before using it."""
if EMAIL_REGEX.match(email) is not None:

View file

@ -18,6 +18,7 @@ def option_namespace(name):
"""ArgumentParser options namespace (prefix of all options)."""
return name + "-"
def dest_namespace(name):
"""ArgumentParser dest namespace (prefix of all destinations)."""
return name.replace("-", "_") + "_"
@ -86,6 +87,7 @@ class Plugin(object):
# other
class Addr(object):
r"""Represents an virtual host address.

View file

@ -101,6 +101,7 @@ class PluginEntryPointTest(unittest.TestCase):
with mock.patch("letsencrypt.plugins."
"disco.zope.interface") as mock_zope:
mock_zope.exceptions = exceptions
def verify_object(iface, obj): # pylint: disable=missing-docstring
assert obj is plugin
assert iface is iface1 or iface is iface2 or iface is iface3

View file

@ -321,10 +321,8 @@ class PerformTest(unittest.TestCase):
self.authenticator.already_listening = mock.Mock(return_value=False)
result = self.authenticator.perform(self.achalls)
self.assertEqual(len(self.authenticator.tasks), 2)
self.assertTrue(
self.authenticator.tasks.has_key(self.achall1.token))
self.assertTrue(
self.authenticator.tasks.has_key(self.achall2.token))
self.assertTrue(self.achall1.token in self.authenticator.tasks)
self.assertTrue(self.achall2.token in self.authenticator.tasks)
self.assertTrue(isinstance(result, list))
self.assertEqual(len(result), 3)
self.assertTrue(isinstance(result[0], challenges.ChallengeResponse))
@ -340,10 +338,8 @@ class PerformTest(unittest.TestCase):
self.authenticator.already_listening = mock.Mock(return_value=False)
result = self.authenticator.perform(self.achalls)
self.assertEqual(len(self.authenticator.tasks), 2)
self.assertTrue(
self.authenticator.tasks.has_key(self.achall1.token))
self.assertTrue(
self.authenticator.tasks.has_key(self.achall2.token))
self.assertTrue(self.achall1.token in self.authenticator.tasks)
self.assertTrue(self.achall2.token in self.authenticator.tasks)
self.assertTrue(isinstance(result, list))
self.assertEqual(len(result), 3)
self.assertEqual(result, [None, None, False])

View file

@ -17,7 +17,7 @@ from letsencrypt.display import util as display_util
logger = logging.getLogger(__name__)
class ProofOfPossession(object): # pylint: disable=too-few-public-methods
class ProofOfPossession(object): # pylint: disable=too-few-public-methods
"""Proof of Possession Identifier Validation Challenge.
Based on draft-barnes-acme, section 6.5.
@ -71,7 +71,7 @@ class ProofOfPossession(object): # pylint: disable=too-few-public-methods
# If we get here, the key wasn't found
return False
def _gen_response(self, achall, key_path): # pylint: disable=no-self-use
def _gen_response(self, achall, key_path): # pylint: disable=no-self-use
"""Create the response to the Proof of Possession Challenge.
:param achall: Proof of Possession Challenge

View file

@ -486,8 +486,8 @@ class RenewableCert(object): # pylint: disable=too-many-instance-attributes
:rtype: bool
"""
if ("autorenew" not in self.configuration
or self.configuration.as_bool("autorenew")):
if ("autorenew" not in self.configuration or
self.configuration.as_bool("autorenew")):
# Consider whether to attempt to autorenew this cert now
# Renewals on the basis of revocation
@ -603,7 +603,6 @@ class RenewableCert(object): # pylint: disable=too-many-instance-attributes
new_config.write()
return cls(new_config, config, cli_config)
def save_successor(self, prior_version, new_cert, new_privkey, new_chain):
"""Save new cert and chain as a successor of a prior version.

View file

@ -30,7 +30,7 @@ POP = challenges.ProofOfPossession(
"16d95b7b63f1972b980b14c20291f3c0d1855d95",
"48b46570d9fc6358108af43ad1649484def0debf"
),
certs=(), # TODO
certs=(), # TODO
subject_key_identifiers=("d0083162dcc4c8a23ecb8aecbd86120e56fd24e5"),
serial_numbers=(34234239832, 23993939911, 17),
issuers=(

View file

@ -37,7 +37,7 @@ class ChallengeFactoryTest(unittest.TestCase):
self.dom = "test"
self.handler.authzr[self.dom] = acme_util.gen_authzr(
messages.STATUS_PENDING, self.dom, acme_util.CHALLENGES,
[messages.STATUS_PENDING]*6, False)
[messages.STATUS_PENDING] * 6, False)
def test_all(self):
cont_c, dv_c = self.handler._challenge_factory(
@ -163,7 +163,7 @@ class GetAuthorizationsTest(unittest.TestCase):
messages.STATUS_VALID,
dom,
[challb.chall for challb in azr.body.challenges],
[messages.STATUS_VALID]*len(azr.body.challenges),
[messages.STATUS_VALID] * len(azr.body.challenges),
azr.body.combinations)
@ -183,15 +183,15 @@ class PollChallengesTest(unittest.TestCase):
self.doms = ["0", "1", "2"]
self.handler.authzr[self.doms[0]] = acme_util.gen_authzr(
messages.STATUS_PENDING, self.doms[0],
acme_util.DV_CHALLENGES, [messages.STATUS_PENDING]*3, False)
acme_util.DV_CHALLENGES, [messages.STATUS_PENDING] * 3, False)
self.handler.authzr[self.doms[1]] = acme_util.gen_authzr(
messages.STATUS_PENDING, self.doms[1],
acme_util.DV_CHALLENGES, [messages.STATUS_PENDING]*3, False)
acme_util.DV_CHALLENGES, [messages.STATUS_PENDING] * 3, False)
self.handler.authzr[self.doms[2]] = acme_util.gen_authzr(
messages.STATUS_PENDING, self.doms[2],
acme_util.DV_CHALLENGES, [messages.STATUS_PENDING]*3, False)
acme_util.DV_CHALLENGES, [messages.STATUS_PENDING] * 3, False)
self.chall_update = {}
for dom in self.doms:
@ -282,6 +282,7 @@ class PollChallengesTest(unittest.TestCase):
)
return (new_authzr, "response")
class GenChallengePathTest(unittest.TestCase):
"""Tests for letsencrypt.auth_handler.gen_challenge_path.
@ -321,7 +322,7 @@ class GenChallengePathTest(unittest.TestCase):
combos = acme_util.gen_combos(challbs)
self.assertEqual(self._call(challbs, prefs, combos), (0, 2))
# dumb_path() trivial test
# dumb_path() trivial test
self.assertTrue(self._call(challbs, prefs, None))
def test_full_cont_server(self):
@ -434,19 +435,22 @@ class ReportFailedChallsTest(unittest.TestCase):
}
self.simple_http = achallenges.SimpleHTTP(
challb=messages.ChallengeBody(**kwargs),# pylint: disable=star-args
# pylint: disable=star-args
challb=messages.ChallengeBody(**kwargs),
domain="example.com",
account_key="key")
kwargs["chall"] = acme_util.DVSNI
self.dvsni_same = achallenges.DVSNI(
challb=messages.ChallengeBody(**kwargs),# pylint: disable=star-args
# pylint: disable=star-args
challb=messages.ChallengeBody(**kwargs),
domain="example.com",
account_key="key")
kwargs["error"] = messages.Error(typ="dnssec", detail="detail")
self.dvsni_diff = achallenges.DVSNI(
challb=messages.ChallengeBody(**kwargs),# pylint: disable=star-args
# pylint: disable=star-args
challb=messages.ChallengeBody(**kwargs),
domain="foo.bar",
account_key="key")
@ -477,7 +481,7 @@ def gen_dom_authzr(domain, unused_new_authzr_uri, challs):
"""Generates new authzr for domains."""
return acme_util.gen_authzr(
messages.STATUS_PENDING, domain, challs,
[messages.STATUS_PENDING]*len(challs))
[messages.STATUS_PENDING] * len(challs))
if __name__ == "__main__":

View file

@ -60,7 +60,7 @@ class CLITest(unittest.TestCase):
for args in itertools.chain(
*(itertools.combinations(flags, r)
for r in xrange(len(flags)))):
self._call(['plugins',] + list(args))
self._call(['plugins'] + list(args))
@mock.patch("letsencrypt.cli.sys")
def test_handle_exception(self, mock_sys):

View file

@ -166,7 +166,7 @@ class RollbackTest(unittest.TestCase):
self.assertEqual(self.m_install().restart.call_count, 1)
def test_no_installer(self):
self._call(1, None) # Just make sure no exceptions are raised
self._call(1, None) # Just make sure no exceptions are raised
if __name__ == "__main__":

View file

@ -35,7 +35,7 @@ class PerformTest(unittest.TestCase):
self.assertRaises(
errors.ContAuthError, self.auth.perform, [
achallenges.DVSNI(
challb=None, domain="0", account_key="invalid_key"),])
challb=None, domain="0", account_key="invalid_key")])
def test_chall_pref(self):
self.assertEqual(

View file

@ -250,6 +250,7 @@ class GenSSLLabURLs(unittest.TestCase):
self.assertTrue("eff.org" in urls[0])
self.assertTrue("umich.edu" in urls[1])
class GenHttpsNamesTest(unittest.TestCase):
"""Test _gen_https_names."""
def setUp(self):

View file

@ -35,7 +35,7 @@ class NcursesDisplayTest(unittest.TestCase):
"help_label": "",
"width": display_util.WIDTH,
"height": display_util.HEIGHT,
"menu_height": display_util.HEIGHT-6,
"menu_height": display_util.HEIGHT - 6,
}
@mock.patch("letsencrypt.display.util.dialog.Dialog.msgbox")

View file

@ -1,9 +1,10 @@
"""Tests for letsencrypt.notify."""
import mock
import socket
import unittest
import mock
class NotifyTests(unittest.TestCase):
"""Tests for the notifier."""

View file

@ -80,4 +80,4 @@ class ProofOfPossessionTest(unittest.TestCase):
if __name__ == "__main__":
unittest.main() # pragma: no cover
unittest.main() # pragma: no cover

View file

@ -24,6 +24,7 @@ def unlink_all(rc_object):
for kind in ALL_FOUR:
os.unlink(getattr(rc_object, kind))
def fill_with_sample_data(rc_object):
"""Put dummy data into all four files of this RenewableCert."""
for kind in ALL_FOUR:
@ -97,7 +98,7 @@ class RenewableCertTests(unittest.TestCase):
self.assertRaises(
errors.CertStorageError, storage.RenewableCert, config, defaults)
def test_consistent(self): # pylint: disable=too-many-statements
def test_consistent(self): # pylint: disable=too-many-statements
oldcert = self.test_rc.cert
self.test_rc.cert = "relative/path"
# Absolute path for item requirement
@ -608,7 +609,6 @@ class RenewableCertTests(unittest.TestCase):
# This should fail because the renewal itself appears to fail
self.assertFalse(renewer.renew(self.test_rc, 1))
@mock.patch("letsencrypt.renewer.notify")
@mock.patch("letsencrypt.storage.RenewableCert")
@mock.patch("letsencrypt.renewer.renew")

View file

@ -106,6 +106,7 @@ class ValidatorTest(unittest.TestCase):
self.assertRaises(
NotImplementedError, self.validator.ocsp_stapling, "test.com")
def create_response(status_code=200, headers=None):
"""Creates a requests.Response object for testing"""
response = requests.Response()
@ -118,4 +119,4 @@ def create_response(status_code=200, headers=None):
if __name__ == '__main__':
unittest.main() # pragma: no cover
unittest.main() # pragma: no cover