Skip to content

Commit

Permalink
Merge branch 'release/0.4.3'
Browse files Browse the repository at this point in the history
  • Loading branch information
suminb committed Oct 29, 2019
2 parents 30c96c2 + c0b853c commit 6a05250
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 76 deletions.
8 changes: 6 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,21 @@ python:
- "3.6"
- "3.7"
- "3.8-dev"
# - "pypy" # disable pypy builds until supported by trusty containers
# Python development lifecycle: https://devguide.python.org/devcycle/
- "pypy"

addons:
sonarcloud:
organization: "suminb-github"

install:
- pip install --requirement tests/requirements.txt
- pip install "black; python_version >= '3.6'"

script:
- |
if [ -x "$(command -v black)" ]; then
black --check .
fi
- py.test tests --cov base62 --durations=10

after_success:
Expand Down
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ base62

A Python module for ``base62`` encoding. Ported from PHP code that I wrote
in mid-2000, which can be found
`here <http://blog.suminb.com/archives/558>`__.
`here <http://philosophical.one/posts/base62>`__.

.. |Build Status| image:: https://travis-ci.org/suminb/base62.svg?branch=master
:target: https://travis-ci.org/suminb/base62
Expand Down
42 changes: 21 additions & 21 deletions base62.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,29 @@
Originated from http://blog.suminb.com/archives/558
"""

__title__ = 'base62'
__author__ = 'Sumin Byeon'
__email__ = 'suminb@gmail.com'
__version__ = '0.4.2'
__title__ = "base62"
__author__ = "Sumin Byeon"
__email__ = "suminb@gmail.com"
__version__ = "0.4.3"

BASE = 62
CHARSET_DEFAULT = (
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
)
CHARSET_INVERTED = (
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
)
CHARSET_DEFAULT = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
CHARSET_INVERTED = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

try:
# NOTE: This is for Python 2. Shall be removed as soon as Python 2 is
# deprecated.
string_types = (str, unicode)
bytes_types = (bytes, bytearray,)
bytes_types = (
bytes,
bytearray,
)
except NameError:
string_types = (str,)
bytes_types = (bytes,)


def bytes_to_int(barray, byteorder='big', signed=False):
def bytes_to_int(barray, byteorder="big", signed=False):
"""Converts a byte array to an integer value.
Python 3 comes with a built-in function to do this, but we would like to
Expand All @@ -40,7 +39,7 @@ def bytes_to_int(barray, byteorder='big', signed=False):
return int.from_bytes(barray, byteorder, signed=signed)
except AttributeError:
# For Python 2.x
if byteorder != 'big' or signed:
if byteorder != "big" or signed:
raise NotImplementedError()

# NOTE: This won't work if a generator is given
Expand All @@ -63,9 +62,9 @@ def encode(n, minlen=1, charset=CHARSET_DEFAULT):
if len(chs) > 0:
chs.reverse()
else:
chs.append('0')
chs.append("0")

s = ''.join(chs)
s = "".join(chs)
s = charset[0] * max(minlen - len(s), 0) + s
return s

Expand All @@ -90,7 +89,7 @@ def decode(encoded, charset=CHARSET_DEFAULT):
"""
_check_type(encoded, string_types)

if encoded.startswith('0z'):
if encoded.startswith("0z"):
encoded = encoded[2:]

l, i, v = len(encoded), 0, 0
Expand All @@ -112,7 +111,7 @@ def decodebytes(encoded, charset=CHARSET_DEFAULT):
decoded = decode(encoded, charset=charset)
buf = bytearray()
while decoded > 0:
buf.append(decoded & 0xff)
buf.append(decoded & 0xFF)
decoded //= 256
buf.reverse()

Expand All @@ -125,13 +124,14 @@ def _value(ch, charset):
try:
return charset.index(ch)
except ValueError:
raise ValueError('base62: Invalid character (%s)' % ch)
raise ValueError("base62: Invalid character (%s)" % ch)


def _check_type(value, expected_type):
"""Checks if the input is in an appropriate type."""

if not isinstance(value, expected_type):
msg = 'Expected {} object, not {}'.format(
expected_type, value.__class__.__name__)
raise TypeError(msg)
msg = "Expected {} object, not {}".format(
expected_type, value.__class__.__name__
)
raise TypeError(msg)
25 changes: 12 additions & 13 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,26 @@

def readme():
try:
with open('README.rst') as f:
with open("README.rst") as f:
return f.read()
except:
return '(Could not read from README.rst)'
return "(Could not read from README.rst)"


setup(
name='pybase62',
py_modules=['base62'],
name="pybase62",
py_modules=["base62"],
version=base62.__version__,
description='Python module for base62 encoding',
description="Python module for base62 encoding",
long_description=readme(),
author='Sumin Byeon',
author_email='suminb@gmail.com',
url='http://github.com/suminb/base62',
author="Sumin Byeon",
author_email="suminb@gmail.com",
url="http://github.com/suminb/base62",
packages=[],
classifiers=[
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
],
)
81 changes: 42 additions & 39 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@


bytes_int_pairs = [
(b'\x00', 0),
(b'\x01', 1),
(b'\x01\x01', 0x0101),
(b'\xff\xff', 0xffff),
(b'\x01\x01\x01', 0x010101),
(b'\x01\x02\x03\x04\x05\x06\x07\x08', 0x0102030405060708),
(b"\x00", 0),
(b"\x01", 1),
(b"\x01\x01", 0x0101),
(b"\xff\xff", 0xFFFF),
(b"\x01\x01\x01", 0x010101),
(b"\x01\x02\x03\x04\x05\x06\x07\x08", 0x0102030405060708),
]


Expand All @@ -21,88 +21,91 @@ def test_const():


def test_basic():
assert base62.encode(0) == '0'
assert base62.encode(0, minlen=0) == '0'
assert base62.encode(0, minlen=1) == '0'
assert base62.encode(0, minlen=5) == '00000'
assert base62.decode('0') == 0
assert base62.decode('0000') == 0
assert base62.decode('000001') == 1
assert base62.encode(0) == "0"
assert base62.encode(0, minlen=0) == "0"
assert base62.encode(0, minlen=1) == "0"
assert base62.encode(0, minlen=5) == "00000"
assert base62.decode("0") == 0
assert base62.decode("0000") == 0
assert base62.decode("000001") == 1

assert base62.encode(34441886726) == 'base62'
assert base62.decode('base62') == 34441886726
assert base62.encode(34441886726) == "base62"
assert base62.decode("base62") == 34441886726

# NOTE: For backward compatibility. When I first wrote this module in PHP,
# I used to use the `0z` prefix to denote a base62 encoded string (similar
# to `0x` for hexadecimal strings).
assert base62.decode('0zbase62') == 34441886726
assert base62.decode("0zbase62") == 34441886726


def test_basic_inverted():
kwargs = {'charset': base62.CHARSET_INVERTED}
kwargs = {"charset": base62.CHARSET_INVERTED}

assert base62.encode(0, **kwargs) == '0'
assert base62.encode(0, minlen=0, **kwargs) == '0'
assert base62.encode(0, minlen=1, **kwargs) == '0'
assert base62.encode(0, minlen=5, **kwargs) == '00000'
assert base62.decode('0', **kwargs) == 0
assert base62.decode('0000', **kwargs) == 0
assert base62.decode('000001', **kwargs) == 1
assert base62.encode(0, **kwargs) == "0"
assert base62.encode(0, minlen=0, **kwargs) == "0"
assert base62.encode(0, minlen=1, **kwargs) == "0"
assert base62.encode(0, minlen=5, **kwargs) == "00000"
assert base62.decode("0", **kwargs) == 0
assert base62.decode("0000", **kwargs) == 0
assert base62.decode("000001", **kwargs) == 1

assert base62.encode(10231951886, **kwargs) == 'base62'
assert base62.decode('base62', **kwargs) == 10231951886
assert base62.encode(10231951886, **kwargs) == "base62"
assert base62.decode("base62", **kwargs) == 10231951886

# NOTE: For backward compatibility. When I first wrote this module in PHP,
# I used to use the `0z` prefix to denote a base62 encoded string (similar
# to `0x` for hexadecimal strings).
assert base62.decode('0zbase62', **kwargs) == 10231951886
assert base62.decode("0zbase62", **kwargs) == 10231951886


@pytest.mark.parametrize('b, i', bytes_int_pairs)
@pytest.mark.parametrize("b, i", bytes_int_pairs)
def test_bytes_to_int(b, i):
assert base62.bytes_to_int(b) == i


@pytest.mark.parametrize('b, i', bytes_int_pairs)
@pytest.mark.parametrize("b, i", bytes_int_pairs)
def test_encodebytes(b, i):
assert base62.encodebytes(b) == base62.encode(i)


@pytest.mark.skipif(
sys.version_info < (3, 0),
reason='Python 2.x does not have clear distinction between str and bytes types')
reason="Python 2.x does not have clear distinction between str and bytes types",
)
def test_encodebytes_type():
with pytest.raises(TypeError):
base62.encodebytes('1234')
base62.encodebytes("1234")


def test_encodebytes_rtype():
"""Make sure the return type of encodebytes() is string."""
encoded = base62.encodebytes(b'1234')
encoded = base62.encodebytes(b"1234")
assert isinstance(encoded, str)


@pytest.mark.parametrize('s', ['0', '1', 'a', 'z', 'ykzvd7ga', '0z1234'])
@pytest.mark.parametrize("s", ["0", "1", "a", "z", "ykzvd7ga", "0z1234"])
def test_decodebytes(s):
assert base62.bytes_to_int(base62.decodebytes(s)) == base62.decode(s)


@pytest.mark.skipif(
sys.version_info < (3, 0),
reason='Python 2.x does not have clear distinction between str and bytes types')
reason="Python 2.x does not have clear distinction between str and bytes types",
)
def test_decodebytes_type():
with pytest.raises(TypeError):
base62.decodebytes(b'1234')
base62.decodebytes(b"1234")


def test_decodebytes_rtype():
"""Make sure the return type of decodebytes() is bytes."""
decoded = base62.decodebytes('1234')
decoded = base62.decodebytes("1234")
assert isinstance(decoded, bytes)


@pytest.mark.parametrize('input_bytes', [
b'', b'0', b'bytes to encode', b'\x01\x00\x80'])
@pytest.mark.parametrize(
"input_bytes", [b"", b"0", b"bytes to encode", b"\x01\x00\x80"]
)
def test_roundtrip(input_bytes):
"""Ensures type consistency. Suggested by @dhimmel"""
base62_encoded = base62.encodebytes(input_bytes)
Expand All @@ -114,7 +117,7 @@ def test_roundtrip(input_bytes):

def test_invalid_alphabet():
with pytest.raises(ValueError):
base62.decode('+')
base62.decode("+")


def test_invalid_string():
Expand Down

0 comments on commit 6a05250

Please sign in to comment.