diff --git a/api/src/shop/gift_card_util.py b/api/src/shop/gift_card_util.py new file mode 100644 index 000000000..7bb911b9b --- /dev/null +++ b/api/src/shop/gift_card_util.py @@ -0,0 +1,14 @@ +from secrets import token_hex + + +def generate_gift_card_code(length=16): + """ + 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() \ No newline at end of file diff --git a/api/src/shop/test/gift_card_test.py b/api/src/shop/test/gift_card_test.py new file mode 100644 index 000000000..d55a3bf58 --- /dev/null +++ b/api/src/shop/test/gift_card_test.py @@ -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)