diff --git a/src/e3/hash.py b/src/e3/hash.py index 49ee1af0..2bff96eb 100644 --- a/src/e3/hash.py +++ b/src/e3/hash.py @@ -9,6 +9,7 @@ if TYPE_CHECKING: from typing import Literal + from os import PathLike class HashError(e3.error.E3Error): @@ -16,7 +17,8 @@ class HashError(e3.error.E3Error): def __compute_hash( - path: str, kind: Literal["md5"] | Literal["sha1"] | Literal["sha256"] + path: PathLike[str] | str, + kind: Literal["md5"] | Literal["sha1"] | Literal["sha256"], ) -> str: if not os.path.isfile(path): raise HashError(kind, f"cannot find {path}") @@ -31,7 +33,7 @@ def __compute_hash( return result.hexdigest() -def md5(path: str) -> str: +def md5(path: PathLike[str] | str) -> str: """Compute md5 hexadecimal digest of a file. :param path: path to a file @@ -42,7 +44,7 @@ def md5(path: str) -> str: return __compute_hash(path, "md5") -def sha1(path: str) -> str: +def sha1(path: PathLike[str] | str) -> str: """Compute sha1 hexadecimal digest of a file. :param str path: path to a file @@ -53,7 +55,7 @@ def sha1(path: str) -> str: return __compute_hash(path, "sha1") -def sha256(path: str) -> str: +def sha256(path: PathLike[str] | str) -> str: """Compute sha256 hexadecimal digest of a file. :param str path: path to a file diff --git a/tests/tests_e3/hash/main_test.py b/tests/tests_e3/hash/main_test.py index 6a67a3ef..a152b0bd 100644 --- a/tests/tests_e3/hash/main_test.py +++ b/tests/tests_e3/hash/main_test.py @@ -1,3 +1,8 @@ +from __future__ import annotations + +import os +from pathlib import Path + import e3.hash import pytest @@ -14,3 +19,15 @@ def test_hash(): ) with pytest.raises(e3.hash.HashError): e3.hash.md5("doesnotexist") + + # Check if PathLike[str] parameter is accepted + p = Path(f.name) + # Ensure `p` follow PathLike[str] rule + assert isinstance(os.fspath(p), str) + + assert e3.hash.md5(p) == "f75b8179e4bbe7e2b4a074dcef62de95" + assert e3.hash.sha1(p) == "7fe70820e08a1aac0ef224d9c66ab66831cc4ab1" + assert ( + e3.hash.sha256(p) + == "434728a410a78f56fc1b5899c3593436e61ab0c731e9072d95e96db290205e53" + )