Skip to content

Commit

Permalink
Add "number to word" tests & forbid too small/big numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
Splines committed Mar 15, 2024
1 parent 6ae7c55 commit e457ce1
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 18 deletions.
2 changes: 1 addition & 1 deletion src/api/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def parse_name(name: str) -> str:
parsed_name += char
elif char.isdigit():
num_digits = len([c for c in name if c.isdigit()]) # greedily get digits
word = Helpers.digit_str_to_word(name[:num_digits])
word = Helpers.number_to_word(int(name[:num_digits]))
if parsed_name != "":
word = Helpers.capitalize(word)
parsed_name += word
Expand Down
17 changes: 0 additions & 17 deletions src/application/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,3 @@ def number_to_word(cls, number: int) -> str:
@classmethod
def capitalize(cls, s: str) -> str:
return s[0].upper() + s[1:]

@classmethod
def digit_str_to_word(cls, digits_str: str) -> str:
"""Converts a string of digits to a word.
For example, "123" -> "oneHundredTwentyThree",
"911" -> "nineHundredEleven".
"""
num_digits = len(digits_str)
if num_digits <= 3:
return cls.number_to_word(int(digits_str))

word = cls.number_to_word(int(digits_str[0]))
for i in range(1, num_digits):
tmp = Helpers.number_to_word(int(digits_str[i]))
word += Helpers.capitalize(tmp)
return word
30 changes: 30 additions & 0 deletions tests/number_word_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from application.helpers import Helpers

import pytest


class TestNumberWord:
@pytest.mark.parametrize(
"input, expected",
[
(1, "one"),
(2, "two"),
(3, "three"),
(10, "ten"),
(18, "eighteen"),
(76, "seventySix"),
(100, "oneHundred"),
(101, "oneHundredOne"),
(123, "oneHundredTwentyThree"),
(305, "threeHundredFive"),
(911, "nineHundredEleven"),
(999, "nineHundredNinetyNine"),
],
)
def test_number_to_word(self, input, expected):
assert Helpers.number_to_word(input) == expected

@pytest.mark.parametrize("input", [1000, 1001, -1, -500])
def test_number_to_word_raises(self, input):
with pytest.raises(ValueError, match="numbers between 0 and 999"):
Helpers.number_to_word(input)

0 comments on commit e457ce1

Please sign in to comment.