diff options
Diffstat (limited to 'openbb_platform/core/tests/app/logs')
11 files changed, 138 insertions, 20 deletions
diff --git a/openbb_platform/core/tests/app/logs/__init__.py b/openbb_platform/core/tests/app/logs/__init__.py index e69de29bb2d..673bc2dec2f 100644 --- a/openbb_platform/core/tests/app/logs/__init__.py +++ b/openbb_platform/core/tests/app/logs/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core.""" diff --git a/openbb_platform/core/tests/app/logs/formatters/__init__.py b/openbb_platform/core/tests/app/logs/formatters/__init__.py index e69de29bb2d..3f4c8aabdda 100644 --- a/openbb_platform/core/tests/app/logs/formatters/__init__.py +++ b/openbb_platform/core/tests/app/logs/formatters/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform core tests.""" diff --git a/openbb_platform/core/tests/app/logs/formatters/test_formatter_with_exceptions.py b/openbb_platform/core/tests/app/logs/formatters/test_formatter_with_exceptions.py index 662187bfdb4..625c0bc87cc 100644 --- a/openbb_platform/core/tests/app/logs/formatters/test_formatter_with_exceptions.py +++ b/openbb_platform/core/tests/app/logs/formatters/test_formatter_with_exceptions.py @@ -1,3 +1,5 @@ +"""Tests for the FormatterWithExceptions class.""" + import logging import os from unittest.mock import Mock @@ -7,6 +9,8 @@ from openbb_core.app.logs.formatters.formatter_with_exceptions import ( FormatterWithExceptions, ) +# pylint: disable=W0621 + logging_settings = Mock() logging_settings.app_name = "test_app_name" logging_settings.app_id = "test_app_id" @@ -16,11 +20,13 @@ logging_settings.user_id = "test_user_id" @pytest.fixture def formatter(): + """Return a FormatterWithExceptions instance.""" return FormatterWithExceptions(logging_settings) # Test when exc_text is not empty (should return "X") def test_level_name_with_exc_text(formatter): + """Test the calculate_level_name method.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, @@ -37,6 +43,7 @@ def test_level_name_with_exc_text(formatter): # Test when levelname is not empty (should return the first character of levelname) def test_level_name_with_levelname(formatter): + """Test the calculate_level_name method.""" record = logging.LogRecord( name="test_logger", level=logging.WARNING, @@ -53,6 +60,7 @@ def test_level_name_with_levelname(formatter): # Test when func_name_override and session_id are present in the record def test_extract_log_extra_with_override_and_session_id(formatter): + """Test the extract_log_extra method.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, @@ -75,6 +83,7 @@ def test_extract_log_extra_with_override_and_session_id(formatter): # Test when only func_name_override is present in the record def test_extract_log_extra_with_override(formatter): + """Test the extract_log_extra method.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, @@ -96,6 +105,7 @@ def test_extract_log_extra_with_override(formatter): # Test when only session_id is present in the record def test_extract_log_extra_with_session_id(formatter): + """Test the extract_log_extra method.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, @@ -117,6 +127,7 @@ def test_extract_log_extra_with_session_id(formatter): # 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): + """Test the extract_log_extra method.""" record = logging.LogRecord( name="test_logger", level=logging.INFO, @@ -144,6 +155,7 @@ def test_extract_log_extra_with_no_override_or_session_id(formatter): ], ) def test_mock_ipv4(input_text, expected_output, formatter): + """Test the mock_ipv4 method.""" assert formatter.mock_ipv4(input_text) == expected_output @@ -158,6 +170,7 @@ def test_mock_ipv4(input_text, expected_output, formatter): ], ) def test_mock_email(input_text, expected_output, formatter): + """Test the mock_email method.""" assert formatter.mock_email(input_text) == expected_output @@ -175,6 +188,7 @@ def test_mock_email(input_text, expected_output, formatter): ], ) def test_mock_password(input_text, expected_output, formatter): + """Test the mock_password method.""" assert formatter.mock_password(input_text) == expected_output @@ -190,6 +204,7 @@ def test_mock_password(input_text, expected_output, formatter): ], ) def test_mock_flair(input_text, expected_output, formatter): + """Test the mock_flair method.""" assert formatter.mock_flair(input_text) == expected_output @@ -212,6 +227,7 @@ def test_mock_flair(input_text, expected_output, formatter): ], ) def test_mock_home_directory(input_text, expected_output, formatter): + """Test the mock_home_directory method.""" assert formatter.mock_home_directory(input_text) == expected_output @@ -232,6 +248,7 @@ def test_mock_home_directory(input_text, expected_output, formatter): ], ) def test_filter_special_tags(input_text, expected_output, formatter): + """Test the filter_special_tags method.""" assert formatter.filter_special_tags(input_text) == expected_output @@ -249,6 +266,7 @@ def test_filter_special_tags(input_text, expected_output, formatter): ], ) def test_filter_piis(input_text, expected_output, formatter): + """Test the filter_piis method.""" assert formatter.filter_piis(input_text) == expected_output @@ -267,15 +285,18 @@ def test_filter_piis(input_text, expected_output, formatter): ], ) def test_filter_log_line(input_text, expected_output, formatter): + """Test the filter_log_line method.""" assert formatter.filter_log_line(input_text) == expected_output def test_formatException_invalid(): + """Test the formatException method with an invalid exception.""" with pytest.raises(Exception): - formatter.formatException(Exception("Big bad error")) + formatter.formatException(Exception("Big bad error")) # type: ignore[attr-defined] def test_format(formatter): + """Test the format method.""" # Prepare the log record log_record = logging.LogRecord( name="test_logger", diff --git a/openbb_platform/core/tests/app/logs/handlers/__init__.py b/openbb_platform/core/tests/app/logs/handlers/__init__.py index e69de29bb2d..55cb40ff9e8 100644 --- a/openbb_platform/core/tests/app/logs/handlers/__init__.py +++ b/openbb_platform/core/tests/app/logs/handlers/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/app/logs/handlers/test_path_tracking_file_handler.py b/openbb_platform/core/tests/app/logs/handlers/test_path_tracking_file_handler.py index 40dae4a702f..ba81d15e1ab 100644 --- a/openbb_platform/core/tests/app/logs/handlers/test_path_tracking_file_handler.py +++ b/openbb_platform/core/tests/app/logs/handlers/test_path_tracking_file_handler.py @@ -12,7 +12,10 @@ from openbb_core.app.logs.handlers.path_tracking_file_handler import ( class MockLoggingSettings: + """Mock logging settings.""" + def __init__(self, app_name, user_logs_directory, session_id, frequency): + """Initialize the mock logging settings.""" self.app_name = app_name self.user_logs_directory = Path(user_logs_directory) self.session_id = session_id @@ -31,17 +34,20 @@ logging_settings.frequency = "H" @pytest.fixture(scope="module") def mocked_path(tmp_path_factory): + """Fixture to create a mocked file path.""" return tmp_path_factory.mktemp("mocked_path") / "mocked_file.log" @pytest.fixture(scope="module") def handler(mocked_path): + """Fixture to create a PathTrackingFileHandler instance.""" # patch `pathlib.Path.joinpath` to return a string containing the joined path with patch.object(Path, "joinpath", return_value=mocked_path): return PathTrackingFileHandler(logging_settings) def test_build_log_file_path(handler, mocked_path): + """Test build_log_file_path method.""" # Define a sample LoggingSettings object with mock attributes settings = MagicMock(spec=MockLoggingSettings) settings.app_name = "my_app" @@ -60,6 +66,7 @@ def test_build_log_file_path(handler, mocked_path): def test_clean_expired_files(handler): + """Test clean_expired_files method.""" with patch( "openbb_core.app.logs.handlers.path_tracking_file_handler.get_expired_file_list" ) as mock_get_expired_file_list, patch( diff --git a/openbb_platform/core/tests/app/logs/handlers/test_posthog_handler.py b/openbb_platform/core/tests/app/logs/handlers/test_posthog_handler.py index 5038f3ec016..5e795a4bf5f 100644 --- a/openbb_platform/core/tests/app/logs/handlers/test_posthog_handler.py +++ b/openbb_platform/core/tests/app/logs/handlers/test_posthog_handler.py @@ -1,3 +1,5 @@ +"""Tests for the PosthogHandler class.""" + import logging from pathlib import Path from unittest.mock import MagicMock @@ -8,7 +10,10 @@ from openbb_core.app.logs.handlers.posthog_handler import ( ) +# pylint: disable=W0621, R0913 class MockLoggingSettings: + """Mock logging settings.""" + def __init__( self, app_name, @@ -22,6 +27,7 @@ class MockLoggingSettings: platform_version, userid, ): + """Initialize the mock logging settings.""" self.app_name = app_name self.sub_app_name = sub_app_name self.user_logs_directory = Path(user_logs_directory) @@ -52,10 +58,12 @@ logging_settings.user_id = "user123" @pytest.fixture def handler(): + """Fixture to create a PosthogHandler instance.""" return PosthogHandler(logging_settings) def test_emit_calls_send(handler): + """Test the emit method.""" # Arrange record = logging.LogRecord( name="test_logger", @@ -78,6 +86,7 @@ def test_emit_calls_send(handler): def test_emit_calls_handleError_when_send_raises_exception(handler): + """Test the emit method.""" # Arrange record = logging.LogRecord( name="test_logger", @@ -104,6 +113,7 @@ def test_emit_calls_handleError_when_send_raises_exception(handler): def test_emit_calls_handleError_when_send_raises_exception_of_specific_type(handler): + """Test the emit method.""" # Arrange record = logging.LogRecord( name="test_logger", @@ -130,6 +140,7 @@ def test_emit_calls_handleError_when_send_raises_exception_of_specific_type(hand def test_emit_calls_handleError_when_send_raises_exception_of_another_type(handler): + """Test the emit method.""" # Arrange record = logging.LogRecord( name="test_logger", @@ -176,6 +187,7 @@ def test_emit_calls_handleError_when_send_raises_exception_of_another_type(handl ], ) def test_log_to_dict(handler, log_info, expected_dict): + """Test the log_to_dict method.""" # Act result = handler.log_to_dict(log_info) @@ -204,6 +216,7 @@ def test_log_to_dict(handler, log_info, expected_dict): ], ) def test_extract_log_extra(handler, record, expected_extra): + """Test the extract_log_extra method.""" # Act result = handler.extract_log_extra(record) diff --git a/openbb_platform/core/tests/app/logs/test_handlers_manager.py b/openbb_platform/core/tests/app/logs/test_handlers_manager.py index 12cb4565d9d..d46451c6314 100644 --- a/openbb_platform/core/tests/app/logs/test_handlers_manager.py +++ b/openbb_platform/core/tests/app/logs/test_handlers_manager.py @@ -1,3 +1,5 @@ +"""Tests for the handlers manager.""" + import logging from unittest.mock import Mock, patch @@ -7,25 +9,37 @@ from openbb_core.app.logs.handlers_manager import ( PosthogHandler, ) +# pylint: disable=W0231 + class MockPosthogHandler(logging.NullHandler): + """Mock posthog handler.""" + def __init__(self, settings): + """Initialize the handler.""" self.settings = settings self.level = logging.DEBUG class MockPathTrackingFileHandler(logging.NullHandler): + """Mock path tracking file handler.""" + def __init__(self, settings): + """Initialize the handler.""" self.settings = settings self.level = logging.DEBUG class MockFormatterWithExceptions(logging.Formatter): + """Mock formatter with exceptions.""" + def __init__(self, settings): + """Initialize the formatter.""" self.settings = settings def test_handlers_added_correctly(): + """Test if the handlers are added correctly.""" with patch( "openbb_core.app.logs.handlers_manager.PosthogHandler", MockPosthogHandler, @@ -60,6 +74,7 @@ def test_handlers_added_correctly(): def test_update_handlers(): + """Test if the handlers are updated correctly.""" with patch( "openbb_core.app.logs.handlers_manager.PosthogHandler", MockPosthogHandler, @@ -85,4 +100,4 @@ def test_update_handlers(): for hdlr in handlers: if isinstance(hdlr, (MockPosthogHandler, MockPathTrackingFileHandler)): assert hdlr.settings == changed_settings - assert hdlr.formatter.settings == changed_settings + assert hdlr.formatter.settings == changed_settings # type: ignore[union-attr] diff --git a/openbb_platform/core/tests/app/logs/test_logging_service.py b/openbb_platform/core/tests/app/logs/test_logging_service.py index bd7460bc3c2..8eef4b90137 100644 --- a/openbb_platform/core/tests/app/logs/test_logging_service.py +++ b/openbb_platform/core/tests/app/logs/test_logging_service.py @@ -1,3 +1,5 @@ +"""Test LoggingService class.""" + import json from typing import Optional from unittest.mock import MagicMock, Mock, patch @@ -8,25 +10,30 @@ from openbb_core.app.model.abstract.error import OpenBBError from pydantic import BaseModel # ruff: noqa: S106 +# pylint: disable=redefined-outer-name, protected-access class MockLoggingSettings: + """Mock logging settings.""" + def __init__(self, system_settings, user_settings): + """Initialize the mock logging settings.""" self.system_settings = system_settings self.user_settings = user_settings class MockOBBject(BaseModel): + """Mock object for testing.""" + output: Optional[str] = None error: Optional[str] = None @pytest.fixture(scope="function") def logging_service(): + """Return a LoggingService instance.""" mock_system_settings = Mock() - mock_system_settings = "mock_system_settings" mock_user_settings = Mock() - mock_user_settings = "mock_user_settings" mock_setup_handlers = Mock() mock_log_startup = Mock() @@ -40,22 +47,42 @@ def logging_service(): "openbb_core.app.logs.logging_service.LoggingService._log_startup", mock_log_startup, ): - logging_service = LoggingService( + _logging_service = LoggingService( system_settings=mock_system_settings, user_settings=mock_user_settings, ) - assert mock_setup_handlers.assert_called_once - assert mock_log_startup.assert_called_once + return _logging_service - return logging_service +def test_correctly_initialized(): + """Test the LoggingService is correctly initialized.""" + mock_system_settings = Mock() + mock_user_settings = Mock() + mock_setup_handlers = Mock() + mock_log_startup = Mock() + + with patch( + "openbb_core.app.logs.logging_service.LoggingSettings", + MockLoggingSettings, + ), patch( + "openbb_core.app.logs.logging_service.LoggingService._setup_handlers", + mock_setup_handlers, + ), patch( + "openbb_core.app.logs.logging_service.LoggingService._log_startup", + mock_log_startup, + ): + LoggingService( + system_settings=mock_system_settings, + user_settings=mock_user_settings, + ) -def test_correctly_initialized(logging_service): - assert logging_service + mock_setup_handlers.assert_called_once() + mock_log_startup.assert_called_once() def test_logging_settings_setter(logging_service): + """Test the logging_settings setter.""" custom_user_settings = "custom_user_settings" custom_system_settings = "custom_system_settings" @@ -68,11 +95,12 @@ def test_logging_settings_setter(logging_service): custom_user_settings, ) - assert logging_service.logging_settings.system_settings == "custom_system_settings" - assert logging_service.logging_settings.user_settings == "custom_user_settings" + assert logging_service.logging_settings.system_settings == "custom_system_settings" # type: ignore[attr-defined] + assert logging_service.logging_settings.user_settings == "custom_user_settings" # type: ignore[attr-defined] def test_log_startup(logging_service): + """Test the log_startup method.""" with patch("logging.getLogger") as mock_get_logger: mock_info = mock_get_logger.return_value.info @@ -93,7 +121,10 @@ def test_log_startup(logging_service): expected_log_data = { "route": "test_route", "PREFERENCES": "your_preferences", - "KEYS": {"username": "defined", "password": "defined"}, + "KEYS": { + "username": "defined", + "password": "defined", # pragma: allowlist secret + }, "SYSTEM": "your_system_settings", "custom_headers": {"X-OpenBB-Test": "test"}, } @@ -101,7 +132,7 @@ def test_log_startup(logging_service): "STARTUP: %s ", json.dumps(expected_log_data), ) - mock_get_logger.assert_called_once + mock_get_logger.assert_called_once() @pytest.mark.parametrize( @@ -146,6 +177,7 @@ def test_log( exec_info, custom_headers, ): + """Test the log method.""" with patch( "openbb_core.app.logs.logging_service.LoggingSettings", MockLoggingSettings, @@ -163,7 +195,7 @@ def test_log( exec_info=exec_info, custom_headers=custom_headers, ) - assert mock_log_startup.assert_called_once + mock_log_startup.assert_called_once() else: mock_info = mock_get_logger.return_value.info diff --git a/openbb_platform/core/tests/app/logs/utils/__init__.py b/openbb_platform/core/tests/app/logs/utils/__init__.py index e69de29bb2d..55cb40ff9e8 100644 --- a/openbb_platform/core/tests/app/logs/utils/__init__.py +++ b/openbb_platform/core/tests/app/logs/utils/__init__.py @@ -0,0 +1 @@ +"""OpenBB Platform Core tests.""" diff --git a/openbb_platform/core/tests/app/logs/utils/test_expired_files.py b/openbb_platform/core/tests/app/logs/utils/test_expired_files.py index 8d785ef80d2..1cb7897eb25 100644 --- a/openbb_platform/core/tests/app/logs/utils/test_expired_files.py +++ b/openbb_platform/core/tests/app/logs/utils/test_expired_files.py @@ -1,7 +1,10 @@ +"""Tests for the expired_files module.""" + import os import tempfile from pathlib import Path from time import time +from typing import List from unittest.mock import MagicMock, patch import pytest @@ -11,9 +14,12 @@ from openbb_core.app.logs.utils.expired_files import ( remove_file_list, ) +# pylint: disable=W0621 + @pytest.fixture def temp_test_files(): + """Create temporary files for testing.""" with tempfile.TemporaryDirectory() as temp_dir: temp_files = [ Path(temp_dir) / "file1.txt", @@ -29,12 +35,14 @@ def temp_test_files(): def test_get_timestamp_from_x_days(): + """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): + """Test get_expired_file_list when all files are expired.""" temp_dir, temp_files = temp_test_files before_timestamp = time() + 3 * 86400 # timestamp 3 days from now expired_files = get_expired_file_list(Path(temp_dir), before_timestamp) @@ -43,14 +51,16 @@ def test_all_files_expired(temp_test_files): # Test case when no files are expired def test_no_files_expired(temp_test_files): + """Test get_expired_file_list when no files are expired.""" temp_dir, _ = temp_test_files before_timestamp = 0 expired_files = get_expired_file_list(Path(temp_dir), before_timestamp) - assert expired_files == [] + assert not expired_files # Test case when some files are expired and some are not def test_some_files_expired(temp_test_files): + """Test get_expired_file_list when some files are expired and some are not.""" temp_dir, _ = temp_test_files # add temp file to temp_dir with timestamp in the future @@ -69,30 +79,34 @@ def test_some_files_expired(temp_test_files): # Test case when the directory does not exist def test_directory_not_exists(): + """Test get_expired_file_list when the directory does not exist.""" directory = Path("/path/that/does/not/exist") before_timestamp = time() expired_files = get_expired_file_list(directory, before_timestamp) - assert expired_files == [] + assert not expired_files # Test case when the directory is not a directory def test_directory_not_dir(temp_test_files): + """Test get_expired_file_list when the directory is not a directory.""" _, temp_files = temp_test_files before_timestamp = time() expired_files = get_expired_file_list(temp_files[0], before_timestamp) - assert expired_files == [] + assert not expired_files @pytest.fixture def mock_path(): + """Return a MagicMock for the Path class.""" # Create a MagicMock for the Path class to represent a file path return MagicMock() def test_remove_file_list_no_files(mock_path): + """Test remove_file_list when there are no files to remove.""" # Arrange # Let's assume the file list is empty, meaning there are no files to remove - file_list = [] + file_list: List[Path] = [] # Act remove_file_list(file_list) @@ -103,6 +117,7 @@ def test_remove_file_list_no_files(mock_path): def test_remove_file_list_remove_files_successfully(mock_path): + """Test remove_file_list when unlink is successful.""" # Arrange # Let's assume we have three files in the file list file_list = [mock_path, mock_path, mock_path] @@ -119,6 +134,7 @@ def test_remove_file_list_remove_files_successfully(mock_path): def test_remove_file_list_ignore_permission_error(mock_path): + """Test remove_file_list when unlink raises a PermissionError.""" # Arrange # Let's assume we have three files in the file list file_list = [mock_path, mock_path, mock_path] @@ -135,6 +151,7 @@ def test_remove_file_list_ignore_permission_error(mock_path): def test_remove_file_list_other_exception(mock_path): + """Test remove_file_list when unlink raises an exception other than PermissionError.""" # Arrange # Let's assume we have three files in the file list file_list = [mock_path, mock_path, mock_path] diff --git a/openbb_platform/core/tests/app/logs/utils/test_utils.py b/openbb_platform/core/tests/app/logs/utils/test_utils.py index f3715abc434..9cda5662e2f 100644 --- a/openbb_platform/core/tests/app/logs/utils/test_utils.py +++ b/openbb_platform/core/tests/app/logs/utils/test_utils.py @@ -1,3 +1,5 @@ +"""OpenBB Platform Core tests.""" + import uuid from pathlib import Path from unittest.mock import patch @@ -9,12 +11,14 @@ from openbb_core.app.logs.utils.utils import get_app_id, get_log_dir, get_sessio def test_get_session_id_return_type(): + """Test if the returned value is a string.""" # Test if the returned value is a string session_id = get_session_id() assert isinstance(session_id, str) def test_get_session_id_format(): + """Test if the returned string has the format "UUID-current_time.""" # Test if the returned string has the format "UUID-current_time" session_id = get_session_id() @@ -33,6 +37,7 @@ def test_get_session_id_format(): def test_get_session_id_uniqueness(): + """Test if subsequent calls return different session IDs.""" # Test if subsequent calls return different session IDs session_id1 = get_session_id() session_id2 = get_session_id() @@ -43,9 +48,10 @@ def test_get_session_id_uniqueness(): def test_get_app_id_success(): + """Test get_app_id function.""" # Mock the return value of get_log_dir to simulate a successful scenario with patch("openbb_core.app.logs.utils.utils.get_log_dir") as mock_get_log_dir: - mock_get_log_dir + mock_get_log_dir # pylint: disable=pointless-statement mock_get_log_dir.return_value = |