Skip to content
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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ Invalid numbers print:
invalid
```

The command exits with status `0` for a valid number and status `1` for an
invalid number, so it can be used directly in shell scripts and CI checks.

Run the test suite:

```bash
Expand Down
5 changes: 4 additions & 1 deletion luhn.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,14 @@ def append_check_digit(payload: NumberLike) -> str:

if __name__ == "__main__":
import argparse
import sys

parser = argparse.ArgumentParser(
description="Validate a number with the Luhn algorithm."
)
parser.add_argument("number", help="number to validate")
args = parser.parse_args()

print("valid" if is_valid(args.number) else "invalid")
valid = is_valid(args.number)
print("valid" if valid else "invalid")
sys.exit(0 if valid else 1)
21 changes: 21 additions & 0 deletions test_luhn.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import subprocess
import sys
import unittest
from pathlib import Path

from luhn import append_check_digit, calculate_check_digit, checksum, is_valid

Expand Down Expand Up @@ -41,6 +44,24 @@ def test_rejects_unsupported_types(self):
with self.assertRaises(ValueError):
function(value)

def test_cli_exit_status_reflects_validity(self):
script = Path(__file__).with_name("luhn.py")

for number, expected_output, expected_status in (
("79927398713", "valid", 0),
("79927398714", "invalid", 1),
):
with self.subTest(number=number):
result = subprocess.run(
[sys.executable, str(script), number],
capture_output=True,
text=True,
check=False,
)

self.assertEqual(result.stdout.strip(), expected_output)
self.assertEqual(result.returncode, expected_status)


if __name__ == "__main__":
unittest.main()
Loading