[Enhancement] Adding an interface to read the reference (#6224)

* unused constant

* reference loader class

* making the reference loader available through the coverage

* adding unit tests

* using the setup and teardown

---------

Co-authored-by: Pratyush Shukla <ps4534@nyu.edu>
Co-authored-by: Igor Radovanovic <74266147+IgorWounds@users.noreply.github.com>
This commit is contained in:
Henrique Joaquim
2024-03-15 18:23:13 +00:00
committed by GitHub
parent 399498c131
commit a3fc04c42b
6 changed files with 118 additions and 1 deletions

View File

@@ -2,7 +2,6 @@
from pathlib import Path
ASSETS_DIRECTORY = Path(__file__).parent / "assets"
HOME_DIRECTORY = Path.home()
OPENBB_DIRECTORY = Path(HOME_DIRECTORY, ".openbb_platform")
USER_SETTINGS_PATH = Path(OPENBB_DIRECTORY, "user_settings.json")

View File

@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional
from openbb_core.api.router.helpers.coverage_helpers import get_route_schema_map
from openbb_core.app.provider_interface import ProviderInterface
from openbb_core.app.router import CommandMap
from openbb_core.app.static.reference_loader import ReferenceLoader
if TYPE_CHECKING:
from openbb_core.app.static.app_factory import BaseApp
@@ -26,6 +27,7 @@ class Coverage:
self._app = app
self._command_map = CommandMap(coverage_sep=".")
self._provider_interface = ProviderInterface()
self._reference_loader = ReferenceLoader()
def __repr__(self) -> str:
"""Return docstring."""
@@ -49,6 +51,11 @@ class Coverage:
for command, value in self._command_map.commands_model.items()
}
@property
def reference(self) -> Dict[str, Dict]:
"""Return reference data."""
return self._reference_loader.reference
def command_schemas(self, filter_by_provider: Optional[str] = None):
"""Return route schema for a command."""
return get_route_schema_map(

View File

@@ -0,0 +1,43 @@
"""ReferenceLoader class for loading reference data from a file."""
import json
from pathlib import Path
from typing import Dict, Optional
from openbb_core.app.model.abstract.singleton import SingletonMeta
class ReferenceLoader(metaclass=SingletonMeta):
"""ReferenceLoader class for loading the `reference.json` file."""
def __init__(self, directory: Optional[Path] = None):
"""
Initialize the ReferenceLoader with a specific directory.
If no directory is provided, a default directory will be used.
Attributes
----------
directory : Optional[Path]
The directory from which to load the assets where the reference file lives.
"""
self.directory = directory or directory or self._get_default_directory()
self._reference = self._load(self.directory / "assets" / "reference.json")
@property
def reference(self) -> Dict[str, Dict]:
"""Get the reference data."""
return self._reference
def _get_default_directory(self) -> Path:
"""Get the default directory for loading references."""
return Path(__file__).parents[4].resolve() / "openbb"
def _load(self, file_path: Path):
"""Load the reference data from a file."""
try:
with open(file_path) as f:
data = json.load(f)
except FileNotFoundError:
data = {}
return data

View File

@@ -37,3 +37,10 @@ def test_coverage_commands(coverage):
command_coverage = coverage.commands
assert command_coverage
assert isinstance(command_coverage, dict)
def test_coverage_reference(coverage):
"""Test coverage reference."""
reference = coverage.reference
assert reference
assert isinstance(reference, dict)

View File

@@ -0,0 +1,59 @@
import json
from pathlib import Path
import pytest
from openbb_core.app.static.reference_loader import ReferenceLoader
@pytest.fixture(scope="function")
def reference_loader():
ReferenceLoader._instances = {}
yield ReferenceLoader
ReferenceLoader._instances = {}
@pytest.fixture
def mock_reference_data(tmp_path):
"""Fixture to create a mock reference.json file."""
directory = tmp_path / "assets"
directory.mkdir(parents=True)
reference_file = directory / "reference.json"
mock_data = {"key": "value"}
with open(reference_file, "w") as f:
json.dump(mock_data, f)
return tmp_path
def test_load_reference_data(mock_reference_data, reference_loader):
"""Test loading of reference data."""
loader = reference_loader(directory=mock_reference_data)
assert loader.reference == {
"key": "value"
}, "Reference data should match the mock data"
def test_default_directory_load(reference_loader):
"""Test loading from the default directory."""
# This test assumes the default directory and reference.json file exist and are correctly set up
loader = reference_loader()
# Perform a basic check to ensure some data is loaded; specifics will depend on the actual reference.json content
assert (
isinstance(loader.reference, dict) and loader.reference
), "Should load data from the default directory"
def test_missing_reference_file(tmp_path, reference_loader):
"""Test behavior when the reference.json file is missing."""
loader = reference_loader(
directory=tmp_path
) # tmp_path does not contain a reference.json file
assert (
loader.reference == {}
), "Should return an empty dictionary if the reference file is missing"
def test_nonexistent_directory(reference_loader):
"""Test initialization with a nonexistent directory."""
assert (
reference_loader(directory=Path("/nonexistent/path")).reference == {}
), "Should return an empty dictionary if the directory does not exist"

View File

@@ -10,6 +10,7 @@ from openbb_core.app.static.app_factory import (
create_app as _create_app,
)
from openbb_core.app.static.package_builder import PackageBuilder as _PackageBuilder
from openbb_core.app.static.reference_loader import ReferenceLoader as _ReferenceLoader
_this_dir = Path(__file__).parent.resolve()
@@ -36,6 +37,7 @@ def build(
_PackageBuilder(_this_dir).auto_build()
_ReferenceLoader(_this_dir)
try:
# pylint: disable=import-outside-toplevel