Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function to generate unique validation code for gift cards. #379

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions api/src/shop/gift_card_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from secrets import token_hex


def generate_gift_card_code(length=16):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Length=10 is probably enough (number of alternatives is then about 10^12). But I don't really care that much.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'd only get a probable collision after about a million gift cards.

"""
Generate a unique validation code for gift cards.

Parameters:
- length: The length of the validation code (default is 16).

Returns:
A unique validation code.
"""
return token_hex(length)[:length].upper()
20 changes: 20 additions & 0 deletions api/src/shop/test/gift_card_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from unittest import TestCase
from shop.gift_card_util import generate_gift_card_code


class GiftCardTest(TestCase):
def test_generate_validation_code_default_length(self):
validation_code = generate_gift_card_code()
msg = "Test failed: validation code is not 16 characters long."
self.assertEqual(len(validation_code), 16, msg=msg)

def test_generate_validation_code_custom_length(self):
validation_code = generate_gift_card_code(32)
msg = "Test failed: validation code is not 32 characters long."
self.assertEqual(len(validation_code), 32, msg=msg)

def test_generate_validation_code_unique(self):
validation_code_1 = generate_gift_card_code()
validation_code_2 = generate_gift_card_code()
msg = "Test failed: validation codes are not unique."
self.assertNotEqual(validation_code_1, validation_code_2, msg=msg)
Loading