Skip to content
Open
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
9 changes: 8 additions & 1 deletion src/validators/card.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
def card_number(value: str, /):
"""Return whether or not given value is a valid generic card number.

This validator is based on [Luhn's algorithm][1].
This validator is based on [Luhn's algorithm][1]. Numbers of fewer than 8
or more than 19 digits are rejected, since no card number has such a length.

[1]: https://github.com/mmcloughlin/luhn

Expand All @@ -20,6 +21,8 @@ def card_number(value: str, /):
True
>>> card_number('4242424242424241')
ValidationError(func=card_number, args={'value': '4242424242424241'})
>>> card_number('18')
ValidationError(func=card_number, args={'value': '18'})

Args:
value:
Expand All @@ -31,6 +34,10 @@ def card_number(value: str, /):
"""
if not value:
return False
if not 8 <= len(value) <= 19:
# an issuer identification number, an account number and a check digit
# take at least 8 digits; the longest card number has 19
return False
try:
digits = list(map(int, value))
odd_sum = sum(digits[-1::-2])
Expand Down
24 changes: 24 additions & 0 deletions tests/test_card.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,30 @@ def test_returns_true_on_valid_card_number(value: str):
assert card_number(value)


# every value below passes the Luhn check, so only its length decides
@pytest.mark.parametrize("value", ["40128886", "6212345678901234569"])
def test_returns_true_on_card_number_of_shortest_and_longest_length(value: str):
"""Test returns true on card numbers of 8 and of 19 digits."""
assert card_number(value)


@pytest.mark.parametrize(
"value",
[
"0",
"00",
"18",
"0000000",
"4012886",
"62123456789012345676",
"00000000000000000000000000000000",
],
)
def test_returns_failed_validation_on_card_number_of_impossible_length(value: str):
"""Test returns failed validation on card numbers of fewer than 8 or more than 19 digits."""
assert isinstance(card_number(value), ValidationError)


@pytest.mark.parametrize(
"value",
[
Expand Down