diff options
| author | Eli Collins <elic@assurancetechnologies.com> | 2015-01-10 18:52:34 -0500 |
|---|---|---|
| committer | Eli Collins <elic@assurancetechnologies.com> | 2015-01-10 18:52:34 -0500 |
| commit | cf8fce4325d259490ada92caa624cb1a1c8e21b5 (patch) | |
| tree | f52587a6308cf389dbadf56492dfbeb592c9ee47 /passlib | |
| parent | 55062360b26ace8d2521fe67a518ebf434f7847f (diff) | |
| download | passlib-cf8fce4325d259490ada92caa624cb1a1c8e21b5.tar.gz | |
removed a LOT of compatibility shims -- dropped python 2.5, 3.0, and 3.1 support;
as well as PyPy 1.x and Jython 2.5.
shims removed
-------------
* b() shim replaced with b'' (py25)
* 'bytes' alias no longer needed (py25)
* callable() shim no longer needed (py30,31)
* PY_MIN_32 flag replaced with PY3 flag (py30,31)
* removed 'abc' module stub used by passlib.ifc (py25)
* removed chain_from_iterable() backport (py25)
* tests: removed catch_warnings() backport,
replaced refs with real warnings.catch_warnings() (py25)
* tests: removed unittest2 backports (py25, py30, py31) --
now throw hard error if unittest2 not present under py26
(the only release remaining which lacks the unittest2 features)
* removed SUPPORTS_DIR_METHOD conditional (py25, pypy 1.x)
* some other minor workarounds
other
-----
* added check in passlib.compat which now throws error telling user
version isn't supported (to prevent spurious errors later)
Diffstat (limited to 'passlib')
44 files changed, 410 insertions, 747 deletions
diff --git a/passlib/apache.py b/passlib/apache.py index 4b5654c..b3917fb 100644 --- a/passlib/apache.py +++ b/passlib/apache.py @@ -14,8 +14,7 @@ from passlib.context import CryptContext from passlib.exc import ExpectedStringError from passlib.hash import htdigest from passlib.utils import render_bytes, to_bytes, deprecated_method, is_ascii_codec -from passlib.utils.compat import b, bytes, join_bytes, unicode, BytesIO, \ - iteritems, PY3 +from passlib.utils.compat import join_bytes, unicode, BytesIO, iteritems, PY3 # local __all__ = [ 'HtpasswdFile', @@ -27,10 +26,10 @@ __all__ = [ #============================================================================= _UNSET = object() -_BCOLON = b(":") +_BCOLON = b":" # byte values that aren't allowed in fields. -_INVALID_FIELD_CHARS = b(":\n\r\t\x00") +_INVALID_FIELD_CHARS = b":\n\r\t\x00" #============================================================================= # backport of OrderedDict for PY2.5 diff --git a/passlib/context.py b/passlib/context.py index da9889f..fe5521f 100644 --- a/passlib/context.py +++ b/passlib/context.py @@ -14,8 +14,8 @@ from passlib.exc import PasslibConfigWarning, ExpectedStringError, ExpectedTypeE from passlib.registry import get_crypt_handler, _validate_handler_name from passlib.utils import rng, tick, to_bytes, deprecated_method, \ to_unicode, splitcomma -from passlib.utils.compat import bytes, iteritems, num_types, \ - PY2, PY3, PY_MIN_32, unicode, SafeConfigParser, \ +from passlib.utils.compat import iteritems, num_types, \ + PY2, PY3, unicode, SafeConfigParser, \ NativeStringIO, BytesIO, base_string_types # local __all__ = [ @@ -1759,7 +1759,7 @@ class CryptContext(object): # and a utf-8 bytes stream under py2, # allowing the resulting dict to always use native strings. p = SafeConfigParser() - if PY_MIN_32: + if PY3: # python 3.2 deprecated readfp in favor of read_file p.read_file(stream, filename) else: diff --git a/passlib/ext/django/models.py b/passlib/ext/django/models.py index 1c74f12..454e653 100644 --- a/passlib/ext/django/models.py +++ b/passlib/ext/django/models.py @@ -13,7 +13,7 @@ from passlib.context import CryptContext from passlib.exc import ExpectedTypeError from passlib.ext.django.utils import _PatchManager, hasher_to_passlib_name, \ get_passlib_hasher, get_preset_config -from passlib.utils.compat import callable, unicode, bytes +from passlib.utils.compat import unicode # local __all__ = ["password_context"] diff --git a/passlib/ext/django/utils.py b/passlib/ext/django/utils.py index 863f11e..894b46b 100644 --- a/passlib/ext/django/utils.py +++ b/passlib/ext/django/utils.py @@ -18,7 +18,7 @@ from passlib.context import CryptContext from passlib.exc import PasslibRuntimeWarning from passlib.registry import get_crypt_handler, list_crypt_handlers from passlib.utils import classproperty -from passlib.utils.compat import bytes, get_method_function, iteritems +from passlib.utils.compat import get_method_function, iteritems # local __all__ = [ "get_preset_config", diff --git a/passlib/handlers/bcrypt.py b/passlib/handlers/bcrypt.py index f1e166f..2a72ede 100644 --- a/passlib/handlers/bcrypt.py +++ b/passlib/handlers/bcrypt.py @@ -27,7 +27,7 @@ _builtin_bcrypt = None # dynamically imported by _load_backend_builtin() from passlib.exc import PasslibHashWarning from passlib.utils import bcrypt64, safe_crypt, repeat_string, to_bytes, parse_version, \ rng, getrandstr, test_crypt, to_unicode -from passlib.utils.compat import bytes, b, u, uascii_to_str, unicode, str_to_uascii +from passlib.utils.compat import u, uascii_to_str, unicode, str_to_uascii import passlib.utils.handlers as uh # local @@ -42,7 +42,7 @@ IDENT_2 = u("$2$") IDENT_2A = u("$2a$") IDENT_2X = u("$2x$") IDENT_2Y = u("$2y$") -_BNULL = b('\x00') +_BNULL = b'\x00' #============================================================================= # handler diff --git a/passlib/handlers/des_crypt.py b/passlib/handlers/des_crypt.py index 5f5729d..9e509da 100644 --- a/passlib/handlers/des_crypt.py +++ b/passlib/handlers/des_crypt.py @@ -9,7 +9,7 @@ from warnings import warn # site # pkg from passlib.utils import h64, h64big, safe_crypt, test_crypt, to_unicode -from passlib.utils.compat import b, bytes, byte_elem_value, u, uascii_to_str, unicode +from passlib.utils.compat import byte_elem_value, u, uascii_to_str, unicode from passlib.utils.des import des_encrypt_int_block import passlib.utils.handlers as uh # local @@ -23,7 +23,7 @@ __all__ = [ #============================================================================= # pure-python backend for des_crypt family #============================================================================= -_BNULL = b('\x00') +_BNULL = b'\x00' def _crypt_secret_to_key(secret): """convert secret to 64-bit DES key. diff --git a/passlib/handlers/fshp.py b/passlib/handlers/fshp.py index 81f5004..821aaec 100644 --- a/passlib/handlers/fshp.py +++ b/passlib/handlers/fshp.py @@ -12,7 +12,7 @@ import logging; log = logging.getLogger(__name__) # pkg from passlib.utils import to_unicode import passlib.utils.handlers as uh -from passlib.utils.compat import b, bytes, bascii_to_str, iteritems, u,\ +from passlib.utils.compat import bascii_to_str, iteritems, u,\ unicode from passlib.utils.pbkdf2 import pbkdf1 # local @@ -170,7 +170,7 @@ class fshp(uh.HasRounds, uh.HasRawSalt, uh.HasRawChecksum, uh.GenericHandler): @property def _stub_checksum(self): - return b('\x00') * self.checksum_size + return b'\x00' * self.checksum_size def to_string(self): chk = self.checksum or self._stub_checksum diff --git a/passlib/handlers/ldap_digests.py b/passlib/handlers/ldap_digests.py index 54a7517..e92c658 100644 --- a/passlib/handlers/ldap_digests.py +++ b/passlib/handlers/ldap_digests.py @@ -12,7 +12,7 @@ import re # pkg from passlib.handlers.misc import plaintext from passlib.utils import unix_crypt_schemes, classproperty, to_unicode -from passlib.utils.compat import b, uascii_to_str, unicode, u +from passlib.utils.compat import uascii_to_str, unicode, u import passlib.utils.handlers as uh # local __all__ = [ @@ -159,7 +159,7 @@ class ldap_salted_md5(_SaltedBase64DigestHelper): checksum_size = 16 _hash_func = md5 _hash_regex = re.compile(u(r"^\{SMD5\}(?P<tmp>[+/a-zA-Z0-9]{27,}={0,2})$")) - _stub_checksum = b('\x00') * 16 + _stub_checksum = b'\x00' * 16 class ldap_salted_sha1(_SaltedBase64DigestHelper): """This class stores passwords using LDAP's salted SHA1 format, and follows the :ref:`password-hash-api`. @@ -199,7 +199,7 @@ class ldap_salted_sha1(_SaltedBase64DigestHelper): checksum_size = 20 _hash_func = sha1 _hash_regex = re.compile(u(r"^\{SSHA\}(?P<tmp>[+/a-zA-Z0-9]{32,}={0,2})$")) - _stub_checksum = b('\x00') * 20 + _stub_checksum = b'\x00' * 20 class ldap_plaintext(plaintext): """This class stores passwords in plaintext, and follows the :ref:`password-hash-api`. diff --git a/passlib/handlers/md5_crypt.py b/passlib/handlers/md5_crypt.py index 64b78bb..489a600 100644 --- a/passlib/handlers/md5_crypt.py +++ b/passlib/handlers/md5_crypt.py @@ -8,7 +8,7 @@ import logging; log = logging.getLogger(__name__) # site # pkg from passlib.utils import h64, safe_crypt, test_crypt, repeat_string -from passlib.utils.compat import b, bytes, unicode, u +from passlib.utils.compat import unicode, u import passlib.utils.handlers as uh # local __all__ = [ @@ -19,9 +19,9 @@ __all__ = [ #============================================================================= # pure-python backend #============================================================================= -_BNULL = b("\x00") -_MD5_MAGIC = b("$1$") -_APR_MAGIC = b("$apr1$") +_BNULL = b"\x00" +_MD5_MAGIC = b"$1$" +_APR_MAGIC = b"$apr1$" # pre-calculated offsets used to speed up C digest stage (see notes below). # sequence generated using the following: diff --git a/passlib/handlers/misc.py b/passlib/handlers/misc.py index a89ac72..7710275 100644 --- a/passlib/handlers/misc.py +++ b/passlib/handlers/misc.py @@ -10,7 +10,7 @@ from warnings import warn # site # pkg from passlib.utils import to_native_str, consteq -from passlib.utils.compat import bytes, unicode, u, b, base_string_types +from passlib.utils.compat import unicode, u, base_string_types import passlib.utils.handlers as uh # local __all__ = [ @@ -88,7 +88,7 @@ class unix_fallback(uh.StaticHandler): return enable_wildcard _MARKER_CHARS = u("*!") -_MARKER_BYTES = b("*!") +_MARKER_BYTES = b"*!" class unix_disabled(uh.PasswordHash): """This class provides disabled password behavior for unix shadow files, diff --git a/passlib/handlers/mssql.py b/passlib/handlers/mssql.py index d50100f..21d7133 100644 --- a/passlib/handlers/mssql.py +++ b/passlib/handlers/mssql.py @@ -43,7 +43,7 @@ from warnings import warn # site # pkg from passlib.utils import consteq -from passlib.utils.compat import b, bytes, bascii_to_str, unicode, u +from passlib.utils.compat import bascii_to_str, unicode, u import passlib.utils.handlers as uh # local __all__ = [ @@ -59,7 +59,7 @@ def _raw_mssql(secret, salt): assert isinstance(salt, bytes) return sha1(secret.encode("utf-16-le") + salt).digest() -BIDENT = b("0x0100") +BIDENT = b"0x0100" ##BIDENT2 = b("\x01\x00") UIDENT = u("0x0100") @@ -127,7 +127,7 @@ class mssql2000(uh.HasRawSalt, uh.HasRawChecksum, uh.GenericHandler): setting_kwds = ("salt",) checksum_size = 40 min_salt_size = max_salt_size = 4 - _stub_checksum = b("\x00") * 40 + _stub_checksum = b"\x00" * 40 #=================================================================== # formatting @@ -206,7 +206,7 @@ class mssql2005(uh.HasRawSalt, uh.HasRawChecksum, uh.GenericHandler): checksum_size = 20 min_salt_size = max_salt_size = 4 - _stub_checksum = b("\x00") * 20 + _stub_checksum = b"\x00" * 20 #=================================================================== # formatting diff --git a/passlib/handlers/mysql.py b/passlib/handlers/mysql.py index 8f57d05..7e31313 100644 --- a/passlib/handlers/mysql.py +++ b/passlib/handlers/mysql.py @@ -30,7 +30,7 @@ from warnings import warn # site # pkg from passlib.utils import to_native_str -from passlib.utils.compat import b, bascii_to_str, bytes, unicode, u, \ +from passlib.utils.compat import bascii_to_str, unicode, u, \ byte_elem_value, str_to_uascii import passlib.utils.handlers as uh # local @@ -70,7 +70,7 @@ class mysql323(uh.StaticHandler): MASK_32 = 0xffffffff MASK_31 = 0x7fffffff - WHITE = b(' \t') + WHITE = b' \t' nr1 = 0x50305735 nr2 = 0x12345671 diff --git a/passlib/handlers/oracle.py b/passlib/handlers/oracle.py index eb84161..252c159 100644 --- a/passlib/handlers/oracle.py +++ b/passlib/handlers/oracle.py @@ -10,7 +10,7 @@ import logging; log = logging.getLogger(__name__) # site # pkg from passlib.utils import to_unicode, xor_bytes -from passlib.utils.compat import b, bytes, irange, u, \ +from passlib.utils.compat import irange, u, \ uascii_to_str, unicode, str_to_uascii from passlib.utils.des import des_encrypt_block import passlib.utils.handlers as uh @@ -23,7 +23,7 @@ __all__ = [ #============================================================================= # oracle10 #============================================================================= -def des_cbc_encrypt(key, value, iv=b('\x00') * 8, pad=b('\x00')): +def des_cbc_encrypt(key, value, iv=b'\x00' * 8, pad=b'\x00'): """performs des-cbc encryption, returns only last block. this performs a specific DES-CBC encryption implementation @@ -47,7 +47,7 @@ def des_cbc_encrypt(key, value, iv=b('\x00') * 8, pad=b('\x00')): return hash # magic string used as initial des key by oracle10 -ORACLE10_MAGIC = b("\x01\x23\x45\x67\x89\xAB\xCD\xEF") +ORACLE10_MAGIC = b"\x01\x23\x45\x67\x89\xAB\xCD\xEF" class oracle10(uh.HasUserContext, uh.StaticHandler): """This class implements the password hash used by Oracle up to version 10g, and follows the :ref:`password-hash-api`. diff --git a/passlib/handlers/pbkdf2.py b/passlib/handlers/pbkdf2.py index 856a825..76f594a 100644 --- a/passlib/handlers/pbkdf2.py +++ b/passlib/handlers/pbkdf2.py @@ -9,7 +9,7 @@ import logging; log = logging.getLogger(__name__) # site # pkg from passlib.utils import ab64_decode, ab64_encode, to_unicode -from passlib.utils.compat import b, str_to_bascii, u, uascii_to_str, unicode +from passlib.utils.compat import str_to_bascii, u, uascii_to_str, unicode from passlib.utils.pbkdf2 import pbkdf2 import passlib.utils.handlers as uh # local @@ -146,7 +146,7 @@ ldap_pbkdf2_sha512 = uh.PrefixWrapper("ldap_pbkdf2_sha512", pbkdf2_sha512, "{PBK #============================================================================= # bytes used by cta hash for base64 values 63 & 64 -CTA_ALTCHARS = b("-_") +CTA_ALTCHARS = b"-_" class cta_pbkdf2_sha1(uh.HasRounds, uh.HasRawSalt, uh.HasRawChecksum, uh.GenericHandler): """This class implements Cryptacular's PBKDF2-based crypt algorithm, and follows the :ref:`password-hash-api`. @@ -379,7 +379,7 @@ class atlassian_pbkdf2_sha1(uh.HasRawSalt, uh.HasRawChecksum, uh.GenericHandler) ident = u("{PKCS5S2}") checksum_size = 32 - _stub_checksum = b("\x00") * 32 + _stub_checksum = b"\x00" * 32 #--HasRawSalt-- min_salt_size = max_salt_size = 16 diff --git a/passlib/handlers/scram.py b/passlib/handlers/scram.py index 06fc40e..0b1186e 100644 --- a/passlib/handlers/scram.py +++ b/passlib/handlers/scram.py @@ -8,7 +8,7 @@ import logging; log = logging.getLogger(__name__) # pkg from passlib.utils import ab64_decode, ab64_encode, consteq, saslprep, \ to_native_str, splitcomma -from passlib.utils.compat import bytes, bascii_to_str, iteritems, u +from passlib.utils.compat import bascii_to_str, iteritems, u from passlib.utils.pbkdf2 import pbkdf2, norm_hash_name import passlib.utils.handlers as uh # local diff --git a/passlib/handlers/sha1_crypt.py b/passlib/handlers/sha1_crypt.py index d8f6fd6..5c617cb 100644 --- a/passlib/handlers/sha1_crypt.py +++ b/passlib/handlers/sha1_crypt.py @@ -10,7 +10,7 @@ import logging; log = logging.getLogger(__name__) # site # pkg from passlib.utils import h64, safe_crypt, test_crypt -from passlib.utils.compat import b, u, unicode, irange +from passlib.utils.compat import u, unicode, irange from passlib.utils.pbkdf2 import get_keyed_prf import passlib.utils.handlers as uh # local @@ -19,7 +19,7 @@ __all__ = [ #============================================================================= # sha1-crypt #============================================================================= -_BNULL = b('\x00') +_BNULL = b'\x00' class sha1_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler): """This class implements the SHA1-Crypt password hash, and follows the :ref:`password-hash-api`. diff --git a/passlib/handlers/sha2_crypt.py b/passlib/handlers/sha2_crypt.py index 0b48f70..a96ee31 100644 --- a/passlib/handlers/sha2_crypt.py +++ b/passlib/handlers/sha2_crypt.py @@ -9,7 +9,7 @@ import logging; log = logging.getLogger(__name__) # pkg from passlib.utils import h64, safe_crypt, test_crypt, \ repeat_string, to_unicode -from passlib.utils.compat import b, bytes, byte_elem_value, u, \ +from passlib.utils.compat import byte_elem_value, u, \ uascii_to_str, unicode import passlib.utils.handlers as uh # local @@ -22,7 +22,7 @@ __all__ = [ # pure-python backend, used by both sha256_crypt & sha512_crypt # when crypt.crypt() backend is not available. #============================================================================= -_BNULL = b('\x00') +_BNULL = b'\x00' # pre-calculated offsets used to speed up C digest stage (see notes below). # sequence generated using the following: diff --git a/passlib/handlers/sun_md5_crypt.py b/passlib/handlers/sun_md5_crypt.py index 9ba3908..72f97bf 100644 --- a/passlib/handlers/sun_md5_crypt.py +++ b/passlib/handlers/sun_md5_crypt.py @@ -18,7 +18,7 @@ from warnings import warn # site # pkg from passlib.utils import h64, to_unicode -from passlib.utils.compat import b, bytes, byte_elem_value, irange, u, \ +from passlib.utils.compat import byte_elem_value, irange, u, \ uascii_to_str, unicode, str_to_bascii import passlib.utils.handlers as uh # local @@ -33,42 +33,42 @@ __all__ = [ # exact bytes as in http://www.ibiblio.org/pub/docs/books/gutenberg/etext98/2ws2610.txt # from Project Gutenberg. -MAGIC_HAMLET = b( - "To be, or not to be,--that is the question:--\n" - "Whether 'tis nobler in the mind to suffer\n" - "The slings and arrows of outrageous fortune\n" - "Or to take arms against a sea of troubles,\n" - "And by opposing end them?--To die,--to sleep,--\n" - "No more; and by a sleep to say we end\n" - "The heartache, and the thousand natural shocks\n" - "That flesh is heir to,--'tis a consummation\n" - "Devoutly to be wish'd. To die,--to sleep;--\n" - "To sleep! perchance to dream:--ay, there's the rub;\n" - "For in that sleep of death what dreams may come,\n" - "When we have shuffled off this mortal coil,\n" - "Must give us pause: there's the respect\n" - "That makes calamity of so long life;\n" - "For who would bear the whips and scorns of time,\n" - "The oppressor's wrong, the proud man's contumely,\n" - "The pangs of despis'd love, the law's delay,\n" - "The insolence of office, and the spurns\n" - "That patient merit of the unworthy takes,\n" - "When he himself might his quietus make\n" - "With a bare bodkin? who would these fardels bear,\n" - "To grunt and sweat under a weary life,\n" - "But that the dread of something after death,--\n" - "The undiscover'd country, from whose bourn\n" - "No traveller returns,--puzzles the will,\n" - "And makes us rather bear those ills we have\n" - "Than fly to others that we know not of?\n" - "Thus conscience does make cowards of us all;\n" - "And thus the native hue of resolution\n" - "Is sicklied o'er with the pale cast of thought;\n" - "And enterprises of great pith and moment,\n" - "With this regard, their currents turn awry,\n" - "And lose the name of action.--Soft you now!\n" - "The fair Ophelia!--Nymph, in thy orisons\n" - "Be all my sins remember'd.\n\x00" #<- apparently null at end of C string is included (test vector won't pass otherwise) +MAGIC_HAMLET = ( + b"To be, or not to be,--that is the question:--\n" + b"Whether 'tis nobler in the mind to suffer\n" + b"The slings and arrows of outrageous fortune\n" + b"Or to take arms against a sea of troubles,\n" + b"And by opposing end them?--To die,--to sleep,--\n" + b"No more; and by a sleep to say we end\n" + b"The heartache, and the thousand natural shocks\n" + b"That flesh is heir to,--'tis a consummation\n" + b"Devoutly to be wish'd. To die,--to sleep;--\n" + b"To sleep! perchance to dream:--ay, there's the rub;\n" + b"For in that sleep of death what dreams may come,\n" + b"When we have shuffled off this mortal coil,\n" + b"Must give us pause: there's the respect\n" + b"That makes calamity of so long life;\n" + b"For who would bear the whips and scorns of time,\n" + b"The oppressor's wrong, the proud man's contumely,\n" + b"The pangs of despis'd love, the law's delay,\n" + b"The insolence of office, and the spurns\n" + b"That patient merit of the unworthy takes,\n" + b"When he himself might his quietus make\n" + b"With a bare bodkin? who would these fardels bear,\n" + b"To grunt and sweat under a weary life,\n" + b"But that the dread of something after death,--\n" + b"The undiscover'd country, from whose bourn\n" + b"No traveller returns,--puzzles the will,\n" + b"And makes us rather bear those ills we have\n" + b"Than fly to others that we know not of?\n" + b"Thus conscience does make cowards of us all;\n" + b"And thus the native hue of resolution\n" + b"Is sicklied o'er with the pale cast of thought;\n" + b"And enterprises of great pith and moment,\n" + b"With this regard, their currents turn awry,\n" + b"And lose the name of action.--Soft you now!\n" + b"The fair Ophelia!--Nymph, in thy orisons\n" + b"Be all my sins remember'd.\n\x00" #<- apparently null at end of C string is included (test vector won't pass otherwise) ) # NOTE: these sequences are pre-calculated iteration ranges used by X & Y loops w/in rounds function below diff --git a/passlib/handlers/windows.py b/passlib/handlers/windows.py index 6c16808..ef246eb 100644 --- a/passlib/handlers/windows.py +++ b/passlib/handlers/windows.py @@ -9,7 +9,7 @@ from warnings import warn # site # pkg from passlib.utils import to_unicode, right_pad_string -from passlib.utils.compat import b, bytes, unicode +from passlib.utils.compat import unicode from passlib.utils.md4 import md4 import passlib.utils.handlers as uh # local @@ -61,7 +61,7 @@ class lmhash(uh.HasEncodingContext, uh.StaticHandler): return hexlify(self.raw(secret, self.encoding)).decode("ascii") # magic constant used by LMHASH - _magic = b("KGS!@#$%") + _magic = b"KGS!@#$%" @classmethod def raw(cls, secret, encoding=None): diff --git a/passlib/ifc.py b/passlib/ifc.py index 5e4e7d4..f7d8125 100644 --- a/passlib/ifc.py +++ b/passlib/ifc.py @@ -13,22 +13,10 @@ __all__ = [ ] #============================================================================= -# 2.5-3.2 compatibility helpers +# 2/3 compatibility helpers #============================================================================= -if sys.version_info >= (2,6): - from abc import ABCMeta, abstractmethod, abstractproperty -else: - # create stub for python 2.5 - ABCMeta = type - def abstractmethod(func): - return func -# def abstractproperty(): -# return None - -def create_with_metaclass(meta): +def recreate_with_metaclass(meta): """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): if meta is type(cls): return cls @@ -38,6 +26,9 @@ def create_with_metaclass(meta): #============================================================================= # PasswordHash interface #============================================================================= +from abc import ABCMeta, abstractmethod, abstractproperty + +@recreate_with_metaclass(ABCMeta) class PasswordHash(object): """This class describes an abstract interface which all password hashes in Passlib adhere to. Under Python 2.6 and up, this is an actual @@ -186,8 +177,6 @@ class PasswordHash(object): # eoc #=================================================================== -PasswordHash = create_with_metaclass(ABCMeta)(PasswordHash) - #============================================================================= # eof #============================================================================= diff --git a/passlib/pwd.py b/passlib/pwd.py index 44a1e51..befb9ac 100644 --- a/passlib/pwd.py +++ b/passlib/pwd.py @@ -71,13 +71,14 @@ from __future__ import division # core from collections import defaultdict from hashlib import sha256 +from itertools import chain from math import ceil, log as logf import logging; log = logging.getLogger(__name__) import os import zlib # site # pkg -from passlib.utils.compat import PY3, irange, itervalues, u, chain_from_iterable +from passlib.utils.compat import PY3, irange, itervalues, u from passlib.utils import rng, getrandstr # local __all__ = [ @@ -204,7 +205,7 @@ def _average_wordset_entropy(wordset): :returns: float bits of entropy """ - return _average_entropy(chain_from_iterable(wordset)) + return _average_entropy(chain.from_iterable(wordset)) def _load_wordset(name): "helper load compressed wordset from package data" diff --git a/passlib/tests/backports.py b/passlib/tests/backports.py index 1868259..347eeb7 100644 --- a/passlib/tests/backports.py +++ b/passlib/tests/backports.py @@ -15,7 +15,6 @@ from passlib.utils.compat import base_string_types __all__ = [ "TestCase", "skip", "skipIf", "skipUnless" - "catch_warnings", ] #============================================================================= @@ -23,307 +22,43 @@ __all__ = [ #============================================================================= try: import unittest2 as unittest - ut_version = 2 except ImportError: + if sys.version_info < (2,7): + raise ImportError("Passlib's tests require 'unittest2' under Python 2.6 (as of Passlib 1.7)") + # python 2.7 and python 3.2 both have unittest2 features (at least, the ones we use) import unittest - if sys.version_info < (2,7) or (3,0) <= sys.version_info < (3,2): - # older versions of python will need to install the unittest2 - # backport (named unittest2_3k for 3.0/3.1) - ##warn("please install unittest2 for python %d.%d, it will be required " - ## "as of passlib 1.x" % sys.version_info[:2]) - ut_version = 1 - else: - ut_version = 2 #============================================================================= -# backport SkipTest support using nose +# unittest aliases #============================================================================= -if ut_version < 2: - # used to provide replacement SkipTest() error - from nose.plugins.skip import SkipTest - - # hack up something to simulate skip() decorator - import functools - def skip(reason): - def decorator(test_item): - if isinstance(test_item, type) and issubclass(test_item, unittest.TestCase): - class skip_wrapper(test_item): - def setUp(self): - raise SkipTest(reason) - else: - @functools.wraps(test_item) - def skip_wrapper(*args, **kwargs): - raise SkipTest(reason) - return skip_wrapper - return decorator - - def skipIf(condition, reason): - if condition: - return skip(reason) - else: - return lambda item: item - - def skipUnless(condition, reason): - if condition: - return lambda item: item - else: - return skip(reason) - -else: - skip = unittest.skip - skipIf = unittest.skipIf - skipUnless = unittest.skipUnless +skip = unittest.skip +skipIf = unittest.skipIf +skipUnless = unittest.skipUnless #============================================================================= # custom test harness #============================================================================= class TestCase(unittest.TestCase): """backports a number of unittest2 features in TestCase""" + #=================================================================== - # backport some methods from unittest2 + # backport some unittest2 names #=================================================================== - if ut_version < 2: - - #---------------------------------------------------------------- - # simplistic backport of addCleanup() framework - #---------------------------------------------------------------- - _cleanups = None - - def addCleanup(self, function, *args, **kwds): - queue = self._cleanups - if queue is None: - queue = self._cleanups = [] - queue.append((function, args, kwds)) - - def doCleanups(self): - queue = self._cleanups - while queue: - func, args, kwds = queue.pop() - func(*args, **kwds) - - def tearDown(self): - self.doCleanups() - unittest.TestCase.tearDown(self) - - #---------------------------------------------------------------- - # backport skipTest (requires nose to work) - #---------------------------------------------------------------- - def skipTest(self, reason): - raise SkipTest(reason) - - #---------------------------------------------------------------- - # backport various assert tests added in unittest2 - #---------------------------------------------------------------- - def assertIs(self, real, correct, msg=None): - if real is not correct: - std = "got %r, expected would be %r" % (real, correct) - msg = self._formatMessage(msg, std) - raise self.failureException(msg) - - def assertIsNot(self, real, correct, msg=None): - if real is correct: - std = "got %r, expected would not be %r" % (real, correct) - msg = self._formatMessage(msg, std) - raise self.failureException(msg) - - def assertIsInstance(self, obj, klass, msg=None): - if not isinstance(obj, klass): - std = "got %r, expected instance of %r" % (obj, klass) - msg = self._formatMessage(msg, std) - raise self.failureException(msg) - - def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None): - """Fail if the two objects are unequal as determined by their - difference rounded to the given number of decimal places - (default 7) and comparing to zero, or by comparing that the - between the two objects is more than the given delta. - - Note that decimal places (from zero) are usually not the same - as significant digits (measured from the most signficant digit). - - If the two objects compare equal then they will automatically - compare almost equal. - """ - if first == second: - # shortcut - return - if delta is not None and places is not None: - raise TypeError("specify delta or places not both") - - if delta is not None: - if abs(first - second) <= delta: - return - - standardMsg = '%s != %s within %s delta' % (repr(first), - repr(second), - repr(delta)) - else: - if places is None: - places = 7 - - if round(abs(second-first), places) == 0: - return - - standardMsg = '%s != %s within %r places' % (repr(first), - repr(second), - places) - msg = self._formatMessage(msg, standardMsg) - raise self.failureException(msg) - - def assertLess(self, left, right, msg=None): - if left >= right: - std = "%r not less than %r" % (left, right) - raise self.failureException(self._formatMessage(msg, std)) - - def assertGreater(self, left, right, msg=None): - if left <= right: - std = "%r not greater than %r" % (left, right) - raise self.failureException(self._formatMessage(msg, std)) - - def assertGreaterEqual(self, left, right, msg=None): - if left < right: - std = "%r less than %r" % (left, right) - raise self.failureException(self._formatMessage(msg, std)) - - def assertIn(self, elem, container, msg=None): - if elem not in container: - std = "%r not found in %r" % (elem, container) - raise self.failureException(self._formatMessage(msg, std)) - - def assertNotIn(self, elem, container, msg=None): - if elem in container: - std = "%r unexpectedly in %r" % (elem, container) - raise self.failureException(self._formatMessage(msg, std)) - - #---------------------------------------------------------------- - # override some unittest1 methods to support _formatMessage - #---------------------------------------------------------------- - def assertEqual(self, real, correct, msg=None): - if real != correct: - std = "got %r, expected would equal %r" % (real, correct) - msg = self._formatMessage(msg, std) - raise self.failureException(msg) - - def assertNotEqual(self, real, correct, msg=None): - if real == correct: - std = "got %r, expected would not equal %r" % (real, correct) - msg = self._formatMessage(msg, std) - raise self.failureException(msg) #--------------------------------------------------------------- - # backport assertRegex() alias from 3.2 to 2.7/3.1 + # backport assertRegex() alias from 3.2 to 2.7 + # was present in 2.7 under an alternate name #--------------------------------------------------------------- if not hasattr(unittest.TestCase, "assertRegex"): - if hasattr(unittest.TestCase, "assertRegexpMatches"): - # was present in 2.7/3.1 under name assertRegexpMatches - assertRegex = unittest.TestCase.assertRegexpMatches - else: - # 3.0 and <= 2.6 didn't have this method at all - def assertRegex(self, text, expected_regex, msg=None): - """Fail the test unless the text matches the regular expression.""" - if isinstance(expected_regex, base_string_types): - assert expected_regex, "expected_regex must not be empty." - expected_regex = re.compile(expected_regex) - if not expected_regex.search(text): - msg = msg or "Regex didn't match: " - std = '%r not found in %r' % (expected_regex.pattern, text) - raise self.failureException(self._formatMessage(msg, std)) + assertRegex = unittest.TestCase.assertRegexpMatches + + if not hasattr(unittest.TestCase, "assertRaisesRegex"): + assertRaisesRegex = unittest.TestCase.assertRaisesRegexp #=================================================================== # eoc #=================================================================== #============================================================================= -# backport catch_warnings -#============================================================================= -try: - from warnings import catch_warnings -except ImportError: - # catch_warnings wasn't added until py26. - # this adds backported copy from py26's stdlib - # so we can use it under py25. - - class WarningMessage(object): - - """Holds the result of a single showwarning() call.""" - - _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file", - "line") - - def __init__(self, message, category, filename, lineno, file=None, - line=None): - local_values = locals() - for attr in self._WARNING_DETAILS: - setattr(self, attr, local_values[attr]) - self._category_name = category.__name__ if category else None - - def __str__(self): - return ("{message : %r, category : %r, filename : %r, lineno : %s, " - "line : %r}" % (self.message, self._category_name, - self.filename, self.lineno, self.line)) - - - class catch_warnings(object): - - """A context manager that copies and restores the warnings filter upon - exiting the context. - - The 'record' argument specifies whether warnings should be captured by a - custom implementation of warnings.showwarning() and be appended to a list - returned by the context manager. Otherwise None is returned by the context - manager. The objects appended to the list are arguments whose attributes - mirror the arguments to showwarning(). - - The 'module' argument is to specify an alternative module to the module - named 'warnings' and imported under that name. This argument is only useful - when testing the warnings module itself. - - """ - - def __init__(self, record=False, module=None): - """Specify whether to record warnings and if an alternative module - should be used other than sys.modules['warnings']. - - For compatibility with Python 3.0, please consider all arguments to be - keyword-only. - - """ - self._record = record - self._module = sys.modules['warnings'] if module is None else module - self._entered = False - - def __repr__(self): - args = [] - if self._record: - args.append("record=True") - if self._module is not sys.modules['warnings']: - args.append("module=%r" % self._module) - name = type(self).__name__ - return "%s(%s)" % (name, ", ".join(args)) - - def __enter__(self): - if self._entered: - raise RuntimeError("Cannot enter %r twice" % self) - self._entered = True - self._filters = self._module.filters - self._module.filters = self._filters[:] - self._showwarning = self._module.showwarning - if self._record: - log = [] - def showwarning(*args, **kwargs): -# self._showwarning(*args, **kwargs) - log.append(WarningMessage(*args, **kwargs)) - self._module.showwarning = showwarning - return log - else: - return None - - def __exit__(self, *exc_info): - if not self._entered: - raise RuntimeError("Cannot exit %r without entering first" % self) - self._module.filters = self._filters - self._module.showwarning = self._showwarning - -#============================================================================= # eof #============================================================================= diff --git a/passlib/tests/test_apache.py b/passlib/tests/test_apache.py index 3c7b07f..68563ec 100644 --- a/passlib/tests/test_apache.py +++ b/passlib/tests/test_apache.py @@ -11,7 +11,7 @@ import os from passlib import apache from passlib.utils.compat import irange from passlib.tests.utils import TestCase, get_file, set_file, ensure_mtime_changed -from passlib.utils.compat import b, u +from passlib.utils.compat import u # module log = getLogger(__name__) @@ -31,26 +31,26 @@ class HtpasswdFileTest(TestCase): descriptionPrefix = "HtpasswdFile" # sample with 4 users - sample_01 = b('user2:2CHkkwa2AtqGs\n' - 'user3:{SHA}3ipNV1GrBtxPmHFC21fCbVCSXIo=\n' - 'user4:pass4\n' - 'user1:$apr1$t4tc7jTh$GPIWVUo8sQKJlUdV8V5vu0\n') + sample_01 = (b'user2:2CHkkwa2AtqGs\n' + b'user3:{SHA}3ipNV1GrBtxPmHFC21fCbVCSXIo=\n' + b'user4:pass4\n' + b'user1:$apr1$t4tc7jTh$GPIWVUo8sQKJlUdV8V5vu0\n') # sample 1 with user 1, 2 deleted; 4 changed - sample_02 = b('user3:{SHA}3ipNV1GrBtxPmHFC21fCbVCSXIo=\nuser4:pass4\n') + sample_02 = b'user3:{SHA}3ipNV1GrBtxPmHFC21fCbVCSXIo=\nuser4:pass4\n' # sample 1 with user2 updated, user 1 first entry removed, and user 5 added - sample_03 = b('user2:pass2x\n' - 'user3:{SHA}3ipNV1GrBtxPmHFC21fCbVCSXIo=\n' - 'user4:pass4\n' - 'user1:$apr1$t4tc7jTh$GPIWVUo8sQKJlUdV8V5vu0\n' - 'user5:pass5\n') + sample_03 = (b'user2:pass2x\n' + b'user3:{SHA}3ipNV1GrBtxPmHFC21fCbVCSXIo=\n' + b'user4:pass4\n' + b'user1:$apr1$t4tc7jTh$GPIWVUo8sQKJlUdV8V5vu0\n' + b'user5:pass5\n') # standalone sample with 8-bit username - sample_04_utf8 = b('user\xc3\xa6:2CHkkwa2AtqGs\n') - sample_04_latin1 = b('user\xe6:2CHkkwa2AtqGs\n') + sample_04_utf8 = b'user\xc3\xa6:2CHkkwa2AtqGs\n' + sample_04_latin1 = b'user\xe6:2CHkkwa2AtqGs\n' - sample_dup = b('user1:pass1\nuser1:pass2\n') + sample_dup = b'user1:pass1\nuser1:pass2\n' def test_00_constructor_autoload(self): """test constructor autoload""" @@ -69,14 +69,14 @@ class HtpasswdFileTest(TestCase): # check new=True ht = apache.HtpasswdFile(path, new=True) - self.assertEqual(ht.to_string(), b("")) + self.assertEqual(ht.to_string(), b"") self.assertEqual(ht.path, path) self.assertFalse(ht.mtime) # check autoload=False (deprecated alias for new=True) with self.assertWarningList("``autoload=False`` is deprecated"): ht = apache.HtpasswdFile(path, autoload=False) - self.assertEqual(ht.to_string(), b("")) + self.assertEqual(ht.to_string(), b"") self.assertEqual(ht.path, path) self.assertFalse(ht.mtime) @@ -107,7 +107,7 @@ class HtpasswdFileTest(TestCase): def test_01_delete_autosave(self): path = self.mktemp() - sample = b('user1:pass1\nuser2:pass2\n') + sample = b'user1:pass1\nuser2:pass2\n' set_file(path, sample) ht = apache.HtpasswdFile(path) @@ -116,7 +116,7 @@ class HtpasswdFileTest(TestCase): ht = apache.HtpasswdFile(path, autosave=True) ht.delete("user1") - self.assertEqual(get_file(path), b("user2:pass2\n")) + self.assertEqual(get_file(path), b"user2:pass2\n") def test_02_set_password(self): """test set_password()""" @@ -143,7 +143,7 @@ class HtpasswdFileTest(TestCase): def test_02_set_password_autosave(self): path = self.mktemp() - sample = b('user1:pass1\n') + sample = b'user1:pass1\n' set_file(path, sample) ht = apache.HtpasswdFile(path) @@ -152,7 +152,7 @@ class HtpasswdFileTest(TestCase): ht = apache.HtpasswdFile(path, default_scheme="plaintext", autosave=True) ht.set_password("user1", "pass2") - self.assertEqual(get_file(path), b("user1:pass2\n")) + self.assertEqual(get_file(path), b"user1:pass2\n") def test_03_users(self): """test users()""" @@ -187,12 +187,12 @@ class HtpasswdFileTest(TestCase): set_file(path, "") backdate_file_mtime(path, 5) ha = apache.HtpasswdFile(path, default_scheme="plaintext") - self.assertEqual(ha.to_string(), b("")) + self.assertEqual(ha.to_string(), b"") # make changes, check load_if_changed() does nothing ha.set_password("user1", "pass1") ha.load_if_changed() - self.assertEqual(ha.to_string(), b("user1:pass1\n")) + self.assertEqual(ha.to_string(), b"user1:pass1\n") # change file set_file(path, self.sample_01) @@ -237,7 +237,7 @@ class HtpasswdFileTest(TestCase): # test save w/ explicit path hb.save(path) - self.assertEqual(get_file(path), b("user1:pass1\n")) + self.assertEqual(get_file(path), b"user1:pass1\n") def test_07_encodings(self): """test 'encoding' kwd""" @@ -252,7 +252,7 @@ class HtpasswdFileTest(TestCase): # test deprecated encoding=None with self.assertWarningList("``encoding=None`` is deprecated"): ht = apache.HtpasswdFile.from_string(self.sample_04_utf8, encoding=None) - self.assertEqual(ht.users(), [ b('user\xc3\xa6') ]) + self.assertEqual(ht.users(), [ b'user\xc3\xa6' ]) # check sample latin-1 ht = apache.HtpasswdFile.from_string(self.sample_04_latin1, @@ -262,12 +262,12 @@ class HtpasswdFileTest(TestCase): def test_08_get_hash(self): """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")) + self.assertEqual(ht.get_hash("user3"), b"{SHA}3ipNV1GrBtxPmHFC21fCbVCSXIo=") + self.assertEqual(ht.get_hash("user4"), b"pass4") self.assertEqual(ht.get_hash("user5"), None) with self.assertWarningList("find\(\) is deprecated"): - self.assertEqual(ht.find("user4"), b("pass4")) + self.assertEqual(ht.find("user4"), b"pass4") def test_09_to_string(self): """test to_string""" @@ -278,7 +278,7 @@ class HtpasswdFileTest(TestCase): # test blank ht = apache.HtpasswdFile() - self.assertEqual(ht.to_string(), b("")) + self.assertEqual(ht.to_string(), b"") def test_10_repr(self): ht = apache.HtpasswdFile("fakepath", autosave=True, new=True, encoding="latin-1") @@ -286,14 +286,14 @@ class HtpasswdFileTest(TestCase): def test_11_malformed(self): self.assertRaises(ValueError, apache.HtpasswdFile.from_string, - b('realm:user1:pass1\n')) + b'realm:user1:pass1\n') self.assertRaises(ValueError, apache.HtpasswdFile.from_string, - b('pass1\n')) + b'pass1\n') def test_12_from_string(self): # forbid path kwd self.assertRaises(TypeError, apache.HtpasswdFile.from_string, - b(''), path=None) + b'', path=None) #=================================================================== # eoc @@ -307,25 +307,25 @@ class HtdigestFileTest(TestCase): descriptionPrefix = "HtdigestFile" # sample with 4 users - sample_01 = b('user2:realm:549d2a5f4659ab39a80dac99e159ab19\n' - 'user3:realm:a500bb8c02f6a9170ae46af10c898744\n' - 'user4:realm:ab7b5d5f28ccc7666315f508c7358519\n' - 'user1:realm:2a6cf53e7d8f8cf39d946dc880b14128\n') + sample_01 = (b'user2:realm:549d2a5f4659ab39a80dac99e159ab19\n' + b'user3:realm:a500bb8c02f6a9170ae46af10c898744\n' + b'user4:realm:ab7b5d5f28ccc7666315f508c7358519\n' + b'user1:realm:2a6cf53e7d8f8cf39d946dc880b14128\n') # sample 1 with user 1, 2 deleted; 4 changed - sample_02 = b('user3:realm:a500bb8c02f6a9170ae46af10c898744\n' - 'user4:realm:ab7b5d5f28ccc7666315f508c7358519\n') + sample_02 = (b'user3:realm:a500bb8c02f6a9170ae46af10c898744\n' + b'user4:realm:ab7b5d5f28ccc7666315f508c7358519\n') # sample 1 with user2 updated, user 1 first entry removed, and user 5 added - sample_03 = b('user2:realm:5ba6d8328943c23c64b50f8b29566059\n' - 'user3:realm:a500bb8c02f6a9170ae46af10c898744\n' - 'user4:realm:ab7b5d5f28ccc7666315f508c7358519\n' - 'user1:realm:2a6cf53e7d8f8cf39d946dc880b14128\n' - 'user5:realm:03c55fdc6bf71552356ad401bdb9af19\n') + sample_03 = (b'user2:realm:5ba6d8328943c23c64b50f8b29566059\n' + b'user3:realm:a500bb8c02f6a9170ae46af10c898744\n' + b'user4:realm:ab7b5d5f28ccc7666315f508c7358519\n' + b'user1:realm:2a6cf53e7d8f8cf39d946dc880b14128\n' + b'user5:realm:03c55fdc6bf71552356ad401bdb9af19\n') # standalone sample with 8-bit username & realm - sample_04_utf8 = b('user\xc3\xa6:realm\xc3\xa6:549d2a5f4659ab39a80dac99e159ab19\n') - sample_04_latin1 = b('user\xe6:realm\xe6:549d2a5f4659ab39a80dac99e159ab19\n') + sample_04_utf8 = b'user\xc3\xa6:realm\xc3\xa6:549d2a5f4659ab39a80dac99e159ab19\n' + sample_04_latin1 = b'user\xe6:realm\xe6:549d2a5f4659ab39a80dac99e159ab19\n' def test_00_constructor_autoload(self): """test constructor autoload""" @@ -337,7 +337,7 @@ class HtdigestFileTest(TestCase): # check without autoload ht = apache.HtdigestFile(path, new=True) - self.assertEqual(ht.to_string(), b("")) + self.assertEqual(ht.to_string(), b"") # check missing file os.remove(path) @@ -444,12 +444,12 @@ class HtdigestFileTest(TestCase): set_file(path, "") backdate_file_mtime(path, 5) ha = apache.HtdigestFile(path) - self.assertEqual(ha.to_string(), b("")) + self.assertEqual(ha.to_string(), b"") # make changes, check load_if_changed() does nothing ha.set_password("user1", "realm", "pass1") ha.load_if_changed() - self.assertEqual(ha.to_string(), b('user1:realm:2a6cf53e7d8f8cf39d946dc880b14128\n')) + self.assertEqual(ha.to_string(), b'user1:realm:2a6cf53e7d8f8cf39d946dc880b14128\n') # change file set_file(path, self.sample_01) @@ -476,7 +476,7 @@ class HtdigestFileTest(TestCase): set_file(path, "") with self.assertWarningList(r"load\(force=False\) is deprecated"): ha.load(force=False) - self.assertEqual(ha.to_string(), b("")) + self.assertEqual(ha.to_string(), b"") def test_06_save(self): """test save()""" @@ -509,7 +509,7 @@ class HtdigestFileTest(TestCase): self.assertEqual(ht.delete_realm("realm"), 4) self.assertEqual(ht.realms(), []) - self.assertEqual(ht.to_string(), b("")) + self.assertEqual(ht.to_string(), b"") def test_08_get_hash(self): """test get_hash()""" @@ -545,13 +545,13 @@ class HtdigestFileTest(TestCase): # check blank ht = apache.HtdigestFile() - self.assertEqual(ht.to_string(), b("")) + self.assertEqual(ht.to_string(), b"") def test_11_malformed(self): self.assertRaises(ValueError, apache.HtdigestFile.from_string, - b('realm:user1:pass1:other\n')) + b'realm:user1:pass1:other\n') self.assertRaises(ValueError, apache.HtdigestFile.from_string, - b('user1:pass1\n')) + b'user1:pass1\n') #=================================================================== # eoc diff --git a/passlib/tests/test_context_deprecated.py b/passlib/tests/test_context_deprecated.py index 2cfdb9c..c300e19 100644 --- a/passlib/tests/test_context_deprecated.py +++ b/passlib/tests/test_context_deprecated.py @@ -22,7 +22,6 @@ except ImportError: from passlib import hash from passlib.context import CryptContext, CryptPolicy, LazyCryptContext from passlib.utils import to_bytes, to_unicode -from passlib.utils.compat import bytes import passlib.utils.handlers as uh from passlib.tests.utils import TestCase, set_file from passlib.registry import (register_crypt_handler_path, diff --git a/passlib/tests/test_handlers.py b/passlib/tests/test_handlers.py index 1009718..b64d3be 100644 --- a/passlib/tests/test_handlers.py +++ b/passlib/tests/test_handlers.py @@ -14,7 +14,7 @@ from passlib import hash from passlib.utils import repeat_string from passlib.utils.compat import irange, PY3, u, get_method_function from passlib.tests.utils import TestCase, HandlerCase, skipUnless, \ - TEST_MODE, b, UserHandlerMixin, randintgauss, EncodingHandlerMixin + TEST_MODE, UserHandlerMixin, randintgauss, EncodingHandlerMixin # module #============================================================================= @@ -26,7 +26,7 @@ UPASS_WAV = u('\u0399\u03c9\u03b1\u03bd\u03bd\u03b7\u03c2') UPASS_USD = u("\u20AC\u00A5$") UPASS_TABLE = u("t\u00e1\u0411\u2113\u0259") -PASS_TABLE_UTF8 = b('t\xc3\xa1\xd0\x91\xe2\x84\x93\xc9\x99') # utf-8 +PASS_TABLE_UTF8 = b't\xc3\xa1\xd0\x91\xe2\x84\x93\xc9\x99' # utf-8 # handlers which support multiple backends, but don't have multi-backend tests. _omitted_backend_tests = ["django_bcrypt", "django_bcrypt_sha256"] @@ -450,18 +450,18 @@ class fshp_test(HandlerCase): def test_90_variant(self): """test variant keyword""" handler = self.handler - kwds = dict(salt=b('a'), rounds=1) + kwds = dict(salt=b'a', rounds=1) # accepts ints handler(variant=1, **kwds) # accepts bytes or unicode handler(variant=u('1'), **kwds) - handler(variant=b('1'), **kwds) + handler(variant=b'1', **kwds) # aliases handler(variant=u('sha256'), **kwds) - handler(variant=b('sha256'), **kwds) + handler(variant=b'sha256', **kwds) # rejects None self.assertRaises(TypeError, handler, variant=None, **kwds) @@ -807,7 +807,7 @@ class _md5_crypt_test(HandlerCase): ('Compl3X AlphaNu3meric', '$1$nX1e7EeI$ljQn72ZUgt6Wxd9hfvHdV0'), ('4lpHa N|_|M3r1K W/ Cur5Es: #$%(*)(*%#', '$1$jQS7o98J$V6iTcr71CGgwW2laf17pi1'), ('test', '$1$SuMrG47N$ymvzYjr7QcEQjaK5m1PGx1'), - (b('test'), '$1$SuMrG47N$ymvzYjr7QcEQjaK5m1PGx1'), + (b'test', '$1$SuMrG47N$ymvzYjr7QcEQjaK5m1PGx1'), (u('s'), '$1$ssssssss$YgmLTApYTv12qgTwBoj8i/'), # ensures utf-8 used for unicode @@ -1010,7 +1010,7 @@ class mssql2000_test(HandlerCase): known_malformed_hashes = [ # non-hex char -----\/ - b('0x01005B200543327G2E1BC2E7C5DF0F9EBFE486E9BEE063E8D3B332752E1BC2E7C5DF0F9EBFE486E9BEE063E8D3B3'), + b'0x01005B200543327G2E1BC2E7C5DF0F9EBFE486E9BEE063E8D3B332752E1BC2E7C5DF0F9EBFE486E9BEE063E8D3B3', u('0x01005B200543327G2E1BC2E7C5DF0F9EBFE486E9BEE063E8D3B332752E1BC2E7C5DF0F9EBFE486E9BEE063E8D3B3'), ] @@ -1187,10 +1187,10 @@ class nthash_test(HandlerCase): ('tigger', 'b7e0ea9fbffcf6dd83086e905089effd'), # utf-8 - (b('\xC3\xBC'), '8bd6e4fb88e01009818749c5443ea712'), - (b('\xC3\xBC\xC3\xBC'), 'cc1260adb6985ca749f150c7e0b22063'), - (b('\xE2\x82\xAC'), '030926b781938db4365d46adc7cfbcb8'), - (b('\xE2\x82\xAC\xE2\x82\xAC'),'682467b963bb4e61943e170a04f7db46'), + (b'\xC3\xBC', '8bd6e4fb88e01009818749c5443ea712'), + (b'\xC3\xBC\xC3\xBC', 'cc1260adb6985ca749f150c7e0b22063'), + (b'\xE2\x82\xAC', '030926b781938db4365d46adc7cfbcb8'), + (b'\xE2\x82\xAC\xE2\x82\xAC','682467b963bb4e61943e170a04f7db46'), # # custom @@ -1208,7 +1208,7 @@ class bsd_nthash_test(HandlerCase): known_correct_hashes = [ ('passphrase', '$3$$7f8fe03093cc84b267b109625f6bbf4b'), - (b('\xC3\xBC'), '$3$$8bd6e4fb88e01009818749c5443ea712'), + (b'\xC3\xBC', '$3$$8bd6e4fb88e01009818749c5443ea712'), ] known_unidentified_hashes = [ @@ -1575,7 +1575,7 @@ class scram_test(HandlerCase): def test_90_algs(self): """test parsing of 'algs' setting""" - defaults = dict(salt=b('A')*10, rounds=1000) + defaults = dict(salt=b'A'*10, rounds=1000) def parse(algs, **kwds): for k in defaults: kwds.setdefault(k, defaults[k]) @@ -1601,7 +1601,7 @@ class scram_test(HandlerCase): # alg & checksum mutually exclusive. self.assertRaises(RuntimeError, parse, ['sha-1'], - checksum={"sha-1": b("\x00"*20)}) + checksum={"sha-1": b"\x00"*20}) def test_90_checksums(self): """test internal parsing of 'checksum' keyword""" @@ -1611,7 +1611,7 @@ class scram_test(HandlerCase): # check sha-1 is required self.assertRaises(ValueError, self.handler, use_defaults=True, - checksum={'sha-256': b('X')*32}) + checksum={'sha-256': b'X'*32}) # XXX: anything else that's not tested by the other code already? @@ -1621,10 +1621,10 @@ class scram_test(HandlerCase): # return appropriate value or throw KeyError h = "$scram$10$AAAAAA$sha-1=AQ,bbb=Ag,ccc=Aw" - s = b('\x00')*4 - self.assertEqual(edi(h,"SHA1"), (s,10, b('\x01'))) - self.assertEqual(edi(h,"bbb"), (s,10, b('\x02'))) - self.assertEqual(edi(h,"ccc"), (s,10, b('\x03'))) + s = b'\x00'*4 + self.assertEqual(edi(h,"SHA1"), (s,10, b'\x01')) + self.assertEqual(edi(h,"bbb"), (s,10, b'\x02')) + self.assertEqual(edi(h,"ccc"), (s,10, b'\x03')) self.assertRaises(KeyError, edi, h, "ddd") # config strings should cause value error. @@ -1658,16 +1658,16 @@ class scram_test(HandlerCase): hash = self.handler.derive_digest # check various encodings of password work. - s1 = b('\x01\x02\x03') - d1 = b('\xb2\xfb\xab\x82[tNuPnI\x8aZZ\x19\x87\xcen\xe9\xd3') + s1 = b'\x01\x02\x03' + d1 = b'\xb2\xfb\xab\x82[tNuPnI\x8aZZ\x19\x87\xcen\xe9\xd3' self.assertEqual(hash(u("\u2168"), s1, 1000, 'sha-1'), d1) - self.assertEqual(hash(b("\xe2\x85\xa8"), s1, 1000, 'SHA-1'), d1) + self.assertEqual(hash(b"\xe2\x85\xa8", s1, 1000, 'SHA-1'), d1) self.assertEqual(hash(u("IX"), s1, 1000, 'sha1'), d1) - self.assertEqual(hash(b("IX"), s1, 1000, 'SHA1'), d1) + self.assertEqual(hash(b"IX", s1, 1000, 'SHA1'), d1) # check algs self.assertEqual(hash("IX", s1, 1000, 'md5'), - b('3\x19\x18\xc0\x1c/\xa8\xbf\xe4\xa3\xc2\x8eM\xe8od')) + b'3\x19\x18\xc0\x1c/\xa8\xbf\xe4\xa3\xc2\x8eM\xe8od') self.assertRaises(ValueError, hash, "IX", s1, 1000, 'sha-666') # check rounds diff --git a/passlib/tests/test_handlers_bcrypt.py b/passlib/tests/test_handlers_bcrypt.py index d43dfad..4e5a69a 100644 --- a/passlib/tests/test_handlers_bcrypt.py +++ b/passlib/tests/test_handlers_bcrypt.py @@ -14,7 +14,7 @@ from passlib import hash from passlib.utils import repeat_string from passlib.utils.compat import irange, PY3, u, get_method_function from passlib.tests.utils import TestCase, HandlerCase, skipUnless, \ - TEST_MODE, b, UserHandlerMixin, randintgauss, EncodingHandlerMixin + TEST_MODE, UserHandlerMixin, randintgauss, EncodingHandlerMixin from passlib.tests.test_handlers import UPASS_WAV, UPASS_USD, UPASS_TABLE # module @@ -52,21 +52,21 @@ class _bcrypt_test(HandlerCase): ('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' '0123456789chars after 72 are ignored', '$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui'), - (b('\xa3'), + (b'\xa3', '$2a$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq'), - (b('\xff\xa3345'), + (b'\xff\xa3345', '$2a$05$/OK.fbVrR/bpIqNJ5ianF.nRht2l/HRhr6zmCp9vYUvvsqynflf9e'), - (b('\xa3ab'), + (b'\xa3ab', '$2a$05$/OK.fbVrR/bpIqNJ5ianF.6IflQkJytoRVc1yuaNtHfiuq.FRlSIS'), - (b('\xaa')*72 + b('chars after 72 are ignored as usual'), + (b'\xaa'*72 + b'chars after 72 are ignored as usual', '$2a$05$/OK.fbVrR/bpIqNJ5ianF.swQOIzjOiJ9GHEPuhEkvqrUyvWhEMx6'), - (b('\xaa\x55'*36), + (b'\xaa\x55'*36, '$2a$05$/OK.fbVrR/bpIqNJ5ianF.R9xrDjiycxMbQE2bp.vgqlYpW5wx2yy'), - (b('\x55\xaa\xff'*24), + (b'\x55\xaa\xff'*24, '$2a$05$/OK.fbVrR/bpIqNJ5ianF.9tQZzcJfm3uj2NvJ/n5xkhpqLrMpWCe'), # keeping one of their 2y tests, because we are supporting that. - (b('\xa3'), + (b'\xa3', '$2y$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq'), # diff --git a/passlib/tests/test_handlers_django.py b/passlib/tests/test_handlers_django.py index d6ac220..c647ff7 100644 --- a/passlib/tests/test_handlers_django.py +++ b/passlib/tests/test_handlers_django.py @@ -13,7 +13,7 @@ from passlib import hash from passlib.utils import repeat_string from passlib.utils.compat import irange, PY3, u, get_method_function from passlib.tests.utils import TestCase, HandlerCase, skipUnless, \ - TEST_MODE, b, UserHandlerMixin, randintgauss, EncodingHandlerMixin + TEST_MODE, UserHandlerMixin, randintgauss, EncodingHandlerMixin from passlib.tests.test_handlers import UPASS_WAV, UPASS_USD, UPASS_TABLE # module diff --git a/passlib/tests/test_pwd.py b/passlib/tests/test_pwd.py index 914a50f..8105ac5 100644 --- a/passlib/tests/test_pwd.py +++ b/passlib/tests/test_pwd.py @@ -38,10 +38,10 @@ class UtilsTest(TestCase): self.assertEqual(_average_entropy("abcd"), 2) self.assertEqual(_average_entropy("abcd"*8), 2) - self.assertAlmostEqual(_average_entropy("abcdaaaa"), 1.5488, 4) + self.assertAlmostEqual(_average_entropy("abcdaaaa"), 1.5488, delta=4) self.assertEqual(_average_entropy("abcd", True), 8) self.assertEqual(_average_entropy("abcd"*8, True), 64) - self.assertAlmostEqual(_average_entropy("abcdaaaa", True), 12.3904, 4) + self.assertAlmostEqual(_average_entropy("abcdaaaa", True), 12.3904, delta=4) #============================================================================= # generation diff --git a/passlib/tests/test_registry.py b/passlib/tests/test_registry.py index 6e96e63..16209cc 100644 --- a/passlib/tests/test_registry.py +++ b/passlib/tests/test_registry.py @@ -13,7 +13,7 @@ from passlib import hash, registry from passlib.registry import register_crypt_handler, register_crypt_handler_path, \ get_crypt_handler, list_crypt_handlers, _unload_handler_name as unload_handler_name import passlib.utils.handlers as uh -from passlib.tests.utils import TestCase, catch_warnings +from passlib.tests.utils import TestCase # module log = getLogger(__name__) @@ -117,7 +117,7 @@ class RegistryTest(TestCase): # TODO: check lazy load which calls register_crypt_handler (warning should be issued) sys.modules.pop("passlib.tests._test_bad_register", None) register_crypt_handler_path("dummy_bad", "passlib.tests._test_bad_register") - with catch_warnings(): + with warnings.catch_warnings(): warnings.filterwarnings("ignore", "xxxxxxxxxx", DeprecationWarning) h = get_crypt_handler("dummy_bad") from passlib.tests import _test_bad_register as tbr @@ -168,7 +168,7 @@ class RegistryTest(TestCase): register_crypt_handler(dummy_1) self.assertIs(get_crypt_handler("dummy_1"), dummy_1) - with catch_warnings(): + with warnings.catch_warnings(): warnings.filterwarnings("ignore", "handler names should be lower-case, and use underscores instead of hyphens:.*", UserWarning) # already loaded handler, using incorrect name diff --git a/passlib/tests/test_totp.py b/passlib/tests/test_totp.py index ce049f3..70944b7 100644 --- a/passlib/tests/test_totp.py +++ b/passlib/tests/test_totp.py @@ -15,7 +15,7 @@ import time as _time # pkg from passlib import exc from passlib.utils import to_bytes, to_unicode -from passlib.utils.compat import unicode, u, b +from passlib.utils.compat import unicode, u from passlib.tests.utils import TestCase # local __all__ = [ diff --git a/passlib/tests/test_utils.py b/passlib/tests/test_utils.py index d68fee3..4985801 100644 --- a/passlib/tests/test_utils.py +++ b/passlib/tests/test_utils.py @@ -4,18 +4,13 @@ #============================================================================= from __future__ import with_statement # core -from binascii import unhexlify import random # site # pkg # module -from passlib.utils.compat import b, bytes, irange, PY3, u, \ - unicode, join_bytes, SUPPORTS_DIR_METHOD +from passlib.utils.compat import irange, PY3, u, unicode, join_bytes from passlib.tests.utils import TestCase -def hb(source): - return unhexlify(b(source)) - #============================================================================= # byte funcs #============================================================================= @@ -33,9 +28,8 @@ class MiscTest(TestCase): # test synthentic dir() dir(compat) - if SUPPORTS_DIR_METHOD: - self.assertTrue('UnicodeIO' in dir(compat)) - self.assertTrue('irange' in dir(compat)) + self.assertTrue('UnicodeIO' in dir(compat)) + self.assertTrue('irange' in dir(compat)) def test_classproperty(self): from passlib.utils import classproperty @@ -127,8 +121,8 @@ class MiscTest(TestCase): self.assertEqual(sorted(set(x)), [u('a'),u('b'),u('c')]) # bytes - x = f(b('abc'), 32) - y = f(b('abc'), 32) + x = f(b'abc', 32) + y = f(b'abc', 32) self.assertIsInstance(x, bytes) self.assertNotEqual(x,y) # NOTE: decoding this due to py3 bytes @@ -179,15 +173,15 @@ class MiscTest(TestCase): # test ascii password h1 = u('aaqPiZY5xR5l.') self.assertEqual(safe_crypt(u('test'), u('aa')), h1) - self.assertEqual(safe_crypt(b('test'), b('aa')), h1) + self.assertEqual(safe_crypt(b'test', b'aa'), h1) # test utf-8 / unicode password h2 = u('aahWwbrUsKZk.') self.assertEqual(safe_crypt(u('test\u1234'), 'aa'), h2) - self.assertEqual(safe_crypt(b('test\xe1\x88\xb4'), 'aa'), h2) + self.assertEqual(safe_crypt(b'test\xe1\x88\xb4', 'aa'), h2) # test latin-1 password - hash = safe_crypt(b('test\xff'), 'aa') + hash = safe_crypt(b'test\xff', 'aa') if PY3: # py3 supports utf-8 bytes only. self.assertEqual(hash, None) else: # but py2 is fine. @@ -224,18 +218,18 @@ class MiscTest(TestCase): from passlib.utils import consteq # ensure error raises for wrong types - self.assertRaises(TypeError, consteq, u(''), b('')) + self.assertRaises(TypeError, consteq, u(''), b'') self.assertRaises(TypeError, consteq, u(''), 1) self.assertRaises(TypeError, consteq, u(''), None) - self.assertRaises(TypeError, consteq, b(''), u('')) - self.assertRaises(TypeError, consteq, b(''), 1) - self.assertRaises(TypeError, consteq, b(''), None) + self.assertRaises(TypeError, consteq, b'', u('')) + self.assertRaises(TypeError, consteq, b'', 1) + self.assertRaises(TypeError, consteq, b'', None) self.assertRaises(TypeError, consteq, None, u('')) - self.assertRaises(TypeError, consteq, None, b('')) + self.assertRaises(TypeError, consteq, None, b'') self.assertRaises(TypeError, consteq, 1, u('')) - self.assertRaises(TypeError, consteq, 1, b('')) + self.assertRaises(TypeError, consteq, 1, b'') # check equal inputs compare correctly for value in [ @@ -309,7 +303,7 @@ class MiscTest(TestCase): # invalid types self.assertRaises(TypeError, sp, None) self.assertRaises(TypeError, sp, 1) - self.assertRaises(TypeError, sp, b('')) + self.assertRaises(TypeError, sp, b'') # empty strings self.assertEqual(sp(u('')), u('')) @@ -404,37 +398,37 @@ class CodecTest(TestCase): import __builtin__ as builtins self.assertIs(bytes, builtins.str) - self.assertIsInstance(b(''), bytes) - self.assertIsInstance(b('\x00\xff'), bytes) + self.assertIsInstance(b'', bytes) + self.assertIsInstance(b'\x00\xff', bytes) if PY3: - self.assertEqual(b('\x00\xff').decode("latin-1"), "\x00\xff") + self.assertEqual(b'\x00\xff'.decode("latin-1"), "\x00\xff") else: - self.assertEqual(b('\x00\xff'), "\x00\xff") + self.assertEqual(b'\x00\xff', "\x00\xff") def test_to_bytes(self): """test to_bytes()""" from passlib.utils import to_bytes # check unicode inputs - self.assertEqual(to_bytes(u('abc')), b('abc')) - self.assertEqual(to_bytes(u('\x00\xff')), b('\x00\xc3\xbf')) + self.assertEqual(to_bytes(u('abc')), b'abc') + self.assertEqual(to_bytes(u('\x00\xff')), b'\x00\xc3\xbf') # check unicode w/ encodings - self.assertEqual(to_bytes(u('\x00\xff'), 'latin-1'), b('\x00\xff')) + self.assertEqual(to_bytes(u('\x00\xff'), 'latin-1'), b'\x00\xff') self.assertRaises(ValueError, to_bytes, u('\x00\xff'), 'ascii') # check bytes inputs - self.assertEqual(to_bytes(b('abc')), b('abc')) - self.assertEqual(to_bytes(b('\x00\xff')), b('\x00\xff')) - self.assertEqual(to_bytes(b('\x00\xc3\xbf')), b('\x00\xc3\xbf')) + self.assertEqual(to_bytes(b'abc'), b'abc') + self.assertEqual(to_bytes(b'\x00\xff'), b'\x00\xff') + self.assertEqual(to_bytes(b'\x00\xc3\xbf'), b'\x00\xc3\xbf') # check byte inputs ignores enocding - self.assertEqual(to_bytes(b('\x00\xc3\xbf'), "latin-1"), - b('\x00\xc3\xbf')) + self.assertEqual(to_bytes(b'\x00\xc3\xbf', "latin-1"), + b'\x00\xc3\xbf') # check bytes transcoding - self.assertEqual(to_bytes(b('\x00\xc3\xbf'), "latin-1", "", "utf-8"), - b('\x00\xff')) + self.assertEqual(to_bytes(b'\x00\xc3\xbf', "latin-1", "", "utf-8"), + b'\x00\xff') # check other self.assertRaises(AssertionError, to_bytes, 'abc', None) @@ -452,11 +446,11 @@ class CodecTest(TestCase): self.assertEqual(to_unicode(u('\x00\xff'), "ascii"), u('\x00\xff')) # check bytes input - self.assertEqual(to_unicode(b('abc')), u('abc')) - self.assertEqual(to_unicode(b('\x00\xc3\xbf')), u('\x00\xff')) - self.assertEqual(to_unicode(b('\x00\xff'), 'latin-1'), + self.assertEqual(to_unicode(b'abc'), u('abc')) + self.assertEqual(to_unicode(b'\x00\xc3\xbf'), u('\x00\xff')) + self.assertEqual(to_unicode(b'\x00\xff', 'latin-1'), u('\x00\xff')) - self.assertRaises(ValueError, to_unicode, b('\x00\xff')) + self.assertRaises(ValueError, to_unicode, b'\x00\xff') # check other self.assertRaises(AssertionError, to_unicode, 'abc', None) @@ -468,26 +462,26 @@ class CodecTest(TestCase): # test plain ascii self.assertEqual(to_native_str(u('abc'), 'ascii'), 'abc') - self.assertEqual(to_native_str(b('abc'), 'ascii'), 'abc') + self.assertEqual(to_native_str(b'abc', 'ascii'), 'abc') # test invalid ascii if PY3: self.assertEqual(to_native_str(u('\xE0'), 'ascii'), '\xE0') - self.assertRaises(UnicodeDecodeError, to_native_str, b('\xC3\xA0'), + self.assertRaises(UnicodeDecodeError, to_native_str, b'\xC3\xA0', 'ascii') else: self.assertRaises(UnicodeEncodeError, to_native_str, u('\xE0'), 'ascii') - self.assertEqual(to_native_str(b('\xC3\xA0'), 'ascii'), '\xC3\xA0') + self.assertEqual(to_native_str(b'\xC3\xA0', 'ascii'), '\xC3\xA0') # test latin-1 self.assertEqual(to_native_str(u('\xE0'), 'latin-1'), '\xE0') - self.assertEqual(to_native_str(b('\xE0'), 'latin-1'), '\xE0') + self.assertEqual(to_native_str(b'\xE0', 'latin-1'), '\xE0') # test utf-8 self.assertEqual(to_native_str(u('\xE0'), 'utf-8'), '\xE0' if PY3 else '\xC3\xA0') - self.assertEqual(to_native_str(b('\xC3\xA0'), 'utf-8'), + self.assertEqual(to_native_str(b'\xC3\xA0', 'utf-8'), '\xE0' if PY3 else '\xC3\xA0') # other types rejected @@ -496,9 +490,9 @@ class CodecTest(TestCase): def test_is_ascii_safe(self): """test is_ascii_safe()""" from passlib.utils import is_ascii_safe - self.assertTrue(is_ascii_safe(b("\x00abc\x7f"))) + self.assertTrue(is_ascii_safe(b"\x00abc\x7f")) self.assertTrue(is_ascii_safe(u("\x00abc\x7f"))) - self.assertFalse(is_ascii_safe(b("\x00abc\x80"))) + self.assertFalse(is_ascii_safe(b"\x00abc\x80")) self.assertFalse(is_ascii_safe(u("\x00abc\x80"))) def test_is_same_codec(self): @@ -560,7 +554,7 @@ class _Base64Test(TestCase): encoded_ints = None # invalid encoded byte - bad_byte = b("?") + bad_byte = b"?" # helper to generate bytemap-specific strings def m(self, *offsets): @@ -602,7 +596,7 @@ class _Base64Test(TestCase): engine = self.engine m = self.m decode = engine.decode_bytes - BNULL = b("\x00") + BNULL = b"\x00" # length == 2 mod 4: 4 bits of padding self.assertEqual(decode(m(0,0)), BNULL) @@ -727,13 +721,13 @@ class _Base64Test(TestCase): transposed = [ # orig, result, transpose map - (b("\x33\x22\x11"), b("\x11\x22\x33"),[2,1,0]), - (b("\x22\x33\x11"), b("\x11\x22\x33"),[1,2,0]), + (b"\x33\x22\x11", b"\x11\x22\x33",[2,1,0]), + (b"\x22\x33\x11", b"\x11\x22\x33",[1,2,0]), ] transposed_dups = [ # orig, result, transpose projection - (b("\x11\x11\x22"), b("\x11\x22\x33"),[0,0,1]), + (b"\x11\x11\x22", b"\x11\x22\x33",[0,0,1]), ] def test_encode_transposed_bytes(self): @@ -867,22 +861,22 @@ class H64_Test(_Base64Test): encoded_data = [ # test lengths 0..6 to ensure tail is encoded properly - (b(""),b("")), - (b("\x55"),b("J/")), - (b("\x55\xaa"),b("Jd8")), - (b("\x55\xaa\x55"),b("JdOJ")), - (b("\x55\xaa\x55\xaa"),b("JdOJe0")), - (b("\x55\xaa\x55\xaa\x55"),b("JdOJeK3")), - (b("\x55\xaa\x55\xaa\x55\xaa"),b("JdOJeKZe")), + (b"",b""), + (b"\x55",b"J/"), + (b"\x55\xaa",b"Jd8"), + (b"\x55\xaa\x55",b"JdOJ"), + (b"\x55\xaa\x55\xaa",b"JdOJe0"), + (b"\x55\xaa\x55\xaa\x55",b"JdOJeK3"), + (b"\x55\xaa\x55\xaa\x55\xaa",b"JdOJeKZe"), # test padding bits are null - (b("\x55\xaa\x55\xaf"),b("JdOJj0")), # len = 1 mod 3 - (b("\x55\xaa\x55\xaa\x5f"),b("JdOJey3")), # len = 2 mod 3 + (b"\x55\xaa\x55\xaf",b"JdOJj0"), # len = 1 mod 3 + (b"\x55\xaa\x55\xaa\x5f",b"JdOJey3"), # len = 2 mod 3 ] encoded_ints = [ - (b("z."), 63, 12), - (b(".z"), 4032, 12), + (b"z.", 63, 12), + (b".z", 4032, 12), ] class H64Big_Test(_Base64Test): @@ -892,22 +886,22 @@ class H64Big_Test(_Base64Test): encoded_data = [ # test lengths 0..6 to ensure tail is encoded properly - (b(""),b("")), - (b("\x55"),b("JE")), - (b("\x55\xaa"),b("JOc")), - (b("\x55\xaa\x55"),b("JOdJ")), - (b("\x55\xaa\x55\xaa"),b("JOdJeU")), - (b("\x55\xaa\x55\xaa\x55"),b("JOdJeZI")), - (b("\x55\xaa\x55\xaa\x55\xaa"),b("JOdJeZKe")), + (b"",b""), + (b"\x55",b"JE"), + (b"\x55\xaa",b"JOc"), + (b"\x55\xaa\x55",b"JOdJ"), + (b"\x55\xaa\x55\xaa",b"JOdJeU"), + (b"\x55\xaa\x55\xaa\x55",b"JOdJeZI"), + (b"\x55\xaa\x55\xaa\x55\xaa",b"JOdJeZKe"), # test padding bits are null - (b("\x55\xaa\x55\xaf"),b("JOdJfk")), # len = 1 mod 3 - (b("\x55\xaa\x55\xaa\x5f"),b("JOdJeZw")), # len = 2 mod 3 + (b"\x55\xaa\x55\xaf",b"JOdJfk"), # len = 1 mod 3 + (b"\x55\xaa\x55\xaa\x5f",b"JOdJeZw"), # len = 2 mod 3 ] encoded_ints = [ - (b(".z"), 63, 12), - (b("z."), 4032, 12), + (b".z", 63, 12), + (b"z.", 4032, 12), ] #============================================================================= diff --git a/passlib/tests/test_utils_crypto.py b/passlib/tests/test_utils_crypto.py index 4829ee5..de50b7a 100644 --- a/passlib/tests/test_utils_crypto.py +++ b/passlib/tests/test_utils_crypto.py @@ -14,14 +14,21 @@ except ImportError: M2Crypto = None # pkg # module -from passlib.utils.compat import b, bascii_to_str, PY3, u, PYPY, JYTHON -from passlib.tests.utils import TestCase, TEST_MODE, catch_warnings, skipUnless +from passlib.utils.compat import bascii_to_str, PY3, u, JYTHON +from passlib.tests.utils import TestCase, TEST_MODE, skipUnless #============================================================================= # support #============================================================================= def hb(source): - return unhexlify(b(source)) + """ + helper for represent byte strings in hex. + + usage: ``hb("deadbeef23")`` + """ + if PY3: + source = source.encode("ascii") + return unhexlify(source) #============================================================================= # test assorted crypto helpers @@ -56,11 +63,11 @@ class CryptoTest(TestCase): # test types self.assertEqual(norm_hash_name(u("MD4")), "md4") - self.assertEqual(norm_hash_name(b("MD4")), "md4") + self.assertEqual(norm_hash_name(b"MD4"), "md4") self.assertRaises(TypeError, norm_hash_name, None) # test selected results - with catch_warnings(): + with warnings.catch_warnings(): warnings.filterwarnings("ignore", '.*unknown hash') for row in chain(_nhn_hash_names, self.ndn_values): for idx, format in enumerate(self.ndn_formats): @@ -93,8 +100,8 @@ class CryptoTest(TestCase): record = get_hash_info("sha") const = record[0] self.assertEqual(record, (const, 20, 64)) - self.assertEqual(hexlify(const(b("abc")).digest()), - b("0164b8a914cd2a5e74c4f7ff082c4d97f1edf880")) + self.assertEqual(hexlify(const(b"abc").digest()), + b"0164b8a914cd2a5e74c4f7ff082c4d97f1edf880") else: self.assertRaises(ValueError, get_hash_info, "sha") @@ -111,8 +118,8 @@ class CryptoTest(TestCase): from passlib.utils.md4 import md4 self.assertIs(const, md4) self.assertEqual(record, (const, 16, 64)) - self.assertEqual(hexlify(const(b("abc")).digest()), - b("a448017aaf21d8525fc10ae87aa6729d")) + self.assertEqual(hexlify(const(b"abc").digest()), + b"a448017aaf21d8525fc10ae87aa6729d") # 4. unknown names should be rejected self.assertRaises(ValueError, get_hash_info, "xxx256") @@ -186,11 +193,11 @@ class DesTest(TestCase): # too large self.assertRaises(ValueError, expand_des_key, INT_56_MASK+1) - self.assertRaises(ValueError, expand_des_key, b("\x00")*8) + self.assertRaises(ValueError, expand_des_key, b"\x00"*8) # too small self.assertRaises(ValueError, expand_des_key, -1) - self.assertRaises(ValueError, expand_des_key, b("\x00")*6) + self.assertRaises(ValueError, expand_des_key, b"\x00"*6) def test_02_shrink(self): """test shrink_des_key()""" @@ -211,11 +218,11 @@ class DesTest(TestCase): # too large self.assertRaises(ValueError, shrink_des_key, INT_64_MASK+1) - self.assertRaises(ValueError, shrink_des_key, b("\x00")*9) + self.assertRaises(ValueError, shrink_des_key, b"\x00"*9) # too small self.assertRaises(ValueError, shrink_des_key, -1) - self.assertRaises(ValueError, shrink_des_key, b("\x00")*7) + self.assertRaises(ValueError, shrink_des_key, b"\x00"*7) def _random_parity(self, key): """randomize parity bits""" @@ -254,13 +261,13 @@ class DesTest(TestCase): (key, key3, plaintext)) # check invalid keys - stub = b('\x00') * 8 + stub = b'\x00' * 8 self.assertRaises(TypeError, des_encrypt_block, 0, stub) - self.assertRaises(ValueError, des_encrypt_block, b('\x00')*6, stub) + self.assertRaises(ValueError, des_encrypt_block, b'\x00'*6, stub) # check invalid input self.assertRaises(TypeError, des_encrypt_block, stub, 0) - self.assertRaises(ValueError, des_encrypt_block, stub, b('\x00')*7) + self.assertRaises(ValueError, des_encrypt_block, stub, b'\x00'*7) # check invalid salts self.assertRaises(ValueError, des_encrypt_block, stub, stub, salt=-1) @@ -288,11 +295,11 @@ class DesTest(TestCase): (key, key3, plaintext)) # check invalid keys - self.assertRaises(TypeError, des_encrypt_int_block, b('\x00'), 0) + self.assertRaises(TypeError, des_encrypt_int_block, b'\x00', 0) self.assertRaises(ValueError, des_encrypt_int_block, -1, 0) # check invalid input - self.assertRaises(TypeError, des_encrypt_int_block, 0, b('\x00')) + self.assertRaises(TypeError, des_encrypt_int_block, 0, b'\x00') self.assertRaises(ValueError, des_encrypt_int_block, 0, -1) # check invalid salts @@ -321,19 +328,19 @@ class _MD4_Test(TestCase): vectors = [ # input -> hex digest # test vectors from http://www.faqs.org/rfcs/rfc1320.html - A.5 - (b(""), "31d6cfe0d16ae931b73c59d7e0c089c0"), - (b("a"), "bde52cb31de33e46245e05fbdbd6fb24"), - (b("abc"), "a448017aaf21d8525fc10ae87aa6729d"), - (b("message digest"), "d9130a8164549fe818874806e1c7014b"), - (b("abcdefghijklmnopqrstuvwxyz"), "d79e1c308aa5bbcdeea8ed63df412da9"), - (b("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), "043f8582f241db351ce627e153e7f0e4"), - (b("12345678901234567890123456789012345678901234567890123456789012345678901234567890"), "e33b4ddc9c38f2199c3e7b164fcc0536"), + (b"", "31d6cfe0d16ae931b73c59d7e0c089c0"), + (b"a", "bde52cb31de33e46245e05fbdbd6fb24"), + (b"abc", "a448017aaf21d8525fc10ae87aa6729d"), + (b"message digest", "d9130a8164549fe818874806e1c7014b"), + (b"abcdefghijklmnopqrstuvwxyz", "d79e1c308aa5bbcdeea8ed63df412da9"), + (b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "043f8582f241db351ce627e153e7f0e4"), + (b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", "e33b4ddc9c38f2199c3e7b164fcc0536"), ] def test_md4_update(self): """test md4 update""" from passlib.utils.md4 import md4 - h = md4(b('')) + h = md4(b'') self.assertEqual(h.hexdigest(), "31d6cfe0d16ae931b73c59d7e0c089c0") # NOTE: under py2, hashlib methods try to encode to ascii, @@ -341,10 +348,10 @@ class _MD4_Test(TestCase): if PY3 or self._disable_native: self.assertRaises(TypeError, h.update, u('x')) - h.update(b('a')) + h.update(b'a') self.assertEqual(h.hexdigest(), "bde52cb31de33e46245e05fbdbd6fb24") - h.update(b('bcdefghijklmnopqrstuvwxyz')) + h.update(b'bcdefghijklmnopqrstuvwxyz') self.assertEqual(h.hexdigest(), "d79e1c308aa5bbcdeea8ed63df412da9") def test_md4_hexdigest(self): @@ -364,13 +371,13 @@ class _MD4_Test(TestCase): def test_md4_copy(self): """test md4 copy()""" from passlib.utils.md4 import md4 - h = md4(b('abc')) + h = md4(b'abc') h2 = h.copy() - h2.update(b('def')) + h2.update(b'def') self.assertEqual(h2.hexdigest(), '804e7f1c2586e50b49ac65db5b645131') - h.update(b('ghi')) + h.update(b'ghi') self.assertEqual(h.hexdigest(), 'c5225580bfe176f6deeee33dee98732c') # create subclasses to test with and without native backend @@ -397,21 +404,21 @@ class Pbkdf1_Test(TestCase): # # from http://www.di-mgt.com.au/cryptoKDFs.html # - (b('password'), hb('78578E5A5D63CB06'), 1000, 16, 'sha1', hb('dc19847e05c64d2faf10ebfb4a3d2a20')), + (b'password', hb('78578E5A5D63CB06'), 1000, 16, 'sha1', hb('dc19847e05c64d2faf10ebfb4a3d2a20')), # # custom # - (b('password'), b('salt'), 1000, 0, 'md5', b('')), - (b('password'), b('salt'), 1000, 1, 'md5', hb('84')), - (b('password'), b('salt'), 1000, 8, 'md5', hb('8475c6a8531a5d27')), - (b('password'), b('salt'), 1000, 16, 'md5', hb('8475c6a8531a5d27e386cd496457812c')), - (b('password'), b('salt'), 1000, None, 'md5', hb('8475c6a8531a5d27e386cd496457812c')), - (b('password'), b('salt'), 1000, None, 'sha1', hb('4a8fd48e426ed081b535be5769892fa396293efb')), + (b'password', b'salt', 1000, 0, 'md5', b''), + (b'password', b'salt', 1000, 1, 'md5', hb('84')), + (b'password', b'salt', 1000, 8, 'md5', hb('8475c6a8531a5d27')), + (b'password', b'salt', 1000, 16, 'md5', hb('8475c6a8531a5d27e386cd496457812c')), + (b'password', b'salt', 1000, None, 'md5', hb('8475c6a8531a5d27e386cd496457812c')), + (b'password', b'salt', 1000, None, 'sha1', hb('4a8fd48e426ed081b535be5769892fa396293efb')), ] - if not (PYPY or JYTHON): + if not JYTHON: pbkdf1_tests.append( - (b('password'), b('salt'), 1000, None, 'md4', hb('f7f2e91100a8f96190f2dd177cb26453')) + (b'password', b'salt', 1000, None, 'md4', hb('f7f2e91100a8f96190f2dd177cb26453')) ) def test_known(self): @@ -424,7 +431,7 @@ class Pbkdf1_Test(TestCase): def test_border(self): """test border cases""" from passlib.utils.pbkdf2 import pbkdf1 - def helper(secret=b('secret'), salt=b('salt'), rounds=1, keylen=1, hash='md5'): + def helper(secret=b'secret', salt=b'salt', rounds=1, keylen=1, hash='md5'): return pbkdf1(secret, salt, rounds, keylen, hash) helper() @@ -467,43 +474,43 @@ class _Pbkdf2_Test(TestCase): # test case 1 / 128 bit ( hb("cdedb5281bb2f801565a1122b2563515"), - b("password"), b("ATHENA.MIT.EDUraeburn"), 1, 16 + b"password", b"ATHENA.MIT.EDUraeburn", 1, 16 ), # test case 2 / 128 bit ( hb("01dbee7f4a9e243e988b62c73cda935d"), - b("password"), b("ATHENA.MIT.EDUraeburn"), 2, 16 + b"password", b"ATHENA.MIT.EDUraeburn", 2, 16 ), # test case 2 / 256 bit ( hb("01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86"), - b("password"), b("ATHENA.MIT.EDUraeburn"), 2, 32 + b"password", b"ATHENA.MIT.EDUraeburn", 2, 32 ), # test case 3 / 256 bit ( hb("5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13"), - b("password"), b("ATHENA.MIT.EDUraeburn"), 1200, 32 + b"password", b"ATHENA.MIT.EDUraeburn", 1200, 32 ), # test case 4 / 256 bit ( hb("d1daa78615f287e6a1c8b120d7062a493f98d203e6be49a6adf4fa574b6e64ee"), - b("password"), b('\x12\x34\x56\x78\x78\x56\x34\x12'), 5, 32 + b"password", b'\x12\x34\x56\x78\x78\x56\x34\x12', 5, 32 ), # test case 5 / 256 bit ( hb("139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1"), - b("X"*64), b("pass phrase equals block size"), 1200, 32 + b"X"*64, b"pass phrase equals block size", 1200, 32 ), # test case 6 / 256 bit ( hb("9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a"), - b("X"*65), b("pass phrase exceeds block size"), 1200, 32 + b"X"*65, b"pass phrase exceeds block size", 1200, 32 ), # @@ -511,17 +518,17 @@ class _Pbkdf2_Test(TestCase): # ( hb("0c60c80f961f0e71f3a9b524af6012062fe037a6"), - b("password"), b("salt"), 1, 20, + b"password", b"salt", 1, 20, ), ( hb("ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"), - b("password"), b("salt"), 2, 20, + b"password", b"salt", 2, 20, ), ( hb("4b007901b765489abead49d926f721d065a429c1"), - b("password"), b("salt"), 4096, 20, + b"password", b"salt", 4096, 20, ), # just runs too long - could enable if ALL option is set @@ -533,14 +540,14 @@ class _Pbkdf2_Test(TestCase): ( hb("3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"), - b("passwordPASSWORDpassword"), - b("saltSALTsaltSALTsaltSALTsaltSALTsalt"), + b"passwordPASSWORDpassword", + b"saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, 25, ), ( hb("56fa6aa75548099dcc37d7f03425e0c3"), - b("pass\00word"), b("sa\00lt"), 4096, 16, + b"pass\00word", b"sa\00lt", 4096, 16, ), # @@ -550,7 +557,7 @@ class _Pbkdf2_Test(TestCase): hb("887CFF169EA8335235D8004242AA7D6187A41E3187DF0CE14E256D85ED" "97A97357AAA8FF0A3871AB9EEFF458392F462F495487387F685B7472FC" "6C29E293F0A0"), - b("hello"), + b"hello", hb("9290F727ED06C38BA4549EF7DE25CF5642659211B7FC076F2D28FEFD71" "784BB8D8F6FB244A8CC5C06240631B97008565A120764C0EE9C2CB0073" "994D79080136"), @@ -562,11 +569,11 @@ class _Pbkdf2_Test(TestCase): # ( hb('e248fb6b13365146f8ac6307cc222812'), - b("secret"), b("salt"), 10, 16, "hmac-sha1", + b"secret", b"salt", 10, 16, "hmac-sha1", ), ( hb('e248fb6b13365146f8ac6307cc2228127872da6d'), - b("secret"), b("salt"), 10, None, "hmac-sha1", + b"secret", b"salt", 10, None, "hmac-sha1", ), ] @@ -583,7 +590,7 @@ class _Pbkdf2_Test(TestCase): def test_border(self): """test border cases""" from passlib.utils.pbkdf2 import pbkdf2 - def helper(secret=b('password'), salt=b('salt'), rounds=1, keylen=None, prf="hmac-sha1"): + def helper(secret=b'password', salt=b'salt', rounds=1, keylen=None, prf="hmac-sha1"): return pbkdf2(secret, salt, rounds, keylen, prf) helper() @@ -609,7 +616,7 @@ class _Pbkdf2_Test(TestCase): def test_default_keylen(self): """test keylen==None""" from passlib.utils.pbkdf2 import pbkdf2 - def helper(secret=b('password'), salt=b('salt'), rounds=1, keylen=None, prf="hmac-sha1"): + def helper(secret=b'password', salt=b'salt', rounds=1, keylen=None, prf="hmac-sha1"): return pbkdf2(secret, salt, rounds, keylen, prf) self.assertEqual(len(helper(prf='hmac-sha1')), 20) self.assertEqual(len(helper(prf='hmac-sha256')), 32) @@ -618,8 +625,8 @@ class _Pbkdf2_Test(TestCase): """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) + return hashlib.md5(key+msg+b'fooey').digest() + result = pbkdf2(b'secret', b'salt', 1000, 20, prf) self.assertEqual(result, hb('5fe7ce9f7e379d3f65cbc66ba8aa6440474a6849')) #------------------------------------------------------------------------ diff --git a/passlib/tests/test_utils_handlers.py b/passlib/tests/test_utils_handlers.py index b95bc17..013c9e0 100644 --- a/passlib/tests/test_utils_handlers.py +++ b/passlib/tests/test_utils_handlers.py @@ -12,10 +12,10 @@ import warnings # pkg from passlib.hash import ldap_md5, sha256_crypt from passlib.exc import MissingBackendError, PasslibHashWarning -from passlib.utils.compat import b, bytes, str_to_uascii, \ - uascii_to_str, unicode, PY_MAX_25, SUPPORTS_DIR_METHOD +from passlib.utils.compat import str_to_uascii, \ + uascii_to_str, unicode import passlib.utils.handlers as uh -from passlib.tests.utils import HandlerCase, TestCase, catch_warnings +from passlib.tests.utils import HandlerCase, TestCase from passlib.utils.compat import u # module log = getLogger(__name__) @@ -63,11 +63,11 @@ class SkeletonTest(TestCase): # check default identify method self.assertTrue(d1.identify(u('_a'))) - self.assertTrue(d1.identify(b('_a'))) + self.assertTrue(d1.identify(b'_a')) self.assertTrue(d1.identify(u('_b'))) self.assertFalse(d1.identify(u('_c'))) - self.assertFalse(d1.identify(b('_c'))) + self.assertFalse(d1.identify(b'_c')) self.assertFalse(d1.identify(u('a'))) self.assertFalse(d1.identify(u('b'))) self.assertFalse(d1.identify(u('c'))) @@ -78,12 +78,12 @@ class SkeletonTest(TestCase): self.assertIs(d1.genconfig(), None) # check default verify method - self.assertTrue(d1.verify('s', b('_a'))) + self.assertTrue(d1.verify('s', b'_a')) self.assertTrue(d1.verify('s',u('_a'))) - self.assertFalse(d1.verify('s', b('_b'))) + self.assertFalse(d1.verify('s', b'_b')) self.assertFalse(d1.verify('s',u('_b'))) - self.assertTrue(d1.verify('s', b('_b'), flag=True)) - self.assertRaises(ValueError, d1.verify, 's', b('_c')) + self.assertTrue(d1.verify('s', b'_b', flag=True)) + self.assertRaises(ValueError, d1.verify, 's', b'_c') self.assertRaises(ValueError, d1.verify, 's', u('_c')) # check default encrypt method @@ -116,7 +116,7 @@ class SkeletonTest(TestCase): secret = secret.encode("utf-8") if hash is not None and not cls.identify(hash): raise ValueError("invalid hash") - return hashlib.sha1(b("xyz") + secret).hexdigest() + return hashlib.sha1(b"xyz" + secret).hexdigest() @classmethod def verify(cls, secret, hash): if hash is None: @@ -199,11 +199,11 @@ class SkeletonTest(TestCase): self.assertRaises(ValueError, norm_checksum, u('xxyx')) # wrong type - self.assertRaises(TypeError, norm_checksum, b('xxyx')) + self.assertRaises(TypeError, norm_checksum, b'xxyx') # relaxed with self.assertWarningList("checksum should be unicode"): - self.assertEqual(norm_checksum(b('xxzx'), relaxed=True), u('xxzx')) + self.assertEqual(norm_checksum(b'xxzx', relaxed=True), u('xxzx')) self.assertRaises(TypeError, norm_checksum, 1, relaxed=True) # test _stub_checksum behavior @@ -214,20 +214,20 @@ class SkeletonTest(TestCase): class d1(uh.HasRawChecksum, uh.GenericHandler): name = 'd1' checksum_size = 4 - _stub_checksum = b('0')*4 + _stub_checksum = b'0'*4 def norm_checksum(*a, **k): return d1(*a, **k).checksum # test bytes - self.assertEqual(norm_checksum(b('1234')), b('1234')) + self.assertEqual(norm_checksum(b'1234'), b'1234') # test unicode self.assertRaises(TypeError, norm_checksum, u('xxyx')) self.assertRaises(TypeError, norm_checksum, u('xxyx'), relaxed=True) # test _stub_checksum behavior - self.assertIs(norm_checksum(b('0')*4), None) + self.assertIs(norm_checksum(b'0'*4), None) def test_20_norm_salt(self): """test GenericHandler + HasSalt mixin""" @@ -256,7 +256,7 @@ class SkeletonTest(TestCase): self.assertIn(norm_salt(use_defaults=True), salts3) # check explicit salts - with catch_warnings(record=True) as wlog: + with warnings.catch_warnings(record=True) as wlog: # check too-small salts self.assertRaises(ValueError, norm_salt, salt='') @@ -277,7 +277,7 @@ class SkeletonTest(TestCase): self.consumeWarningList(wlog, PasslibHashWarning) # check generated salts - with catch_warnings(record=True) as wlog: + with warnings.catch_warnings(record=True) as wlog: # check too-small salt size self.assertRaises(ValueError, gen_salt, 0) @@ -327,7 +327,7 @@ class SkeletonTest(TestCase): self.assertRaises(TypeError, norm_rounds, rounds=1.5) # check explicit rounds - with catch_warnings(record=True) as wlog: + with warnings.catch_warnings(record=True) as wlog: # too small self.assertRaises(ValueError, norm_rounds, rounds=0) self.consumeWarningList(wlog) @@ -608,9 +608,9 @@ class SkeletonTest(TestCase): h1 = '$pbkdf2$60000$DoEwpvQeA8B4T.k951yLUQ$O26Y3/NJEiLCVaOVPxGXshyjW8k' result = hash.pbkdf2_sha1.parsehash(h1) self.assertEqual(result, dict( - checksum=b(';n\x98\xdf\xf3I\x12"\xc2U\xa3\x95?\x11\x97\xb2\x1c\xa3[\xc9'), + checksum=b';n\x98\xdf\xf3I\x12"\xc2U\xa3\x95?\x11\x97\xb2\x1c\xa3[\xc9', rounds=60000, - salt=b('\x0e\x810\xa6\xf4\x1e\x03\xc0xO\xe9=\xe7\\\x8bQ'), + salt=b'\x0e\x810\xa6\xf4\x1e\x03\xc0xO\xe9=\xe7\\\x8bQ', )) # sanitizing of raw checksums & salts @@ -727,10 +727,7 @@ class PrefixWrapperTest(TestCase): d2 = uh.PrefixWrapper("d2", "sha256_crypt", "{XXX}") self.assertIs(d2.setting_kwds, sha256_crypt.setting_kwds) - if SUPPORTS_DIR_METHOD: - self.assertTrue('max_rounds' in dir(d2)) - else: - self.assertFalse('max_rounds' in dir(d2)) + self.assertTrue('max_rounds' in dir(d2)) def test_11_wrapped_methods(self): d1 = uh.PrefixWrapper("d1", "ldap_md5", "{XXX}", "{MD5}") @@ -835,7 +832,7 @@ class UnsaltedHash(uh.StaticHandler): def _calc_checksum(self, secret): if isinstance(secret, unicode): secret = secret.encode("utf-8") - data = b("boblious") + secret + data = b"boblious" + secret return str_to_uascii(hashlib.sha1(data).hexdigest()) class SaltedHash(uh.HasSalt, uh.GenericHandler): @@ -888,11 +885,7 @@ class UnsaltedHashTest(HandlerCase): ] def test_bad_kwds(self): - if not PY_MAX_25: - # annoyingly, py25's ``super().__init__()`` doesn't throw TypeError - # when passing unknown keywords to object. just ignoring - # this issue for now, since it's a minor border case. - self.assertRaises(TypeError, UnsaltedHash, salt='x') + self.assertRaises(TypeError, UnsaltedHash, salt='x') self.assertRaises(TypeError, UnsaltedHash.genconfig, rounds=1) class SaltedHashTest(HandlerCase): diff --git a/passlib/tests/utils.py b/passlib/tests/utils.py index b0e20b1..b0a0edd 100644 --- a/passlib/tests/utils.py +++ b/passlib/tests/utils.py @@ -12,18 +12,18 @@ import tempfile import threading import time from passlib.exc import PasslibHashWarning -from passlib.utils.compat import PY27, PY_MIN_32, PY3, JYTHON +from passlib.utils.compat import PY3, JYTHON import warnings from warnings import warn # site # pkg from passlib.exc import MissingBackendError import passlib.registry as registry -from passlib.tests.backports import TestCase as _TestCase, catch_warnings, skip, skipIf, skipUnless +from passlib.tests.backports import TestCase as _TestCase, skip, skipIf, skipUnless from passlib.utils import has_rounds_info, has_salt_info, rounds_cost_values, \ classproperty, rng, getrandstr, is_ascii_safe, to_native_str, \ repeat_string, tick -from passlib.utils.compat import b, bytes, iteritems, irange, callable, \ +from passlib.utils.compat import iteritems, irange, \ base_string_types, exc_err, u, unicode, PY2 import passlib.utils.handlers as uh # local @@ -373,7 +373,7 @@ class TestCase(_TestCase): "WarningMessage instance") self.assertEqual(wmsg.lineno, lineno, msg) - class _AssertWarningList(catch_warnings): + class _AssertWarningList(warnings.catch_warnings): """context manager for assertWarningList()""" def __init__(self, case, **kwds): self.case = case @@ -560,7 +560,7 @@ class HandlerCase(TestCase): stock_passwords = [ u("test"), u("\u20AC\u00A5$"), - b('\xe2\x82\xac\xc2\xa5$') + b'\xe2\x82\xac\xc2\xa5$' ] #--------------------------------------------------------------- @@ -591,7 +591,7 @@ class HandlerCase(TestCase): # anything that supports crypt() interface should forbid null chars, # since crypt() uses null-terminated strings. if 'os_crypt' in getattr(cls.handler, "backends", ()): - return b("\x00") + return b"\x00" return None #=================================================================== @@ -1137,7 +1137,7 @@ class HandlerCase(TestCase): # should accept too-large salt in relaxed mode # if has_relaxed_setting(handler): - with catch_warnings(record=True): # issues passlibhandlerwarning + with warnings.catch_warnings(record=True): # issues passlibhandlerwarning c2 = self.do_genconfig(salt=s2, relaxed=True) self.assertEqual(c2, c1) @@ -1213,7 +1213,7 @@ class HandlerCase(TestCase): # bytes should be accepted only if salt_type is bytes, # OR if salt type is unicode and running PY2 - to allow native strings. if not (salt_type is bytes or (PY2 and salt_type is unicode)): - self.assertRaises(TypeError, self.do_encrypt, 'stub', salt=b('x')) + self.assertRaises(TypeError, self.do_encrypt, 'stub', salt=b'x') #=================================================================== # rounds @@ -1644,7 +1644,7 @@ class HandlerCase(TestCase): # # test hash='' is rejected for all but the plaintext hashes # - for hash in [u(''), b('')]: + for hash in [u(''), b'']: if self.accepts_all_hashes: # then it accepts empty string as well. self.assertTrue(self.do_identify(hash)) @@ -2228,7 +2228,7 @@ class EncodingHandlerMixin(HandlerCase): # so different encodings can be tested safely. stock_passwords = [ u("test"), - b("test"), + b"test", u("\u00AC\u00BA"), ] @@ -2247,7 +2247,7 @@ class EncodingHandlerMixin(HandlerCase): #============================================================================= # warnings helpers #============================================================================= -class reset_warnings(catch_warnings): +class reset_warnings(warnings.catch_warnings): """catch_warnings() wrapper which clears warning registry & filters""" def __init__(self, reset_filter="always", reset_registry=".*", **kwds): super(reset_warnings, self).__init__(**kwds) diff --git a/passlib/totp.py b/passlib/totp.py index 0265f58..e3932de 100644 --- a/passlib/totp.py +++ b/passlib/totp.py @@ -23,7 +23,7 @@ from passlib import exc from passlib.utils import (to_unicode, to_bytes, consteq, memoized_property, getrandbytes, rng, xor_bytes) from passlib.utils.compat import (u, unicode, bascii_to_str, int_types, num_types, - irange, bytes, byte_elem_value, UnicodeIO) + irange, byte_elem_value, UnicodeIO) from passlib.utils.pbkdf2 import get_prf, norm_hash_name, pbkdf2 # local __all__ = [ diff --git a/passlib/utils/__init__.py b/passlib/utils/__init__.py index de3e9f2..70b7873 100644 --- a/passlib/utils/__init__.py +++ b/passlib/utils/__init__.py @@ -2,7 +2,7 @@ #============================================================================= # imports #============================================================================= -from passlib.utils.compat import PYPY, JYTHON +from passlib.utils.compat import JYTHON # core from base64 import b64encode, b64decode from codecs import lookup as _lookup_codec @@ -30,13 +30,12 @@ from warnings import warn # site # pkg from passlib.exc import ExpectedStringError -from passlib.utils.compat import add_doc, b, bytes, join_bytes, join_byte_values, \ +from passlib.utils.compat import add_doc, join_bytes, join_byte_values, \ join_byte_elems, exc_err, irange, imap, PY3, u, \ - join_unicode, unicode, byte_elem_value, PY_MIN_32, next_method_attr + join_unicode, unicode, byte_elem_value, next_method_attr # local __all__ = [ # constants - 'PYPY', 'JYTHON', 'sys_bits', 'unix_crypt_schemes', @@ -110,7 +109,7 @@ rounds_cost_values = [ "linear", "log2" ] from passlib.exc import MissingBackendError # internal helpers -_BEMPTY = b('') +_BEMPTY = b'' _UEMPTY = u("") _USPACE = u(" ") @@ -482,7 +481,8 @@ def render_bytes(source, *args): else arg for arg in args) return result.encode("latin-1") -if PY_MIN_32: +if PY3: + # new in py32 def bytes_to_int(value): return int.from_bytes(value, 'big') def int_to_bytes(value, count): @@ -492,13 +492,8 @@ else: from binascii import hexlify, unhexlify def bytes_to_int(value): return int(hexlify(value),16) - if PY3: - # grr, why did py3 have to break % for bytes? - def int_to_bytes(value, count): - return unhexlify((('%%0%dx' % (count<<1)) % value).encode("ascii")) - else: - def int_to_bytes(value, count): - return unhexlify(('%%0%dx' % (count<<1)) % value) + def int_to_bytes(value, count): + return unhexlify(('%%0%dx' % (count<<1)) % value) 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") @@ -516,7 +511,7 @@ def repeat_string(source, size): else: return source[:size] -_BNULL = b("\x00") +_BNULL = b"\x00" _UNULL = u("\x00") def right_pad_string(source, size, pad=None): @@ -532,7 +527,7 @@ def right_pad_string(source, size, pad=None): #============================================================================= # encoding helpers #============================================================================= -_ASCII_TEST_BYTES = b("\x00\n aA:#!\x7f") +_ASCII_TEST_BYTES = b"\x00\n aA:#!\x7f" _ASCII_TEST_UNICODE = _ASCII_TEST_BYTES.decode("ascii") def is_ascii_codec(codec): @@ -547,7 +542,7 @@ def is_same_codec(left, right): return False return _lookup_codec(left).name == _lookup_codec(right).name -_B80 = b('\x80')[0] +_B80 = b'\x80'[0] _U80 = u('\x80') def is_ascii_safe(source): """Check if string (bytes or unicode) contains only 7-bit ascii""" @@ -1290,10 +1285,10 @@ bcrypt64 = LazyBase64Engine(BCRYPT_CHARS, big=True) #============================================================================= # adapted-base64 encoding #============================================================================= -_A64_ALTCHARS = b("./") -_A64_STRIP = b("=\n") -_A64_PAD1 = b("=") -_A64_PAD2 = b("==") +_A64_ALTCHARS = b"./" +_A64_STRIP = b"=\n" +_A64_PAD1 = b"=" +_A64_PAD2 = b"==" def ab64_encode(data): """encode using variant of base64 diff --git a/passlib/utils/_blowfish/__init__.py b/passlib/utils/_blowfish/__init__.py index d7aa19f..73204ca 100644 --- a/passlib/utils/_blowfish/__init__.py +++ b/passlib/utils/_blowfish/__init__.py @@ -55,7 +55,7 @@ from itertools import chain import struct # pkg from passlib.utils import bcrypt64, getrandbytes, rng -from passlib.utils.compat import b, bytes, BytesIO, unicode, u +from passlib.utils.compat import BytesIO, unicode, u from passlib.utils._blowfish.unrolled import BlowfishEngine # local __all__ = [ @@ -82,7 +82,7 @@ digest_struct = struct.Struct(">6I") # interface designed only for use by passlib.handlers.bcrypt:BCrypt # probably not suitable for other purposes #============================================================================= -BNULL = b('\x00') +BNULL = b'\x00' def raw_bcrypt(password, ident, salt, log_rounds): """perform central password hashing step in bcrypt scheme. diff --git a/passlib/utils/_blowfish/base.py b/passlib/utils/_blowfish/base.py index 5621e4c..b0a761e 100644 --- a/passlib/utils/_blowfish/base.py +++ b/passlib/utils/_blowfish/base.py @@ -5,7 +5,6 @@ # core import struct # pkg -from passlib.utils.compat import bytes from passlib.utils import repeat_string # local __all__ = [ diff --git a/passlib/utils/compat.py b/passlib/utils/compat.py index ce61ac9..54e4458 100644 --- a/passlib/utils/compat.py +++ b/passlib/utils/compat.py @@ -9,22 +9,18 @@ import sys PY2 = sys.version_info < (3,0) PY3 = sys.version_info >= (3,0) -PY_MAX_25 = sys.version_info < (2,6) # py 2.5 or earlier -PY27 = sys.version_info[:2] == (2,7) # supports last 2.x release -PY_MIN_32 = sys.version_info >= (3,2) # py 3.2 or later + +# make sure it's not an unsupported version, even if we somehow got this far +if sys.version_info < (2,6) or (3,0) <= sys.version_info < (3,2): + raise RuntimeError("Passlib requires Python 2.6, 2.7, or >= 3.2 (as of passlib 1.7)") #------------------------------------------------------------------------ # python implementation #------------------------------------------------------------------------ -PYPY = hasattr(sys, "pypy_version_info") JYTHON = sys.platform.startswith('java') -#------------------------------------------------------------------------ -# capabilities -#------------------------------------------------------------------------ - -# __dir__() added in py2.6 -SUPPORTS_DIR_METHOD = not PY_MAX_25 and not (PYPY and sys.pypy_version_info < (1,6)) +if hasattr(sys, "pypy_version_info") and sys.pypy_version_info < (2,0): + raise AssertionError("passlib requires pypy >= 2.0 (as of passlib 1.7)") #============================================================================= # common imports @@ -44,7 +40,7 @@ def add_doc(obj, doc): #============================================================================= __all__ = [ # python versions - 'PY2', 'PY3', 'PY_MAX_25', 'PY27', 'PY_MIN_32', + 'PY2', 'PY3', # io 'BytesIO', 'StringIO', 'NativeStringIO', 'SafeConfigParser', @@ -52,14 +48,13 @@ __all__ = [ # type detection ## 'is_mapping', - 'callable', 'int_types', 'num_types', 'base_string_types', # unicode/bytes types & helpers - 'u', 'b', - 'unicode', 'bytes', + 'u', + 'unicode', 'uascii_to_str', 'bascii_to_str', 'str_to_uascii', 'str_to_bascii', 'join_unicode', 'join_bytes', @@ -86,30 +81,21 @@ _lazy_attrs = dict() #============================================================================= if PY3: unicode = str - bytes = builtins.bytes + # TODO: drop python 3.2 support, and use u'' again! def u(s): assert isinstance(s, str) return s - def b(s): - assert isinstance(s, str) - return s.encode("latin-1") - base_string_types = (unicode, bytes) else: unicode = builtins.unicode - bytes = str if PY_MAX_25 else builtins.bytes def u(s): assert isinstance(s, str) return s.decode("unicode_escape") - def b(s): - assert isinstance(s, str) - return s - base_string_types = basestring #============================================================================= @@ -119,7 +105,7 @@ else: join_unicode = u('').join # function to join list of byte strings -join_bytes = b('').join +join_bytes = b''.join if PY3: def uascii_to_str(s): @@ -250,25 +236,6 @@ else: next_method_attr = "next" -if PY_MAX_25: - _undef = object() - def next(itr, default=_undef): - """compat wrapper for next()""" - if default is _undef: - return itr.next() - try: - return itr.next() - except StopIteration: - return default - def chain_from_iterable(itr): - for subitr in itr: - for elem in subitr: - yield elem -else: - from itertools import chain - next = builtins.next - chain_from_iterable = chain.from_iterable - #============================================================================= # typing #============================================================================= @@ -276,14 +243,6 @@ else: ## # non-exhaustive check, enough to distinguish from lists, etc ## return hasattr(obj, "items") -if (3,0) <= sys.version_info < (3,2): - # callable isn't dead, it's just resting - from collections import Callable - def callable(obj): - return isinstance(obj, Callable) -else: - callable = builtins.callable - #============================================================================= # introspection #============================================================================= diff --git a/passlib/utils/des.py b/passlib/utils/des.py index a2fc2bf..1a7985a 100644 --- a/passlib/utils/des.py +++ b/passlib/utils/des.py @@ -47,8 +47,8 @@ The netbsd des-crypt implementation has some nice notes on how this all works - import struct # pkg from passlib import exc -from passlib.utils.compat import bytes, join_byte_values, byte_elem_value, \ - b, irange, irange, int_types +from passlib.utils.compat import join_byte_values, byte_elem_value, \ + irange, irange, int_types from passlib.utils import deprecated_function # local __all__ = [ @@ -584,7 +584,7 @@ def _permute(c, p): #============================================================================= _uint64_struct = struct.Struct(">Q") -_BNULL = b('\x00') +_BNULL = b'\x00' def _pack64(value): return _uint64_struct.pack(value) diff --git a/passlib/utils/handlers.py b/passlib/utils/handlers.py index 1eca2ee..72b0a4c 100644 --- a/passlib/utils/handlers.py +++ b/passlib/utils/handlers.py @@ -17,7 +17,7 @@ from passlib.utils import classproperty, consteq, getrandstr, getrandbytes,\ BASE64_CHARS, HASH64_CHARS, rng, to_native_str, \ is_crypt_handler, to_unicode, \ MAX_PASSWORD_SIZE -from passlib.utils.compat import b, join_byte_values, bytes, irange, u, callable, \ +from passlib.utils.compat import join_byte_values, irange, u, \ uascii_to_str, join_unicode, unicode, str_to_uascii, \ join_unicode, base_string_types, PY2, int_types # local diff --git a/passlib/utils/md4.py b/passlib/utils/md4.py index cd067d9..7b34f17 100644 --- a/passlib/utils/md4.py +++ b/passlib/utils/md4.py @@ -15,7 +15,7 @@ from binascii import hexlify import struct from warnings import warn # site -from passlib.utils.compat import b, bytes, bascii_to_str, irange, PY3 +from passlib.utils.compat import bascii_to_str, irange, PY3 # local __all__ = [ "md4" ] #============================================================================= @@ -72,7 +72,7 @@ class md4(object): def __init__(self, content=None): self._count = 0 self._state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] - self._buf = b('') + self._buf = b'' if content: self.update(content) @@ -208,7 +208,7 @@ class md4(object): # then last 8 bytes = msg length in bits buf = self._buf msglen = self._count*512 + len(buf)*8 - block = buf + b('\x80') + b('\x00') * ((119-len(buf)) % 64) + \ + block = buf + b'\x80' + b'\x00' * ((119-len(buf)) % 64) + \ struct.pack("<2I", msglen & MASK_32, (msglen>>32) & MASK_32) if len(block) == 128: self._process(block[:64]) @@ -236,7 +236,6 @@ _builtin_md4 = md4 # check if hashlib provides accelarated md4 #============================================================================= import hashlib -from passlib.utils import PYPY def _has_native_md4(): # pragma: no cover -- runtime detection try: @@ -247,9 +246,6 @@ def _has_native_md4(): # pragma: no cover -- runtime detection result = h.hexdigest() if result == '31d6cfe0d16ae931b73c59d7e0c089c0': return True - if PYPY and result == '': - # workaround for https://bugs.pypy.org/issue957, fixed in PyPy 1.8 - return False # anything else and we should alert user from passlib.exc import PasslibRuntimeWarning warn("native md4 support disabled, sanity check failed!", PasslibRuntimeWarning) @@ -259,7 +255,7 @@ if _has_native_md4(): # overwrite md4 class w/ hashlib wrapper def md4(content=None): """wrapper for hashlib.new('md4')""" - return hashlib.new('md4', content or b('')) + return hashlib.new('md4', content or b'') #============================================================================= # eof diff --git a/passlib/utils/pbkdf2.py b/passlib/utils/pbkdf2.py index 6985ed5..07471fb 100644 --- a/passlib/utils/pbkdf2.py +++ b/passlib/utils/pbkdf2.py @@ -21,7 +21,7 @@ except ImportError: # pkg from passlib.exc import PasslibRuntimeWarning, ExpectedTypeError from passlib.utils import join_bytes, to_native_str, bytes_to_int, int_to_bytes, join_byte_values -from passlib.utils.compat import b, bytes, BytesIO, irange, callable, int_types, PYPY +from passlib.utils.compat import BytesIO, irange, int_types # local __all__ = [ # hash utils @@ -167,16 +167,13 @@ def _get_hash_const(name): # second, check hashlib.new() in case SSL supports the digest try: # new() should throw ValueError if alg is unknown - tmp = hashlib.new(name, b("")) - if PYPY and not tmp.digest(): - # detect https://bugs.pypy.org/issue957, fixed in PyPy 1.8 - raise ValueError("not actually supported") + tmp = hashlib.new(name, b"") except ValueError: pass else: # create wrapper function # XXX: find a better way to just return hash constructor - def const(msg=b("")): + def const(msg=b""): return hashlib.new(name, msg) const.__name__ = "new(%r)" % name const.__module__ = "hashlib" @@ -229,10 +226,10 @@ def get_hash_info(name): # prf lookup #============================================================================= -_BNULL = b('\x00') +_BNULL = b'\x00' # sanity check -_TEST_HMAC_SHA1 = b(',\x1cb\xe0H\xa5\x82M\xfb>\xd6\x98\xef\x8e\xf9oQ\x85\xa3i') +_TEST_HMAC_SHA1 = b',\x1cb\xe0H\xa5\x82M\xfb>\xd6\x98\xef\x8e\xf9oQ\x85\xa3i' # xlat tables used by hmac routines _TRANS_5C = join_byte_values((x ^ 0x5C) for x in irange(256)) @@ -258,14 +255,14 @@ def _get_hmac_prf(digest): if _EVP: # use m2crypto function directly for sha1, since that's its default digest if digest == "sha1": - if _EVP.hmac(b('x'), b('y')) != _TEST_HMAC_SHA1: + if _EVP.hmac(b'x', b'y') != _TEST_HMAC_SHA1: # don't expect to ever get here, but just in case raise RuntimeError("M2Crypto.EVP.hmac() failed sanity check") return _EVP.hmac, 20 # else check if it supports given digest as an option try: - result = _EVP.hmac(b('x'), b('y'), digest) + result = _EVP.hmac(b'x', b'y', digest) except ValueError: pass else: @@ -346,7 +343,7 @@ def get_prf(name): raise ValueError("unknown prf algorithm: %r" % (name,)) elif callable(name): # assume it's a callable, use it directly - digest_size = len(name(b('x'), b('y'))) + digest_size = len(name(b'x', b'y')) record = (name, digest_size) else: raise ExpectedTypeError(name, "str or callable", "prf name") diff --git a/passlib/win32.py b/passlib/win32.py index fd6febe..bbdcd57 100644 --- a/passlib/win32.py +++ b/passlib/win32.py @@ -34,7 +34,7 @@ warn("the 'passlib.win32' module is deprecated, and will be removed in " from binascii import hexlify # site # pkg -from passlib.utils.compat import b, unicode +from passlib.utils.compat import unicode from passlib.utils.des import des_encrypt_block from passlib.hash import nthash # local @@ -46,7 +46,7 @@ __all__ = [ #============================================================================= # helpers #============================================================================= -LM_MAGIC = b("KGS!@#$%") +LM_MAGIC = b"KGS!@#$%" raw_nthash = nthash.raw_nthash @@ -59,7 +59,7 @@ def raw_lmhash(secret, encoding="ascii", hex=False): # from being made w/o user explicitly choosing an encoding. if isinstance(secret, unicode): secret = secret.encode(encoding) - ns = secret.upper()[:14] + b("\x00") * (14-len(secret)) + ns = secret.upper()[:14] + b"\x00" * (14-len(secret)) out = des_encrypt_block(ns[:7], LM_MAGIC) + des_encrypt_block(ns[7:], LM_MAGIC) return hexlify(out).decode("ascii") if hex else out |
