diff options
| author | Eli Collins <elic@assurancetechnologies.com> | 2013-04-09 13:50:04 -0400 |
|---|---|---|
| committer | Eli Collins <elic@assurancetechnologies.com> | 2013-04-09 13:50:04 -0400 |
| commit | 2dbabd30e3639bc8f382db1ecc69aada0a6c827d (patch) | |
| tree | 774aabe6a02b37df0ac8a5aee0c96f247c041766 /passlib | |
| parent | 6e158b409ec52814ee4ae015daa13028806e21de (diff) | |
| download | passlib-2dbabd30e3639bc8f382db1ecc69aada0a6c827d.tar.gz | |
style cleanups
Diffstat (limited to 'passlib')
45 files changed, 489 insertions, 494 deletions
diff --git a/passlib/_setup/docdist.py b/passlib/_setup/docdist.py index dadb4b5..19c4dc1 100644 --- a/passlib/_setup/docdist.py +++ b/passlib/_setup/docdist.py @@ -1,4 +1,4 @@ -"custom command to build doc.zip file" +"""custom command to build doc.zip file""" #============================================================================= # imports #============================================================================= diff --git a/passlib/_setup/stamp.py b/passlib/_setup/stamp.py index dfa62bc..8a68658 100644 --- a/passlib/_setup/stamp.py +++ b/passlib/_setup/stamp.py @@ -1,4 +1,4 @@ -"update version string during build" +"""update version string during build""" #============================================================================= # imports #============================================================================= @@ -21,7 +21,7 @@ def get_command_class(opts, name): return opts['cmdclass'].get(name) or Distribution().get_command_class(name) def stamp_source(base_dir, version, dry_run=False): - "update version string in passlib dist" + """update version string in passlib dist""" path = os.path.join(base_dir, "passlib", "__init__.py") with open(path) as fh: input = fh.read() diff --git a/passlib/apache.py b/passlib/apache.py index c0841f3..ad39704 100644 --- a/passlib/apache.py +++ b/passlib/apache.py @@ -188,7 +188,7 @@ class _CommonFile(object): @property def mtime(self): - "modify time when last loaded (if bound to a local file)" + """modify time when last loaded (if bound to a local file)""" return self._mtime #=================================================================== @@ -240,13 +240,13 @@ class _CommonFile(object): return True def load_string(self, data): - "Load state from unicode or bytes string, replacing current state" + """Load state from unicode or bytes string, replacing current state""" data = to_bytes(data, self.encoding, "data") self._mtime = 0 self._load_lines(BytesIO(data)) def _load_lines(self, lines): - "load from sequence of lists" + """load from sequence of lists""" # XXX: found reference that "#" comment lines may be supported by # htpasswd, should verify this, and figure out how to handle them. # if true, this would also affect what can be stored in user field. @@ -262,15 +262,15 @@ class _CommonFile(object): if key not in records: records[key] = value - def _parse_record(cls, record, lineno): # pragma: no cover - abstract method - "parse line of file into (key, value) pair" + def _parse_record(self, record, lineno): # pragma: no cover - abstract method + """parse line of file into (key, value) pair""" raise NotImplementedError("should be implemented in subclass") #=================================================================== # saving #=================================================================== def _autosave(self): - "subclass helper to call save() after any changes" + """subclass helper to call save() after any changes""" if self.autosave and self._path: self.save() @@ -289,26 +289,26 @@ class _CommonFile(object): self.__class__.__name__) def to_string(self): - "Export current state as a string of bytes" + """Export current state as a string of bytes""" return join_bytes(self._iter_lines()) def _iter_lines(self): - "iterator yielding lines of database" + """iterator yielding lines of database""" return (self._render_record(key,value) for key,value in iteritems(self._records)) - def _render_record(cls, key, value): # pragma: no cover - abstract method - "given key/value pair, encode as line of file" + def _render_record(self, key, value): # pragma: no cover - abstract method + """given key/value pair, encode as line of file""" raise NotImplementedError("should be implemented in subclass") #=================================================================== # field encoding #=================================================================== def _encode_user(self, user): - "user-specific wrapper for _encode_field()" + """user-specific wrapper for _encode_field()""" return self._encode_field(user, "user") def _encode_realm(self, realm): # pragma: no cover - abstract method - "realm-specific wrapper for _encode_field()" + """realm-specific wrapper for _encode_field()""" return self._encode_field(realm, "realm") def _encode_field(self, value, param="field"): @@ -566,7 +566,7 @@ class HtpasswdFile(_CommonFile): #=================================================================== def users(self): - "Return list of all users in database" + """Return list of all users in database""" return [self._decode_field(user) for user in self._records] ##def has_user(self, user): @@ -605,7 +605,7 @@ class HtpasswdFile(_CommonFile): @deprecated_method(deprecated="1.6", removed="1.8", replacement="set_password") def update(self, user, password): - "set password for user" + """set password for user""" return self.set_password(user, password) def get_hash(self, user): @@ -624,7 +624,7 @@ class HtpasswdFile(_CommonFile): @deprecated_method(deprecated="1.6", removed="1.8", replacement="get_hash") def find(self, user): - "return hash for user" + """return hash for user""" return self.get_hash(user) # XXX: rename to something more explicit, like delete_user()? @@ -673,7 +673,7 @@ class HtpasswdFile(_CommonFile): @deprecated_method(deprecated="1.6", removed="1.8", replacement="check_password") def verify(self, user, password): - "verify password for user" + """verify password for user""" return self.check_password(user, password) #=================================================================== @@ -931,7 +931,7 @@ class HtdigestFile(_CommonFile): @deprecated_method(deprecated="1.6", removed="1.8", replacement="set_password") def update(self, user, realm, password): - "set password for user" + """set password for user""" return self.set_password(user, realm, password) # XXX: rename to something more explicit, like get_hash()? @@ -957,7 +957,7 @@ class HtdigestFile(_CommonFile): @deprecated_method(deprecated="1.6", removed="1.8", replacement="get_hash") def find(self, user, realm): - "return hash for user" + """return hash for user""" return self.get_hash(user, realm) # XXX: rename to something more explicit, like delete_user()? @@ -1025,7 +1025,7 @@ class HtdigestFile(_CommonFile): @deprecated_method(deprecated="1.6", removed="1.8", replacement="check_password") def verify(self, user, realm, password): - "verify password for user" + """verify password for user""" return self.check_password(user, realm, password) #=================================================================== diff --git a/passlib/apps.py b/passlib/apps.py index 0afb73a..c64730e 100644 --- a/passlib/apps.py +++ b/passlib/apps.py @@ -124,7 +124,7 @@ def _iter_ldap_crypt_schemes(): return ('ldap_' + name for name in unix_crypt_schemes) def _iter_ldap_schemes(): - "helper which iterates over supported std ldap schemes" + """helper which iterates over supported std ldap schemes""" return chain(std_ldap_schemes, _iter_ldap_crypt_schemes()) ldap_context = LazyCryptContext(_iter_ldap_schemes()) @@ -151,7 +151,7 @@ postgres_context = LazyCryptContext(["postgres_md5"]) # phpass & variants #============================================================================= def _create_phpass_policy(**kwds): - "helper to choose default alg based on bcrypt availability" + """helper to choose default alg based on bcrypt availability""" kwds['default'] = 'bcrypt' if hash.bcrypt.has_backend() else 'phpass' return kwds diff --git a/passlib/context.py b/passlib/context.py index 827a215..e489f7d 100644 --- a/passlib/context.py +++ b/passlib/context.py @@ -40,7 +40,7 @@ _UNSET = object() # TODO: merge the following helpers into _CryptConfig def _coerce_vary_rounds(value): - "parse vary_rounds string to percent as [0,1) float, or integer" + """parse vary_rounds string to percent as [0,1) float, or integer""" if value.endswith("%"): # XXX: deprecate this in favor of raw float? return float(value.rstrip("%"))*.01 @@ -642,7 +642,7 @@ class _CryptRecord(object): @property def _errprefix(self): - "string used to identify record in error messages" + """string used to identify record in error messages""" handler = self.handler category = self.category if category: @@ -657,7 +657,7 @@ class _CryptRecord(object): # rounds generation & limits - used by encrypt & deprecation code #=================================================================== def _init_rounds_options(self, mn, mx, df, vr): - "parse options and compile efficient generate_rounds function" + """parse options and compile efficient generate_rounds function""" #---------------------------------------------------- # extract hard limits from handler itself #---------------------------------------------------- @@ -669,7 +669,7 @@ class _CryptRecord(object): hmx = getattr(handler, "max_rounds", None) def check_against_handler(value, name): - "issue warning if value outside handler limits" + """issue warning if value outside handler limits""" if hmn is not None and value < hmn: warn("%s: %s value is below handler minimum %d: %d" % (self._errprefix, name, hmn, value), PasslibConfigWarning) @@ -721,7 +721,7 @@ class _CryptRecord(object): # is calculated, so that proportion vr values are scaled against # the effective default. def clip(value): - "clip value to intersection of policy + handler limits" + """clip value to intersection of policy + handler limits""" if mn is not None and value < mn: value = mn if hmn is not None and value < hmn: @@ -799,7 +799,7 @@ class _CryptRecord(object): # encrypt() / genconfig() #=================================================================== def _init_encrypt_and_genconfig(self): - "initialize genconfig/encrypt wrapper methods" + """initialize genconfig/encrypt wrapper methods""" settings = self.settings handler = self.handler @@ -817,17 +817,17 @@ class _CryptRecord(object): self.encrypt = handler.encrypt def genconfig(self, **kwds): - "wrapper for handler.genconfig() which adds custom settings/rounds" + """wrapper for handler.genconfig() which adds custom settings/rounds""" self._prepare_settings(kwds) return self.handler.genconfig(**kwds) def encrypt(self, secret, **kwds): - "wrapper for handler.encrypt() which adds custom settings/rounds" + """wrapper for handler.encrypt() which adds custom settings/rounds""" self._prepare_settings(kwds) return self.handler.encrypt(secret, **kwds) def _prepare_settings(self, kwds): - "add default values to settings for encrypt & genconfig" + """add default values to settings for encrypt & genconfig""" # load in default values for any settings if kwds: for k,v in iteritems(self.settings): @@ -869,7 +869,7 @@ class _CryptRecord(object): # of handler.verify() def _init_verify(self, mvt): - "initialize verify() wrapper - implements min_verify_time" + """initialize verify() wrapper - implements min_verify_time""" if mvt: assert isinstance(mvt, (int,float)) and mvt > 0, "CryptPolicy should catch this" self._min_verify_time = mvt @@ -878,7 +878,7 @@ class _CryptRecord(object): self.verify = self.handler.verify def verify(self, secret, hash, **context): - "verify helper - adds min_verify_time delay" + """verify helper - adds min_verify_time delay""" mvt = self._min_verify_time assert mvt > 0, "wrapper should have been replaced for mvt=0" start = tick() @@ -1167,7 +1167,8 @@ class _CryptConfig(object): #--------------------------------------------------------------- def get_context_optionmap(self, key, _default={}): """return dict mapping category->value for specific context option. - (treat retval as readonly). + + .. warning:: treat return value as readonly! """ return self._context_options.get(key, _default) @@ -1195,7 +1196,8 @@ class _CryptConfig(object): #--------------------------------------------------------------- def _get_scheme_optionmap(self, scheme, category, default={}): """return all options for (scheme,category) combination - (treat return as readonly) + + .. warning:: treat return value as readonly! """ try: return self._scheme_options[scheme][category] @@ -1281,7 +1283,7 @@ class _CryptConfig(object): "cannot be deprecated" % cat) def default_scheme(self, category): - "return default scheme for specific category" + """return default scheme for specific category""" defaults = self._default_schemes try: return defaults[category] @@ -1293,7 +1295,7 @@ class _CryptConfig(object): return defaults[None] def is_deprecated_with_flag(self, scheme, category): - "is scheme deprecated under particular category?" + """is scheme deprecated under particular category?""" depmap = self.get_context_optionmap("deprecated") def test(cat): source = depmap.get(cat, depmap.get(None)) @@ -1370,7 +1372,7 @@ class _CryptConfig(object): return kwds, has_cat_options def get_record(self, scheme, category): - "return record for specific scheme & category (cached)" + """return record for specific scheme & category (cached)""" # NOTE: this is part of the critical path shared by # all of CryptContext's PasswordHash methods, # hence all the caching and error checking. @@ -1550,7 +1552,7 @@ class CryptContext(object): #=================================================================== @classmethod def _norm_source(cls, source): - "internal helper - accepts string, dict, or context" + """internal helper - accepts string, dict, or context""" if isinstance(source, dict): return cls(**source) elif isinstance(source, cls): @@ -1669,7 +1671,7 @@ class CryptContext(object): return other def replace(self, **kwds): - "deprecated alias of :meth:`copy`" + """deprecated alias of :meth:`copy`""" warn("CryptContext().replace() has been deprecated in Passlib 1.6, " "and will be removed in Passlib 1.8, " "it has been renamed to CryptContext().copy()", @@ -1752,7 +1754,7 @@ class CryptContext(object): #=================================================================== @staticmethod def _parse_ini_stream(stream, section, filename): - "helper read INI from stream, extract passlib section as dict" + """helper read INI from stream, extract passlib section as dict""" # NOTE: this expects a unicode stream under py3, # and a utf-8 bytes stream under py2, # allowing the resulting dict to always use native strings. @@ -2019,7 +2021,7 @@ class CryptContext(object): # and then decide whether to expose ability as deprecated_schemes(), # is_deprecated(), or a just add a schemes(deprecated=True) flag. def _is_deprecated_scheme(self, scheme, category=None): - "helper used by unittests to check if scheme is deprecated" + """helper used by unittests to check if scheme is deprecated""" return self._get_record(scheme, category).deprecated def default_scheme(self, category=None, resolve=False): @@ -2092,7 +2094,7 @@ class CryptContext(object): "CryptContext instance") def _get_unregistered_handlers(self): - "check if any handlers in this context aren't in the global registry" + """check if any handlers in this context aren't in the global registry""" return tuple(handler for handler in self._config.handlers if not _is_handler_registered(handler)) @@ -2101,7 +2103,7 @@ class CryptContext(object): #=================================================================== @staticmethod def _render_config_key(key): - "convert 3-part config key to single string" + """convert 3-part config key to single string""" cat, scheme, option = key if cat: return "%s__%s__%s" % (cat, scheme or "context", option) @@ -2112,7 +2114,7 @@ class CryptContext(object): @staticmethod def _render_ini_value(key, value): - "render value to string suitable for INI file" + """render value to string suitable for INI file""" # convert lists to comma separated lists # (mainly 'schemes' & 'deprecated') if isinstance(value, (list,tuple)): @@ -2167,7 +2169,7 @@ class CryptContext(object): for key, value in self._config.iter_config(resolve)) def _write_to_parser(self, parser, section): - "helper to write to ConfigParser instance" + """helper to write to ConfigParser instance""" render_key = self._render_config_key render_value = self._render_ini_value parser.add_section(section) @@ -2248,7 +2250,7 @@ class CryptContext(object): # stored in CryptContext for speed. def _get_or_identify_record(self, hash, scheme=None, category=None): - "return record based on scheme, or failing that, by identifying hash" + """return record based on scheme, or failing that, by identifying hash""" if scheme: if not isinstance(hash, base_string_types): raise ExpectedStringError(hash, "hash") diff --git a/passlib/exc.py b/passlib/exc.py index 60dae90..daac72a 100644 --- a/passlib/exc.py +++ b/passlib/exc.py @@ -116,7 +116,7 @@ def _get_name(handler): # generic helpers #------------------------------------------------------------------------ def type_name(value): - "return pretty-printed string containing name of value's type" + """return pretty-printed string containing name of value's type""" cls = value.__class__ if cls.__module__ and cls.__module__ not in ["__builtin__", "builtins"]: return "%s.%s" % (cls.__module__, cls.__name__) @@ -126,26 +126,26 @@ def type_name(value): return cls.__name__ def ExpectedTypeError(value, expected, param): - "error message when param was supposed to be one type, but found another" + """error message when param was supposed to be one type, but found another""" # NOTE: value is never displayed, since it may sometimes be a password. name = type_name(value) return TypeError("%s must be %s, not %s" % (param, expected, name)) def ExpectedStringError(value, param): - "error message when param was supposed to be unicode or bytes" + """error message when param was supposed to be unicode or bytes""" return ExpectedTypeError(value, "unicode or bytes", param) #------------------------------------------------------------------------ # encrypt/verify parameter errors #------------------------------------------------------------------------ def MissingDigestError(handler=None): - "raised when verify() method gets passed config string instead of hash" + """raised when verify() method gets passed config string instead of hash""" name = _get_name(handler) return ValueError("expected %s hash, got %s config string instead" % (name, name)) def NullPasswordError(handler=None): - "raised by OS crypt() supporting hashes, which forbid NULLs in password" + """raised by OS crypt() supporting hashes, which forbid NULLs in password""" name = _get_name(handler) return ValueError("%s does not allow NULL bytes in password" % name) @@ -153,25 +153,25 @@ def NullPasswordError(handler=None): # errors when parsing hashes #------------------------------------------------------------------------ def InvalidHashError(handler=None): - "error raised if unrecognized hash provided to handler" + """error raised if unrecognized hash provided to handler""" return ValueError("not a valid %s hash" % _get_name(handler)) def MalformedHashError(handler=None, reason=None): - "error raised if recognized-but-malformed hash provided to handler" + """error raised if recognized-but-malformed hash provided to handler""" text = "malformed %s hash" % _get_name(handler) if reason: text = "%s (%s)" % (text, reason) return ValueError(text) def ZeroPaddedRoundsError(handler=None): - "error raised if hash was recognized but contained zero-padded rounds field" + """error raised if hash was recognized but contained zero-padded rounds field""" return MalformedHashError(handler, "zero-padded rounds") #------------------------------------------------------------------------ # settings / hash component errors #------------------------------------------------------------------------ def ChecksumSizeError(handler, raw=False): - "error raised if hash was recognized, but checksum was wrong size" + """error raised if hash was recognized, but checksum was wrong size""" # TODO: if handler.use_defaults is set, this came from app-provided value, # not from parsing a hash string, might want different error msg. checksum_size = handler.checksum_size diff --git a/passlib/ext/django/models.py b/passlib/ext/django/models.py index f035263..0e02ffd 100644 --- a/passlib/ext/django/models.py +++ b/passlib/ext/django/models.py @@ -72,7 +72,7 @@ def _apply_patch(): from django.contrib.auth.models import UNUSABLE_PASSWORD def is_password_usable(encoded): - return (encoded is not None and encoded != UNUSABLE_PASSWORD) + return encoded is not None and encoded != UNUSABLE_PASSWORD def is_valid_secret(secret): return secret is not None @@ -109,7 +109,7 @@ def _apply_patch(): # @_manager.monkeypatch(USER_PATH) def set_password(user, password): - "passlib replacement for User.set_password()" + """passlib replacement for User.set_password()""" if is_valid_secret(password): # NOTE: pulls _get_category from module globals cat = _get_category(user) @@ -119,7 +119,7 @@ def _apply_patch(): @_manager.monkeypatch(USER_PATH) def check_password(user, password): - "passlib replacement for User.check_password()" + """passlib replacement for User.check_password()""" hash = user.password if not is_valid_secret(password) or not is_password_usable(hash): return False @@ -139,7 +139,7 @@ def _apply_patch(): @_manager.monkeypatch(HASHERS_PATH, enable=has_hashers) @_manager.monkeypatch(MODELS_PATH) def check_password(password, encoded, setter=None, preferred="default"): - "passlib replacement for check_password()" + """passlib replacement for check_password()""" # XXX: this currently ignores "preferred" keyword, since its purpose # was for hash migration, and that's handled by the context. if not is_valid_secret(password) or not is_password_usable(encoded): @@ -157,7 +157,7 @@ def _apply_patch(): @_manager.monkeypatch(HASHERS_PATH) @_manager.monkeypatch(MODELS_PATH) def make_password(password, salt=None, hasher="default"): - "passlib replacement for make_password()" + """passlib replacement for make_password()""" if not is_valid_secret(password): return UNUSABLE_PASSWORD kwds = {} @@ -170,7 +170,7 @@ def _apply_patch(): @_manager.monkeypatch(HASHERS_PATH) @_manager.monkeypatch(FORMS_PATH) def get_hasher(algorithm="default"): - "passlib replacement for get_hasher()" + """passlib replacement for get_hasher()""" if algorithm == "default": scheme = None else: @@ -183,7 +183,7 @@ def _apply_patch(): @_manager.monkeypatch(HASHERS_PATH) @_manager.monkeypatch(FORMS_PATH) def identify_hasher(encoded): - "passlib helper to identify hasher from encoded password" + """passlib helper to identify hasher from encoded password""" handler = password_context.identify(encoded, resolve=True, required=True) return get_passlib_hasher(handler) diff --git a/passlib/ext/django/utils.py b/passlib/ext/django/utils.py index e8f4e78..7b9eaca 100644 --- a/passlib/ext/django/utils.py +++ b/passlib/ext/django/utils.py @@ -109,14 +109,14 @@ DJANGO_PASSLIB_PREFIX = "django_" _other_django_hashes = ["hex_md5"] def passlib_to_hasher_name(passlib_name): - "convert passlib handler name -> hasher name" + """convert passlib handler name -> hasher name""" handler = get_crypt_handler(passlib_name) if hasattr(handler, "django_name"): return handler.django_name return PASSLIB_HASHER_PREFIX + passlib_name def hasher_to_passlib_name(hasher_name): - "convert hasher name -> passlib handler name" + """convert hasher name -> passlib handler name""" if hasher_name.startswith(PASSLIB_HASHER_PREFIX): return hasher_name[len(PASSLIB_HASHER_PREFIX):] for name in list_crypt_handlers(): @@ -217,7 +217,7 @@ def get_passlib_hasher(handler): return hasher def _get_hasher(algorithm): - "wrapper to call django.contrib.auth.hashers:get_hasher()" + """wrapper to call django.contrib.auth.hashers:get_hasher()""" import sys module = sys.modules.get("passlib.ext.django.models") if module is None: @@ -329,7 +329,7 @@ def _get_hasher(algorithm): _UNSET = object() class _PatchManager(object): - "helper to manage monkeypatches and run sanity checks" + """helper to manage monkeypatches and run sanity checks""" # NOTE: this could easily use a dict interface, # but keeping it distinct to make clear that it's not a dict, @@ -348,7 +348,7 @@ class _PatchManager(object): __bool__ = __nonzero__ = lambda self: bool(self._state) def _import_path(self, path): - "retrieve obj and final attribute name from resource path" + """retrieve obj and final attribute name from resource path""" name, attr = path.split(":") obj = __import__(name, fromlist=[attr], level=0) while '.' in attr: @@ -358,7 +358,7 @@ class _PatchManager(object): @staticmethod def _is_same_value(left, right): - "check if two values are the same (stripping method wrappers, etc)" + """check if two values are the same (stripping method wrappers, etc)""" return get_method_function(left) == get_method_function(right) #=================================================================== @@ -369,11 +369,11 @@ class _PatchManager(object): return getattr(obj, attr, default) def get(self, path, default=None): - "return current value for path" + """return current value for path""" return self._get_path(path, default) def getorig(self, path, default=None): - "return original (unpatched) value for path" + """return original (unpatched) value for path""" try: value, _= self._state[path] except KeyError: @@ -404,7 +404,7 @@ class _PatchManager(object): setattr(obj, attr, value) def patch(self, path, value): - "monkeypatch object+attr at <path> to have <value>, stores original" + """monkeypatch object+attr at <path> to have <value>, stores original""" assert value != _UNSET current = self._get_path(path) try: @@ -426,7 +426,7 @@ class _PatchManager(object): ## self.patch(path, value) def monkeypatch(self, parent, name=None, enable=True): - "function decorator which patches function of same name in <parent>" + """function decorator which patches function of same name in <parent>""" def builder(func): if enable: sep = "." if ":" in parent else ":" diff --git a/passlib/handlers/bcrypt.py b/passlib/handlers/bcrypt.py index 61b0829..4bbfdc4 100644 --- a/passlib/handlers/bcrypt.py +++ b/passlib/handlers/bcrypt.py @@ -160,7 +160,7 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. return uascii_to_str(hash) def _get_config(self, ident=None): - "internal helper to prepare config string for backends" + """internal helper to prepare config string for backends""" if ident is None: ident = self.ident if ident == IDENT_2Y: @@ -195,7 +195,7 @@ class bcrypt(uh.HasManyIdents, uh.HasRounds, uh.HasSalt, uh.HasManyBackends, uh. @classmethod def normhash(cls, hash): - "helper to normalize hash, correcting any bcrypt padding bits" + """helper to normalize hash, correcting any bcrypt padding bits""" if cls.identify(hash): return cls.from_string(hash).to_string() else: diff --git a/passlib/handlers/cisco.py b/passlib/handlers/cisco.py index 947c88e..1588e80 100644 --- a/passlib/handlers/cisco.py +++ b/passlib/handlers/cisco.py @@ -156,7 +156,7 @@ class cisco_type7(uh.GenericHandler): self.salt = self._norm_salt(salt) def _norm_salt(self, salt): - "the salt for this algorithm is an integer 0-52, not a string" + """the salt for this algorithm is an integer 0-52, not a string""" # XXX: not entirely sure that values >15 are valid, so for # compatibility we don't output those values, but we do accept them. if salt is None: @@ -206,7 +206,7 @@ class cisco_type7(uh.GenericHandler): @classmethod def _cipher(cls, data, salt): - "xor static key against data - encrypts & decrypts" + """xor static key against data - encrypts & decrypts""" key = cls._key key_size = len(key) return join_byte_values( diff --git a/passlib/handlers/des_crypt.py b/passlib/handlers/des_crypt.py index 1699e1d..dc28783 100644 --- a/passlib/handlers/des_crypt.py +++ b/passlib/handlers/des_crypt.py @@ -40,7 +40,7 @@ def _crypt_secret_to_key(secret): for i, c in enumerate(secret[:8])) def _raw_des_crypt(secret, salt): - "pure-python backed for des_crypt" + """pure-python backed for des_crypt""" assert len(salt) == 2 # NOTE: some OSes will accept non-HASH64 characters in the salt, @@ -73,7 +73,7 @@ def _raw_des_crypt(secret, salt): return h64big.encode_int64(result) def _bsdi_secret_to_key(secret): - "covert secret to DES key used by bsdi_crypt" + """covert secret to DES key used by bsdi_crypt""" key_value = _crypt_secret_to_key(secret) idx = 8 end = len(secret) @@ -85,7 +85,7 @@ def _bsdi_secret_to_key(secret): return key_value def _raw_bsdi_crypt(secret, rounds, salt): - "pure-python backend for bsdi_crypt" + """pure-python backend for bsdi_crypt""" # decode salt try: diff --git a/passlib/handlers/digests.py b/passlib/handlers/digests.py index dd8400c..402c670 100644 --- a/passlib/handlers/digests.py +++ b/passlib/handlers/digests.py @@ -27,7 +27,7 @@ __all__ = [ # helpers for hexadecimal hashes #============================================================================= class HexDigestHash(uh.StaticHandler): - "this provides a template for supporting passwords stored as plain hexadecimal hashes" + """this provides a template for supporting passwords stored as plain hexadecimal hashes""" #=================================================================== # class attrs #=================================================================== @@ -106,7 +106,7 @@ class htdigest(uh.PasswordHash): @classmethod def _norm_hash(cls, hash): - "normalize hash to native string, and validate it" + """normalize hash to native string, and validate it""" hash = to_native_str(hash, param="hash") if len(hash) != 32: raise uh.exc.MalformedHashError(cls, "wrong size") diff --git a/passlib/handlers/ldap_digests.py b/passlib/handlers/ldap_digests.py index a25a394..fb378c0 100644 --- a/passlib/handlers/ldap_digests.py +++ b/passlib/handlers/ldap_digests.py @@ -38,7 +38,7 @@ __all__ = [ # ldap helpers #============================================================================= class _Base64DigestHelper(uh.StaticHandler): - "helper for ldap_md5 / ldap_sha1" + """helper for ldap_md5 / ldap_sha1""" # XXX: could combine this with hex digests in digests.py ident = None # required - prefix identifier @@ -48,7 +48,7 @@ class _Base64DigestHelper(uh.StaticHandler): @classproperty def _hash_prefix(cls): - "tell StaticHandler to strip ident from checksum" + """tell StaticHandler to strip ident from checksum""" return cls.ident def _calc_checksum(self, secret): @@ -58,7 +58,7 @@ class _Base64DigestHelper(uh.StaticHandler): return b64encode(chk).decode("ascii") class _SaltedBase64DigestHelper(uh.HasRawSalt, uh.HasRawChecksum, uh.GenericHandler): - "helper for ldap_salted_md5 / ldap_salted_sha1" + """helper for ldap_salted_md5 / ldap_salted_sha1""" setting_kwds = ("salt", "salt_size") checksum_chars = uh.PADDED_BASE64_CHARS diff --git a/passlib/handlers/md5_crypt.py b/passlib/handlers/md5_crypt.py index 642316e..bb28b16 100644 --- a/passlib/handlers/md5_crypt.py +++ b/passlib/handlers/md5_crypt.py @@ -191,7 +191,7 @@ def _raw_md5_crypt(pwd, salt, use_apr=False): # handler #============================================================================= class _MD5_Common(uh.HasSalt, uh.GenericHandler): - "common code for md5_crypt and apr_md5_crypt" + """common code for md5_crypt and apr_md5_crypt""" #=================================================================== # class attrs #=================================================================== diff --git a/passlib/handlers/mssql.py b/passlib/handlers/mssql.py index 1d89273..d50100f 100644 --- a/passlib/handlers/mssql.py +++ b/passlib/handlers/mssql.py @@ -64,7 +64,7 @@ BIDENT = b("0x0100") UIDENT = u("0x0100") def _ident_mssql(hash, csize, bsize): - "common identify for mssql 2000/2005" + """common identify for mssql 2000/2005""" if isinstance(hash, unicode): if len(hash) == csize and hash.startswith(UIDENT): return True @@ -78,7 +78,7 @@ def _ident_mssql(hash, csize, bsize): return False def _parse_mssql(hash, csize, bsize, handler): - "common parser for mssql 2000/2005; returns 4 byte salt + checksum" + """common parser for mssql 2000/2005; returns 4 byte salt + checksum""" if isinstance(hash, unicode): if len(hash) == csize and hash.startswith(UIDENT): try: diff --git a/passlib/handlers/pbkdf2.py b/passlib/handlers/pbkdf2.py index 931521b..acd1a08 100644 --- a/passlib/handlers/pbkdf2.py +++ b/passlib/handlers/pbkdf2.py @@ -28,7 +28,7 @@ __all__ = [ # #============================================================================= class Pbkdf2DigestHandler(uh.HasRounds, uh.HasRawSalt, uh.HasRawChecksum, uh.GenericHandler): - "base class for various pbkdf2_{digest} algorithms" + """base class for various pbkdf2_{digest} algorithms""" #=================================================================== # class attrs #=================================================================== @@ -84,7 +84,7 @@ class Pbkdf2DigestHandler(uh.HasRounds, uh.HasRawSalt, uh.HasRawChecksum, uh.Gen return pbkdf2(secret, self.salt, self.rounds, self.checksum_size, self._prf) def create_pbkdf2_hash(hash_name, digest_size, rounds=12000, ident=None, module=__name__): - "create new Pbkdf2DigestHandler subclass for a specific hash" + """create new Pbkdf2DigestHandler subclass for a specific hash""" name = 'pbkdf2_' + hash_name if ident is None: ident = u("$pbkdf2-%s$") % (hash_name,) diff --git a/passlib/handlers/scram.py b/passlib/handlers/scram.py index 0dbc823..437a83d 100644 --- a/passlib/handlers/scram.py +++ b/passlib/handlers/scram.py @@ -317,7 +317,7 @@ class scram(uh.HasRounds, uh.HasRawSalt, uh.HasRawChecksum, uh.GenericHandler): return checksum def _norm_algs(self, algs): - "normalize algs parameter" + """normalize algs parameter""" # determine default algs value if algs is None: # derive algs list from checksum (if present). @@ -348,7 +348,7 @@ class scram(uh.HasRounds, uh.HasRawSalt, uh.HasRawChecksum, uh.GenericHandler): @classmethod def _bind_needs_update(cls, **settings): - "generate a deprecation detector for CryptContext to use" + """generate a deprecation detector for CryptContext to use""" # generate deprecation hook which marks hashes as deprecated # if they don't support a superset of current algs. algs = frozenset(cls(use_defaults=True, **settings).algs) diff --git a/passlib/handlers/sha2_crypt.py b/passlib/handlers/sha2_crypt.py index dbd848f..f087e09 100644 --- a/passlib/handlers/sha2_crypt.py +++ b/passlib/handlers/sha2_crypt.py @@ -240,7 +240,7 @@ _UZERO = u("0") class _SHA2_Common(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler): - "class containing common code shared by sha256_crypt & sha512_crypt" + """class containing common code shared by sha256_crypt & sha512_crypt""" #=================================================================== # class attrs #=================================================================== diff --git a/passlib/handlers/sun_md5_crypt.py b/passlib/handlers/sun_md5_crypt.py index a99289c..6c0c826 100644 --- a/passlib/handlers/sun_md5_crypt.py +++ b/passlib/handlers/sun_md5_crypt.py @@ -82,7 +82,7 @@ _XY_ROUNDS = [ del xr def raw_sun_md5_crypt(secret, rounds, salt): - "given secret & salt, return encoded sun-md5-crypt checksum" + """given secret & salt, return encoded sun-md5-crypt checksum""" global MAGIC_HAMLET assert isinstance(secret, bytes) assert isinstance(salt, bytes) diff --git a/passlib/hosts.py b/passlib/hosts.py index f6eb007..7df3efd 100644 --- a/passlib/hosts.py +++ b/passlib/hosts.py @@ -71,7 +71,7 @@ if has_crypt: # and can be introspected and used much more flexibly. def _iter_os_crypt_schemes(): - "helper which iterates over supported os_crypt schemes" + """helper which iterates over supported os_crypt schemes""" found = False for name in unix_crypt_schemes: handler = get_crypt_handler(name) diff --git a/passlib/ifc.py b/passlib/ifc.py index 908890a..5e4e7d4 100644 --- a/passlib/ifc.py +++ b/passlib/ifc.py @@ -26,7 +26,7 @@ else: # return None def create_with_metaclass(meta): - "class decorator that re-creates class using metaclass" + """class decorator that re-creates class using metaclass""" # have to do things this way since abc not present in py25, # and py2/py3 have different ways of doing metaclasses. def builder(cls): @@ -84,13 +84,13 @@ class PasswordHash(object): @classmethod @abstractmethod def encrypt(cls, secret, **setting_and_context_kwds): # pragma: no cover -- abstract method - "encrypt secret, returning resulting hash" + """encrypt secret, returning resulting hash""" raise NotImplementedError("must be implemented by subclass") @classmethod @abstractmethod def verify(cls, secret, hash, **context_kwds): # pragma: no cover -- abstract method - "verify secret against hash, returns True/False" + """verify secret against hash, returns True/False""" raise NotImplementedError("must be implemented by subclass") #=================================================================== @@ -99,19 +99,19 @@ class PasswordHash(object): @classmethod @abstractmethod def identify(cls, hash): # pragma: no cover -- abstract method - "check if hash belongs to this scheme, returns True/False" + """check if hash belongs to this scheme, returns True/False""" raise NotImplementedError("must be implemented by subclass") @classmethod @abstractmethod def genconfig(cls, **setting_kwds): # pragma: no cover -- abstract method - "compile settings into a configuration string for genhash()" + """compile settings into a configuration string for genhash()""" raise NotImplementedError("must be implemented by subclass") @classmethod @abstractmethod def genhash(cls, secret, config, **context_kwds): # pragma: no cover -- abstract method - "generated hash for secret, using settings from config/hash string" + """generated hash for secret, using settings from config/hash string""" raise NotImplementedError("must be implemented by subclass") #=================================================================== diff --git a/passlib/tests/_test_bad_register.py b/passlib/tests/_test_bad_register.py index 26cc6bb..f0683fc 100644 --- a/passlib/tests/_test_bad_register.py +++ b/passlib/tests/_test_bad_register.py @@ -1,4 +1,4 @@ -"helper for method in test_registry.py" +"""helper for method in test_registry.py""" from passlib.registry import register_crypt_handler import passlib.utils.handlers as uh diff --git a/passlib/tests/test_apache.py b/passlib/tests/test_apache.py index 68a992f..0792d60 100644 --- a/passlib/tests/test_apache.py +++ b/passlib/tests/test_apache.py @@ -18,7 +18,7 @@ from passlib.utils.compat import b, bytes, u log = getLogger(__name__) def backdate_file_mtime(path, offset=10): - "backdate file's mtime by specified amount" + """backdate file's mtime by specified amount""" # NOTE: this is used so we can test code which detects mtime changes, # without having to actually *pause* for that long. atime = os.path.getatime(path) @@ -29,7 +29,7 @@ def backdate_file_mtime(path, offset=10): # htpasswd #============================================================================= class HtpasswdFileTest(TestCase): - "test HtpasswdFile class" + """test HtpasswdFile class""" descriptionPrefix = "HtpasswdFile" # sample with 4 users @@ -55,7 +55,7 @@ class HtpasswdFileTest(TestCase): sample_dup = b('user1:pass1\nuser1:pass2\n') def test_00_constructor_autoload(self): - "test constructor autoload" + """test constructor autoload""" # check with existing file path = self.mktemp() set_file(path, self.sample_01) @@ -97,7 +97,7 @@ class HtpasswdFileTest(TestCase): self.assertFalse(ht.mtime) def test_01_delete(self): - "test delete()" + """test delete()""" ht = apache.HtpasswdFile.from_string(self.sample_01) self.assertTrue(ht.delete("user1")) # should delete both entries self.assertTrue(ht.delete("user2")) @@ -121,7 +121,7 @@ class HtpasswdFileTest(TestCase): self.assertEqual(get_file(path), b("user2:pass2\n")) def test_02_set_password(self): - "test set_password()" + """test set_password()""" ht = apache.HtpasswdFile.from_string( self.sample_01, default_scheme="plaintext") self.assertTrue(ht.set_password("user2", "pass2x")) @@ -157,7 +157,7 @@ class HtpasswdFileTest(TestCase): self.assertEqual(get_file(path), b("user1:pass2\n")) def test_03_users(self): - "test users()" + """test users()""" ht = apache.HtpasswdFile.from_string(self.sample_01) ht.set_password("user5", "pass5") ht.delete("user3") @@ -166,7 +166,7 @@ class HtpasswdFileTest(TestCase): "user3"]) def test_04_check_password(self): - "test check_password()" + """test check_password()""" ht = apache.HtpasswdFile.from_string(self.sample_01) self.assertRaises(TypeError, ht.check_password, 1, 'pass5') self.assertTrue(ht.check_password("user5","pass5") is None) @@ -183,7 +183,7 @@ class HtpasswdFileTest(TestCase): self.assertFalse(ht.verify("user1", "pass2")) def test_05_load(self): - "test load()" + """test load()""" # setup empty file path = self.mktemp() set_file(path, "") @@ -220,7 +220,7 @@ class HtpasswdFileTest(TestCase): # NOTE: load_string() tested via from_string(), which is used all over this file def test_06_save(self): - "test save()" + """test save()""" # load from file path = self.mktemp() set_file(path, self.sample_01) @@ -242,7 +242,7 @@ class HtpasswdFileTest(TestCase): self.assertEqual(get_file(path), b("user1:pass1\n")) def test_07_encodings(self): - "test 'encoding' kwd" + """test 'encoding' kwd""" # test bad encodings cause failure in constructor self.assertRaises(ValueError, apache.HtpasswdFile, encoding="utf-16") @@ -262,7 +262,7 @@ class HtpasswdFileTest(TestCase): self.assertEqual(ht.users(), [ u("user\u00e6") ]) def test_08_get_hash(self): - "test get_hash()" + """test get_hash()""" ht = apache.HtpasswdFile.from_string(self.sample_01) self.assertEqual(ht.get_hash("user3"), b("{SHA}3ipNV1GrBtxPmHFC21fCbVCSXIo=")) self.assertEqual(ht.get_hash("user4"), b("pass4")) @@ -272,7 +272,7 @@ class HtpasswdFileTest(TestCase): self.assertEqual(ht.find("user4"), b("pass4")) def test_09_to_string(self): - "test to_string" + """test to_string""" # check with known sample ht = apache.HtpasswdFile.from_string(self.sample_01) @@ -305,7 +305,7 @@ class HtpasswdFileTest(TestCase): # htdigest #============================================================================= class HtdigestFileTest(TestCase): - "test HtdigestFile class" + """test HtdigestFile class""" descriptionPrefix = "HtdigestFile" # sample with 4 users @@ -330,7 +330,7 @@ class HtdigestFileTest(TestCase): sample_04_latin1 = b('user\xe6:realm\xe6:549d2a5f4659ab39a80dac99e159ab19\n') def test_00_constructor_autoload(self): - "test constructor autoload" + """test constructor autoload""" # check with existing file path = self.mktemp() set_file(path, self.sample_01) @@ -348,7 +348,7 @@ class HtdigestFileTest(TestCase): # NOTE: default_realm option checked via other tests. def test_01_delete(self): - "test delete()" + """test delete()""" ht = apache.HtdigestFile.from_string(self.sample_01) self.assertTrue(ht.delete("user1", "realm")) self.assertTrue(ht.delete("user2", "realm")) @@ -377,7 +377,7 @@ class HtdigestFileTest(TestCase): self.assertEqual(get_file(path), self.sample_02) def test_02_set_password(self): - "test update()" + """test update()""" ht = apache.HtdigestFile.from_string(self.sample_01) self.assertTrue(ht.set_password("user2", "realm", "pass2x")) self.assertFalse(ht.set_password("user5", "realm", "pass5")) @@ -405,7 +405,7 @@ class HtdigestFileTest(TestCase): # TODO: test set_password autosave def test_03_users(self): - "test users()" + """test users()""" ht = apache.HtdigestFile.from_string(self.sample_01) ht.set_password("user5", "realm", "pass5") ht.delete("user3", "realm") @@ -415,7 +415,7 @@ class HtdigestFileTest(TestCase): self.assertRaises(TypeError, ht.users, 1) def test_04_check_password(self): - "test check_password()" + """test check_password()""" ht = apache.HtdigestFile.from_string(self.sample_01) self.assertRaises(TypeError, ht.check_password, 1, 'realm', 'pass5') self.assertRaises(TypeError, ht.check_password, 'user', 1, 'pass5') @@ -440,7 +440,7 @@ class HtdigestFileTest(TestCase): self.assertRaises(ValueError, ht.check_password, "user:", "realm", "pass") def test_05_load(self): - "test load()" + """test load()""" # setup empty file path = self.mktemp() set_file(path, "") @@ -481,7 +481,7 @@ class HtdigestFileTest(TestCase): self.assertEqual(ha.to_string(), b("")) def test_06_save(self): - "test save()" + """test save()""" # load from file path = self.mktemp() set_file(path, self.sample_01) @@ -503,7 +503,7 @@ class HtdigestFileTest(TestCase): self.assertEqual(get_file(path), hb.to_string()) def test_07_realms(self): - "test realms() & delete_realm()" + """test realms() & delete_realm()""" ht = apache.HtdigestFile.from_string(self.sample_01) self.assertEqual(ht.delete_realm("x"), 0) @@ -514,7 +514,7 @@ class HtdigestFileTest(TestCase): self.assertEqual(ht.to_string(), b("")) def test_08_get_hash(self): - "test get_hash()" + """test get_hash()""" ht = apache.HtdigestFile.from_string(self.sample_01) self.assertEqual(ht.get_hash("user3", "realm"), "a500bb8c02f6a9170ae46af10c898744") self.assertEqual(ht.get_hash("user4", "realm"), "ab7b5d5f28ccc7666315f508c7358519") @@ -524,7 +524,7 @@ class HtdigestFileTest(TestCase): self.assertEqual(ht.find("user4", "realm"), "ab7b5d5f28ccc7666315f508c7358519") def test_09_encodings(self): - "test encoding parameter" + """test encoding parameter""" # test bad encodings cause failure in constructor self.assertRaises(ValueError, apache.HtdigestFile, encoding="utf-16") @@ -539,7 +539,7 @@ class HtdigestFileTest(TestCase): self.assertEqual(ht.users(u("realm\u00e6")), [ u("user\u00e6") ]) def test_10_to_string(self): - "test to_string()" + """test to_string()""" # check sample ht = apache.HtdigestFile.from_string(self.sample_01) diff --git a/passlib/tests/test_apps.py b/passlib/tests/test_apps.py index 421f83b..c3d6820 100644 --- a/passlib/tests/test_apps.py +++ b/passlib/tests/test_apps.py @@ -15,7 +15,7 @@ from passlib.tests.utils import TestCase # test predefined app contexts #============================================================================= class AppsTest(TestCase): - "perform general tests to make sure contexts work" + """perform general tests to make sure contexts work""" # NOTE: these tests are not really comprehensive, # since they would do little but duplicate # the presets in apps.py diff --git a/passlib/tests/test_context.py b/passlib/tests/test_context.py index 650124a..f2f86b6 100644 --- a/passlib/tests/test_context.py +++ b/passlib/tests/test_context.py @@ -178,7 +178,7 @@ sha512_crypt__min_rounds = 45000 # constructors #=================================================================== def test_01_constructor(self): - "test class constructor" + """test class constructor""" # test blank constructor works correctly ctx = CryptContext() @@ -201,7 +201,7 @@ sha512_crypt__min_rounds = 45000 self.assertEqual(ctx.to_dict(), self.sample_3_dict) def test_02_from_string(self): - "test from_string() constructor" + """test from_string() constructor""" # test sample 1 unicode ctx = CryptContext.from_string(self.sample_1_unicode) self.assertEqual(ctx.to_dict(), self.sample_1_dict) @@ -231,7 +231,7 @@ sha512_crypt__min_rounds = 45000 self.sample_1_unicode, section="fakesection") def test_03_from_path(self): - "test from_path() constructor" + """test from_path() constructor""" # make sure sample files exist if not os.path.exists(self.sample_1_path): raise RuntimeError("can't find data file: %r" % self.sample_1_path) @@ -258,7 +258,7 @@ sha512_crypt__min_rounds = 45000 self.sample_1_path, section="fakesection") def test_04_copy(self): - "test copy() method" + """test copy() method""" cc1 = CryptContext(**self.sample_1_dict) # overlay sample 2 onto copy @@ -287,7 +287,7 @@ sha512_crypt__min_rounds = 45000 self.assertEqual(cc4.to_dict(), self.sample_12_dict) def test_09_repr(self): - "test repr()" + """test repr()""" cc1 = CryptContext(**self.sample_1_dict) self.assertRegex(repr(cc1), "^<CryptContext at 0x[0-9a-f]+>$") @@ -295,7 +295,7 @@ sha512_crypt__min_rounds = 45000 # modifiers #=================================================================== def test_10_load(self): - "test load() / load_path() method" + """test load() / load_path() method""" # NOTE: load() is the workhorse that handles all policy parsing, # compilation, and validation. most of its features are tested # elsewhere, since all the constructors and modifiers are just @@ -338,7 +338,7 @@ sha512_crypt__min_rounds = 45000 self.assertEqual(ctx.to_dict(), self.sample_2_dict) def test_11_load_rollback(self): - "test load() errors restore old state" + """test load() errors restore old state""" # create initial context cc = CryptContext(["des_crypt", "sha256_crypt"], sha256_crypt__default_rounds=5000, @@ -362,7 +362,7 @@ sha512_crypt__min_rounds = 45000 self.assertEqual(cc.to_string(), result) def test_12_update(self): - "test update() method" + """test update() method""" # empty overlay ctx = CryptContext(**self.sample_1_dict) @@ -399,7 +399,7 @@ sha512_crypt__min_rounds = 45000 # option parsing #=================================================================== def test_20_options(self): - "test basic option parsing" + """test basic option parsing""" def parse(**kwds): return CryptContext(**kwds).to_dict() @@ -475,7 +475,7 @@ sha512_crypt__min_rounds = 45000 all__salt="xx") def test_21_schemes(self): - "test 'schemes' context option parsing" + """test 'schemes' context option parsing""" # schemes can be empty cc = CryptContext(schemes=None) @@ -511,7 +511,7 @@ sha512_crypt__min_rounds = 45000 admin__context__schemes=["md5_crypt"]) def test_22_deprecated(self): - "test 'deprecated' context option parsing" + """test 'deprecated' context option parsing""" def getdep(ctx, category=None): return [name for name in ctx.schemes() if ctx._is_deprecated_scheme(name, category)] @@ -603,7 +603,7 @@ sha512_crypt__min_rounds = 45000 self.assertEqual(getdep(cc, "admin"), []) def test_23_default(self): - "test 'default' context option parsing" + """test 'default' context option parsing""" # anything allowed if no schemes self.assertEqual(CryptContext(default="md5_crypt").to_dict(), @@ -640,7 +640,7 @@ sha512_crypt__min_rounds = 45000 self.assertEqual(ctx.default_scheme("admin"), "md5_crypt") def test_24_vary_rounds(self): - "test 'vary_rounds' hash option parsing" + """test 'vary_rounds' hash option parsing""" def parse(v): return CryptContext(all__vary_rounds=v).to_dict()['all__vary_rounds'] @@ -659,7 +659,7 @@ sha512_crypt__min_rounds = 45000 # inspection & serialization #=================================================================== def test_30_schemes(self): - "test schemes() method" + """test schemes() method""" # NOTE: also checked under test_21 # test empty @@ -677,7 +677,7 @@ sha512_crypt__min_rounds = 45000 self.assertEqual(ctx.schemes(), ()) def test_31_default_scheme(self): - "test default_scheme() method" + """test default_scheme() method""" # NOTE: also checked under test_23 # test empty @@ -700,7 +700,7 @@ sha512_crypt__min_rounds = 45000 # categories tested under test_23 def test_32_handler(self): - "test handler() method" + """test handler() method""" # default for empty ctx = CryptContext() @@ -729,7 +729,7 @@ sha512_crypt__min_rounds = 45000 self.assertEqual(ctx.handler(category=u("admin")), hash.md5_crypt) def test_33_options(self): - "test internal _get_record_options() method" + """test internal _get_record_options() method""" def options(ctx, scheme, category=None): return ctx._config._get_record_options_with_flag(scheme, category)[0] @@ -804,14 +804,14 @@ sha512_crypt__min_rounds = 45000 )) def test_34_to_dict(self): - "test to_dict() method" + """test to_dict() method""" # NOTE: this is tested all throughout this test case. ctx = CryptContext(**self.sample_1_dict) self.assertEqual(ctx.to_dict(), self.sample_1_dict) self.assertEqual(ctx.to_dict(resolve=True), self.sample_1_resolved_dict) def test_35_to_string(self): - "test to_string() method" + """test to_string() method""" # create ctx and serialize ctx = CryptContext(**self.sample_1_dict) @@ -834,7 +834,6 @@ sha512_crypt__min_rounds = 45000 self.assertEqual(other, dump.replace("[passlib]","[password-security]")) # test unmanaged handler warning - from passlib import hash from passlib.tests.test_utils_handlers import UnsaltedHash ctx3 = CryptContext([UnsaltedHash, "md5_crypt"]) dump = ctx3.to_string() @@ -852,7 +851,7 @@ sha512_crypt__min_rounds = 45000 ] def test_40_basic(self): - "test basic encrypt/identify/verify functionality" + """test basic encrypt/identify/verify functionality""" handlers = [hash.md5_crypt, hash.des_crypt, hash.bsdi_crypt] cc = CryptContext(handlers, bsdi_crypt__default_rounds=5) @@ -878,7 +877,7 @@ sha512_crypt__min_rounds = 45000 self.assertRaises(ValueError, cc.genhash, 'secret', cc.genconfig(), scheme="des_crypt") def test_41_genconfig(self): - "test genconfig() method" + """test genconfig() method""" cc = CryptContext(schemes=["md5_crypt", "phpass"], phpass__ident="H", phpass__default_rounds=7, @@ -927,7 +926,7 @@ sha512_crypt__min_rounds = 45000 def test_42_genhash(self): - "test genhash() method" + """test genhash() method""" #-------------------------------------------------------------- # border cases @@ -960,7 +959,7 @@ sha512_crypt__min_rounds = 45000 def test_43_encrypt(self): - "test encrypt() method" + """test encrypt() method""" cc = CryptContext(**self.sample_4_dict) # hash specific settings @@ -1015,7 +1014,7 @@ sha512_crypt__min_rounds = 45000 def test_44_identify(self): - "test identify() border cases" + """test identify() border cases""" handlers = ["md5_crypt", "des_crypt", "bsdi_crypt"] cc = CryptContext(handlers, bsdi_crypt__default_rounds=5) @@ -1041,7 +1040,7 @@ sha512_crypt__min_rounds = 45000 self.assertRaises(TypeError, cc.identify, None, category=1) def test_45_verify(self): - "test verify() scheme kwd" + """test verify() scheme kwd""" handlers = ["md5_crypt", "des_crypt", "bsdi_crypt"] cc = CryptContext(handlers, bsdi_crypt__default_rounds=5) @@ -1087,7 +1086,7 @@ sha512_crypt__min_rounds = 45000 self.assertRaises(TypeError, cc.verify, 'secret', refhash, category=1) def test_46_needs_update(self): - "test needs_update() method" + """test needs_update() method""" cc = CryptContext(**self.sample_4_dict) # check deprecated scheme @@ -1167,7 +1166,7 @@ sha512_crypt__min_rounds = 45000 self.assertRaises(TypeError, cc.needs_update, refhash, category=1) def test_47_verify_and_update(self): - "test verify_and_update()" + """test verify_and_update()""" cc = CryptContext(**self.sample_4_dict) # create some hashes @@ -1227,7 +1226,7 @@ sha512_crypt__min_rounds = 45000 # genconfig(). it's assumed encrypt() takes the same codepath. def test_50_rounds_limits(self): - "test rounds limits" + """test rounds limits""" cc = CryptContext(schemes=["sha256_crypt"], all__min_rounds=2000, all__max_rounds=3000, @@ -1344,7 +1343,7 @@ sha512_crypt__min_rounds = 45000 self.assertRaises(TypeError, CryptContext, "sha256_crypt", all__default_rounds=bad) def test_51_linear_vary_rounds(self): - "test linear vary rounds" + """test linear vary rounds""" cc = CryptContext(schemes=["sha256_crypt"], all__min_rounds=1995, all__max_rounds=2005, @@ -1376,7 +1375,7 @@ sha512_crypt__min_rounds = 45000 self.assert_rounds_range(c2, "sha256_crypt", 1995, 2005) def test_52_log2_vary_rounds(self): - "test log2 vary rounds" + """test log2 vary rounds""" cc = CryptContext(schemes=["bcrypt"], all__min_rounds=15, all__max_rounds=25, @@ -1415,7 +1414,7 @@ sha512_crypt__min_rounds = 45000 self.assert_rounds_range(c2, "bcrypt", 15, 21) def assert_rounds_range(self, context, scheme, lower, upper): - "helper to check vary_rounds covers specified range" + """helper to check vary_rounds covers specified range""" # NOTE: this runs enough times the min and max *should* be hit, # though there's a faint chance it will randomly fail. handler = context.handler(scheme) @@ -1432,7 +1431,7 @@ sha512_crypt__min_rounds = 45000 # feature tests #=================================================================== def test_60_min_verify_time(self): - "test verify() honors min_verify_time" + """test verify() honors min_verify_time""" delta = .05 if TICK_RESOLUTION >= delta/10: raise self.skipTest("timer not accurate enough") @@ -1441,7 +1440,7 @@ sha512_crypt__min_rounds = 45000 max_delay = 8*delta class TimedHash(uh.StaticHandler): - "psuedo hash that takes specified amount of time" + """psuedo hash that takes specified amount of time""" name = "timed_hash" delay = 0 @@ -1498,7 +1497,7 @@ sha512_crypt__min_rounds = 45000 self.assertRaises(ValueError, CryptContext, min_verify_time=-1) def test_61_autodeprecate(self): - "test deprecated='auto' is handled correctly" + """test deprecated='auto' is handled correctly""" def getstate(ctx, category=None): return [ctx._is_deprecated_scheme(scheme, category) for scheme in ctx.schemes()] @@ -1533,7 +1532,7 @@ sha512_crypt__min_rounds = 45000 # handler deprecation detectors #=================================================================== def test_62_bcrypt_update(self): - "test verify_and_update / needs_update corrects bcrypt padding" + """test verify_and_update / needs_update corrects bcrypt padding""" # see issue 25. bcrypt = hash.bcrypt @@ -1554,7 +1553,7 @@ sha512_crypt__min_rounds = 45000 self.assertTrue(new_hash and new_hash != BAD1) def test_63_bsdi_crypt_update(self): - "test verify_and_update / needs_update corrects bsdi even rounds" + """test verify_and_update / needs_update corrects bsdi even rounds""" even_hash = '_Y/../cG0zkJa6LY6k4c' odd_hash = '_Z/..TgFg0/ptQtpAgws' secret = 'test' @@ -1588,7 +1587,7 @@ class LazyCryptContextTest(TestCase): self.addCleanup(unload_handler_name, "dummy_2") def test_kwd_constructor(self): - "test plain kwds" + """test plain kwds""" self.assertFalse(has_crypt_handler("dummy_2")) register_crypt_handler_path("dummy_2", "passlib.tests.test_context") diff --git a/passlib/tests/test_context_deprecated.py b/passlib/tests/test_context_deprecated.py index db0c49d..df9e1b3 100644 --- a/passlib/tests/test_context_deprecated.py +++ b/passlib/tests/test_context_deprecated.py @@ -41,7 +41,7 @@ log = getLogger(__name__) # #============================================================================= class CryptPolicyTest(TestCase): - "test CryptPolicy object" + """test CryptPolicy object""" # TODO: need to test user categories w/in all this @@ -220,7 +220,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt r"the method.*hash_needs_update.*is deprecated") def test_00_constructor(self): - "test CryptPolicy() constructor" + """test CryptPolicy() constructor""" policy = CryptPolicy(**self.sample_config_1pd) self.assertEqual(policy.to_dict(), self.sample_config_1pd) @@ -260,7 +260,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt default='md5_crypt') def test_01_from_path_simple(self): - "test CryptPolicy.from_path() constructor" + """test CryptPolicy.from_path() constructor""" # NOTE: this is separate so it can also run under GAE # test preset stored in existing file @@ -272,7 +272,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt self.assertRaises(EnvironmentError, CryptPolicy.from_path, path + 'xxx') def test_01_from_path(self): - "test CryptPolicy.from_path() constructor with encodings" + """test CryptPolicy.from_path() constructor with encodings""" path = self.mktemp() # test "\n" linesep @@ -292,7 +292,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt self.assertEqual(policy.to_dict(), self.sample_config_1pd) def test_02_from_string(self): - "test CryptPolicy.from_string() constructor" + """test CryptPolicy.from_string() constructor""" # test "\n" linesep policy = CryptPolicy.from_string(self.sample_config_1s) self.assertEqual(policy.to_dict(), self.sample_config_1pd) @@ -317,7 +317,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt self.assertEqual(policy.to_dict(), self.sample_config_4pd) def test_03_from_source(self): - "test CryptPolicy.from_source() constructor" + """test CryptPolicy.from_source() constructor""" # pass it a path policy = CryptPolicy.from_source(self.sample_config_1s_path) self.assertEqual(policy.to_dict(), self.sample_config_1pd) @@ -339,7 +339,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt self.assertRaises(TypeError, CryptPolicy.from_source, []) def test_04_from_sources(self): - "test CryptPolicy.from_sources() constructor" + """test CryptPolicy.from_sources() constructor""" # pass it empty list self.assertRaises(ValueError, CryptPolicy.from_sources, []) @@ -358,7 +358,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt self.assertEqual(policy.to_dict(), self.sample_config_123pd) def test_05_replace(self): - "test CryptPolicy.replace() constructor" + """test CryptPolicy.replace() constructor""" p1 = CryptPolicy(**self.sample_config_1pd) @@ -375,7 +375,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt self.assertEqual(p3.to_dict(), self.sample_config_123pd) def test_06_forbidden(self): - "test CryptPolicy() forbidden kwds" + """test CryptPolicy() forbidden kwds""" # salt not allowed to be set self.assertRaises(KeyError, CryptPolicy, @@ -397,7 +397,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt # reading #=================================================================== def test_10_has_schemes(self): - "test has_schemes() method" + """test has_schemes() method""" p1 = CryptPolicy(**self.sample_config_1pd) self.assertTrue(p1.has_schemes()) @@ -406,7 +406,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt self.assertTrue(not p3.has_schemes()) def test_11_iter_handlers(self): - "test iter_handlers() method" + """test iter_handlers() method""" p1 = CryptPolicy(**self.sample_config_1pd) s = self.sample_config_1prd['schemes'] @@ -416,7 +416,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt self.assertEqual(list(p3.iter_handlers()), []) def test_12_get_handler(self): - "test get_handler() method" + """test get_handler() method""" p1 = CryptPolicy(**self.sample_config_1pd) @@ -431,7 +431,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt self.assertIs(p1.get_handler(), hash.md5_crypt) def test_13_get_options(self): - "test get_options() method" + """test get_options() method""" p12 = CryptPolicy(**self.sample_config_12pd) @@ -470,7 +470,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt )) def test_14_handler_is_deprecated(self): - "test handler_is_deprecated() method" + """test handler_is_deprecated() method""" pa = CryptPolicy(**self.sample_config_1pd) pb = CryptPolicy(**self.sample_config_5pd) @@ -500,7 +500,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt self.assertTrue(pc.handler_is_deprecated("des_crypt", "user")) def test_15_min_verify_time(self): - "test get_min_verify_time() method" + """test get_min_verify_time() method""" # silence deprecation warnings for min verify time warnings.filterwarnings("ignore", category=DeprecationWarning) @@ -524,20 +524,20 @@ admin__context__deprecated = des_crypt, bsdi_crypt # serialization #=================================================================== def test_20_iter_config(self): - "test iter_config() method" + """test iter_config() method""" p5 = CryptPolicy(**self.sample_config_5pd) self.assertEqual(dict(p5.iter_config()), self.sample_config_5pd) self.assertEqual(dict(p5.iter_config(resolve=True)), self.sample_config_5prd) self.assertEqual(dict(p5.iter_config(ini=True)), self.sample_config_5pid) def test_21_to_dict(self): - "test to_dict() method" + """test to_dict() method""" p5 = CryptPolicy(**self.sample_config_5pd) self.assertEqual(p5.to_dict(), self.sample_config_5pd) self.assertEqual(p5.to_dict(resolve=True), self.sample_config_5prd) def test_22_to_string(self): - "test to_string() method" + """test to_string() method""" pa = CryptPolicy(**self.sample_config_5pd) s = pa.to_string() # NOTE: can't compare string directly, ordering etc may not match pb = CryptPolicy.from_string(s) @@ -554,7 +554,7 @@ admin__context__deprecated = des_crypt, bsdi_crypt # CryptContext #============================================================================= class CryptContextTest(TestCase): - "test CryptContext class" + """test CryptContext class""" descriptionPrefix = "CryptContext" def setUp(self): @@ -571,7 +571,7 @@ class CryptContextTest(TestCase): # constructor #=================================================================== def test_00_constructor(self): - "test constructor" + """test constructor""" # create crypt context using handlers cc = CryptContext([hash.md5_crypt, hash.bsdi_crypt, hash.des_crypt]) c,b,a = cc.policy.iter_handlers() @@ -600,7 +600,7 @@ class CryptContextTest(TestCase): self.assertRaises(TypeError, CryptContext, policy='x') def test_01_replace(self): - "test replace()" + """test replace()""" cc = CryptContext(["md5_crypt", "bsdi_crypt", "des_crypt"]) self.assertIs(cc.policy.get_handler(), hash.md5_crypt) @@ -617,7 +617,7 @@ class CryptContextTest(TestCase): self.assertIs(cc3.policy.get_handler(), hash.bsdi_crypt) def test_02_no_handlers(self): - "test no handlers" + """test no handlers""" # check constructor... cc = CryptContext() @@ -653,7 +653,7 @@ class CryptContextTest(TestCase): ) def test_12_hash_needs_update(self): - "test hash_needs_update() method" + """test hash_needs_update() method""" cc = CryptContext(**self.sample_policy_1) # check deprecated scheme @@ -672,7 +672,7 @@ class CryptContextTest(TestCase): # border cases #=================================================================== def test_30_nonstring_hash(self): - "test non-string hash values cause error" + """test non-string hash values cause error""" # # test hash=None or some other non-string causes TypeError # and that explicit-scheme code path behaves the same. @@ -716,7 +716,7 @@ class LazyCryptContextTest(TestCase): warnings.filterwarnings("ignore", ".*(CryptPolicy|context\.policy).*(has|have) been deprecated.*") def test_kwd_constructor(self): - "test plain kwds" + """test plain kwds""" self.assertFalse(has_crypt_handler("dummy_2")) register_crypt_handler_path("dummy_2", "passlib.tests.test_context") @@ -730,7 +730,7 @@ class LazyCryptContextTest(TestCase): self.assertTrue(has_crypt_handler("dummy_2", True)) def test_callable_constructor(self): - "test create_policy() hook, returning CryptPolicy" + """test create_policy() hook, returning CryptPolicy""" self.assertFalse(has_crypt_handler("dummy_2")) register_crypt_handler_path("dummy_2", "passlib.tests.test_context") diff --git a/passlib/tests/test_ext_django.py b/passlib/tests/test_ext_django.py index f9fd689..0f72937 100644 --- a/passlib/tests/test_ext_django.py +++ b/passlib/tests/test_ext_django.py @@ -76,7 +76,7 @@ if has_django: from django.contrib.auth.models import User class FakeUser(User): - "mock user object for use in testing" + """mock user object for use in testing""" # NOTE: this mainly just overrides .save() to test commit behavior. @memoized_property @@ -124,7 +124,7 @@ else: # test utils #============================================================================= class _ExtensionSupport(object): - "support funcs for loading/unloading extension" + """support funcs for loading/unloading extension""" #=================================================================== # support funcs #=================================================================== @@ -167,7 +167,7 @@ class _ExtensionSupport(object): # verify current patch state #=================================================================== def assert_unpatched(self): - "test that django is in unpatched state" + """test that django is in unpatched state""" # make sure we aren't currently patched mod = sys.modules.get("passlib.ext.django.models") self.assertFalse(mod and mod._patched, "patch should not be enabled") @@ -184,7 +184,7 @@ class _ExtensionSupport(object): (obj, attr, source)) def assert_patched(self, context=None): - "helper to ensure django HAS been patched, and is using specified config" + """helper to ensure django HAS been patched, and is using specified config""" # make sure we're currently patched mod = sys.modules.get("passlib.ext.django.models") self.assertTrue(mod and mod._patched, "patch should have been enabled") @@ -210,9 +210,8 @@ class _ExtensionSupport(object): # load / unload the extension (and verify it worked) #=================================================================== _config_keys = ["PASSLIB_CONFIG", "PASSLIB_CONTEXT", "PASSLIB_GET_CATEGORY"] - def load_extension(self, check=True, **kwds): - "helper to load extension with specified config & patch django" + """helper to load extension with specified config & patch django""" self.unload_extension() if check: config = kwds.get("PASSLIB_CONFIG") or kwds.get("PASSLIB_CONTEXT") @@ -224,7 +223,7 @@ class _ExtensionSupport(object): self.assert_patched(context=config) def unload_extension(self): - "helper to remove patches and unload extension" + """helper to remove patches and unload extension""" # remove patches and unload module mod = sys.modules.get("passlib.ext.django.models") if mod: @@ -258,7 +257,7 @@ class _ExtensionTest(TestCase, _ExtensionSupport): # extension tests #============================================================================= class DjangoBehaviorTest(_ExtensionTest): - "tests model to verify it matches django's behavior" + """tests model to verify it matches django's behavior""" descriptionPrefix = "verify django behavior" patched = False config = stock_config @@ -588,7 +587,7 @@ class DjangoBehaviorTest(_ExtensionTest): self.assertEqual(name, scheme) class ExtensionBehaviorTest(DjangoBehaviorTest): - "test model to verify passlib.ext.django conforms to it" + """test model to verify passlib.ext.django conforms to it""" descriptionPrefix = "verify extension behavior" patched = True config = dict( @@ -608,7 +607,7 @@ class DjangoExtensionTest(_ExtensionTest): # monkeypatch testing #=================================================================== def test_00_patch_control(self): - "test set_django_password_context patch/unpatch" + """test set_django_password_context patch/unpatch""" # check config="disabled" self.load_extension(PASSLIB_CONFIG="disabled", check=False) @@ -634,7 +633,7 @@ class DjangoExtensionTest(_ExtensionTest): self.unload_extension() def test_01_overwrite_detection(self): - "test detection of foreign monkeypatching" + """test detection of foreign monkeypatching""" # NOTE: this sets things up, and spot checks two methods, # this should be enough to verify patch manager is working. # TODO: test unpatch behavior honors flag. @@ -664,7 +663,7 @@ class DjangoExtensionTest(_ExtensionTest): models.check_password = orig def test_02_handler_wrapper(self): - "test Hasher-compatible handler wrappers" + """test Hasher-compatible handler wrappers""" if not has_django14: raise self.skipTest("Django >= 1.4 not installed") from passlib.ext.django.utils import get_passlib_hasher @@ -703,7 +702,7 @@ class DjangoExtensionTest(_ExtensionTest): # PASSLIB_CONFIG settings #=================================================================== def test_11_config_disabled(self): - "test PASSLIB_CONFIG='disabled'" + """test PASSLIB_CONFIG='disabled'""" # test config=None (deprecated) with self.assertWarningList("PASSLIB_CONFIG=None is deprecated"): self.load_extension(PASSLIB_CONFIG=None, check=False) @@ -714,7 +713,7 @@ class DjangoExtensionTest(_ExtensionTest): self.assert_unpatched() def test_12_config_presets(self): - "test PASSLIB_CONFIG='<preset>'" + """test PASSLIB_CONFIG='<preset>'""" # test django presets self.load_extension(PASSLIB_CONTEXT="django-default", check=False) if has_django14: @@ -730,7 +729,7 @@ class DjangoExtensionTest(_ExtensionTest): self.assert_patched(django14_context) def test_13_config_defaults(self): - "test PASSLIB_CONFIG default behavior" + """test PASSLIB_CONFIG default behavior""" # check implicit default from passlib.ext.django.utils import PASSLIB_DEFAULT default = CryptContext.from_string(PASSLIB_DEFAULT) @@ -746,7 +745,7 @@ class DjangoExtensionTest(_ExtensionTest): self.assert_patched(PASSLIB_DEFAULT) def test_14_config_invalid(self): - "test PASSLIB_CONFIG type checks" + """test PASSLIB_CONFIG type checks""" update_settings(PASSLIB_CONTEXT=123, PASSLIB_CONFIG=UNSET) self.assertRaises(TypeError, __import__, 'passlib.ext.django.models') @@ -758,7 +757,7 @@ class DjangoExtensionTest(_ExtensionTest): # PASSLIB_GET_CATEGORY setting #=================================================================== def test_21_category_setting(self): - "test PASSLIB_GET_CATEGORY parameter" + """test PASSLIB_GET_CATEGORY parameter""" # define config where rounds can be used to detect category config = dict( schemes = ["sha256_crypt"], @@ -769,7 +768,7 @@ class DjangoExtensionTest(_ExtensionTest): from passlib.hash import sha256_crypt def run(**kwds): - "helper to take in user opts, return rounds used in password" + """helper to take in user opts, return rounds used in password""" user = FakeUser(**kwds) user.set_password("stub") return sha256_crypt.from_string(user.password).rounds diff --git a/passlib/tests/test_handlers.py b/passlib/tests/test_handlers.py index 4845824..ab35883 100644 --- a/passlib/tests/test_handlers.py +++ b/passlib/tests/test_handlers.py @@ -29,7 +29,7 @@ UPASS_TABLE = u("t\u00e1\u0411\u2113\u0259") PASS_TABLE_UTF8 = b('t\xc3\xa1\xd0\x91\xe2\x84\x93\xc9\x99') # utf-8 def get_handler_case(scheme): - "return HandlerCase instance for scheme, used by other tests" + """return HandlerCase instance for scheme, used by other tests""" from passlib.registry import get_crypt_handler handler = get_crypt_handler(scheme) if hasattr(handler, "backends") and not hasattr(handler, "wrapped"): @@ -68,7 +68,7 @@ class apr_md5_crypt_test(HandlerCase): # bcrypt #============================================================================= class _bcrypt_test(HandlerCase): - "base for BCrypt test cases" + """base for BCrypt test cases""" handler = hash.bcrypt secret_size = 72 reduce_default_rounds = True @@ -211,7 +211,7 @@ class _bcrypt_test(HandlerCase): # fuzz testing #=================================================================== def os_supports_ident(self, hash): - "check if OS crypt is expected to support given ident" + """check if OS crypt is expected to support given ident""" if hash is None: return True # most OSes won't support 2x/2y @@ -230,7 +230,7 @@ class _bcrypt_test(HandlerCase): except ImportError: return def check_pybcrypt(secret, hash): - "pybcrypt" + """pybcrypt""" secret = to_native_str(secret, self.fuzz_password_encoding) if hash.startswith(IDENT_2Y): hash = IDENT_2A + hash[4:] @@ -249,7 +249,7 @@ class _bcrypt_test(HandlerCase): except ImportError: return def check_bcryptor(secret, hash): - "bcryptor" + """bcryptor""" secret = to_native_str(secret, self.fuzz_password_encoding) if hash.startswith(IDENT_2Y): hash = IDENT_2A + hash[4:] @@ -310,7 +310,7 @@ class _bcrypt_test(HandlerCase): ] def test_90_bcrypt_padding(self): - "test passlib correctly handles bcrypt padding bits" + """test passlib correctly handles bcrypt padding bits""" self.require_TEST_MODE("full") # # prevents reccurrence of issue 25 (https://code.google.com/p/passlib/issues/detail?id=25) @@ -340,10 +340,12 @@ class _bcrypt_test(HandlerCase): self.assertEqual(hash, "$2a$05$" + "." * 22) # - # make sure genhash() corrects input + # test public methods against good & bad hashes # samples = self.known_incorrect_padding for pwd, bad, good in samples: + + # make sure genhash() corrects bad configs, leaves good unchanged with self.assertWarningList([corr_desc]): self.assertEqual(bcrypt.genhash(pwd, bad), good) with self.assertWarningList([]): @@ -418,7 +420,7 @@ class bigcrypt_test(HandlerCase): # bsdi crypt #============================================================================= class _bsdi_crypt_test(HandlerCase): - "test BSDiCrypt algorithm" + """test BSDiCrypt algorithm""" handler = hash.bsdi_crypt known_correct_hashes = [ @@ -587,7 +589,7 @@ class cisco_type7_test(HandlerCase): ] def test_90_decode(self): - "test cisco_type7.decode()" + """test cisco_type7.decode()""" from passlib.utils import to_unicode, to_bytes handler = self.handler @@ -601,7 +603,7 @@ class cisco_type7_test(HandlerCase): '0958EDC8A9F495F6F8A5FD', 'ascii') def test_91_salt(self): - "test salt value border cases" + """test salt value border cases""" handler = self.handler self.assertRaises(TypeError, handler, salt=None) handler(salt=None, use_defaults=True) @@ -644,7 +646,7 @@ class crypt16_test(HandlerCase): # des crypt #============================================================================= class _des_crypt_test(HandlerCase): - "test des-crypt algorithm" + """test des-crypt algorithm""" handler = hash.des_crypt secret_size = 8 @@ -706,7 +708,7 @@ class _DjangoHelper(object): return None from django.contrib.auth.models import check_password def verify_django(secret, hash): - "django/check_password" + """django/check_password""" if has_django14 and not secret: return "skip" if self.handler.name == "django_bcrypt" and hash.startswith("bcrypt$$2y$"): @@ -715,7 +717,7 @@ class _DjangoHelper(object): return verify_django def test_90_django_reference(self): - "run known correct hashes through Django's check_password()" + """run known correct hashes through Django's check_password()""" from passlib.tests.test_ext_django import has_django1, has_django14 if self.requires14 and not has_django14: raise self.skipTest("Django >= 1.4 not installed") @@ -737,7 +739,7 @@ class _DjangoHelper(object): (secret, hash)) def test_91_django_generation(self): - "test against output of Django's make_password()" + """test against output of Django's make_password()""" from passlib.tests.test_ext_django import has_django14 if not has_django14: raise self.skipTest("Django >= 1.4 not installed") @@ -755,7 +757,7 @@ class _DjangoHelper(object): self.assertFalse(self.do_verify(other, hash)) class django_disabled_test(HandlerCase): - "test django_disabled" + """test django_disabled""" handler = hash.django_disabled is_disabled_handler = True @@ -767,7 +769,7 @@ class django_disabled_test(HandlerCase): ] class django_des_crypt_test(HandlerCase, _DjangoHelper): - "test django_des_crypt" + """test django_des_crypt""" handler = hash.django_des_crypt secret_size = 8 @@ -808,7 +810,7 @@ class django_des_crypt_test(HandlerCase, _DjangoHelper): ] class django_salted_md5_test(HandlerCase, _DjangoHelper): - "test django_salted_md5" + """test django_salted_md5""" handler = hash.django_salted_md5 known_correct_hashes = [ @@ -846,7 +848,7 @@ class django_salted_md5_test(HandlerCase, _DjangoHelper): return randintgauss(lower, upper, default, default*.5) class django_salted_sha1_test(HandlerCase, _DjangoHelper): - "test django_salted_sha1" + """test django_salted_sha1""" handler = hash.django_salted_sha1 known_correct_hashes = [ @@ -876,7 +878,7 @@ class django_salted_sha1_test(HandlerCase, _DjangoHelper): fuzz_setting_salt_size = get_method_function(django_salted_md5_test.fuzz_setting_salt_size) class django_pbkdf2_sha256_test(HandlerCase, _DjangoHelper): - "test django_pbkdf2_sha256" + """test django_pbkdf2_sha256""" handler = hash.django_pbkdf2_sha256 requires14 = True @@ -891,7 +893,7 @@ class django_pbkdf2_sha256_test(HandlerCase, _DjangoHelper): ] class django_pbkdf2_sha1_test(HandlerCase, _DjangoHelper): - "test django_pbkdf2_sha1" + """test django_pbkdf2_sha1""" handler = hash.django_pbkdf2_sha1 requires14 = True @@ -906,7 +908,7 @@ class django_pbkdf2_sha1_test(HandlerCase, _DjangoHelper): ] class django_bcrypt_test(HandlerCase, _DjangoHelper): - "test django_bcrypt" + """test django_bcrypt""" handler = hash.django_bcrypt secret_size = 72 requires14 = True @@ -945,7 +947,7 @@ django_bcrypt_test = skipUnless(hash.bcrypt.has_backend(), # fshp #============================================================================= class fshp_test(HandlerCase): - "test fshp algorithm" + """test fshp algorithm""" handler = hash.fshp known_correct_hashes = [ @@ -998,7 +1000,7 @@ class fshp_test(HandlerCase): ] def test_90_variant(self): - "test variant keyword" + """test variant keyword""" handler = self.handler kwds = dict(salt=b('a'), rounds=1) @@ -1095,7 +1097,7 @@ class htdigest_test(UserHandlerMixin, HandlerCase): raise self.skipTest("test case doesn't support 'realm' keyword") def populate_context(self, secret, kwds): - "insert username into kwds" + """insert username into kwds""" if isinstance(secret, tuple): secret, user, realm = secret else: @@ -1251,7 +1253,7 @@ ldap_sha1_crypt_os_crypt_test, = _ldap_sha1_crypt_test.create_backend_cases(["os class ldap_pbkdf2_test(TestCase): def test_wrappers(self): - "test ldap pbkdf2 wrappers" + """test ldap pbkdf2 wrappers""" self.assertTrue( hash.ldap_pbkdf2_sha1.verify( @@ -1317,7 +1319,7 @@ class lmhash_test(EncodingHandlerMixin, HandlerCase): ] def test_90_raw(self): - "test lmhash.raw() method" + """test lmhash.raw() method""" from binascii import unhexlify from passlib.utils.compat import str_to_bascii lmhash = self.handler @@ -1683,7 +1685,7 @@ class mysql323_test(HandlerCase): ] def test_90_whitespace(self): - "check whitespace is ignored per spec" + """check whitespace is ignored per spec""" h = self.do_encrypt("mypass") h2 = self.do_encrypt("my pass") self.assertEqual(h, h2) @@ -2124,7 +2126,7 @@ class scram_test(HandlerCase): warnings.filterwarnings("ignore", r"norm_hash_name\(\): unknown hash") def test_90_algs(self): - "test parsing of 'algs' setting" + """test parsing of 'algs' setting""" defaults = dict(salt=b('A')*10, rounds=1000) def parse(algs, **kwds): for k in defaults: @@ -2154,7 +2156,7 @@ class scram_test(HandlerCase): checksum={"sha-1": b("\x00"*20)}) def test_90_checksums(self): - "test internal parsing of 'checksum' keyword" + """test internal parsing of 'checksum' keyword""" # check non-bytes checksum values are rejected self.assertRaises(TypeError, self.handler, use_defaults=True, checksum={'sha-1': u('X')*20}) @@ -2166,7 +2168,7 @@ class scram_test(HandlerCase): # XXX: anything else that's not tested by the other code already? def test_91_extract_digest_info(self): - "test scram.extract_digest_info()" + """test scram.extract_digest_info()""" edi = self.handler.extract_digest_info # return appropriate value or throw KeyError @@ -2184,7 +2186,7 @@ class scram_test(HandlerCase): self.assertRaises(ValueError, edi, c, "ddd") def test_92_extract_digest_algs(self): - "test scram.extract_digest_algs()" + """test scram.extract_digest_algs()""" eda = self.handler.extract_digest_algs self.assertEqual(eda('$scram$4096$QSXCR.Q6sek8bf92$' @@ -2202,10 +2204,9 @@ class scram_test(HandlerCase): ["sha-1","sha-256","sha-512"]) def test_93_derive_digest(self): - "test scram.derive_digest()" + """test scram.derive_digest()""" # NOTE: this just does a light test, since derive_digest # is used by encrypt / verify, and is tested pretty well via those. - hash = self.handler.derive_digest # check various encodings of password work. @@ -2228,7 +2229,7 @@ class scram_test(HandlerCase): self.assertRaises(TypeError, hash, "IX", u('\x01'), 1000, 'md5') def test_94_saslprep(self): - "test encrypt/verify use saslprep" + """test encrypt/verify use saslprep""" # NOTE: this just does a light test that saslprep() is being # called in various places, relying in saslpreps()'s tests # to verify full normalization behavior. @@ -2248,7 +2249,7 @@ class scram_test(HandlerCase): self.assertRaises(ValueError, self.do_verify, u("\uFDD0"), h) def test_95_context_algs(self): - "test handling of 'algs' in context object" + """test handling of 'algs' in context object""" handler = self.handler from passlib.context import CryptContext c1 = CryptContext(["scram"], scram__algs="sha1,md5") @@ -2264,7 +2265,7 @@ class scram_test(HandlerCase): self.assertTrue(c2.needs_update(h)) def test_96_full_verify(self): - "test verify(full=True) flag" + """test verify(full=True) flag""" def vpart(s, h): return self.handler.verify(s, h) def vfull(s, h): @@ -2352,7 +2353,6 @@ sha1_crypt_os_crypt_test, sha1_crypt_builtin_test = \ # NOTE: all roundup hashes use PrefixWrapper, # so there's nothing natively to test. # so we just have a few quick cases... -from passlib.handlers import roundup class RoundupTest(TestCase): @@ -2674,7 +2674,6 @@ class sun_md5_crypt_test(HandlerCase): ("solaris", True), ("freebsd|openbsd|netbsd|linux|darwin", False), ] - def do_verify(self, secret, hash): # override to fake error for "$..." hash strings listed in known_config. # these have to be hash strings, in order to test bare salt issue. @@ -2711,7 +2710,7 @@ class unix_disabled_test(HandlerCase): super(unix_disabled_test, self).test_76_hash_border() def test_90_special(self): - "test marker option & special behavior" + """test marker option & special behavior""" handler = self.handler # preserve hash if provided @@ -2743,16 +2742,16 @@ class unix_fallback_test(HandlerCase): warnings.filterwarnings("ignore", "'unix_fallback' is deprecated") def test_90_wildcard(self): - "test enable_wildcard flag" + """test enable_wildcard flag""" h = self.handler self.assertTrue(h.verify('password','', enable_wildcard=True)) self.assertFalse(h.verify('password','')) - for c in ("!*x"): + for c in "!*x": self.assertFalse(h.verify('password',c, enable_wildcard=True)) self.assertFalse(h.verify('password',c)) def test_91_preserves_existing(self): - "test preserves existing disabled hash" + """test preserves existing disabled hash""" handler = self.handler # use marker if no hash diff --git a/passlib/tests/test_hosts.py b/passlib/tests/test_hosts.py index b01a108..c1572ae 100644 --- a/passlib/tests/test_hosts.py +++ b/passlib/tests/test_hosts.py @@ -17,7 +17,7 @@ from passlib.tests.utils import TestCase # test predefined app contexts #============================================================================= class HostsTest(TestCase): - "perform general tests to make sure contexts work" + """perform general tests to make sure contexts work""" # NOTE: these tests are not really comprehensive, # since they would do little but duplicate # the presets in apps.py diff --git a/passlib/tests/test_registry.py b/passlib/tests/test_registry.py index 306e95a..ff7703d 100644 --- a/passlib/tests/test_registry.py +++ b/passlib/tests/test_registry.py @@ -47,7 +47,7 @@ class RegistryTest(TestCase): unload_handler_name(name) def test_hash_proxy(self): - "test passlib.hash proxy object" + """test passlib.hash proxy object""" # check dir works dir(hash) @@ -80,7 +80,7 @@ class RegistryTest(TestCase): self.assertRaises(ValueError, setattr, hash, "dummy_1x", dummy_1) def test_register_crypt_handler_path(self): - "test register_crypt_handler_path()" + """test register_crypt_handler_path()""" # NOTE: this messes w/ internals of registry, shouldn't be used publically. paths = registry._locations @@ -127,7 +127,7 @@ class RegistryTest(TestCase): self.assertIs(h, tbr.alt_dummy_bad) def test_register_crypt_handler(self): - "test register_crypt_handler()" + """test register_crypt_handler()""" self.assertRaises(TypeError, register_crypt_handler, {}) @@ -158,7 +158,7 @@ class RegistryTest(TestCase): self.assertTrue('dummy_1' in list_crypt_handlers()) def test_get_crypt_handler(self): - "test get_crypt_handler()" + """test get_crypt_handler()""" class dummy_1(uh.StaticHandler): name = "dummy_1" @@ -189,7 +189,7 @@ class RegistryTest(TestCase): self.assertIs(get_crypt_handler(name, None), None) def test_list_crypt_handlers(self): - "test list_crypt_handlers()" + """test list_crypt_handlers()""" from passlib.registry import list_crypt_handlers # check system & private names aren't returned diff --git a/passlib/tests/test_utils.py b/passlib/tests/test_utils.py index 67834a0..936b739 100644 --- a/passlib/tests/test_utils.py +++ b/passlib/tests/test_utils.py @@ -22,12 +22,12 @@ def hb(source): # byte funcs #============================================================================= class MiscTest(TestCase): - "tests various parts of utils module" + """tests various parts of utils module""" # NOTE: could test xor_bytes(), but it's exercised well enough by pbkdf2 test def test_compat(self): - "test compat's lazymodule" + """test compat's lazymodule""" from passlib.utils import compat # "<module 'passlib.utils.compat' from 'passlib/utils/compat.pyc'>" self.assertRegex(repr(compat), @@ -58,7 +58,7 @@ class MiscTest(TestCase): @deprecated_function(deprecated="1.6", removed="1.8") def test_func(*args): - "test docstring" + """test docstring""" return args self.assertTrue(".. deprecated::" in test_func.__doc__) @@ -91,7 +91,7 @@ class MiscTest(TestCase): self.assertIs(prop.im_func, prop.__func__) def test_getrandbytes(self): - "test getrandbytes()" + """test getrandbytes()""" from passlib.utils import getrandbytes, rng def f(*a,**k): return getrandbytes(rng, *a, **k) @@ -104,7 +104,7 @@ class MiscTest(TestCase): self.assertNotEqual(a, b) def test_getrandstr(self): - "test getrandstr()" + """test getrandstr()""" from passlib.utils import getrandstr, rng def f(*a,**k): return getrandstr(rng, *a, **k) @@ -141,7 +141,7 @@ class MiscTest(TestCase): self.assertEqual(len(generate_password(15)), 15) def test_is_crypt_context(self): - "test is_crypt_context()" + """test is_crypt_context()""" from passlib.utils import is_crypt_context from passlib.context import CryptContext cc = CryptContext(["des_crypt"]) @@ -149,7 +149,7 @@ class MiscTest(TestCase): self.assertFalse(not is_crypt_context(cc)) def test_genseed(self): - "test genseed()" + """test genseed()""" import random from passlib.utils import genseed rng = random.Random(genseed()) @@ -163,7 +163,7 @@ class MiscTest(TestCase): rng.seed(genseed(rng)) def test_crypt(self): - "test crypt.crypt() wrappers" + """test crypt.crypt() wrappers""" from passlib.utils import has_crypt, safe_crypt, test_crypt # test everything is disabled @@ -220,7 +220,7 @@ class MiscTest(TestCase): mod._crypt = orig def test_consteq(self): - "test consteq()" + """test consteq()""" # NOTE: this test is kind of over the top, but that's only because # this is used for the critical task of comparing hashes for equality. from passlib.utils import consteq @@ -304,7 +304,7 @@ class MiscTest(TestCase): ## ##print ", ".join(str(c) for c in [run] + times) def test_saslprep(self): - "test saslprep() unicode normalizer" + """test saslprep() unicode normalizer""" self.require_stringprep() from passlib.utils import saslprep as sp @@ -395,10 +395,10 @@ class MiscTest(TestCase): # byte/unicode helpers #============================================================================= class CodecTest(TestCase): - "tests bytes/unicode helpers in passlib.utils" + """tests bytes/unicode helpers in passlib.utils""" def test_bytes(self): - "test b() helper, bytes and native str type" + """test b() helper, bytes and native str type""" if PY3: import builtins self.assertIs(bytes, builtins.bytes) @@ -414,7 +414,7 @@ class CodecTest(TestCase): self.assertEqual(b('\x00\xff'), "\x00\xff") def test_to_bytes(self): - "test to_bytes()" + """test to_bytes()""" from passlib.utils import to_bytes # check unicode inputs @@ -443,7 +443,7 @@ class CodecTest(TestCase): self.assertRaises(TypeError, to_bytes, None) def test_to_unicode(self): - "test to_unicode()" + """test to_unicode()""" from passlib.utils import to_unicode # check unicode inputs @@ -465,7 +465,7 @@ class CodecTest(TestCase): self.assertRaises(TypeError, to_unicode, None) def test_to_native_str(self): - "test to_native_str()" + """test to_native_str()""" from passlib.utils import to_native_str # test plain ascii @@ -496,7 +496,7 @@ class CodecTest(TestCase): self.assertRaises(TypeError, to_native_str, None, 'ascii') def test_is_ascii_safe(self): - "test is_ascii_safe()" + """test is_ascii_safe()""" from passlib.utils import is_ascii_safe self.assertTrue(is_ascii_safe(b("\x00abc\x7f"))) self.assertTrue(is_ascii_safe(u("\x00abc\x7f"))) @@ -504,7 +504,7 @@ class CodecTest(TestCase): self.assertFalse(is_ascii_safe(u("\x00abc\x80"))) def test_is_same_codec(self): - "test is_same_codec()" + """test is_same_codec()""" from passlib.utils import is_same_codec self.assertTrue(is_same_codec(None, None)) @@ -523,7 +523,7 @@ class CodecTest(TestCase): # base64engine #============================================================================= class Base64EngineTest(TestCase): - "test standalone parts of Base64Engine" + """test standalone parts of Base64Engine""" # NOTE: most Base64Engine testing done via _Base64Test subclasses below. def test_constructor(self): @@ -547,7 +547,7 @@ class Base64EngineTest(TestCase): self.assertRaises(ValueError, ab64_decode, "abcde") class _Base64Test(TestCase): - "common tests for all Base64Engine instances" + """common tests for all Base64Engine instances""" #=================================================================== # class attrs #=================================================================== @@ -566,14 +566,14 @@ class _Base64Test(TestCase): # helper to generate bytemap-specific strings def m(self, *offsets): - "generate byte string from offsets" + """generate byte string from offsets""" return join_bytes(self.engine.bytemap[o:o+1] for o in offsets) #=================================================================== # test encode_bytes #=================================================================== def test_encode_bytes(self): - "test encode_bytes() against reference inputs" + """test encode_bytes() against reference inputs""" engine = self.engine encode = engine.encode_bytes for raw, encoded in self.encoded_data: @@ -581,7 +581,7 @@ class _Base64Test(TestCase): self.assertEqual(result, encoded, "encode %r:" % (raw,)) def test_encode_bytes_bad(self): - "test encode_bytes() with bad input" + """test encode_bytes() with bad input""" engine = self.engine encode = engine.encode_bytes self.assertRaises(TypeError, encode, u('\x00')) @@ -591,7 +591,7 @@ class _Base64Test(TestCase): # test decode_bytes #=================================================================== def test_decode_bytes(self): - "test decode_bytes() against reference inputs" + """test decode_bytes() against reference inputs""" engine = self.engine decode = engine.decode_bytes for raw, encoded in self.encoded_data: @@ -599,7 +599,7 @@ class _Base64Test(TestCase): self.assertEqual(result, raw, "decode %r:" % (encoded,)) def test_decode_bytes_padding(self): - "test decode_bytes() ignores padding bits" + """test decode_bytes() ignores padding bits""" bchr = (lambda v: bytes([v])) if PY3 else chr engine = self.engine m = self.m @@ -626,7 +626,7 @@ class _Base64Test(TestCase): "%d/2 bits:" % i) def test_decode_bytes_bad(self): - "test decode_bytes() with bad input" + """test decode_bytes() with bad input""" engine = self.engine decode = engine.decode_bytes @@ -645,7 +645,7 @@ class _Base64Test(TestCase): # encode_bytes+decode_bytes #=================================================================== def test_codec(self): - "test encode_bytes/decode_bytes against random data" + """test encode_bytes/decode_bytes against random data""" engine = self.engine from passlib.utils import getrandbytes, getrandstr saw_zero = False @@ -691,7 +691,7 @@ class _Base64Test(TestCase): self.assertEqual(result, encoded) def test_repair_unused(self): - "test repair_unused()" + """test repair_unused()""" # NOTE: this test relies on encode_bytes() always returning clear # padding bits - which should be ensured by test vectors. from passlib.utils import rng, getrandstr @@ -739,7 +739,7 @@ class _Base64Test(TestCase): ] def test_encode_transposed_bytes(self): - "test encode_transposed_bytes()" + """test encode_transposed_bytes()""" engine = self.engine for result, input, offsets in self.transposed + self.transposed_dups: tmp = engine.encode_transposed_bytes(input, offsets) @@ -749,7 +749,7 @@ class _Base64Test(TestCase): self.assertRaises(TypeError, engine.encode_transposed_bytes, u("a"), []) def test_decode_transposed_bytes(self): - "test decode_transposed_bytes()" + """test decode_transposed_bytes()""" engine = self.engine for input, result, offsets in self.transposed: tmp = engine.encode_bytes(input) @@ -757,7 +757,7 @@ class _Base64Test(TestCase): self.assertEqual(out, result) def test_decode_transposed_bytes_bad(self): - "test decode_transposed_bytes() fails if map is a one-way" + """test decode_transposed_bytes() fails if map is a one-way""" engine = self.engine for input, _, offsets in self.transposed_dups: tmp = engine.encode_bytes(input) @@ -768,7 +768,7 @@ class _Base64Test(TestCase): # test 6bit handling #=================================================================== def check_int_pair(self, bits, encoded_pairs): - "helper to check encode_intXX & decode_intXX functions" + """helper to check encode_intXX & decode_intXX functions""" engine = self.engine encode = getattr(engine, "encode_int%s" % bits) decode = getattr(engine, "decode_int%s" % bits) @@ -795,7 +795,7 @@ class _Base64Test(TestCase): self.assertRaises(TypeError, decode, None) # do random testing. - from passlib.utils import getrandbytes, getrandstr + from passlib.utils import getrandstr for i in irange(100): # generate random value, encode, and then decode value = random.randint(0, upper-1) @@ -844,7 +844,7 @@ class _Base64Test(TestCase): else m(63,63,63,63, 63,63,63,63, 63,63,15))]) def test_encoded_ints(self): - "test against reference integer encodings" + """test against reference integer encodings""" if not self.encoded_ints: raise self.skipTests("none defined for class") engine = self.engine @@ -863,7 +863,7 @@ class _Base64Test(TestCase): from passlib.utils import h64, h64big class H64_Test(_Base64Test): - "test H64 codec functions" + """test H64 codec functions""" engine = h64 descriptionPrefix = "h64 codec" @@ -888,7 +888,7 @@ class H64_Test(_Base64Test): ] class H64Big_Test(_Base64Test): - "test H64Big codec functions" + """test H64Big codec functions""" engine = h64big descriptionPrefix = "h64big codec" diff --git a/passlib/tests/test_utils_crypto.py b/passlib/tests/test_utils_crypto.py index 873ed30..55ef951 100644 --- a/passlib/tests/test_utils_crypto.py +++ b/passlib/tests/test_utils_crypto.py @@ -31,7 +31,7 @@ def hb(source): # test assorted crypto helpers #============================================================================= class CryptoTest(TestCase): - "test various crypto functions" + """test various crypto functions""" ndn_formats = ["hashlib", "iana"] ndn_values = [ @@ -48,7 +48,7 @@ class CryptoTest(TestCase): ] def test_norm_hash_name(self): - "test norm_hash_name()" + """test norm_hash_name()""" from itertools import chain from passlib.utils.pbkdf2 import norm_hash_name, _nhn_hash_names @@ -76,7 +76,7 @@ class CryptoTest(TestCase): format)) def test_get_hash_info(self): - "test get_hash_info()" + """test get_hash_info()""" import hashlib from passlib.utils.pbkdf2 import get_hash_info @@ -173,7 +173,7 @@ class DesTest(TestCase): ] def test_01_expand(self): - "test expand_des_key()" + """test expand_des_key()""" from passlib.utils.des import expand_des_key, shrink_des_key, \ _KDATA_MASK, INT_56_MASK @@ -197,7 +197,7 @@ class DesTest(TestCase): self.assertRaises(ValueError, expand_des_key, b("\x00")*6) def test_02_shrink(self): - "test shrink_des_key()" + """test shrink_des_key()""" from passlib.utils.des import expand_des_key, shrink_des_key, \ INT_64_MASK from passlib.utils import random, getrandbytes @@ -222,13 +222,13 @@ class DesTest(TestCase): self.assertRaises(ValueError, shrink_des_key, b("\x00")*7) def _random_parity(self, key): - "randomize parity bits" + """randomize parity bits""" from passlib.utils.des import _KDATA_MASK, _KPARITY_MASK, INT_64_MASK from passlib.utils import rng return (key & _KDATA_MASK) | (rng.randint(0,INT_64_MASK) & _KPARITY_MASK) def test_03_encrypt_bytes(self): - "test des_encrypt_block()" + """test des_encrypt_block()""" from passlib.utils.des import (des_encrypt_block, shrink_des_key, _pack64, _unpack64) @@ -274,8 +274,8 @@ class DesTest(TestCase): self.assertRaises(ValueError, des_encrypt_block, stub, stub, 0, rounds=0) def test_04_encrypt_ints(self): - "test des_encrypt_int_block()" - from passlib.utils.des import (des_encrypt_int_block, shrink_des_key) + """test des_encrypt_int_block()""" + from passlib.utils.des import des_encrypt_int_block # run through test vectors for key, plaintext, correct in self.des_test_vectors: @@ -335,7 +335,7 @@ class _MD4_Test(TestCase): ] def test_md4_update(self): - "test md4 update" + """test md4 update""" from passlib.utils.md4 import md4 h = md4(b('')) self.assertEqual(h.hexdigest(), "31d6cfe0d16ae931b73c59d7e0c089c0") @@ -352,21 +352,21 @@ class _MD4_Test(TestCase): self.assertEqual(h.hexdigest(), "d79e1c308aa5bbcdeea8ed63df412da9") def test_md4_hexdigest(self): - "test md4 hexdigest()" + """test md4 hexdigest()""" from passlib.utils.md4 import md4 for input, hex in self.vectors: out = md4(input).hexdigest() self.assertEqual(out, hex) def test_md4_digest(self): - "test md4 digest()" + """test md4 digest()""" from passlib.utils.md4 import md4 for input, hex in self.vectors: out = bascii_to_str(hexlify(md4(input).digest())) self.assertEqual(out, hex) def test_md4_copy(self): - "test md4 copy()" + """test md4 copy()""" from passlib.utils.md4 import md4 h = md4(b('abc')) @@ -392,7 +392,7 @@ MD4_Builtin_Test = skipUnless(TEST_MODE("full") or not has_native_md4, # test PBKDF1 support #============================================================================= class Pbkdf1_Test(TestCase): - "test kdf helpers" + """test kdf helpers""" descriptionPrefix = "pbkdf1" pbkdf1_tests = [ @@ -419,14 +419,14 @@ class Pbkdf1_Test(TestCase): ) def test_known(self): - "test reference vectors" + """test reference vectors""" from passlib.utils.pbkdf2 import pbkdf1 for secret, salt, rounds, keylen, digest, correct in self.pbkdf1_tests: result = pbkdf1(secret, salt, rounds, keylen, digest) self.assertEqual(result, correct) def test_border(self): - "test border cases" + """test border cases""" from passlib.utils.pbkdf2 import pbkdf1 def helper(secret=b('secret'), salt=b('salt'), rounds=1, keylen=1, hash='md5'): return pbkdf1(secret, salt, rounds, keylen, hash) @@ -452,7 +452,7 @@ class Pbkdf1_Test(TestCase): # test PBKDF2 support #============================================================================= class _Pbkdf2_Test(TestCase): - "test pbkdf2() support" + """test pbkdf2() support""" def setUp(self): super(_Pbkdf2_Test, self).setUp() @@ -576,7 +576,7 @@ class _Pbkdf2_Test(TestCase): ] def test_known(self): - "test reference vectors" + """test reference vectors""" from passlib.utils.pbkdf2 import pbkdf2 for row in self.pbkdf2_test_vectors: correct, secret, salt, rounds, keylen = row[:5] @@ -585,7 +585,7 @@ class _Pbkdf2_Test(TestCase): self.assertEqual(result, correct) def test_border(self): - "test border cases" + """test border cases""" from passlib.utils.pbkdf2 import pbkdf2 def helper(secret=b('password'), salt=b('salt'), rounds=1, keylen=None, prf="hmac-sha1"): return pbkdf2(secret, salt, rounds, keylen, prf) @@ -611,7 +611,7 @@ class _Pbkdf2_Test(TestCase): self.assertRaises(TypeError, helper, prf=5) def test_default_keylen(self): - "test keylen==None" + """test keylen==None""" from passlib.utils.pbkdf2 import pbkdf2 def helper(secret=b('password'), salt=b('salt'), rounds=1, keylen=None, prf="hmac-sha1"): return pbkdf2(secret, salt, rounds, keylen, prf) @@ -619,16 +619,16 @@ class _Pbkdf2_Test(TestCase): self.assertEqual(len(helper(prf='hmac-sha256')), 32) def test_custom_prf(self): - "test custom prf function" + """test custom prf function""" from passlib.utils.pbkdf2 import pbkdf2 def prf(key, msg): return hashlib.md5(key+msg+b('fooey')).digest() result = pbkdf2(b('secret'), b('salt'), 1000, 20, prf) self.assertEqual(result, hb('5fe7ce9f7e379d3f65cbc66ba8aa6440474a6849')) -#-------------------------------------------------------------------- +#------------------------------------------------------------------------ # create subclasses to test with- and without- m2crypto -#-------------------------------------------------------------------- +#------------------------------------------------------------------------ class Pbkdf2_M2Crypto_Test(_Pbkdf2_Test): descriptionPrefix = "pbkdf2 (m2crypto backend)" diff --git a/passlib/tests/test_utils_handlers.py b/passlib/tests/test_utils_handlers.py index 6e4bfee..d5525b6 100644 --- a/passlib/tests/test_utils_handlers.py +++ b/passlib/tests/test_utils_handlers.py @@ -27,7 +27,7 @@ log = getLogger(__name__) # utils #============================================================================= def _makelang(alphabet, size): - "generate all strings of given size using alphabet" + """generate all strings of given size using alphabet""" def helper(size): if size < 2: for char in alphabet: @@ -42,13 +42,13 @@ def _makelang(alphabet, size): # test GenericHandler & associates mixin classes #============================================================================= class SkeletonTest(TestCase): - "test hash support classes" + """test hash support classes""" #=================================================================== # StaticHandler #=================================================================== def test_00_static_handler(self): - "test StaticHandler class" + """test StaticHandler class""" class d1(uh.StaticHandler): name = "d1" @@ -94,7 +94,7 @@ class SkeletonTest(TestCase): self.assertEqual(d1.encrypt('s', flag=True), '_b') def test_01_calc_checksum_hack(self): - "test StaticHandler legacy attr" + """test StaticHandler legacy attr""" # release 1.5 StaticHandler required genhash(), # not _calc_checksum, be implemented. we have backward compat wrapper, # this tests that it works. @@ -103,7 +103,7 @@ class SkeletonTest(TestCase): name = "d1" @classmethod - def identify(self, hash): + def identify(cls, hash): if not hash or len(hash) != 40: return False try: @@ -111,7 +111,6 @@ class SkeletonTest(TestCase): except ValueError: return False return True - @classmethod def genhash(cls, secret, hash): if secret is None: @@ -121,7 +120,6 @@ class SkeletonTest(TestCase): if hash is not None and not cls.identify(hash): raise ValueError("invalid hash") return hashlib.sha1(b("xyz") + secret).hexdigest() - @classmethod def verify(cls, secret, hash): if hash is None: @@ -144,9 +142,8 @@ class SkeletonTest(TestCase): # GenericHandler & mixins #=================================================================== def test_10_identify(self): - "test GenericHandler.identify()" + """test GenericHandler.identify()""" class d1(uh.GenericHandler): - @classmethod def from_string(cls, hash): if isinstance(hash, bytes): @@ -180,7 +177,7 @@ class SkeletonTest(TestCase): del d1.ident def test_11_norm_checksum(self): - "test GenericHandler checksum handling" + """test GenericHandler checksum handling""" # setup helpers class d1(uh.GenericHandler): name = 'd1' @@ -216,7 +213,7 @@ class SkeletonTest(TestCase): self.assertIs(norm_checksum(u('zzzz')), None) def test_12_norm_checksum_raw(self): - "test GenericHandler + HasRawChecksum mixin" + """test GenericHandler + HasRawChecksum mixin""" class d1(uh.HasRawChecksum, uh.GenericHandler): name = 'd1' checksum_size = 4 @@ -236,7 +233,7 @@ class SkeletonTest(TestCase): self.assertIs(norm_checksum(b('0')*4), None) def test_20_norm_salt(self): - "test GenericHandler + HasSalt mixin" + """test GenericHandler + HasSalt mixin""" # setup helpers class d1(uh.HasSalt, uh.GenericHandler): name = 'd1' @@ -312,7 +309,7 @@ class SkeletonTest(TestCase): # TODO: test HasRawSalt mixin def test_30_norm_rounds(self): - "test GenericHandler + HasRounds mixin" + """test GenericHandler + HasRounds mixin""" # setup helpers class d1(uh.HasRounds, uh.GenericHandler): name = 'd1' @@ -359,7 +356,7 @@ class SkeletonTest(TestCase): self.assertRaises(TypeError, norm_rounds, use_defaults=True) def test_40_backends(self): - "test GenericHandler + HasManyBackends mixin" + """test GenericHandler + HasManyBackends mixin""" class d1(uh.HasManyBackends, uh.GenericHandler): name = 'd1' setting_kwds = () @@ -412,7 +409,7 @@ class SkeletonTest(TestCase): self.assertRaises(ValueError, d1.has_backend, 'c') def test_50_norm_ident(self): - "test GenericHandler + HasManyIdents" + """test GenericHandler + HasManyIdents""" # setup helpers class d1(uh.HasManyIdents, uh.GenericHandler): name = 'd1' @@ -458,7 +455,7 @@ class SkeletonTest(TestCase): # but way work correctly for some hashes #=================================================================== def test_91_parsehash(self): - "test parsehash()" + """test parsehash()""" # NOTE: this just tests some existing GenericHandler classes from passlib import hash @@ -514,7 +511,7 @@ class SkeletonTest(TestCase): )) def test_92_bitsize(self): - "test bitsize()" + """test bitsize()""" # NOTE: this just tests some existing GenericHandler classes from passlib import hash @@ -546,7 +543,7 @@ class SkeletonTest(TestCase): # PrefixWrapper #============================================================================= class dummy_handler_in_registry(object): - "context manager that inserts dummy handler in registry" + """context manager that inserts dummy handler in registry""" def __init__(self, name): self.name = name self.dummy = type('dummy_' + name, (uh.GenericHandler,), dict( @@ -566,10 +563,10 @@ class dummy_handler_in_registry(object): registry._unload_handler_name(self.name, locations=False) class PrefixWrapperTest(TestCase): - "test PrefixWrapper class" + """test PrefixWrapper class""" def test_00_lazy_loading(self): - "test PrefixWrapper lazy loading of handler" + """test PrefixWrapper lazy loading of handler""" d1 = uh.PrefixWrapper("d1", "ldap_md5", "{XXX}", "{MD5}", lazy=True) # check base state @@ -585,7 +582,7 @@ class PrefixWrapperTest(TestCase): self.assertIs(d1.wrapped, ldap_md5) def test_01_active_loading(self): - "test PrefixWrapper active loading of handler" + """test PrefixWrapper active loading of handler""" d1 = uh.PrefixWrapper("d1", "ldap_md5", "{XXX}", "{MD5}") # check base state @@ -598,7 +595,7 @@ class PrefixWrapperTest(TestCase): self.assertIs(d1.wrapped, ldap_md5) def test_02_explicit(self): - "test PrefixWrapper with explicitly specified handler" + """test PrefixWrapper with explicitly specified handler""" d1 = uh.PrefixWrapper("d1", ldap_md5, "{XXX}", "{MD5}") @@ -696,7 +693,7 @@ class PrefixWrapperTest(TestCase): self.assertEqual(h.ident, None) def test_13_repr(self): - "test repr()" + """test repr()""" h = uh.PrefixWrapper("h2", "md5_crypt", "{XXX}", orig_prefix="$1$") self.assertRegex(repr(h), r"""(?x)^PrefixWrapper\( @@ -707,7 +704,7 @@ class PrefixWrapperTest(TestCase): \)$""") def test_14_bad_hash(self): - "test orig_prefix sanity check" + """test orig_prefix sanity check""" # shoudl throw InvalidHashError if wrapped hash doesn't begin # with orig_prefix. h = uh.PrefixWrapper("h2", "md5_crypt", orig_prefix="$6$") @@ -719,7 +716,7 @@ class PrefixWrapperTest(TestCase): # parts of passlib. they shouldn't be used as actual password schemes. #============================================================================= class UnsaltedHash(uh.StaticHandler): - "test algorithm which lacks a salt" + """test algorithm which lacks a salt""" name = "unsalted_test_hash" checksum_chars = uh.LOWER_HEX_CHARS checksum_size = 40 @@ -731,7 +728,7 @@ class UnsaltedHash(uh.StaticHandler): return str_to_uascii(hashlib.sha1(data).hexdigest()) class SaltedHash(uh.HasSalt, uh.GenericHandler): - "test algorithm with a salt" + """test algorithm with a salt""" name = "salted_test_hash" setting_kwds = ("salt",) diff --git a/passlib/tests/test_win32.py b/passlib/tests/test_win32.py index 9b01752..6bcdaf5 100644 --- a/passlib/tests/test_win32.py +++ b/passlib/tests/test_win32.py @@ -15,7 +15,7 @@ from passlib.utils.compat import u # #============================================================================= class UtilTest(TestCase): - "test util funcs in passlib.win32" + """test util funcs in passlib.win32""" ##test hashes from http://msdn.microsoft.com/en-us/library/cc245828(v=prot.10).aspx ## among other places diff --git a/passlib/tests/tox_support.py b/passlib/tests/tox_support.py index b5c80b7..92612f5 100644 --- a/passlib/tests/tox_support.py +++ b/passlib/tests/tox_support.py @@ -25,7 +25,7 @@ __all__ = [ TH_PATH = "passlib.tests.test_handlers" def do_hash_tests(*args): - "return list of hash algorithm tests that match regexes" + """return list of hash algorithm tests that match regexes""" if not args: print(TH_PATH) return @@ -44,7 +44,7 @@ def do_hash_tests(*args): return not names def do_preset_tests(name): - "return list of preset test names" + """return list of preset test names""" if name == "django" or name == "django-hashes": do_hash_tests("django_.*_test", "hex_md5_test") if name == "django": @@ -53,7 +53,7 @@ def do_preset_tests(name): raise ValueError("unknown name: %r" % name) def do_setup_gae(path, runtime): - "write fake GAE ``app.yaml`` to current directory so nosegae will work" + """write fake GAE ``app.yaml`` to current directory so nosegae will work""" from passlib.tests.utils import set_file set_file(os.path.join(path, "app.yaml"), """\ application: fake-app diff --git a/passlib/tests/utils.py b/passlib/tests/utils.py index 2a3fba0..b2211d0 100644 --- a/passlib/tests/utils.py +++ b/passlib/tests/utils.py @@ -50,7 +50,7 @@ else: GAE = True def ensure_mtime_changed(path): - "ensure file's mtime has changed" + """ensure file's mtime has changed""" # NOTE: this is hack to deal w/ filesystems whose mtime resolution is >= 1s, # when a test needs to be sure the mtime changed after writing to the file. last = os.path.getmtime(path) @@ -103,14 +103,14 @@ def TEST_MODE(min=None, max=None): # hash object inspection #============================================================================= def has_crypt_support(handler): - "check if host's crypt() supports this natively" + """check if host's crypt() supports this natively""" if hasattr(handler, "orig_prefix"): # ignore wrapper classes return False return 'os_crypt' in getattr(handler, "backends", ()) and handler.has_backend("os_crypt") def has_relaxed_setting(handler): - "check if handler supports 'relaxed' kwd" + """check if handler supports 'relaxed' kwd""" # FIXME: I've been lazy, should probably just add 'relaxed' kwd # to all handlers that derive from GenericHandler @@ -122,7 +122,7 @@ def has_relaxed_setting(handler): uh.GenericHandler) def has_active_backend(handler): - "return active backend for handler, if any" + """return active backend for handler, if any""" if not hasattr(handler, "get_backend"): return "builtin" try: @@ -131,7 +131,7 @@ def has_active_backend(handler): return None def is_default_backend(handler, backend): - "check if backend is the default for source" + """check if backend is the default for source""" try: orig = handler.get_backend() except MissingBackendError: @@ -142,7 +142,7 @@ def is_default_backend(handler, backend): handler.set_backend(orig) class temporary_backend(object): - "temporarily set handler to specific backend" + """temporarily set handler to specific backend""" def __init__(self, handler, backend=None): self.handler = handler self.backend = backend @@ -160,19 +160,19 @@ class temporary_backend(object): # misc helpers #============================================================================= def set_file(path, content): - "set file to specified bytes" + """set file to specified bytes""" if isinstance(content, unicode): content = content.encode("utf-8") with open(path, "wb") as fh: fh.write(content) def get_file(path): - "read file as bytes" + """read file as bytes""" with open(path, "rb") as fh: return fh.read() def tonn(source): - "convert native string to non-native string" + """convert native string to non-native string""" if not isinstance(source, str): return source elif PY3: @@ -191,11 +191,11 @@ def limit(value, lower, upper): return value def randintgauss(lower, upper, mu, sigma): - "hack used by fuzz testing" + """hack used by fuzz testing""" return int(limit(rng.normalvariate(mu, sigma), lower, upper)) def quicksleep(delay): - "because time.sleep() doesn't even have 10ms accuracy on some OSes" + """because time.sleep() doesn't even have 10ms accuracy on some OSes""" start = tick() while tick()-start < delay: pass @@ -225,7 +225,7 @@ class TestCase(_TestCase): descriptionPrefix = None def shortDescription(self): - "wrap shortDescription() method to prepend descriptionPrefix" + """wrap shortDescription() method to prepend descriptionPrefix""" desc = super(TestCase, self).shortDescription() prefix = self.descriptionPrefix if prefix: @@ -263,7 +263,7 @@ class TestCase(_TestCase): self.setUpWarnings() def setUpWarnings(self): - "helper to init warning filters before subclass setUp()" + """helper to init warning filters before subclass setUp()""" if self.resetWarningState: ctx = reset_warnings() ctx.__enter__() @@ -426,7 +426,7 @@ class TestCase(_TestCase): # capability tests #=================================================================== def require_stringprep(self): - "helper to skip test if stringprep is missing" + """helper to skip test if stringprep is missing""" from passlib.utils import stringprep if not stringprep: from passlib.utils import _stringprep_missing_reason @@ -434,12 +434,12 @@ class TestCase(_TestCase): _stringprep_missing_reason) def require_TEST_MODE(self, level): - "skip test for all PASSLIB_TEST_MODE values below <level>" + """skip test for all PASSLIB_TEST_MODE values below <level>""" if not TEST_MODE(level): raise self.skipTest("requires >= %r test mode" % level) def require_writeable_filesystem(self): - "skip test if writeable FS not available" + """skip test if writeable FS not available""" if GAE: return self.skipTest("GAE doesn't offer read/write filesystem access") @@ -449,7 +449,7 @@ class TestCase(_TestCase): _mktemp_queue = None def mktemp(self, *args, **kwds): - "create temp file that's cleaned up at end of test" + """create temp file that's cleaned up at end of test""" self.require_writeable_filesystem() fd, path = tempfile.mkstemp(*args, **kwds) os.close(fd) @@ -609,7 +609,7 @@ class HandlerCase(TestCase): @classmethod def iter_known_hashes(cls): - "iterate through known (secret, hash) pairs" + """iterate through known (secret, hash) pairs""" for secret, hash in cls.known_correct_hashes: yield secret, hash for config, secret, hash in cls.known_correct_configs: @@ -618,7 +618,7 @@ class HandlerCase(TestCase): yield secret, hash def get_sample_hash(self): - "test random sample secret/hash pair" + """test random sample secret/hash pair""" known = list(self.iter_known_hashes()) return rng.choice(known) @@ -626,7 +626,7 @@ class HandlerCase(TestCase): # test helpers #--------------------------------------------------------------- def check_verify(self, secret, hash, msg=None, negate=False): - "helper to check verify() outcome, honoring is_disabled_handler" + """helper to check verify() outcome, honoring is_disabled_handler""" result = self.do_verify(secret, hash) self.assertTrue(result is True or result is False, "verify() returned non-boolean value: %r" % (result,)) @@ -653,7 +653,7 @@ class HandlerCase(TestCase): # so that subclasses can fill in defaults and account for other specialized behavior #--------------------------------------------------------------- def populate_settings(self, kwds): - "subclassable method to populate default settings" + """subclassable method to populate default settings""" # use lower rounds settings for certain test modes handler = self.handler if 'rounds' in handler.setting_kwds and 'rounds' not in kwds: @@ -668,35 +668,35 @@ class HandlerCase(TestCase): if getattr(handler, "rounds_cost", None) == "log2": df -= factor else: - df = df//(1<<factor) + df //= (1<<factor) kwds['rounds'] = max(3, mn, df) def populate_context(self, secret, kwds): - "subclassable method allowing 'secret' to be encode context kwds" + """subclassable method allowing 'secret' to be encode context kwds""" return secret def do_encrypt(self, secret, **kwds): - "call handler's encrypt method with specified options" + """call handler's encrypt method with specified options""" secret = self.populate_context(secret, kwds) self.populate_settings(kwds) return self.handler.encrypt(secret, **kwds) def do_verify(self, secret, hash, **kwds): - "call handler's verify method" + """call handler's verify method""" secret = self.populate_context(secret, kwds) return self.handler.verify(secret, hash, **kwds) def do_identify(self, hash): - "call handler's identify method" + """call handler's identify method""" return self.handler.identify(hash) def do_genconfig(self, **kwds): - "call handler's genconfig method with specified options" + """call handler's genconfig method with specified options""" self.populate_settings(kwds) return self.handler.genconfig(**kwds) def do_genhash(self, secret, config, **kwds): - "call handler's genhash method with specified options" + """call handler's genhash method with specified options""" secret = self.populate_context(secret, kwds) return self.handler.genhash(secret, config, **kwds) @@ -706,7 +706,7 @@ class HandlerCase(TestCase): #--------------------------------------------------------------- @classmethod def _enable_backend_case(cls, backend): - "helper for create_backend_cases(); returns reason to skip backend, or None" + """helper for create_backend_cases(); returns reason to skip backend, or None""" handler = cls.handler if not is_default_backend(handler, backend) and not TEST_MODE("full"): return "only default backend is being tested" @@ -751,7 +751,7 @@ class HandlerCase(TestCase): @classmethod def find_crypt_replacement(cls): - "find other backend which can be used to mock the os_crypt backend" + """find other backend which can be used to mock the os_crypt backend""" handler = cls.handler for name in handler.backends: if name != "os_crypt" and handler.has_backend(name): @@ -777,7 +777,7 @@ class HandlerCase(TestCase): # basic tests #=================================================================== def test_01_required_attributes(self): - "validate required attributes" + """validate required attributes""" handler = self.handler def ga(name): return getattr(handler, name, None) @@ -903,7 +903,7 @@ class HandlerCase(TestCase): self.assertTrue(self.do_identify(result)) def test_04_hash_types(self): - "test hashes can be unicode or bytes" + """test hashes can be unicode or bytes""" # this runs through workflow similar to 03, but wraps # everything using tonn() so we test unicode under py2, # and bytes under py3. @@ -932,7 +932,7 @@ class HandlerCase(TestCase): self.assertTrue(self.do_identify(tonn(result))) def test_05_backends(self): - "test multi-backend support" + """test multi-backend support""" handler = self.handler if not hasattr(handler, "set_backend"): raise self.skipTest("handler only has one backend") @@ -979,9 +979,8 @@ class HandlerCase(TestCase): raise self.skipTest("handler doesn't provide salt info") def test_10_optional_salt_attributes(self): - "validate optional salt attributes" + """validate optional salt attributes""" self.require_salt_info() - AssertionError = self.failureException cls = self.handler @@ -1023,7 +1022,7 @@ class HandlerCase(TestCase): @property def salt_bits(self): - "calculate number of salt bits in hash" + """calculate number of salt bits in hash""" # XXX: replace this with bitsize() method? handler = self.handler assert has_salt_info(handler), "need explicit bit-size for " + handler.name @@ -1034,7 +1033,7 @@ class HandlerCase(TestCase): log(len(handler.default_salt_chars), 2)) def test_11_unique_salt(self): - "test encrypt() / genconfig() creates new salt each time" + """test encrypt() / genconfig() creates new salt each time""" self.require_salt() # odds of picking 'n' identical salts at random is '(.5**salt_bits)**n'. # we want to pick the smallest N needed s.t. odds are <1/1000, just @@ -1055,7 +1054,7 @@ class HandlerCase(TestCase): sampler(lambda : self.do_encrypt("stub")) def test_12_min_salt_size(self): - "test encrypt() / genconfig() honors min_salt_size" + """test encrypt() / genconfig() honors min_salt_size""" self.require_salt_info() handler = self.handler @@ -1081,7 +1080,7 @@ class HandlerCase(TestCase): salt_size=min_size-1) def test_13_max_salt_size(self): - "test encrypt() / genconfig() honors max_salt_size" + """test encrypt() / genconfig() honors max_salt_size""" self.require_salt_info() handler = self.handler @@ -1134,14 +1133,14 @@ class HandlerCase(TestCase): self.assertNotEqual(c3, c1) def prepare_salt(self, salt): - "prepare generated salt" + """prepare generated salt""" if self.handler.name in ["bcrypt", "django_bcrypt"]: from passlib.utils import bcrypt64 salt = bcrypt64.repair_unused(salt) return salt def test_14_salt_chars(self): - "test genconfig() honors salt_chars" + """test genconfig() honors salt_chars""" self.require_salt_info() handler = self.handler @@ -1171,7 +1170,7 @@ class HandlerCase(TestCase): @property def salt_type(self): - "hack to determine salt keyword's datatype" + """hack to determine salt keyword's datatype""" # NOTE: cisco_type7 uses 'int' if getattr(self.handler, "_salt_is_bytes", False): return bytes @@ -1179,7 +1178,7 @@ class HandlerCase(TestCase): return unicode def test_15_salt_type(self): - "test non-string salt values" + """test non-string salt values""" self.require_salt() salt_type = self.salt_type @@ -1205,7 +1204,7 @@ class HandlerCase(TestCase): raise self.skipTest("handler lacks rounds attributes") def test_20_optional_rounds_attributes(self): - "validate optional rounds attributes" + """validate optional rounds attributes""" self.require_rounds_info() cls = self.handler @@ -1235,7 +1234,7 @@ class HandlerCase(TestCase): raise AssertionError("unknown rounds cost constant: %r" % (cls.rounds_cost,)) def test_21_rounds_limits(self): - "test encrypt() / genconfig() honors rounds limits" + """test encrypt() / genconfig() honors rounds limits""" self.require_rounds_info() handler = self.handler min_rounds = handler.min_rounds @@ -1272,7 +1271,7 @@ class HandlerCase(TestCase): # idents #=================================================================== def test_30_HasManyIdents(self): - "validate HasManyIdents configuration" + """validate HasManyIdents configuration""" cls = self.handler if not isinstance(cls, type) or not issubclass(cls, uh.HasManyIdents): raise self.skipTest("handler doesn't derive from HasManyIdents") @@ -1327,7 +1326,7 @@ class HandlerCase(TestCase): # passwords #=================================================================== def test_60_secret_size(self): - "test password size limits" + """test password size limits""" sc = self.secret_size base = "too many secrets" # 16 chars alt = 'x' # char that's not in base string @@ -1365,7 +1364,7 @@ class HandlerCase(TestCase): "full password not used in digest") def test_61_secret_case_sensitive(self): - "test password case sensitivity" + """test password case sensitivity""" hash_insensitive = self.secret_case_insensitive is True verify_insensitive = self.secret_case_insensitive in [True, "verify-only"] @@ -1389,7 +1388,7 @@ class HandlerCase(TestCase): "genhash() should be case sensitive") def test_62_secret_border(self): - "test non-string passwords are rejected" + """test non-string passwords are rejected""" hash = self.get_sample_hash()[1] # secret=None @@ -1403,7 +1402,7 @@ class HandlerCase(TestCase): self.assertRaises(TypeError, self.do_verify, 1, hash) def test_63_large_secret(self): - "test MAX_PASSWORD_SIZE is enforced" + """test MAX_PASSWORD_SIZE is enforced""" from passlib.exc import PasswordSizeError from passlib.utils import MAX_PASSWORD_SIZE secret = '.' * (1+MAX_PASSWORD_SIZE) @@ -1413,7 +1412,7 @@ class HandlerCase(TestCase): self.assertRaises(PasswordSizeError, self.do_verify, secret, hash) def test_64_forbidden_chars(self): - "test forbidden characters not allowed in password" + """test forbidden characters not allowed in password""" chars = self.forbidden_characters if not chars: raise self.skipTest("none listed") @@ -1433,7 +1432,7 @@ class HandlerCase(TestCase): return not is_ascii_safe(secret) def test_70_hashes(self): - "test known hashes" + """test known hashes""" # sanity check self.assertTrue(self.known_correct_hashes or self.known_correct_configs, "test must set at least one of 'known_correct_hashes' " @@ -1466,10 +1465,9 @@ class HandlerCase(TestCase): warn("%s: no 8-bit secrets tested" % self.__class__) def test_71_alternates(self): - "test known alternate hashes" + """test known alternate hashes""" if not self.known_alternate_hashes: raise self.skipTest("no alternate hashes provided") - for alt, secret, hash in self.known_alternate_hashes: # hash should be positively identified by handler @@ -1490,7 +1488,7 @@ class HandlerCase(TestCase): "result=%r" % (secret, alt, hash, result)) def test_72_configs(self): - "test known config strings" + """test known config strings""" # special-case handlers without settings if not self.handler.setting_kwds: self.assertFalse(self.known_correct_configs, @@ -1525,7 +1523,7 @@ class HandlerCase(TestCase): "result=%r" % (secret, config, hash, result)) def test_73_unidentified(self): - "test known unidentifiably-mangled strings" + """test known unidentifiably-mangled strings""" if not self.known_unidentified_hashes: raise self.skipTest("no unidentified hashes provided") for hash in self.known_unidentified_hashes: @@ -1546,7 +1544,7 @@ class HandlerCase(TestCase): "hash: %r" % (hash,)) def test_74_malformed(self): - "test known identifiable-but-malformed strings" + """test known identifiable-but-malformed strings""" if not self.known_malformed_hashes: raise self.skipTest("no malformed hashes provided") for hash in self.known_malformed_hashes: @@ -1567,7 +1565,7 @@ class HandlerCase(TestCase): "hash: %r" % (hash,)) def test_75_foreign(self): - "test known foreign hashes" + """test known foreign hashes""" if self.accepts_all_hashes: raise self.skipTest("not applicable") if not self.known_other_hashes: @@ -1605,7 +1603,7 @@ class HandlerCase(TestCase): "belonging to %s: %r" % (name, hash)) def test_76_hash_border(self): - "test non-string hashes are rejected" + """test non-string hashes are rejected""" # # test hash=None is rejected (except if config=None) # @@ -1733,7 +1731,7 @@ class HandlerCase(TestCase): @property def max_fuzz_time(self): - "amount of time to spend on fuzz testing" + """amount of time to spend on fuzz testing""" value = float(os.environ.get("PASSLIB_TEST_FUZZ_TIME") or 0) if value: return value @@ -1745,7 +1743,7 @@ class HandlerCase(TestCase): return 5 def os_supports_ident(self, ident): - "whether native OS crypt() supports particular ident value" + """whether native OS crypt() supports particular ident value""" return True #--------------------------------------------------------------- @@ -1797,13 +1795,13 @@ class HandlerCase(TestCase): return check_default def fuzz_verifier_crypt(self): - "test results against OS crypt()" + """test results against OS crypt()""" handler = self.handler if self.using_patched_crypt or not has_crypt_support(handler): return None from crypt import crypt def check_crypt(secret, hash): - "stdlib-crypt" + """stdlib-crypt""" if not self.os_supports_ident(hash): return "skip" secret = to_native_str(secret, self.fuzz_password_encoding) @@ -1814,7 +1812,7 @@ class HandlerCase(TestCase): # fuzz settings generation #--------------------------------------------------------------- def get_fuzz_settings(self): - "generate random password and options for fuzz testing" + """generate random password and options for fuzz testing""" prefix = "fuzz_setting_" kwds = {} for name in dir(self): @@ -1863,7 +1861,7 @@ class HandlerCase(TestCase): # fuzz password generation #--------------------------------------------------------------- def get_fuzz_password(self): - "generate random passwords for fuzz testing" + """generate random passwords for fuzz testing""" # occasionally try an empty password if rng.random() < .0001: return u('') @@ -1875,11 +1873,11 @@ class HandlerCase(TestCase): return getrandstr(rng, self.fuzz_password_alphabet, size) def accept_fuzz_pair(self, secret, other): - "verify fuzz pair contains different passwords" + """verify fuzz pair contains different passwords""" return secret != other def get_fuzz_password_pair(self): - "generate random password, and non-matching alternate password" + """generate random password, and non-matching alternate password""" secret = self.get_fuzz_password() while True: other = self.get_fuzz_password() @@ -1965,7 +1963,7 @@ class OsCryptMixin(HandlerCase): # custom tests #=================================================================== def _use_mock_crypt(self): - "patch safe_crypt() so it returns mock value" + """patch safe_crypt() so it returns mock value""" import passlib.utils as mod if not self.using_patched_crypt: self.addCleanup(setattr, mod, "_crypt", mod._crypt) @@ -1976,7 +1974,7 @@ class OsCryptMixin(HandlerCase): return setter def test_80_faulty_crypt(self): - "test with faulty crypt()" + """test with faulty crypt()""" hash = self.get_sample_hash()[1] exc_types = (AssertionError,) setter = self._use_mock_crypt() @@ -1994,7 +1992,7 @@ class OsCryptMixin(HandlerCase): test(hash + 'x') # detect too long def test_81_crypt_fallback(self): - "test per-call crypt() fallback" + """test per-call crypt() fallback""" # set safe_crypt to return None setter = self._use_mock_crypt() setter(None) @@ -2013,7 +2011,7 @@ class OsCryptMixin(HandlerCase): self.assertRaises(MissingBackendError, self.do_verify, 'stub', hash) def test_82_crypt_support(self): - "test platform-specific crypt() support detection" + """test platform-specific crypt() support detection""" # NOTE: this is mainly just a sanity check to ensure the runtime # detection is functioning correctly on some known platforms, # so that I can feel more confident it'll work right on unknown ones. @@ -2065,7 +2063,7 @@ class UserHandlerMixin(HandlerCase): # custom tests #=================================================================== def test_80_user(self): - "test user context keyword" + """test user context keyword""" handler = self.handler password = 'stub' hash = handler.encrypt(password, user=self.default_user) @@ -2081,7 +2079,7 @@ class UserHandlerMixin(HandlerCase): handler.verify(password, hash) def test_81_user_case(self): - "test user case sensitivity" + """test user case sensitivity""" lower = self.default_user.lower() upper = lower.upper() hash = self.do_encrypt('stub', user=lower) @@ -2093,7 +2091,7 @@ class UserHandlerMixin(HandlerCase): "user should be case sensitive") def test_82_user_salt(self): - "test user used as salt" + """test user used as salt""" config = self.do_genconfig() h1 = self.do_genhash('stub', config, user='admin') h2 = self.do_genhash('stub', config, user='admin') @@ -2107,7 +2105,7 @@ class UserHandlerMixin(HandlerCase): # override test helpers #=================================================================== def populate_context(self, secret, kwds): - "insert username into kwds" + """insert username into kwds""" if isinstance(secret, tuple): secret, user = secret elif not self.requires_user: @@ -2156,7 +2154,7 @@ class EncodingHandlerMixin(HandlerCase): fuzz_password_alphabet = u('qwerty1234<>.@*#! \u00AC') def populate_context(self, secret, kwds): - "insert encoding into kwds" + """insert encoding into kwds""" if isinstance(secret, tuple): secret, encoding = secret kwds.setdefault('encoding', encoding) diff --git a/passlib/utils/__init__.py b/passlib/utils/__init__.py index ef1a962..b4c3f90 100644 --- a/passlib/utils/__init__.py +++ b/passlib/utils/__init__.py @@ -130,7 +130,7 @@ class classproperty(object): @property def __func__(self): - "py3 compatible alias" + """py3 compatible alias""" return self.im_func def deprecated_function(msg=None, deprecated=None, removed=None, updoc=True, @@ -221,7 +221,7 @@ class memoized_property(object): @property def __func__(self): - "py3 alias" + """py3 alias""" return self.im_func # works but not used @@ -456,7 +456,7 @@ def saslprep(source, param="value"): # replace saslprep() with stub when stringprep is missing if stringprep is None: # pragma: no cover -- runtime detection def saslprep(source, param="value"): - "stub for saslprep()" + """stub for saslprep()""" raise NotImplementedError("saslprep() support requires the 'stringprep' " "module, which is " + _stringprep_missing_reason) @@ -503,11 +503,11 @@ add_doc(bytes_to_int, "decode byte string as single big-endian integer") add_doc(int_to_bytes, "encode integer as single big-endian byte string") def xor_bytes(left, right): - "Perform bitwise-xor of two byte strings (must be same size)" + """Perform bitwise-xor of two byte strings (must be same size)""" return int_to_bytes(bytes_to_int(left) ^ bytes_to_int(right), len(left)) def repeat_string(source, size): - "repeat or truncate <source> string, so it has length <size>" + """repeat or truncate <source> string, so it has length <size>""" cur = len(source) if size > cur: mult = (size+cur-1)//cur @@ -519,7 +519,7 @@ _BNULL = b("\x00") _UNULL = u("\x00") def right_pad_string(source, size, pad=None): - "right-pad or truncate <source> string, so it has length <size>" + """right-pad or truncate <source> string, so it has length <size>""" cur = len(source) if size > cur: if pad is None: @@ -535,11 +535,11 @@ _ASCII_TEST_BYTES = b("\x00\n aA:#!\x7f") _ASCII_TEST_UNICODE = _ASCII_TEST_BYTES.decode("ascii") def is_ascii_codec(codec): - "Test if codec is compatible with 7-bit ascii (e.g. latin-1, utf-8; but not utf-16)" + """Test if codec is compatible with 7-bit ascii (e.g. latin-1, utf-8; but not utf-16)""" return _ASCII_TEST_UNICODE.encode(codec) == _ASCII_TEST_BYTES def is_same_codec(left, right): - "Check if two codec names are aliases for same codec" + """Check if two codec names are aliases for same codec""" if left == right: return True if not (left and right): @@ -549,7 +549,7 @@ def is_same_codec(left, right): _B80 = b('\x80')[0] _U80 = u('\x80') def is_ascii_safe(source): - "Check if string (bytes or unicode) contains only 7-bit ascii" + """Check if string (bytes or unicode) contains only 7-bit ascii""" r = _B80 if isinstance(source, bytes) else _U80 return all(c < r for c in source) @@ -656,7 +656,7 @@ add_doc(to_native_str, @deprecated_function(deprecated="1.6", removed="1.7") def to_hash_str(source, encoding="ascii"): # pragma: no cover -- deprecated & unused - "deprecated, use to_native_str() instead" + """deprecated, use to_native_str() instead""" return to_native_str(source, encoding, param="hash") #============================================================================= @@ -783,7 +783,7 @@ class Base64Engine(object): @property def charmap(self): - "charmap as unicode" + """charmap as unicode""" return self.bytemap.decode("latin-1") #=================================================================== @@ -811,7 +811,7 @@ class Base64Engine(object): return out def _encode_bytes_little(self, next_value, chunks, tail): - "helper used by encode_bytes() to handle little-endian encoding" + """helper used by encode_bytes() to handle little-endian encoding""" # # output bit layout: # @@ -850,7 +850,7 @@ class Base64Engine(object): yield v2>>4 def _encode_bytes_big(self, next_value, chunks, tail): - "helper used by encode_bytes() to handle big-endian encoding" + """helper used by encode_bytes() to handle big-endian encoding""" # # output bit layout: # @@ -916,7 +916,7 @@ class Base64Engine(object): raise ValueError("invalid character: %r" % (err.args[0],)) def _decode_bytes_little(self, next_value, chunks, tail): - "helper used by decode_bytes() to handle little-endian encoding" + """helper used by decode_bytes() to handle little-endian encoding""" # # input bit layout: # @@ -951,7 +951,7 @@ class Base64Engine(object): yield (v2>>2) | ((v3 & 0xF) << 4) def _decode_bytes_big(self, next_value, chunks, tail): - "helper used by decode_bytes() to handle big-endian encoding" + """helper used by decode_bytes() to handle big-endian encoding""" # # input bit layout: # @@ -993,21 +993,21 @@ class Base64Engine(object): # equivalent char with no padding bits set. def __make_padset(self, bits): - "helper to generate set of valid last chars & bytes" + """helper to generate set of valid last chars & bytes""" pset = set(c for i,c in enumerate(self.bytemap) if not i & bits) pset.update(c for i,c in enumerate(self.charmap) if not i & bits) return frozenset(pset) @memoized_property def _padinfo2(self): - "mask to clear padding bits, and valid last bytes (for strings 2 % 4)" + """mask to clear padding bits, and valid last bytes (for strings 2 % 4)""" # 4 bits of last char unused (lsb for big, msb for little) bits = 15 if self.big else (15<<2) return ~bits, self.__make_padset(bits) @memoized_property def _padinfo3(self): - "mask to clear padding bits, and valid last bytes (for strings 3 % 4)" + """mask to clear padding bits, and valid last bytes (for strings 3 % 4)""" # 2 bits of last char unused (lsb for big, msb for little) bits = 3 if self.big else (3<<4) return ~bits, self.__make_padset(bits) @@ -1072,14 +1072,14 @@ class Base64Engine(object): # transposed encoding/decoding #=================================================================== def encode_transposed_bytes(self, source, offsets): - "encode byte string, first transposing source using offset list" + """encode byte string, first transposing source using offset list""" if not isinstance(source, bytes): raise TypeError("source must be bytes, not %s" % (type(source),)) tmp = join_byte_elems(source[off] for off in offsets) return self.encode_bytes(tmp) def decode_transposed_bytes(self, source, offsets): - "decode byte string, then reverse transposition described by offset list" + """decode byte string, then reverse transposition described by offset list""" # NOTE: if transposition does not use all bytes of source, # the original can't be recovered... and join_byte_elems() will throw # an error because 1+ values in <buf> will be None. @@ -1133,7 +1133,7 @@ class Base64Engine(object): #--------------------------------------------------------------- def decode_int6(self, source): - "decode single character -> 6 bit integer" + """decode single character -> 6 bit integer""" if not isinstance(source, bytes): raise TypeError("source must be bytes, not %s" % (type(source),)) if len(source) != 1: @@ -1147,7 +1147,7 @@ class Base64Engine(object): raise ValueError("invalid character") def decode_int12(self, source): - "decodes 2 char string -> 12-bit integer" + """decodes 2 char string -> 12-bit integer""" if not isinstance(source, bytes): raise TypeError("source must be bytes, not %s" % (type(source),)) if len(source) != 2: @@ -1162,7 +1162,7 @@ class Base64Engine(object): raise ValueError("invalid character") def decode_int24(self, source): - "decodes 4 char string -> 24-bit integer" + """decodes 4 char string -> 24-bit integer""" if not isinstance(source, bytes): raise TypeError("source must be bytes, not %s" % (type(source),)) if len(source) != 4: @@ -1216,7 +1216,7 @@ class Base64Engine(object): #--------------------------------------------------------------- def encode_int6(self, value): - "encodes 6-bit integer -> single hash64 character" + """encodes 6-bit integer -> single hash64 character""" if value < 0 or value > 63: raise ValueError("value out of range") if PY3: @@ -1225,7 +1225,7 @@ class Base64Engine(object): return self._encode64(value) def encode_int12(self, value): - "encodes 12-bit integer -> 2 char string" + """encodes 12-bit integer -> 2 char string""" if value < 0 or value > 0xFFF: raise ValueError("value out of range") raw = [value & 0x3f, (value>>6) & 0x3f] @@ -1234,7 +1234,7 @@ class Base64Engine(object): return join_byte_elems(imap(self._encode64, raw)) def encode_int24(self, value): - "encodes 24-bit integer -> 4 char string" + """encodes 24-bit integer -> 4 char string""" if value < 0 or value > 0xFFFFFF: raise ValueError("value out of range") raw = [value & 0x3f, (value>>6) & 0x3f, @@ -1258,7 +1258,7 @@ class Base64Engine(object): #=================================================================== class LazyBase64Engine(Base64Engine): - "Base64Engine which delays initialization until it's accessed" + """Base64Engine which delays initialization until it's accessed""" _lazy_opts = None def __init__(self, *args, **kwds): @@ -1331,6 +1331,7 @@ def ab64_decode(data): try: from crypt import crypt as _crypt except ImportError: # pragma: no cover + _crypt = None has_crypt = False def safe_crypt(secret, hash): return None @@ -1451,7 +1452,7 @@ except NotImplementedError: # pragma: no cover has_urandom = False def genseed(value=None): - "generate prng seed value from system resources" + """generate prng seed value from system resources""" from hashlib import sha512 text = u("%s %s %s %s %.15f %.15f %s") % ( # if caller specified a seed value, mix it in @@ -1572,7 +1573,7 @@ _handler_attrs = ( ) def is_crypt_handler(obj): - "check if object follows the :ref:`password-hash-api`" + """check if object follows the :ref:`password-hash-api`""" # XXX: change to use isinstance(obj, PasswordHash) under py26+? return all(hasattr(obj, name) for name in _handler_attrs) @@ -1583,7 +1584,7 @@ _context_attrs = ( ) def is_crypt_context(obj): - "check if object appears to be a :class:`~passlib.context.CryptContext` instance" + """check if object appears to be a :class:`~passlib.context.CryptContext` instance""" # XXX: change to use isinstance(obj, CryptContext)? return all(hasattr(obj, name) for name in _context_attrs) @@ -1593,12 +1594,12 @@ def is_crypt_context(obj): ## return hasattr(handler, "set_backend") def has_rounds_info(handler): - "check if handler provides the optional :ref:`rounds information <rounds-attributes>` attributes" + """check if handler provides the optional :ref:`rounds information <rounds-attributes>` attributes""" return ('rounds' in handler.setting_kwds and getattr(handler, "min_rounds", None) is not None) def has_salt_info(handler): - "check if handler provides the optional :ref:`salt information <salt-attributes>` attributes" + """check if handler provides the optional :ref:`salt information <salt-attributes>` attributes""" return ('salt' in handler.setting_kwds and getattr(handler, "min_salt_size", None) is not None) diff --git a/passlib/utils/_blowfish/_gen_files.py b/passlib/utils/_blowfish/_gen_files.py index a5757f2..a8fca48 100644 --- a/passlib/utils/_blowfish/_gen_files.py +++ b/passlib/utils/_blowfish/_gen_files.py @@ -17,7 +17,7 @@ def varlist(name, count): def indent_block(block, padding): - "ident block of text" + """ident block of text""" lines = block.split("\n") return "\n".join( padding + line if line else "" diff --git a/passlib/utils/_blowfish/base.py b/passlib/utils/_blowfish/base.py index 65b6da0..b52a3ae 100644 --- a/passlib/utils/_blowfish/base.py +++ b/passlib/utils/_blowfish/base.py @@ -339,7 +339,7 @@ class BlowfishEngine(object): # blowfish routines #=================================================================== def encipher(self, l, r): - "loop version of blowfish encipher routine" + """loop version of blowfish encipher routine""" P, S = self.P, self.S l ^= P[0] i = 1 @@ -355,7 +355,7 @@ class BlowfishEngine(object): # NOTE: decipher is same as above, just with reversed(P) instead. def expand(self, key_words): - "perform stock Blowfish keyschedule setup" + """perform stock Blowfish keyschedule setup""" assert len(key_words) >= 18, "key_words must be at least as large as P" P, S, encipher = self.P, self.S, self.encipher @@ -379,7 +379,7 @@ class BlowfishEngine(object): # eks-blowfish routines #=================================================================== def eks_expand(self, key_words, salt_words): - "perform EKS version of Blowfish keyschedule setup" + """perform EKS version of Blowfish keyschedule setup""" # NOTE: this is the same as expand(), except for the addition # of the operations involving *salt_words*. @@ -416,7 +416,7 @@ class BlowfishEngine(object): i += 2 def eks_rounds_expand0(self, key_words, salt_words, rounds): - "perform rounds stage of EKS keyschedule setup" + """perform rounds stage of EKS keyschedule setup""" expand = self.expand n = 0 while n < rounds: @@ -425,7 +425,7 @@ class BlowfishEngine(object): n += 1 def repeat_encipher(self, l, r, count): - "repeatedly apply encipher operation to a block" + """repeatedly apply encipher operation to a block""" encipher = self.encipher n = 0 while n < count: diff --git a/passlib/utils/compat.py b/passlib/utils/compat.py index a7bb626..ecaaffe 100644 --- a/passlib/utils/compat.py +++ b/passlib/utils/compat.py @@ -253,7 +253,7 @@ else: if PY_MAX_25: _undef = object() def next(itr, default=_undef): - "compat wrapper for next()" + """compat wrapper for next()""" if default is _undef: return itr.next() try: @@ -282,7 +282,7 @@ else: # introspection #============================================================================= def exc_err(): - "return current error object (to avoid try/except syntax change)" + """return current error object (to avoid try/except syntax change)""" return sys.exc_info()[1] if PY3: @@ -291,7 +291,7 @@ else: method_function_attr = "im_func" def get_method_function(func): - "given (potential) method, return underlying function" + """given (potential) method, return underlying function""" return getattr(func, method_function_attr, func) #============================================================================= @@ -366,7 +366,7 @@ else: from types import ModuleType def _import_object(source): - "helper to import object from module; accept format `path.to.object`" + """helper to import object from module; accept format `path.to.object`""" modname, modattr = source.rsplit(".",1) mod = __import__(modname, fromlist=[modattr], level=0) return getattr(mod, modattr) diff --git a/passlib/utils/des.py b/passlib/utils/des.py index 65dfe8a..a2fc2bf 100644 --- a/passlib/utils/des.py +++ b/passlib/utils/des.py @@ -81,7 +81,7 @@ _KS_MASK = 0xfcfcfcfcffffffff PCXROT = IE3264 = SPE = CF6464 = None def _load_tables(): - "delay loading tables until they are actually needed" + """delay loading tables until they are actually needed""" global PCXROT, IE3264, SPE, CF6464 #--------------------------------------------------------------- @@ -612,7 +612,7 @@ def _unpack56(value): _EXPAND_ITER = irange(49,-7,-7) def expand_des_key(key): - "convert DES from 7 bytes to 8 bytes (by inserting empty parity bits)" + """convert DES from 7 bytes to 8 bytes (by inserting empty parity bits)""" if isinstance(key, bytes): if len(key) != 7: raise ValueError("key must be 7 bytes in size") @@ -631,7 +631,7 @@ def expand_des_key(key): return join_byte_values(((key>>shift) & 0x7f)<<1 for shift in _EXPAND_ITER) def shrink_des_key(key): - "convert DES key from 8 bytes to 7 bytes (by discarding the parity bits)" + """convert DES key from 8 bytes to 7 bytes (by discarding the parity bits)""" if isinstance(key, bytes): if len(key) != 8: raise ValueError("key must be 8 bytes in size") @@ -779,7 +779,7 @@ def des_encrypt_int_block(key, input, salt=0, rounds=1): # NOTE: generation was modified to output two elements at a time, # so that per-round loop could do two passes at once. def _iter_key_schedule(ks_odd): - "given 64-bit key, iterates over the 8 (even,odd) key schedule pairs" + """given 64-bit key, iterates over the 8 (even,odd) key schedule pairs""" for p_even, p_odd in PCXROT: ks_even = _permute(ks_odd, p_even) ks_odd = _permute(ks_even, p_odd) diff --git a/passlib/utils/handlers.py b/passlib/utils/handlers.py index 0a873ee..2aabdd5 100644 --- a/passlib/utils/handlers.py +++ b/passlib/utils/handlers.py @@ -88,14 +88,14 @@ _UDOLLAR = u("$") _UZERO = u("0") def validate_secret(secret): - "ensure secret has correct type & size" + """ensure secret has correct type & size""" if not isinstance(secret, base_string_types): raise exc.ExpectedStringError(secret, "secret") if len(secret) > MAX_PASSWORD_SIZE: raise exc.PasswordSizeError() def to_unicode_for_identify(hash): - "convert hash to unicode for identify method" + """convert hash to unicode for identify method""" if isinstance(hash, unicode): return hash elif isinstance(hash, bytes): @@ -584,7 +584,7 @@ class GenericHandler(PasswordHash): @staticmethod def _sanitize(value, char=u("*")): - "default method to obscure sensitive fields" + """default method to obscure sensitive fields""" if value is None: return None if isinstance(value, bytes): @@ -634,7 +634,7 @@ class GenericHandler(PasswordHash): @classmethod def bitsize(cls, **kwds): - "[experimental method] return info about bitsizes of hash" + """[experimental method] return info about bitsizes of hash""" try: info = super(GenericHandler, cls).bitsize(**kwds) except AttributeError: @@ -692,7 +692,7 @@ class StaticHandler(GenericHandler): @classmethod def _norm_hash(cls, hash): - "helper for subclasses to normalize case if needed" + """helper for subclasses to normalize case if needed""" return hash def to_string(self): @@ -737,7 +737,7 @@ class StaticHandler(GenericHandler): hash = wrapper_cls.genhash(secret, None, **context) warn("%r should be updated to implement StaticHandler._calc_checksum() " "instead of StaticHandler.genhash(), support for the latter " - "style will be removed in Passlib 1.8" % (cls), + "style will be removed in Passlib 1.8" % cls, DeprecationWarning) return str_to_uascii(hash) @@ -986,12 +986,12 @@ class HasSalt(GenericHandler): @classproperty def default_salt_size(cls): - "default salt size (defaults to *max_salt_size*)" + """default salt size (defaults to *max_salt_size*)""" return cls.max_salt_size @classproperty def default_salt_chars(cls): - "charset used to generate new salt strings (defaults to *salt_chars*)" + """charset used to generate new salt strings (defaults to *salt_chars*)""" return cls.salt_chars # private helpers for HasRawSalt, shouldn't be used by subclasses @@ -1095,7 +1095,7 @@ class HasSalt(GenericHandler): @classmethod def bitsize(cls, salt_size=None, **kwds): - "[experimental method] return info about bitsizes of hash" + """[experimental method] return info about bitsizes of hash""" info = super(HasSalt, cls).bitsize(**kwds) if salt_size is None: salt_size = cls.default_salt_size @@ -1259,7 +1259,7 @@ class HasRounds(GenericHandler): @classmethod def bitsize(cls, rounds=None, vary_rounds=.1, **kwds): - "[experimental method] return info about bitsizes of hash" + """[experimental method] return info about bitsizes of hash""" info = super(HasRounds, cls).bitsize(**kwds) # NOTE: this essentially estimates how many bits of "salt" # can be added by varying the rounds value just a little bit. @@ -1448,7 +1448,7 @@ class HasManyBackends(GenericHandler): return name def _calc_checksum(self, secret): - "stub for _calc_checksum(), default backend will be selected first time stub is called" + """stub for _calc_checksum(), default backend will be selected first time stub is called""" # if we got here, no backend has been loaded; so load default backend assert not self._backend, "set_backend() failed to replace lazy loader" self.set_backend() @@ -1601,13 +1601,13 @@ class PrefixWrapper(object): return list(attrs) def __getattr__(self, attr): - "proxy most attributes from wrapped class (e.g. rounds, salt size, etc)" + """proxy most attributes from wrapped class (e.g. rounds, salt size, etc)""" if attr in self._proxy_attrs: return getattr(self.wrapped, attr) raise AttributeError("missing attribute: %r" % (attr,)) def _unwrap_hash(self, hash): - "given hash belonging to wrapper, return orig version" + """given hash belonging to wrapper, return orig version""" # NOTE: assumes hash has been validated as unicode already prefix = self.prefix if not hash.startswith(prefix): @@ -1616,7 +1616,7 @@ class PrefixWrapper(object): return self.orig_prefix + hash[len(prefix):] def _wrap_hash(self, hash): - "given orig hash; return one belonging to wrapper" + """given orig hash; return one belonging to wrapper""" # NOTE: should usually be native string. # (which does mean extra work under py2, but not py3) if isinstance(hash, bytes): diff --git a/passlib/utils/md4.py b/passlib/utils/md4.py index 0f739e1..cd067d9 100644 --- a/passlib/utils/md4.py +++ b/passlib/utils/md4.py @@ -146,7 +146,7 @@ class md4(object): ] def _process(self, block): - "process 64 byte block" + """process 64 byte block""" # unpack block into 16 32-bit ints X = struct.unpack("<16I", block) @@ -258,7 +258,7 @@ def _has_native_md4(): # pragma: no cover -- runtime detection if _has_native_md4(): # overwrite md4 class w/ hashlib wrapper def md4(content=None): - "wrapper for hashlib.new('md4')" + """wrapper for hashlib.new('md4')""" return hashlib.new('md4', content or b('')) #============================================================================= diff --git a/passlib/utils/pbkdf2.py b/passlib/utils/pbkdf2.py index fede683..6fe93c0 100644 --- a/passlib/utils/pbkdf2.py +++ b/passlib/utils/pbkdf2.py @@ -39,7 +39,7 @@ __all__ = [ ] def _clear_caches(): - "unittest helper -- clears get_hash_info() / get_prf() caches" + """unittest helper -- clears get_hash_info() / get_prf() caches""" _ghi_cache.clear() _prf_cache.clear() @@ -150,7 +150,7 @@ def norm_hash_name(name, format="hashlib"): return row[idx] def _get_hash_const(name): - "internal helper for :func:`get_hash_const`" + """internal helper for :func:`get_hash_const`""" # typecheck if not isinstance(name, str): raise TypeError("expected digest name") @@ -249,14 +249,14 @@ _TRANS_36 = join_byte_values((x ^ 0x36) for x in irange(256)) # prefixes for recognizing hmac-{digest} prf names _HMAC_PREFIXES = ("hmac_", "hmac-") -#----------------------------------------------------------------------------- +#------------------------------------------------------------------------ # general prf lookup -#----------------------------------------------------------------------------- +#------------------------------------------------------------------------ def _get_hmac_prf(digest): - "helper for get_prf() -- returns HMAC-based prf for specified digest" + """helper for get_prf() -- returns HMAC-based prf for specified digest""" # helpers def tag_wrapper(prf): - "helper to document generated wrappers" + """helper to document generated wrappers""" prf.__name__ = "hmac_" + digest prf.__doc__ = ("hmac_%s(key, msg) -> digest;" " generated by passlib.utils.pbkdf2.get_prf()" % @@ -361,9 +361,9 @@ def get_prf(name): _prf_cache[name] = record return record -#----------------------------------------------------------------------------- +#------------------------------------------------------------------------ # keyed prf generation -#----------------------------------------------------------------------------- +#------------------------------------------------------------------------ def _get_keyed_hmac_prf(digest, key): """get_keyed_prf() helper -- returns efficent hmac() function diff --git a/passlib/win32.py b/passlib/win32.py index 783cc9e..fd6febe 100644 --- a/passlib/win32.py +++ b/passlib/win32.py @@ -51,7 +51,7 @@ LM_MAGIC = b("KGS!@#$%") raw_nthash = nthash.raw_nthash def raw_lmhash(secret, encoding="ascii", hex=False): - "encode password using des-based LMHASH algorithm; returns string of raw bytes, or unicode hex" + """encode password using des-based LMHASH algorithm; returns string of raw bytes, or unicode hex""" # NOTE: various references say LMHASH uses the OEM codepage of the host # for its encoding. until a clear reference is found, # as well as a path for getting the encoding, |
