Skip to content

Commit 7f2ea4b

Browse files
committed
Merge branch 'mr/cardao/e3.hash/add-PathLike-support' into 'master'
Add PathLike type support for e3.hash methods See merge request it/e3-core!69
2 parents 25a4a43 + 39ab353 commit 7f2ea4b

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

src/e3/hash.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,16 @@
99

1010
if TYPE_CHECKING:
1111
from typing import Literal
12+
from os import PathLike
1213

1314

1415
class HashError(e3.error.E3Error):
1516
pass
1617

1718

1819
def __compute_hash(
19-
path: str, kind: Literal["md5"] | Literal["sha1"] | Literal["sha256"]
20+
path: PathLike[str] | str,
21+
kind: Literal["md5"] | Literal["sha1"] | Literal["sha256"],
2022
) -> str:
2123
if not os.path.isfile(path):
2224
raise HashError(kind, f"cannot find {path}")
@@ -31,7 +33,7 @@ def __compute_hash(
3133
return result.hexdigest()
3234

3335

34-
def md5(path: str) -> str:
36+
def md5(path: PathLike[str] | str) -> str:
3537
"""Compute md5 hexadecimal digest of a file.
3638
3739
:param path: path to a file
@@ -42,7 +44,7 @@ def md5(path: str) -> str:
4244
return __compute_hash(path, "md5")
4345

4446

45-
def sha1(path: str) -> str:
47+
def sha1(path: PathLike[str] | str) -> str:
4648
"""Compute sha1 hexadecimal digest of a file.
4749
4850
:param str path: path to a file
@@ -53,7 +55,7 @@ def sha1(path: str) -> str:
5355
return __compute_hash(path, "sha1")
5456

5557

56-
def sha256(path: str) -> str:
58+
def sha256(path: PathLike[str] | str) -> str:
5759
"""Compute sha256 hexadecimal digest of a file.
5860
5961
:param str path: path to a file

tests/tests_e3/hash/main_test.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
from __future__ import annotations
2+
3+
import os
4+
from pathlib import Path
5+
16
import e3.hash
27

38
import pytest
@@ -14,3 +19,15 @@ def test_hash():
1419
)
1520
with pytest.raises(e3.hash.HashError):
1621
e3.hash.md5("doesnotexist")
22+
23+
# Check if PathLike[str] parameter is accepted
24+
p = Path(f.name)
25+
# Ensure `p` follow PathLike[str] rule
26+
assert isinstance(os.fspath(p), str)
27+
28+
assert e3.hash.md5(p) == "f75b8179e4bbe7e2b4a074dcef62de95"
29+
assert e3.hash.sha1(p) == "7fe70820e08a1aac0ef224d9c66ab66831cc4ab1"
30+
assert (
31+
e3.hash.sha256(p)
32+
== "434728a410a78f56fc1b5899c3593436e61ab0c731e9072d95e96db290205e53"
33+
)

0 commit comments

Comments
 (0)