Skip to content

Commit

Permalink
add tests for example generators
Browse files Browse the repository at this point in the history
  • Loading branch information
lilioid committed Mar 24, 2022
1 parent 5cd3a86 commit fdfa41c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
8 changes: 4 additions & 4 deletions configurations/example_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ def gen_random_string(length: int, allowed_chars: str = RANDOM_STRING_CHARS) ->
Create a parameterized generator which generates a cryptographically secure random string of the given length
containing the given characters.
"""
def generate() -> str:
def _gen_random_string() -> str:
return get_random_string(length, allowed_chars)
return generate
return _gen_random_string


def gen_bytes(length: int, encoding: str) -> Callable[[], str]:
Expand All @@ -36,12 +36,12 @@ def gen_bytes(length: int, encoding: str) -> Callable[[], str]:
raise ValueError(f"Cannot gen_bytes with encoding '{encoding}'. Valid encodings are 'base64', 'base64_urlsafe'"
f" and 'hex'")

def generate() -> str:
def _gen_bytes() -> str:
b = secrets.token_bytes(length)
if encoding == "base64":
return base64.standard_b64encode(b).decode("ASCII")
elif encoding == "base64_urlsafe":
return base64.urlsafe_b64encode(b).decode("ASCII")
elif encoding == "hex":
return b.hex().upper()
return generate
return _gen_bytes
32 changes: 32 additions & 0 deletions tests/test_example_generators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import base64
from django.test import TestCase
from configurations.example_generators import gen_bytes, gen_random_string, gen_django_secret_key


class ExampleGeneratorsTestCase(TestCase):
def test_generators_dont_raise_exceptions(self):
for gen in [gen_bytes(64, "hex"), gen_bytes(64, "base64"), gen_bytes(64, "base64_urlsafe"),
gen_random_string(16, "ab"), gen_random_string(5),
gen_django_secret_key]:
with self.subTest(gen.__name__):
gen()

# gen_django_secret_key() and gen_random_string() are not tested beyond the above general test case
# because they are just wrappers around existing django utilities.
# They are thus assumed to work.

def test_gen_bytes(self):
with self.subTest("base64"):
result = gen_bytes(64, "base64")()
b = base64.standard_b64decode(result.encode("ASCII"))
self.assertEqual(len(b), 64)

with self.subTest("base64_urlsafe"):
result = gen_bytes(64, "base64_urlsafe")()
b = base64.urlsafe_b64decode(result.encode("ASCII"))
self.assertEqual(len(b), 64)

with self.subTest("hex"):
result = gen_bytes(64, "hex")()
b = bytes.fromhex(result)
self.assertEqual(len(b), 64)

0 comments on commit fdfa41c

Please sign in to comment.