mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-12-01 13:44:16 +00:00
adding tests for logs
This commit is contained in:
@@ -82,8 +82,8 @@ class FormatterWithExceptions(logging.Formatter):
|
||||
|
||||
return text_mocked
|
||||
|
||||
@classmethod
|
||||
def filter_special_tags(cls, text: str) -> str:
|
||||
@staticmethod
|
||||
def filter_special_tags(text: str) -> str:
|
||||
text_filtered = text.replace("\n", " MOCKING_BREAKLINE ")
|
||||
text_filtered = text_filtered.replace("'Traceback", "Traceback")
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@ def get_timestamp_from_x_days(x: int) -> float:
|
||||
|
||||
|
||||
def get_expired_file_list(directory: Path, before_timestamp: float) -> List[Path]:
|
||||
expired_files = list()
|
||||
if directory.exists and directory.is_dir(): # type: ignore
|
||||
expired_files = []
|
||||
if directory.is_dir(): # Check if the directory exists and is a directory
|
||||
for file in directory.iterdir():
|
||||
if file.is_file() and file.lstat().st_mtime < before_timestamp:
|
||||
expired_files.append(file)
|
||||
|
||||
@@ -1,5 +1,308 @@
|
||||
import pytest
|
||||
import logging
|
||||
import os
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from openbb_core.app.logs.formatters.formatter_with_exceptions import (
|
||||
FormatterWithExceptions,
|
||||
)
|
||||
|
||||
logging_settings = Mock()
|
||||
logging_settings.app_name = "test_app_name"
|
||||
logging_settings.app_id = "test_app_id"
|
||||
logging_settings.session_id = "test_session_id"
|
||||
logging_settings.commit_hash = "test_commit_hash"
|
||||
logging_settings.user_id = "test_user_id"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def formatter():
|
||||
return FormatterWithExceptions(logging_settings)
|
||||
|
||||
|
||||
# Test when exc_text is not empty (should return "X")
|
||||
def test_level_name_with_exc_text(formatter):
|
||||
record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.INFO,
|
||||
pathname="",
|
||||
lineno=0,
|
||||
msg="",
|
||||
args=None,
|
||||
exc_info=None,
|
||||
func=None,
|
||||
)
|
||||
record.exc_text = "Exception occurred!"
|
||||
assert formatter.calculate_level_name(record) == "X"
|
||||
|
||||
|
||||
# Test when levelname is not empty (should return the first character of levelname)
|
||||
def test_level_name_with_levelname(formatter):
|
||||
record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.WARNING,
|
||||
pathname="",
|
||||
lineno=0,
|
||||
msg="",
|
||||
args=None,
|
||||
exc_info=None,
|
||||
func=None,
|
||||
)
|
||||
record.levelname = "WARNING"
|
||||
assert formatter.calculate_level_name(record) == "W"
|
||||
|
||||
|
||||
# Test when func_name_override and session_id are present in the record
|
||||
def test_extract_log_extra_with_override_and_session_id(formatter):
|
||||
record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.INFO,
|
||||
pathname="",
|
||||
lineno=0,
|
||||
msg="",
|
||||
args=None,
|
||||
exc_info=None,
|
||||
func=None,
|
||||
)
|
||||
record.func_name_override = "custom_function"
|
||||
record.session_id = "1234567890"
|
||||
|
||||
log_extra = formatter.extract_log_extra(record)
|
||||
|
||||
assert log_extra == {
|
||||
"sessionId": "1234567890",
|
||||
}
|
||||
|
||||
|
||||
# Test when only func_name_override is present in the record
|
||||
def test_extract_log_extra_with_override(formatter):
|
||||
record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.INFO,
|
||||
pathname="",
|
||||
lineno=0,
|
||||
msg="",
|
||||
args=None,
|
||||
exc_info=None,
|
||||
func=None,
|
||||
)
|
||||
record.func_name_override = "custom_function"
|
||||
|
||||
log_extra = formatter.extract_log_extra(record)
|
||||
|
||||
assert log_extra == {}
|
||||
assert record.funcName == "custom_function"
|
||||
assert record.lineno == 0
|
||||
|
||||
|
||||
# Test when only session_id is present in the record
|
||||
def test_extract_log_extra_with_session_id(formatter):
|
||||
record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.INFO,
|
||||
pathname="",
|
||||
lineno=0,
|
||||
msg="",
|
||||
args=None,
|
||||
exc_info=None,
|
||||
func=None,
|
||||
)
|
||||
record.session_id = "1234567890"
|
||||
|
||||
log_extra = formatter.extract_log_extra(record)
|
||||
|
||||
assert log_extra == {
|
||||
"sessionId": "1234567890",
|
||||
}
|
||||
|
||||
|
||||
# Test when neither func_name_override nor session_id are present in the record
|
||||
def test_extract_log_extra_with_no_override_or_session_id(formatter):
|
||||
record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.INFO,
|
||||
pathname="",
|
||||
lineno=0,
|
||||
msg="",
|
||||
args=None,
|
||||
exc_info=None,
|
||||
func=None,
|
||||
)
|
||||
|
||||
log_extra = formatter.extract_log_extra(record)
|
||||
|
||||
assert log_extra == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_text, expected_output",
|
||||
[
|
||||
("Hello, this is 192.168.1.1", "Hello, this is FILTERED_IP "),
|
||||
("IP address: 10.0.0.1", "IP address: FILTERED_IP "),
|
||||
("No IPs here!", "No IPs here!"),
|
||||
("Another IP: 172.16.32.1", "Another IP: FILTERED_IP "),
|
||||
("1.2.3.4", " FILTERED_IP "),
|
||||
],
|
||||
)
|
||||
def test_mock_ipv4(input_text, expected_output, formatter):
|
||||
assert formatter.mock_ipv4(input_text) == expected_output
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_text, expected_output",
|
||||
[
|
||||
("Send an email to john@example.com", "Send an email to FILTERED_EMAIL "),
|
||||
("No emails here!", "No emails here!"),
|
||||
("Another email: alice@example.co.uk", "Another email: FILTERED_EMAIL "),
|
||||
("Contact us: support@example.net", "Contact us: FILTERED_EMAIL "),
|
||||
("myemail@example.com 12345", " FILTERED_EMAIL 12345"),
|
||||
],
|
||||
)
|
||||
def test_mock_email(input_text, expected_output, formatter):
|
||||
assert formatter.mock_email(input_text) == expected_output
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_text, expected_output",
|
||||
[
|
||||
('{"password": "secure_pass_123"}', '{"password": " FILTERED_PASSWORD "}'),
|
||||
('{"password": "p@$$w0rd!"}', '{"password": " FILTERED_PASSWORD "}'),
|
||||
('{"password": "12345"}', '{"password": " FILTERED_PASSWORD "}'),
|
||||
('{"password": "abc"}', '{"password": " FILTERED_PASSWORD "}'),
|
||||
(
|
||||
'{"password": "my_password"} {"password": "test123"}',
|
||||
'{"password": " FILTERED_PASSWORD "} {"password": " FILTERED_PASSWORD "}',
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_mock_password(input_text, expected_output, formatter):
|
||||
assert formatter.mock_password(input_text) == expected_output
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_text, expected_output",
|
||||
[
|
||||
('{"FLAIR": "[python]"}', '{"FLAIR": "[ FILTERED_FLAIR ]"}'),
|
||||
('{"FLAIR": "[question]"}', '{"FLAIR": "[ FILTERED_FLAIR ]"}'),
|
||||
('{"FLAIR": "[bug]"}', '{"FLAIR": "[ FILTERED_FLAIR ]"}'),
|
||||
('{"FLAIR": "[feature]"}', '{"FLAIR": "[ FILTERED_FLAIR ]"}'),
|
||||
('{"FLAIR": "[announcement]"}', '{"FLAIR": "[ FILTERED_FLAIR ]"}'),
|
||||
('{"FLAIR": "[FILTERED_FLAIR]"}', '{"FLAIR": "[ FILTERED_FLAIR ]"}'),
|
||||
],
|
||||
)
|
||||
def test_mock_flair(input_text, expected_output, formatter):
|
||||
assert formatter.mock_flair(input_text) == expected_output
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_text, expected_output",
|
||||
[
|
||||
(
|
||||
"This is C:\\Users\\username\\file.txt",
|
||||
"This is C:\\Users\\username\\file.txt",
|
||||
),
|
||||
("No home directory here!", "No home directory here!"),
|
||||
(
|
||||
f"This is {os.path.expanduser('~')}\\file.txt",
|
||||
"This is MOCKING_USER_PATH\\file.txt",
|
||||
),
|
||||
(
|
||||
f"Some path: {os.path.expanduser('~/subfolder')}",
|
||||
"Some path: MOCKING_USER_PATH/subfolder",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_mock_home_directory(input_text, expected_output, formatter):
|
||||
assert formatter.mock_home_directory(input_text) == expected_output
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_text, expected_output",
|
||||
[
|
||||
(
|
||||
"This is a string with a\nnewline",
|
||||
"This is a string with a MOCKING_BREAKLINE newline",
|
||||
),
|
||||
("'Traceback occurred", "Traceback occurred"),
|
||||
("No newlines or 'Traceback'", "No newlines or Traceback'"),
|
||||
("'Traceback in the\nmiddle'", "Traceback in the MOCKING_BREAKLINE middle'"),
|
||||
(
|
||||
"Multiple\n\nnewlines",
|
||||
"Multiple MOCKING_BREAKLINE MOCKING_BREAKLINE newlines",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_filter_special_tags(input_text, expected_output, formatter):
|
||||
assert formatter.filter_special_tags(input_text) == expected_output
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_text, expected_output",
|
||||
[
|
||||
(
|
||||
f"This is {os.path.expanduser('~')}\\file.txt",
|
||||
"This is MOCKING_USER_PATH\\file.txt",
|
||||
),
|
||||
('{"FLAIR": "[announcement]"}', '{"FLAIR": "[ FILTERED_FLAIR ]"}'),
|
||||
("Another email: alice@example.co.uk", "Another email: FILTERED_EMAIL "),
|
||||
("Another IP: 172.16.32.1", "Another IP: FILTERED_IP "),
|
||||
('{"password": "secure_pass_123"}', '{"password": " FILTERED_PASSWORD "}'),
|
||||
],
|
||||
)
|
||||
def test_filter_piis(input_text, expected_output, formatter):
|
||||
assert formatter.filter_piis(input_text) == expected_output
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_text, expected_output",
|
||||
[
|
||||
(
|
||||
f"This is {os.path.expanduser('~')}\\file.txt",
|
||||
"This is MOCKING_USER_PATH\\file.txt",
|
||||
),
|
||||
('{"FLAIR": "[announcement]"}', '{"FLAIR": "[ FILTERED_FLAIR ]"}'),
|
||||
("Another email: alice@example.co.uk", "Another email: FILTERED_EMAIL "),
|
||||
("Another IP: 172.16.32.1", "Another IP: FILTERED_IP "),
|
||||
('{"password": "secure_pass_123"}', '{"password": " FILTERED_PASSWORD "}'),
|
||||
("'Traceback in the\nmiddle'", "Traceback in the MOCKING_BREAKLINE middle'"),
|
||||
],
|
||||
)
|
||||
def test_filter_log_line(input_text, expected_output, formatter):
|
||||
assert formatter.filter_log_line(input_text) == expected_output
|
||||
|
||||
|
||||
def test_formatException_invalid():
|
||||
with pytest.raises(Exception):
|
||||
formatter.formatException(Exception("Big bad error"))
|
||||
|
||||
|
||||
def test_format(formatter):
|
||||
# Prepare the log record
|
||||
log_record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.INFO,
|
||||
pathname="/path/to/module.py",
|
||||
lineno=42,
|
||||
msg="This is a test log message with | symbol",
|
||||
args=(),
|
||||
exc_info=None,
|
||||
)
|
||||
|
||||
# Set up the mock objects
|
||||
formatter.calculate_level_name = Mock(return_value="INFO")
|
||||
formatter.filter_log_line = Mock(return_value="Filtered log message")
|
||||
|
||||
# Call the format method
|
||||
formatted_log = formatter.format(log_record)
|
||||
|
||||
# Assertions
|
||||
expected_log = "INFO|test_app_name|test_commit_hash|test_app_id|test_session_id|test_user_id|Filtered log message"
|
||||
|
||||
print(expected_log)
|
||||
print(formatted_log)
|
||||
|
||||
assert formatted_log == expected_log
|
||||
|
||||
# Check if the mock methods were called
|
||||
formatter.calculate_level_name.assert_called_once()
|
||||
formatter.filter_log_line.assert_called_once()
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from openbb_core.app.logs.handlers.path_tracking_file_handler import (
|
||||
PathTrackingFileHandler,
|
||||
)
|
||||
|
||||
|
||||
class MockLoggingSettings:
|
||||
def __init__(self, app_name, user_logs_directory, session_id, frequency):
|
||||
self.app_name = app_name
|
||||
self.user_logs_directory = Path(user_logs_directory)
|
||||
self.session_id = session_id
|
||||
self.frequency = frequency
|
||||
|
||||
|
||||
logging_settings = MagicMock(spec=MockLoggingSettings)
|
||||
logging_settings.app_name = "test_app_name_xpto"
|
||||
logging_settings.user_logs_directory = MagicMock()
|
||||
logging_settings.user_logs_directory.absolute.return_value = Path(
|
||||
"/mocked/logs/directory"
|
||||
)
|
||||
logging_settings.session_id = "test_session_id"
|
||||
logging_settings.frequency = "H"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def handler():
|
||||
# patch `pathlib.Path.joinpath` to return a string containing the joined path
|
||||
with patch.object(Path, "joinpath", return_value=Path("mocked_path")):
|
||||
return PathTrackingFileHandler(logging_settings)
|
||||
|
||||
|
||||
def test_build_log_file_path(handler):
|
||||
# Define a sample LoggingSettings object with mock attributes
|
||||
settings = MagicMock(spec=MockLoggingSettings)
|
||||
settings.app_name = "my_app"
|
||||
settings.user_logs_directory = MagicMock()
|
||||
settings.user_logs_directory.absolute.return_value = Path("/mocked/logs/directory")
|
||||
settings.session_id = "abc123"
|
||||
|
||||
# patch `pathlib.Path.joinpath` to return a string containing the joined path
|
||||
with patch.object(
|
||||
Path, "joinpath", return_value=Path("mocked_path")
|
||||
) as mock_joinpath:
|
||||
result_path = handler.build_log_file_path(settings)
|
||||
|
||||
# Assert the result is correct
|
||||
assert result_path == Path("mocked_path")
|
||||
|
||||
mock_joinpath.assert_called_once_with("my_app_abc123")
|
||||
|
||||
|
||||
def test_clean_expired_files(handler):
|
||||
with patch(
|
||||
"openbb_core.app.logs.handlers.path_tracking_file_handler.get_expired_file_list"
|
||||
) as mock_get_expired_file_list, patch(
|
||||
"openbb_core.app.logs.handlers.path_tracking_file_handler.remove_file_list"
|
||||
) as mock_remove_file_list:
|
||||
handler.clean_expired_files(123)
|
||||
|
||||
assert mock_get_expired_file_list.call_count == 3
|
||||
assert mock_remove_file_list.call_count == 3
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from openbb_core.app.logs.handlers.posthog_handler import (
|
||||
PosthogHandler,
|
||||
)
|
||||
import logging
|
||||
|
||||
|
||||
class MockLoggingSettings:
|
||||
def __init__(
|
||||
self,
|
||||
app_name,
|
||||
user_logs_directory,
|
||||
session_id,
|
||||
frequency,
|
||||
appid,
|
||||
commit_hash,
|
||||
platform,
|
||||
python_version,
|
||||
terminal_version,
|
||||
branch,
|
||||
userid,
|
||||
):
|
||||
self.app_name = app_name
|
||||
self.user_logs_directory = Path(user_logs_directory)
|
||||
self.session_id = session_id
|
||||
self.frequency = frequency
|
||||
self.app_id = appid
|
||||
self.commit_hash = commit_hash
|
||||
self.platform = platform
|
||||
self.python_version = python_version
|
||||
self.terminal_version = terminal_version
|
||||
self.branch = branch
|
||||
self.user_id = userid
|
||||
|
||||
|
||||
logging_settings = MagicMock(spec=MockLoggingSettings)
|
||||
logging_settings.app_name = "TestApp"
|
||||
logging_settings.user_logs_directory = MagicMock()
|
||||
logging_settings.user_logs_directory.absolute.return_value = Path(
|
||||
"/mocked/logs/directory"
|
||||
)
|
||||
logging_settings.session_id = "session123"
|
||||
logging_settings.frequency = "H"
|
||||
logging_settings.app_id = "test123"
|
||||
logging_settings.commit_hash = "commit123"
|
||||
logging_settings.platform = "Windows"
|
||||
logging_settings.python_version = "3.9"
|
||||
logging_settings.terminal_version = "1.2.3"
|
||||
logging_settings.branch = "main"
|
||||
logging_settings.user_id = "user123"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def handler():
|
||||
return PosthogHandler(logging_settings)
|
||||
|
||||
|
||||
def test_emit_calls_send(mocker, handler):
|
||||
# Arrange
|
||||
record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.INFO,
|
||||
pathname="test.py",
|
||||
lineno=42,
|
||||
msg="Test message",
|
||||
args=None,
|
||||
exc_info=None,
|
||||
)
|
||||
|
||||
# Mock the send method
|
||||
handler.send = mocker.MagicMock()
|
||||
|
||||
# Act
|
||||
handler.emit(record)
|
||||
|
||||
# Assert
|
||||
handler.send.assert_called_once_with(record=record)
|
||||
|
||||
|
||||
def test_emit_calls_handleError_when_send_raises_exception(mocker, handler):
|
||||
# Arrange
|
||||
record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.ERROR,
|
||||
pathname="test.py",
|
||||
lineno=42,
|
||||
msg="Test error message",
|
||||
args=None,
|
||||
exc_info=None,
|
||||
)
|
||||
|
||||
# Mock the send method to raise an exception
|
||||
handler.send = mocker.MagicMock(side_effect=Exception)
|
||||
|
||||
# Mock the handleError method
|
||||
handler.handleError = mocker.MagicMock()
|
||||
|
||||
# Act
|
||||
handler.emit(record)
|
||||
|
||||
# Assert
|
||||
handler.send.assert_called_once_with(record=record)
|
||||
handler.handleError.assert_called_once_with(record)
|
||||
|
||||
|
||||
def test_emit_calls_handleError_when_send_raises_exception_of_specific_type(
|
||||
mocker, handler
|
||||
):
|
||||
# Arrange
|
||||
record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.ERROR,
|
||||
pathname="test.py",
|
||||
lineno=42,
|
||||
msg="Test error message",
|
||||
args=None,
|
||||
exc_info=None,
|
||||
)
|
||||
|
||||
# Mock the send method to raise an exception of a specific type
|
||||
handler.send = mocker.MagicMock(side_effect=ValueError)
|
||||
|
||||
# Mock the handleError method
|
||||
handler.handleError = mocker.MagicMock()
|
||||
|
||||
# Act
|
||||
handler.emit(record)
|
||||
|
||||
# Assert
|
||||
handler.send.assert_called_once_with(record=record)
|
||||
handler.handleError.assert_called_once_with(record)
|
||||
|
||||
|
||||
def test_emit_calls_handleError_when_send_raises_exception_of_another_type(
|
||||
mocker, handler
|
||||
):
|
||||
# Arrange
|
||||
record = logging.LogRecord(
|
||||
name="test_logger",
|
||||
level=logging.ERROR,
|
||||
pathname="test.py",
|
||||
lineno=42,
|
||||
msg="Test error message",
|
||||
args=None,
|
||||
exc_info=None,
|
||||
)
|
||||
|
||||
# Mock the send method to raise an exception of another type
|
||||
handler.send = mocker.MagicMock(side_effect=TypeError)
|
||||
|
||||
# Mock the handleError method
|
||||
handler.handleError = mocker.MagicMock()
|
||||
|
||||
# Act
|
||||
handler.emit(record)
|
||||
|
||||
# Assert
|
||||
handler.send.assert_called_once_with(record=record)
|
||||
handler.handleError.assert_called_once_with(record)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"log_info, expected_dict",
|
||||
[
|
||||
(
|
||||
'STARTUP: {"status": "success"}',
|
||||
{"STARTUP": {"status": "success"}},
|
||||
),
|
||||
(
|
||||
'{"INPUT": {"something_something":"something_something"}}',
|
||||
{
|
||||
"SDK": {"INPUT": {"something_something": "something_something"}},
|
||||
},
|
||||
),
|
||||
(
|
||||
'CMD: {"path": "/stocks/", "known_cmd": "load", "other_args": "aapl", "input": "load aapl"}',
|
||||
{
|
||||
"CMD": {
|
||||
"path": "/stocks/",
|
||||
"known_cmd": "load",
|
||||
"other_args": "aapl",
|
||||
"input": "load aapl",
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_log_to_dict(handler, log_info, expected_dict):
|
||||
# Act
|
||||
result = handler.log_to_dict(log_info)
|
||||
|
||||
# Assert
|
||||
assert result == expected_dict
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"record, expected_extra",
|
||||
[
|
||||
(
|
||||
logging.LogRecord(
|
||||
"name", logging.INFO, "pathname", 42, "message", (), None, None
|
||||
),
|
||||
{
|
||||
"appName": "TestApp",
|
||||
"appId": "test123",
|
||||
"sessionId": "session123",
|
||||
"commitHash": "commit123",
|
||||
"platform": "Windows",
|
||||
"pythonVersion": "3.9",
|
||||
"terminalVersion": "1.2.3",
|
||||
"branch": "main",
|
||||
"userId": "user123",
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_extract_log_extra(handler, record, expected_extra):
|
||||
# Act
|
||||
result = handler.extract_log_extra(record)
|
||||
|
||||
# Assert
|
||||
assert result == expected_extra
|
||||
|
||||
@@ -1,6 +1,149 @@
|
||||
from openbb_core.app.logs.utils.expired_files import get_timestamp_from_x_days
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from time import time
|
||||
|
||||
import pytest
|
||||
from openbb_core.app.logs.utils.expired_files import (
|
||||
get_expired_file_list,
|
||||
get_timestamp_from_x_days,
|
||||
remove_file_list,
|
||||
)
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_test_files():
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
temp_files = [
|
||||
Path(temp_dir) / "file1.txt",
|
||||
Path(temp_dir) / "file2.txt",
|
||||
Path(temp_dir) / "file3.txt",
|
||||
]
|
||||
|
||||
# Create some test files
|
||||
for file_path in temp_files:
|
||||
file_path.touch()
|
||||
|
||||
yield temp_dir, temp_files
|
||||
|
||||
|
||||
def test_get_timestamp_from_x_days():
|
||||
result = get_timestamp_from_x_days(0)
|
||||
assert isinstance(result, float)
|
||||
|
||||
|
||||
# Test case when all files are expired
|
||||
def test_all_files_expired(temp_test_files):
|
||||
temp_dir, temp_files = temp_test_files
|
||||
before_timestamp = time() + 3 * 86400 # timestmap 3 days from now
|
||||
expired_files = get_expired_file_list(Path(temp_dir), before_timestamp)
|
||||
assert set(expired_files) == set(temp_files)
|
||||
|
||||
|
||||
# Test case when no files are expired
|
||||
def test_no_files_expired(temp_test_files):
|
||||
temp_dir, _ = temp_test_files
|
||||
before_timestamp = 0
|
||||
expired_files = get_expired_file_list(Path(temp_dir), before_timestamp)
|
||||
assert expired_files == []
|
||||
|
||||
|
||||
# Test case when some files are expired and some are not
|
||||
def test_some_files_expired(temp_test_files):
|
||||
temp_dir, _ = temp_test_files
|
||||
|
||||
# add temp file to temp_dir with timestamp in the future
|
||||
temp_file = Path(temp_dir) / "file4.txt"
|
||||
temp_file.touch()
|
||||
time_in_future = time() + 4 * 86400 # timestmap 4 days from now
|
||||
os.utime(temp_file, times=(time_in_future, time_in_future))
|
||||
|
||||
before_timestamp = time() + 3 * 86400 # timestmap 3 days from now
|
||||
expired_files = get_expired_file_list(Path(temp_dir), before_timestamp)
|
||||
assert len(expired_files) == 3
|
||||
|
||||
# assert number of files in temp_dir is 4
|
||||
assert len(list(Path(temp_dir).iterdir())) == 4
|
||||
|
||||
|
||||
# Test case when the directory does not exist
|
||||
def test_directory_not_exists():
|
||||
directory = Path("/path/that/does/not/exist")
|
||||
before_timestamp = time()
|
||||
expired_files = get_expired_file_list(directory, before_timestamp)
|
||||
assert expired_files == []
|
||||
|
||||
|
||||
# Test case when the directory is not a directory
|
||||
def test_directory_not_dir(temp_test_files):
|
||||
_, temp_files = temp_test_files
|
||||
before_timestamp = time()
|
||||
expired_files = get_expired_file_list(temp_files[0], before_timestamp)
|
||||
assert expired_files == []
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_path():
|
||||
# Create a MagicMock for the Path class to represent a file path
|
||||
return MagicMock()
|
||||
|
||||
|
||||
def test_remove_file_list_no_files(mock_path, mocker):
|
||||
# Arrange
|
||||
# Let's assume the file list is empty, meaning there are no files to remove
|
||||
file_list = []
|
||||
|
||||
# Act
|
||||
remove_file_list(file_list)
|
||||
|
||||
# Assert
|
||||
# No interaction with the filesystem should occur
|
||||
assert not mock_path.unlink.called
|
||||
|
||||
|
||||
def test_remove_file_list_remove_files_successfully(mock_path, mocker):
|
||||
# Arrange
|
||||
# Let's assume we have three files in the file list
|
||||
file_list = [mock_path, mock_path, mock_path]
|
||||
|
||||
# Mock the unlink method to avoid actual filesystem interaction
|
||||
mocker.patch.object(mock_path, "unlink")
|
||||
|
||||
# Act
|
||||
remove_file_list(file_list)
|
||||
|
||||
# Assert
|
||||
# unlink should have been called three times since there are three files in the list
|
||||
assert mock_path.unlink.call_count == 3
|
||||
|
||||
|
||||
def test_remove_file_list_ignore_permission_error(mock_path, mocker):
|
||||
# Arrange
|
||||
# Let's assume we have three files in the file list
|
||||
file_list = [mock_path, mock_path, mock_path]
|
||||
|
||||
# Mock the unlink method to raise a PermissionError
|
||||
mocker.patch.object(mock_path, "unlink", side_effect=PermissionError)
|
||||
|
||||
# Act
|
||||
remove_file_list(file_list)
|
||||
|
||||
# Assert
|
||||
# unlink should have been called three times since there are three files in the list
|
||||
assert mock_path.unlink.call_count == 3
|
||||
|
||||
|
||||
def test_remove_file_list_other_exception(mock_path, mocker):
|
||||
# Arrange
|
||||
# Let's assume we have three files in the file list
|
||||
file_list = [mock_path, mock_path, mock_path]
|
||||
|
||||
# Mock the unlink method to raise an exception other than PermissionError
|
||||
mocker.patch.object(mock_path, "unlink", side_effect=OSError)
|
||||
|
||||
# Act & Assert
|
||||
# The exception should be raised since it is not suppressed by the contextlib
|
||||
with pytest.raises(OSError):
|
||||
remove_file_list(file_list)
|
||||
|
||||
Reference in New Issue
Block a user