Skip to content

Commit

Permalink
Common: Add get_file_sha256_hash()
Browse files Browse the repository at this point in the history
  • Loading branch information
mssalvatore committed Jul 16, 2021
1 parent 07937d7 commit 3912b85
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
monkey/tests/data_for_tests/ransomware_targets/** -text
monkey/tests/data_for_tests/stable_file.txt -text
10 changes: 10 additions & 0 deletions monkey/common/utils/file_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import hashlib
import os
from pathlib import Path

Expand All @@ -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()
10 changes: 10 additions & 0 deletions monkey/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,13 @@
@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"
1 change: 1 addition & 0 deletions monkey/tests/data_for_tests/stable_file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Don't change me!
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

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):
Expand All @@ -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

0 comments on commit 3912b85

Please sign in to comment.