summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorIgor Radovanovic <74266147+IgorWounds@users.noreply.github.com>2024-05-12 17:58:55 +0200
committerIgor Radovanovic <74266147+IgorWounds@users.noreply.github.com>2024-05-12 17:58:55 +0200
commit89db70230116831fa2fac636e18b6d005f1a2c48 (patch)
treef8a024be9c1ae785f39f49d9e661e6def99c5750
parentac745adb05e732a94e7f19d92a72b805902c49bf (diff)
Unit test batch 1
-rw-r--r--cli/tests/test_cli.py45
-rw-r--r--cli/tests/test_controllers_base_controller.py79
-rw-r--r--cli/tests/test_controllers_base_platform_controller.py70
-rw-r--r--cli/tests/test_controllers_choices.py51
-rw-r--r--cli/tests/test_models_settings.py72
-rw-r--r--cli/tests/test_session.py44
6 files changed, 361 insertions, 0 deletions
diff --git a/cli/tests/test_cli.py b/cli/tests/test_cli.py
new file mode 100644
index 00000000000..1fe19344f0f
--- /dev/null
+++ b/cli/tests/test_cli.py
@@ -0,0 +1,45 @@
+"""Test the CLI module."""
+
+from unittest.mock import patch
+
+from openbb_cli.cli import main
+
+
+@patch("openbb_cli.cli.bootstrap")
+@patch("openbb_cli.cli.launch")
+@patch("sys.argv", ["openbb", "--dev", "--debug"])
+def test_main_with_dev_and_debug(mock_launch, mock_bootstrap):
+ """Test the main function with dev and debug flags."""
+ main()
+ mock_bootstrap.assert_called_once()
+ mock_launch.assert_called_once_with(True, True)
+
+
+@patch("openbb_cli.cli.bootstrap")
+@patch("openbb_cli.cli.launch")
+@patch("sys.argv", ["openbb"])
+def test_main_without_arguments(mock_launch, mock_bootstrap):
+ """Test the main function without arguments."""
+ main()
+ mock_bootstrap.assert_called_once()
+ mock_launch.assert_called_once_with(False, False)
+
+
+@patch("openbb_cli.cli.bootstrap")
+@patch("openbb_cli.cli.launch")
+@patch("sys.argv", ["openbb", "--dev"])
+def test_main_with_dev_only(mock_launch, mock_bootstrap):
+ """Test the main function with dev flag only."""
+ main()
+ mock_bootstrap.assert_called_once()
+ mock_launch.assert_called_once_with(True, False)
+
+
+@patch("openbb_cli.cli.bootstrap")
+@patch("openbb_cli.cli.launch")
+@patch("sys.argv", ["openbb", "--debug"])
+def test_main_with_debug_only(mock_launch, mock_bootstrap):
+ """Test the main function with debug flag only."""
+ main()
+ mock_bootstrap.assert_called_once()
+ mock_launch.assert_called_once_with(False, True)
diff --git a/cli/tests/test_controllers_base_controller.py b/cli/tests/test_controllers_base_controller.py
new file mode 100644
index 00000000000..465a5b61e5e
--- /dev/null
+++ b/cli/tests/test_controllers_base_controller.py
@@ -0,0 +1,79 @@
+"""Test the base controller."""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from openbb_cli.controllers.base_controller import BaseController
+
+# pylint: disable=unused-argument, unused-variable
+
+
+class TestableBaseController(BaseController):
+ """Testable Base Controller."""
+
+ def __init__(self, queue=None):
+ """Initialize the TestableBaseController."""
+ self.PATH = "/valid/path/"
+ super().__init__(queue=queue)
+
+ def print_help(self):
+ """Print help."""
+
+
+def test_base_controller_initialization():
+ """Test the initialization of the base controller."""
+ with patch.object(TestableBaseController, "check_path", return_value=None):
+ controller = TestableBaseController()
+ assert controller.path == ["valid", "path"] # Checking for correct path split
+
+
+def test_path_validation():
+ """Test the path validation method."""
+ controller = TestableBaseController()
+
+ with pytest.raises(ValueError):
+ controller.PATH = "invalid/path"
+ controller.check_path()
+
+ with pytest.raises(ValueError):
+ controller.PATH = "/invalid/path"
+ controller.check_path()
+
+ with pytest.raises(ValueError):
+ controller.PATH = "/Invalid/Path/"
+ controller.check_path()
+
+ controller.PATH = "/valid/path/"
+
+
+def test_parse_input():
+ """Test the parse input method."""
+ controller = TestableBaseController()
+ input_str = "cmd1/cmd2/cmd3"
+ expected = ["cmd1", "cmd2", "cmd3"]
+ result = controller.parse_input(input_str)
+ assert result == expected
+
+
+def test_switch():
+ """Test the switch method."""
+ controller = TestableBaseController()
+ with patch.object(controller, "call_exit", MagicMock()) as mock_exit:
+ controller.queue = ["exit"]
+ controller.switch("exit")
+ mock_exit.assert_called_once()
+
+
+def test_call_help():
+ """Test the call help method."""
+ controller = TestableBaseController()
+ with patch("openbb_cli.controllers.base_controller.session.console.print"):
+ controller.call_help(None)
+
+
+def test_call_exit():
+ """Test the call exit method."""
+ controller = TestableBaseController()
+ with patch.object(controller, "save_class", MagicMock()):
+ controller.queue = ["quit"]
+ controller.call_exit(None)
diff --git a/cli/tests/test_controllers_base_platform_controller.py b/cli/tests/test_controllers_base_platform_controller.py
new file mode 100644
index 00000000000..cabfe44cd6b
--- /dev/null
+++ b/cli/tests/test_controllers_base_platform_controller.py
@@ -0,0 +1,70 @@
+"""Test the BasePlatformController."""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from openbb_cli.controllers.base_platform_controller import PlatformController, Session
+
+# pylint: disable=redefined-outer-name, protected-access, unused-argument, unused-variable
+
+
+@pytest.fixture
+def mock_session():
+ """Mock session fixture."""
+ with patch(
+ "openbb_cli.controllers.base_platform_controller.session",
+ MagicMock(spec=Session),
+ ) as mock:
+ yield mock
+
+
+def test_initialization_with_valid_params(mock_session):
+ """Test the initialization of the BasePlatformController."""
+ translators = {"dummy_translator": MagicMock()}
+ controller = PlatformController(
+ name="test", parent_path=["parent"], translators=translators
+ )
+ assert controller._name == "test"
+ assert controller.translators == translators
+
+
+def test_initialization_without_required_params():
+ """Test the initialization of the BasePlatformController without required params."""
+ with pytest.raises(ValueError):
+ PlatformController(name="test", parent_path=["parent"])
+
+
+def test_command_generation(mock_session):
+ """Test the command generation method."""
+ translator = MagicMock()
+ translators = {"test_command": translator}
+ controller = PlatformController(
+ name="test", parent_path=["parent"], translators=translators
+ )
+
+ # Check if command function is correctly linked
+ assert "test_command" in controller.translators
+
+
+def test_print_help(mock_session):
+ """Test the print help method."""
+ translators = {"test_command": MagicMock()}
+ controller = PlatformController(
+ name="test", parent_path=["parent"], translators=translators
+ )
+
+ with patch(
+ "openbb_cli.controllers.base_platform_controller.MenuText"
+ ) as mock_menu_text:
+ controller.print_help()
+ mock_menu_text.assert_called_once_with("/parent/test/")
+
+
+def test_sub_controller_generation(mock_session):
+ """Test the sub controller generation method."""
+ translators = {"test_menu_item": MagicMock()}
+ controller = PlatformController(
+ name="test", parent_path=["parent"], translators=translators
+ )
+
+ assert "test_menu_item" in controller.translators
diff --git a/cli/tests/test_controllers_choices.py b/cli/tests/test_controllers_choices.py
new file mode 100644
index 00000000000..6d604751b1f
--- /dev/null
+++ b/cli/tests/test_controllers_choices.py
@@ -0,0 +1,51 @@
+"""Test the choices controller."""
+
+from argparse import ArgumentParser
+from unittest.mock import patch
+
+import pytest
+from openbb_cli.controllers.choices import (
+ build_controller_choice_map,
+)
+
+# pylint: disable=redefined-outer-name, protected-access, unused-argument, unused-variable
+
+
+class MockController:
+ """Mock controller class for testing."""
+
+ CHOICES_COMMANDS = ["test_command"]
+ controller_choices = ["test_command", "help"]
+
+ def call_test_command(self, args):
+ """Mock function for test_command."""
+ parser = ArgumentParser()
+ parser.add_argument(
+ "--example", choices=["option1", "option2"], help="Example argument."
+ )
+ return parser.parse_args(args)
+
+
+@pytest.fixture
+def mock_controller():
+ """Mock controller fixture."""
+ return MockController()
+
+
+def test_build_command_choice_map(mock_controller):
+ """Test the building of a command choice map."""
+ with patch(
+ "openbb_cli.controllers.choices._get_argument_parser"
+ ) as mock_get_parser:
+ parser = ArgumentParser()
+ parser.add_argument(
+ "--option", choices=["opt1", "opt2"], help="A choice option."
+ )
+ mock_get_parser.return_value = parser
+
+ choice_map = build_controller_choice_map(controller=mock_controller)
+
+ assert "test_command" in choice_map
+ assert "--option" in choice_map["test_command"]
+ assert "opt1" in choice_map["test_command"]["--option"]
+ assert "opt2" in choice_map["test_command"]["--option"]
diff --git a/cli/tests/test_models_settings.py b/cli/tests/test_models_settings.py
new file mode 100644
index 00000000000..0834355516f
--- /dev/null
+++ b/cli/tests/test_models_settings.py
@@ -0,0 +1,72 @@
+"""Test the Models Settings module."""
+
+from unittest.mock import mock_open, patch
+
+from openbb_cli.models.settings import Settings
+
+# pylint: disable=unused-argument
+
+
+def test_default_values():
+ """Test the default values of the settings model."""
+ settings = Settings()
+ assert settings.VERSION == "1.0.0"
+ assert settings.TEST_MODE is False
+ assert settings.DEBUG_MODE is False
+ assert settings.DEV_BACKEND is False
+ assert settings.FILE_OVERWRITE is False
+ assert settings.SHOW_VERSION is True
+ assert settings.USE_INTERACTIVE_DF is True
+ assert settings.USE_CLEAR_AFTER_CMD is False
+ assert settings.USE_DATETIME is True
+ assert settings.USE_PROMPT_TOOLKIT is True
+ assert settings.ENABLE_EXIT_AUTO_HELP is True
+ assert settings.REMEMBER_CONTEXTS is True
+ assert settings.ENABLE_RICH_PANEL is True
+ assert settings.TOOLBAR_HINT is True
+ assert settings.SHOW_MSG_OBBJECT_REGISTRY is False
+ assert settings.TIMEZONE == "America/New_York"
+ assert settings.FLAIR == ":openbb"
+ assert settings.PREVIOUS_USE is False
+ assert settings.N_TO_KEEP_OBBJECT_REGISTRY == 10
+ assert settings.N_TO_DISPLAY_OBBJECT_REGISTRY == 5
+ assert settings.RICH_STYLE == "dark"
+ assert settings.ALLOWED_NUMBER_OF_ROWS == 20
+ assert settings.ALLOWED_NUMBER_OF_COLUMNS == 5
+ assert settings.HUB_URL == "https://my.openbb.co"
+ assert settings.BASE_URL == "https://payments.openbb.co"
+
+
+# Test __repr__ output
+def test_repr():
+ """Test the __repr__ method of the settings model."""
+ settings = Settings()
+ repr_str = settings.__repr__() # pylint: disable=C2801
+ assert "Settings\n\n" in repr_str
+ assert "VERSION: 1.0.0" in repr_str
+
+
+# Test loading from environment variables
+@patch(
+ "openbb_cli.models.settings.dotenv_values",
+ return_value={"OPENBB_TEST_MODE": "True", "OPENBB_VERSION": "2.0.0"},
+)
+def test_from_env(mock_dotenv_values):
+ """Test loading settings from environment variables."""
+ settings = Settings.from_env({}) # type: ignore
+ assert settings["TEST_MODE"] == "True"
+ assert settings["VERSION"] == "2.0.0"
+
+
+# Test setting an item and updating .env
+@patch("openbb_cli.models.settings.set_key")
+@patch(
+ "openbb_cli.models.settings.open",
+ new_callable=mock_open,
+ read_data="TEST_MODE=False\n",
+)
+def test_set_item(mock_file, mock_set_key):
+ """Test setting an item and updating the .env file."""
+ settings = Settings()
+ settings.set_item("TEST_MODE", True)
+ assert settings.TEST_MODE is True
diff --git a/cli/tests/test_session.py b/cli/tests/test_session.py
new file mode 100644
index 00000000000..66ca9fccab8
--- /dev/null
+++ b/cli/tests/test_session.py
@@ -0,0 +1,44 @@
+"Test the Session class."
+from unittest.mock import MagicMock, patch
+
+import pytest
+from openbb_cli.models.settings import Settings
+from openbb_cli.session import Session, sys
+
+# pylint: disable=redefined-outer-name, unused-argument, protected-access
+
+
+def mock_isatty(return_value):
+ """Mock the isatty method."""
+ original_isatty = sys.stdin.isatty
+ sys.stdin.isatty = MagicMock(return_value=return_value) # type: ignore
+ return original_isatty
+
+
+@pytest.fixture
+def session():
+ """Session fixture."""
+ return Session()
+
+
+def test_session_initialization(session):
+ """Test the initialization of the Session class."""
+ assert session.settings is not None
+ assert session.style is not None
+ assert session.console is not None
+ assert session.obbject_registry is not None
+ assert isinstance(session.settings, Settings)
+
+
+@patch("sys.stdin.isatty", return_value=True)
+def test_get_prompt_session_true(mock_isatty, session):
+ "Test get_prompt_session method."
+ prompt_session = session._get_prompt_session()
+ assert prompt_session is not None
+
+
+@patch("sys.stdin.isatty", return_value=False)
+def test_get_prompt_session_false(mock_isatty, session):
+ "Test get_prompt_session method."
+ prompt_session = session._get_prompt_session()
+ assert prompt_session is None