diff --git a/fixit/cli.py b/fixit/cli.py index b5d70bd..4c2e603 100644 --- a/fixit/cli.py +++ b/fixit/cli.py @@ -16,6 +16,7 @@ convert, health, fizzbuzz, + hashing, jsonfmt, lorem, password, @@ -170,6 +171,11 @@ def run_base(args: argparse.Namespace) -> None: """Print a number in binary, octal and hexadecimal.""" print(bases.to_bases(args.number)) + +def run_hash(args: argparse.Namespace) -> None: + """Print the hex digest of the given text.""" + print(hashing.hash_text(args.text, args.algo)) + COMMAND_TABLE = { "wc": run_wc, "convert": run_convert, @@ -189,6 +195,7 @@ def run_base(args: argparse.Namespace) -> None: "bmi": run_bmi, "fizzbuzz": run_fizzbuzz, "base": run_base, + "hash": run_hash, } @@ -294,6 +301,15 @@ def build_parser() -> argparse.ArgumentParser: ) base.add_argument("number", type=int, help="non-negative integer") + hs = sub.add_parser("hash", help="print the hash of a text") + hs.add_argument("text", help="text to hash") + hs.add_argument( + "--algo", + choices=hashing.SUPPORTED_ALGORITHMS, + default="sha256", + help="hash algorithm (default: sha256)", + ) + return parser diff --git a/fixit/hashing.py b/fixit/hashing.py new file mode 100644 index 0000000..bcbb657 --- /dev/null +++ b/fixit/hashing.py @@ -0,0 +1,15 @@ +"""Hash text with common algorithms.""" + +import hashlib + +SUPPORTED_ALGORITHMS = ("md5", "sha1", "sha256") + + +def hash_text(text: str, algo: str = "sha256") -> str: + """Return the hex digest of ``text`` encoded as UTF-8. + + Raises ValueError if ``algo`` is not one of SUPPORTED_ALGORITHMS. + """ + if algo not in SUPPORTED_ALGORITHMS: + raise ValueError(f"Error: unsupported algorithm '{algo}'") + return hashlib.new(algo, text.encode("utf-8")).hexdigest() diff --git a/tests/test_hashing.py b/tests/test_hashing.py new file mode 100644 index 0000000..7dfad6c --- /dev/null +++ b/tests/test_hashing.py @@ -0,0 +1,38 @@ +import hashlib + +import pytest + +from fixit.cli import main +from fixit.hashing import hash_text + + +def test_md5_of_hello(): + assert hash_text("hello", "md5") == "5d41402abc4b2a76b9719d911017c592" + + +def test_sha256_is_default(): + assert hash_text("hello") == hashlib.sha256(b"hello").hexdigest() + + +def test_empty_text_hashes_to_known_md5(): + assert hash_text("", "md5") == "d41d8cd98f00b204e9800998ecf8427e" + + +def test_unsupported_algorithm_raises(): + with pytest.raises(ValueError): + hash_text("hello", "sha512") + + +def test_hash_command_default_sha256(capsys): + assert main(["hash", "hello"]) == 0 + assert capsys.readouterr().out.strip() == hashlib.sha256(b"hello").hexdigest() + + +def test_hash_command_md5(capsys): + assert main(["hash", "hello", "--algo", "md5"]) == 0 + assert capsys.readouterr().out.strip() == "5d41402abc4b2a76b9719d911017c592" + + +def test_hash_command_rejects_unknown_algo(capsys): + with pytest.raises(SystemExit): + main(["hash", "hello", "--algo", "sha512"])