Common: Add get_file_sha256_hash()

This commit is contained in:
Mike Salvatore 2021-07-16 10:08:24 -04:00
parent 07937d7238
commit 3912b85d08
5 changed files with 27 additions and 1 deletions

1
.gitattributes vendored
View File

@ -1 +1,2 @@
monkey/tests/data_for_tests/ransomware_targets/** -text
monkey/tests/data_for_tests/stable_file.txt -text

View File

@ -1,3 +1,4 @@
import hashlib
import os
from pathlib import Path
@ -11,3 +12,12 @@ def expand_path(path: str) -> Path:
raise InvalidPath("Empty path provided")
return Path(os.path.expandvars(os.path.expanduser(path)))
def get_file_sha256_hash(filepath: Path):
sha256 = hashlib.sha256()
with open(filepath, "rb") as f:
for block in iter(lambda: f.read(65536), b""):
sha256.update(block)
return sha256.hexdigest()

View File

@ -11,3 +11,13 @@ sys.path.insert(0, MONKEY_BASE_PATH)
@pytest.fixture(scope="session")
def data_for_tests_dir(pytestconfig):
return Path(os.path.join(pytestconfig.rootdir, "monkey", "tests", "data_for_tests"))
@pytest.fixture(scope="session")
def stable_file(data_for_tests_dir) -> Path:
return data_for_tests_dir / "stable_file.txt"
@pytest.fixture(scope="session")
def stable_file_sha256_hash() -> str:
return "d9dcaadc91261692dafa86e7275b1bf39bb7e19d2efcfacd6fe2bfc9a1ae1062"

View File

@ -0,0 +1 @@
Don't change me!

View File

@ -2,7 +2,7 @@ import os
import pytest
from common.utils.file_utils import InvalidPath, expand_path
from common.utils.file_utils import InvalidPath, expand_path, get_file_sha256_hash
def test_expand_user(patched_home_env):
@ -22,3 +22,7 @@ def test_expand_vars(patched_home_env):
def test_expand_path__empty_path_provided():
with pytest.raises(InvalidPath):
expand_path("")
def test_get_file_sha256_hash(stable_file, stable_file_sha256_hash):
assert get_file_sha256_hash(stable_file) == stable_file_sha256_hash