57 lines
1.8 KiB
Python
57 lines
1.8 KiB
Python
"""Tests for the base32 encode/decode utilities
|
||
"""
|
||
|
||
from base64 import _b32decode, _b32encode # type: ignore
|
||
from base64 import b32decode, b32encode
|
||
from random import choice
|
||
|
||
import pytest
|
||
|
||
from earthsnake.base32 import base32_bytes_to_string, base32_string_to_bytes
|
||
from earthsnake.types import B32_CHAR
|
||
|
||
|
||
def test_alphabet() -> None:
|
||
"""Test if Python’s Base32 alphabet is the uppercase version of the one we expect"""
|
||
|
||
alphabet = B32_CHAR.encode('utf-8')
|
||
test_data = b'\x00D2\x14\xc7BT\xb65\xcf\x84e:V\xd7\xc6u\xbew\xdf'
|
||
test_encoded = B32_CHAR.upper().encode('utf-8')
|
||
|
||
assert _b32encode(alphabet, test_data) == b32encode(test_data).lower()
|
||
assert _b32decode(alphabet, alphabet) == b32decode(test_encoded)
|
||
|
||
|
||
def test_bytes_to_string() -> None:
|
||
"""Test if base32_bytes_to_string encodes bytes as expected"""
|
||
|
||
data = bytes(choice(range(255)) for _ in range(10))
|
||
our_version = base32_bytes_to_string(data)
|
||
py_version = 'b' + b32encode(data).lower().strip(b'=').decode('utf-8')
|
||
|
||
assert our_version == py_version
|
||
|
||
|
||
def test_string_to_bytes_noprefix() -> None:
|
||
"""Test if base32_string_to_bytes refuses to decode strings without the 'b' prefix"""
|
||
|
||
with pytest.raises(ValueError) as ctx:
|
||
base32_string_to_bytes('test')
|
||
|
||
assert 'it should start with a \'b\'' in str(ctx.value)
|
||
|
||
|
||
def test_string_to_bytes_padding() -> None:
|
||
"""Test if base32_string_to_bytes refuses to decode strings with padding characters"""
|
||
|
||
with pytest.raises(ValueError) as ctx:
|
||
base32_string_to_bytes('btest=')
|
||
|
||
assert 'it contains padding characters (\'=\')' in str(ctx.value)
|
||
|
||
|
||
def test_string_to_bytes() -> None:
|
||
"""Test if base32_string_to_bytes dedoces strings as expected"""
|
||
|
||
assert base32_string_to_bytes('borsxg5a') == b'test'
|