[BugFix] openbb_platform_api & openbb_mcp_server: Fix app_import path handling for drive paths. (#7344)

* fix colon handling in import_app to handle drives and add cross-platform tests

* the test collection helper too
This commit is contained in:
Danglewood
2026-02-06 16:21:17 -08:00
committed by GitHub
parent 48fb67144f
commit ed414415bd
5 changed files with 732 additions and 12 deletions

View File

@@ -13,6 +13,17 @@ def import_app(app_path: str, name: str = "app", factory: bool = False) -> FastA
# pylint: disable=import-outside-toplevel
from importlib import import_module, util
def _is_module_colon_notation(app_path: str) -> bool:
"""Check if the path uses module:name notation vs a Windows path."""
if ":" not in app_path:
return False
# Windows absolute path check (e.g., C:\path or D:/path)
if len(app_path) >= 2 and app_path[1] == ":" and app_path[0].isalpha():
# Could still have colon notation: C:\path\file.py:app
parts = app_path.split(":")
return len(parts) > 2 # More than just drive letter colon
return True
def _load_module_from_file_path(file_path: str):
"""Load a Python module from a file path."""
spec_name = os.path.basename(file_path).split(".")[0]
@@ -27,8 +38,8 @@ def import_app(app_path: str, name: str = "app", factory: bool = False) -> FastA
return module
# Case 1: Module path with colon notation (e.g., "my_app.main:app" or "main:app")
if ":" in app_path:
module_path, name = app_path.split(":")
if _is_module_colon_notation(app_path):
module_path, name = app_path.rsplit(":", 1)
try: # First try to import as a module
module = import_module(module_path)
except ImportError: # If module import fails, try to load as a local file
@@ -50,7 +61,7 @@ def import_app(app_path: str, name: str = "app", factory: bool = False) -> FastA
# Case 2: File path (e.g., "main.py" or "my_app/main.py")
else:
if not str(app_path).startswith("/"):
if not Path(app_path).is_absolute():
cwd = Path.cwd()
app_path = str(cwd.joinpath(app_path).resolve())

View File

@@ -161,3 +161,255 @@ def test_parse_args_factory_no_name_error():
),
):
parse_args()
# =============================================================================
# Path Handling Tests - Cross-Platform Compatibility
# =============================================================================
class TestPathHandling:
"""Test cross-platform path handling in import_app function."""
@pytest.fixture
def app_file(self, tmp_path: Path):
"""Create a simple FastAPI app file for testing."""
app_content = """
from fastapi import FastAPI
app = FastAPI(title="Test App")
"""
app_file = tmp_path / "test_app.py"
app_file.write_text(app_content)
return app_file
def test_unix_absolute_path(self, app_file: Path):
"""Test Unix-style absolute paths (e.g., /home/user/app.py)."""
app = import_app(str(app_file), "app", False)
assert isinstance(app, FastAPI)
assert app.title == "Test App"
def test_relative_path(self, tmp_path: Path, monkeypatch):
"""Test relative paths are resolved correctly."""
app_content = """
from fastapi import FastAPI
app = FastAPI(title="Relative Path App")
"""
app_file = tmp_path / "relative_app.py"
app_file.write_text(app_content)
monkeypatch.chdir(tmp_path)
app = import_app("relative_app.py", "app", False)
assert isinstance(app, FastAPI)
assert app.title == "Relative Path App"
def test_relative_path_with_subdirectory(self, tmp_path: Path, monkeypatch):
"""Test relative paths with subdirectories."""
subdir = tmp_path / "subdir"
subdir.mkdir()
app_content = """
from fastapi import FastAPI
app = FastAPI(title="Subdir App")
"""
app_file = subdir / "myapp.py"
app_file.write_text(app_content)
monkeypatch.chdir(tmp_path)
app = import_app("subdir/myapp.py", "app", False)
assert isinstance(app, FastAPI)
assert app.title == "Subdir App"
def test_module_colon_notation(self, tmp_path: Path):
"""Test module:name colon notation (e.g., 'my_module:app')."""
app_content = """
from fastapi import FastAPI
myapp = FastAPI(title="Module Colon App")
"""
app_file = tmp_path / "colon_module.py"
app_file.write_text(app_content)
sys.path.insert(0, str(tmp_path))
try:
app = import_app("colon_module:myapp", "myapp", False)
assert isinstance(app, FastAPI)
assert app.title == "Module Colon App"
finally:
sys.path.pop(0)
if "colon_module" in sys.modules:
del sys.modules["colon_module"]
def test_file_path_with_colon_notation(self, app_file: Path):
"""Test file path with colon notation (e.g., 'myfile.py:app')."""
app = import_app(f"{app_file}:app", "app", False)
assert isinstance(app, FastAPI)
assert app.title == "Test App"
def test_file_not_found_error(self, tmp_path: Path):
"""Test FileNotFoundError is raised for non-existent files."""
non_existent_path = tmp_path / "does_not_exist.py"
with pytest.raises(FileNotFoundError):
import_app(str(non_existent_path), "app", False)
def test_attribute_error_missing_app_instance(self, tmp_path: Path):
"""Test AttributeError is raised when app instance is missing."""
app_content = """
# No app defined here
x = 1
"""
app_file = tmp_path / "no_app.py"
app_file.write_text(app_content)
with pytest.raises(AttributeError, match="does not contain an 'app'"):
import_app(str(app_file), "app", False)
def test_custom_app_name(self, tmp_path: Path):
"""Test importing app with custom name."""
app_content = """
from fastapi import FastAPI
custom_app = FastAPI(title="Custom Named App")
"""
app_file = tmp_path / "custom_name.py"
app_file.write_text(app_content)
app = import_app(f"{app_file}:custom_app", "custom_app", False)
assert isinstance(app, FastAPI)
assert app.title == "Custom Named App"
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
def test_windows_absolute_path(self, app_file: Path):
"""Test Windows-style absolute paths (e.g., C:\\Users\\app.py)."""
# On Windows, tmp_path will have a drive letter (e.g., C:\...)
app = import_app(str(app_file), "app", False)
assert isinstance(app, FastAPI)
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
def test_windows_path_with_colon_notation(self, app_file: Path):
"""Test Windows path with colon notation (e.g., C:\\path\\app.py:myapp)."""
# Windows path with colon notation: C:\path\app.py:app
app = import_app(f"{app_file}:app", "app", False)
assert isinstance(app, FastAPI)
class TestPathDetectionHelpers:
"""Test path detection logic for cross-platform compatibility."""
def test_is_absolute_path_detection_unix(self):
"""Test absolute path detection for Unix paths."""
# Unix absolute paths
assert Path("/home/user/app.py").is_absolute() is True
assert Path("/app.py").is_absolute() is True
# Relative paths
assert Path("app.py").is_absolute() is False
assert Path("./app.py").is_absolute() is False
assert Path("subdir/app.py").is_absolute() is False
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
def test_is_absolute_path_detection_windows(self):
"""Test absolute path detection for Windows paths."""
# Windows absolute paths
assert Path("C:\\Users\\app.py").is_absolute() is True
assert Path("D:/Projects/app.py").is_absolute() is True
# Relative paths
assert Path("app.py").is_absolute() is False
assert Path(".\\app.py").is_absolute() is False
def test_colon_notation_vs_windows_drive(self):
"""Test distinguishing module:name notation from Windows drive letters."""
# These should be recognized as module:name notation
module_notations = [
"module:app",
"package.module:app",
"my_app.main:create_app",
]
for notation in module_notations:
# Has colon and is not a Windows drive letter pattern
assert ":" in notation
# First char before colon is not a single letter (drive)
parts = notation.split(":")
assert len(parts[0]) > 1 or not parts[0].isalpha()
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
def test_windows_drive_letter_detection(self):
"""Test detection of Windows drive letters vs colon notation."""
# Windows paths with drive letters
windows_paths = [
"C:\\app.py",
"D:/Projects/app.py",
"E:\\Users\\test\\app.py",
]
for path_str in windows_paths:
path = Path(path_str)
# Should be detected as absolute (has drive)
assert path.is_absolute()
# Drive should be detected
assert path.drive != ""
# Windows path WITH colon notation (e.g., C:\path\app.py:myapp)
complex_path = "C:\\Projects\\app.py:myapp"
# This has multiple colons - drive colon + notation colon
assert complex_path.count(":") == 2
class TestModuleColonNotationHelper:
"""Test the _is_module_colon_notation helper function behavior."""
def test_simple_module_notation(self):
"""Test simple module:name notation is detected correctly."""
# These should be recognized as module colon notation
from openbb_mcp_server.utils.app_import import import_app
# We test the behavior indirectly through import_app
# Module notation without file should try import first
with pytest.raises((ImportError, FileNotFoundError)):
import_app("nonexistent_module:app")
def test_file_path_without_colon(self, tmp_path: Path):
"""Test file paths without colons are handled correctly."""
app_content = """
from fastapi import FastAPI
app = FastAPI(title="No Colon App")
"""
app_file = tmp_path / "no_colon_app.py"
app_file.write_text(app_content)
app = import_app(str(app_file), "app", False)
assert isinstance(app, FastAPI)
assert app.title == "No Colon App"
def test_dotted_module_path_notation(self, tmp_path: Path):
"""Test dotted module paths like 'package.subpackage.module:app'."""
# Create a package structure
pkg_dir = tmp_path / "mypkg"
pkg_dir.mkdir()
(pkg_dir / "__init__.py").write_text("")
subpkg_dir = pkg_dir / "subpkg"
subpkg_dir.mkdir()
(subpkg_dir / "__init__.py").write_text("")
app_content = """
from fastapi import FastAPI
app = FastAPI(title="Dotted Module App")
"""
(subpkg_dir / "mymodule.py").write_text(app_content)
sys.path.insert(0, str(tmp_path))
try:
app = import_app("mypkg.subpkg.mymodule:app")
assert isinstance(app, FastAPI)
assert app.title == "Dotted Module App"
finally:
sys.path.pop(0)
# Clean up sys.modules
for mod in list(sys.modules.keys()):
if mod.startswith("mypkg"):
del sys.modules[mod]

View File

@@ -218,6 +218,17 @@ def import_app(app_path: str, name: str = "app", factory: bool = False):
from openbb_core.api.app_loader import AppLoader
from openbb_core.api.rest_api import system
def _is_module_colon_notation(app_path: str) -> bool:
"""Check if the path uses module:name notation vs a Windows path."""
if ":" not in app_path:
return False
# Windows absolute path check (e.g., C:\path or D:/path)
if len(app_path) >= 2 and app_path[1] == ":" and app_path[0].isalpha():
# Could still have colon notation: C:\path\file.py:app
parts = app_path.split(":")
return len(parts) > 2 # More than just drive letter colon
return True
def _load_module_from_file_path(file_path: str):
spec_name = os.path.basename(file_path).split(".")[0]
spec = util.spec_from_file_location(spec_name, file_path)
@@ -230,16 +241,15 @@ def import_app(app_path: str, name: str = "app", factory: bool = False):
spec.loader.exec_module(module) # type: ignore
return module
# Case 1: Module path with colon notation (e.g., "my_app.main:app" or "main:app")
if ":" in app_path:
module_path, name = app_path.split(":")
if _is_module_colon_notation(app_path):
module_path, name = app_path.rsplit(":", 1)
try: # First try to import as a module
module = import_module(module_path)
except ImportError: # If module import fails, try to load as a local file
if not module_path.endswith(".py"):
module_path += ".py"
if not str(module_path).startswith("/"):
if not Path(module_path).is_absolute():
cwd = Path.cwd()
file_path = str(cwd.joinpath(module_path).resolve())
else:
@@ -254,7 +264,7 @@ def import_app(app_path: str, name: str = "app", factory: bool = False):
# Case 2: File path (e.g., "main.py" or "my_app/main.py")
else:
if not str(app_path).startswith("/"):
if not Path(app_path).is_absolute():
cwd = Path.cwd()
app_path = str(cwd.joinpath(app_path).resolve())

View File

@@ -338,6 +338,449 @@ def test_import_factory_app():
assert isinstance(result, MockFastAPI)
# =============================================================================
# Path Handling Tests - Cross-Platform Compatibility
# =============================================================================
class TestPathHandling:
"""Test cross-platform path handling in import_app function."""
@pytest.fixture
def mock_fastapi_env(self):
"""Set up common mocks for FastAPI import tests."""
# pylint: disable=import-outside-toplevel
from fastapi import FastAPI as RealFastAPI
class MockFastAPI(RealFastAPI):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_middleware = MagicMock()
mock_rest_api = MagicMock()
mock_rest_api.system = MagicMock()
return MockFastAPI, mock_rest_api
def _create_app_file(self, tmp_path, filename="test_app.py"):
"""Create a test app file."""
app_file = tmp_path / filename
app_file.write_text("from fastapi import FastAPI\n\napp = FastAPI()\n")
return app_file
def test_unix_absolute_path(self, tmp_path, mock_fastapi_env):
"""Test Unix-style absolute paths (e.g., /home/user/app.py)."""
MockFastAPI, mock_rest_api = mock_fastapi_env
app_file = self._create_app_file(tmp_path)
with (
patch.dict(
"sys.modules",
{
"openbb_core.api.rest_api": mock_rest_api,
"openbb_core.api.router.commands": MagicMock(),
"openbb_core.app.command_runner": MagicMock(),
"openbb_core.app.static.package_builder": MagicMock(),
"openbb_core.app.provider_interface": MagicMock(),
"openbb_core.provider.registry": MagicMock(),
"openbb_core.app.extension_loader": MagicMock(),
},
),
patch("fastapi.FastAPI", new=MockFastAPI),
patch("openbb_core.app.service.user_service.UserService.read_from_file"),
patch(
"openbb_core.app.model.credentials.CredentialsLoader.load",
return_value=MagicMock(),
),
patch(
"openbb_core.app.service.system_service.SystemService"
) as mock_system,
patch("openbb_core.api.app_loader.AppLoader.add_routers"),
):
mock_system.return_value.system_settings.cors.allow_origins = ["*"]
mock_system.return_value.system_settings.cors.allow_methods = ["*"]
mock_system.return_value.system_settings.cors.allow_headers = ["*"]
# Test with absolute Unix-style path
result = import_app(str(app_file), "app", False)
assert isinstance(result, MockFastAPI)
def test_relative_path(self, tmp_path, mock_fastapi_env, monkeypatch):
"""Test relative paths are resolved correctly."""
MockFastAPI, mock_rest_api = mock_fastapi_env
app_file = self._create_app_file(tmp_path)
monkeypatch.chdir(tmp_path)
with (
patch.dict(
"sys.modules",
{
"openbb_core.api.rest_api": mock_rest_api,
"openbb_core.api.router.commands": MagicMock(),
"openbb_core.app.command_runner": MagicMock(),
"openbb_core.app.static.package_builder": MagicMock(),
"openbb_core.app.provider_interface": MagicMock(),
"openbb_core.provider.registry": MagicMock(),
"openbb_core.app.extension_loader": MagicMock(),
},
),
patch("fastapi.FastAPI", new=MockFastAPI),
patch("openbb_core.app.service.user_service.UserService.read_from_file"),
patch(
"openbb_core.app.model.credentials.CredentialsLoader.load",
return_value=MagicMock(),
),
patch(
"openbb_core.app.service.system_service.SystemService"
) as mock_system,
patch("openbb_core.api.app_loader.AppLoader.add_routers"),
):
mock_system.return_value.system_settings.cors.allow_origins = ["*"]
mock_system.return_value.system_settings.cors.allow_methods = ["*"]
mock_system.return_value.system_settings.cors.allow_headers = ["*"]
# Test with relative path
result = import_app(app_file.name, "app", False)
assert isinstance(result, MockFastAPI)
def test_relative_path_with_subdirectory(
self, tmp_path, mock_fastapi_env, monkeypatch
):
"""Test relative paths with subdirectories."""
MockFastAPI, mock_rest_api = mock_fastapi_env
subdir = tmp_path / "subdir"
subdir.mkdir()
app_file = subdir / "myapp.py"
app_file.write_text("from fastapi import FastAPI\n\napp = FastAPI()\n")
monkeypatch.chdir(tmp_path)
with (
patch.dict(
"sys.modules",
{
"openbb_core.api.rest_api": mock_rest_api,
"openbb_core.api.router.commands": MagicMock(),
"openbb_core.app.command_runner": MagicMock(),
"openbb_core.app.static.package_builder": MagicMock(),
"openbb_core.app.provider_interface": MagicMock(),
"openbb_core.provider.registry": MagicMock(),
"openbb_core.app.extension_loader": MagicMock(),
},
),
patch("fastapi.FastAPI", new=MockFastAPI),
patch("openbb_core.app.service.user_service.UserService.read_from_file"),
patch(
"openbb_core.app.model.credentials.CredentialsLoader.load",
return_value=MagicMock(),
),
patch(
"openbb_core.app.service.system_service.SystemService"
) as mock_system,
patch("openbb_core.api.app_loader.AppLoader.add_routers"),
):
mock_system.return_value.system_settings.cors.allow_origins = ["*"]
mock_system.return_value.system_settings.cors.allow_methods = ["*"]
mock_system.return_value.system_settings.cors.allow_headers = ["*"]
# Test with relative path including subdirectory
result = import_app("subdir/myapp.py", "app", False)
assert isinstance(result, MockFastAPI)
def test_module_colon_notation(self, mock_fastapi_env):
"""Test module:name colon notation (e.g., 'my_module:app')."""
MockFastAPI, mock_rest_api = mock_fastapi_env
with (
patch.dict(
"sys.modules",
{
"openbb_core.api.rest_api": mock_rest_api,
"openbb_core.api.router.commands": MagicMock(),
"openbb_core.app.command_runner": MagicMock(),
"openbb_core.app.static.package_builder": MagicMock(),
"openbb_core.app.provider_interface": MagicMock(),
"openbb_core.provider.registry": MagicMock(),
"openbb_core.app.extension_loader": MagicMock(),
},
),
patch("importlib.import_module") as mock_import,
patch("fastapi.FastAPI", new=MockFastAPI),
patch(
"openbb_core.app.service.system_service.SystemService"
) as mock_system,
patch("openbb_core.app.service.user_service.UserService.read_from_file"),
patch("openbb_core.app.model.credentials.CredentialsLoader.load"),
patch("openbb_core.api.app_loader.AppLoader.add_routers"),
):
mock_system.return_value.system_settings.cors.allow_origins = ["*"]
mock_system.return_value.system_settings.cors.allow_methods = ["*"]
mock_system.return_value.system_settings.cors.allow_headers = ["*"]
mock_module = MagicMock()
mock_module.__spec__ = MagicMock()
mock_module.myapp = MockFastAPI()
mock_import.return_value = mock_module
result = import_app("some_package.module:myapp", "myapp", False)
assert isinstance(result, MockFastAPI)
# Verify the target module was imported (among other imports)
mock_import.assert_any_call("some_package.module")
def test_file_path_with_colon_notation(self, tmp_path, mock_fastapi_env):
"""Test file path with colon notation (e.g., 'myfile.py:app')."""
MockFastAPI, mock_rest_api = mock_fastapi_env
app_file = self._create_app_file(tmp_path, "custom_app.py")
with (
patch.dict(
"sys.modules",
{
"openbb_core.api.rest_api": mock_rest_api,
"openbb_core.api.router.commands": MagicMock(),
"openbb_core.app.command_runner": MagicMock(),
"openbb_core.app.static.package_builder": MagicMock(),
"openbb_core.app.provider_interface": MagicMock(),
"openbb_core.provider.registry": MagicMock(),
"openbb_core.app.extension_loader": MagicMock(),
},
),
patch("fastapi.FastAPI", new=MockFastAPI),
patch("openbb_core.app.service.user_service.UserService.read_from_file"),
patch(
"openbb_core.app.model.credentials.CredentialsLoader.load",
return_value=MagicMock(),
),
patch(
"openbb_core.app.service.system_service.SystemService"
) as mock_system,
patch("openbb_core.api.app_loader.AppLoader.add_routers"),
):
mock_system.return_value.system_settings.cors.allow_origins = ["*"]
mock_system.return_value.system_settings.cors.allow_methods = ["*"]
mock_system.return_value.system_settings.cors.allow_headers = ["*"]
# Test with file path + colon notation
result = import_app(f"{app_file}:app", "app", False)
assert isinstance(result, MockFastAPI)
def test_file_not_found_error(self, tmp_path, mock_fastapi_env):
"""Test FileNotFoundError is raised for non-existent files."""
MockFastAPI, mock_rest_api = mock_fastapi_env
non_existent_path = tmp_path / "does_not_exist.py"
with (
patch.dict(
"sys.modules",
{
"openbb_core.api.rest_api": mock_rest_api,
"openbb_core.api.router.commands": MagicMock(),
"openbb_core.app.command_runner": MagicMock(),
"openbb_core.app.static.package_builder": MagicMock(),
"openbb_core.app.provider_interface": MagicMock(),
"openbb_core.provider.registry": MagicMock(),
"openbb_core.app.extension_loader": MagicMock(),
},
),
patch("fastapi.FastAPI", new=MockFastAPI),
patch("openbb_core.app.service.user_service.UserService.read_from_file"),
patch(
"openbb_core.app.model.credentials.CredentialsLoader.load",
return_value=MagicMock(),
),
patch(
"openbb_core.app.service.system_service.SystemService"
) as mock_system,
patch("openbb_core.api.app_loader.AppLoader.add_routers"),
):
mock_system.return_value.system_settings.cors.allow_origins = ["*"]
mock_system.return_value.system_settings.cors.allow_methods = ["*"]
mock_system.return_value.system_settings.cors.allow_headers = ["*"]
with pytest.raises(FileNotFoundError):
import_app(str(non_existent_path), "app", False)
def test_attribute_error_missing_app_instance(self, tmp_path, mock_fastapi_env):
"""Test AttributeError is raised when app instance is missing."""
MockFastAPI, mock_rest_api = mock_fastapi_env
app_file = tmp_path / "no_app.py"
app_file.write_text("# No app defined here\nx = 1\n")
with (
patch.dict(
"sys.modules",
{
"openbb_core.api.rest_api": mock_rest_api,
"openbb_core.api.router.commands": MagicMock(),
"openbb_core.app.command_runner": MagicMock(),
"openbb_core.app.static.package_builder": MagicMock(),
"openbb_core.app.provider_interface": MagicMock(),
"openbb_core.provider.registry": MagicMock(),
"openbb_core.app.extension_loader": MagicMock(),
},
),
patch("fastapi.FastAPI", new=MockFastAPI),
patch("openbb_core.app.service.user_service.UserService.read_from_file"),
patch(
"openbb_core.app.model.credentials.CredentialsLoader.load",
return_value=MagicMock(),
),
patch(
"openbb_core.app.service.system_service.SystemService"
) as mock_system,
patch("openbb_core.api.app_loader.AppLoader.add_routers"),
):
mock_system.return_value.system_settings.cors.allow_origins = ["*"]
mock_system.return_value.system_settings.cors.allow_methods = ["*"]
mock_system.return_value.system_settings.cors.allow_headers = ["*"]
with pytest.raises(AttributeError):
import_app(str(app_file), "app", False)
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
def test_windows_absolute_path(self, tmp_path, mock_fastapi_env):
"""Test Windows-style absolute paths (e.g., C:\\Users\\app.py)."""
MockFastAPI, mock_rest_api = mock_fastapi_env
app_file = self._create_app_file(tmp_path)
with (
patch.dict(
"sys.modules",
{
"openbb_core.api.rest_api": mock_rest_api,
"openbb_core.api.router.commands": MagicMock(),
"openbb_core.app.command_runner": MagicMock(),
"openbb_core.app.static.package_builder": MagicMock(),
"openbb_core.app.provider_interface": MagicMock(),
"openbb_core.provider.registry": MagicMock(),
"openbb_core.app.extension_loader": MagicMock(),
},
),
patch("fastapi.FastAPI", new=MockFastAPI),
patch("openbb_core.app.service.user_service.UserService.read_from_file"),
patch(
"openbb_core.app.model.credentials.CredentialsLoader.load",
return_value=MagicMock(),
),
patch(
"openbb_core.app.service.system_service.SystemService"
) as mock_system,
patch("openbb_core.api.app_loader.AppLoader.add_routers"),
):
mock_system.return_value.system_settings.cors.allow_origins = ["*"]
mock_system.return_value.system_settings.cors.allow_methods = ["*"]
mock_system.return_value.system_settings.cors.allow_headers = ["*"]
# On Windows, tmp_path will have a drive letter (e.g., C:\...)
result = import_app(str(app_file), "app", False)
assert isinstance(result, MockFastAPI)
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
def test_windows_path_with_colon_notation(self, tmp_path, mock_fastapi_env):
"""Test Windows path with colon notation (e.g., C:\\path\\app.py:myapp)."""
MockFastAPI, mock_rest_api = mock_fastapi_env
app_file = self._create_app_file(tmp_path)
with (
patch.dict(
"sys.modules",
{
"openbb_core.api.rest_api": mock_rest_api,
"openbb_core.api.router.commands": MagicMock(),
"openbb_core.app.command_runner": MagicMock(),
"openbb_core.app.static.package_builder": MagicMock(),
"openbb_core.app.provider_interface": MagicMock(),
"openbb_core.provider.registry": MagicMock(),
"openbb_core.app.extension_loader": MagicMock(),
},
),
patch("fastapi.FastAPI", new=MockFastAPI),
patch("openbb_core.app.service.user_service.UserService.read_from_file"),
patch(
"openbb_core.app.model.credentials.CredentialsLoader.load",
return_value=MagicMock(),
),
patch(
"openbb_core.app.service.system_service.SystemService"
) as mock_system,
patch("openbb_core.api.app_loader.AppLoader.add_routers"),
):
mock_system.return_value.system_settings.cors.allow_origins = ["*"]
mock_system.return_value.system_settings.cors.allow_methods = ["*"]
mock_system.return_value.system_settings.cors.allow_headers = ["*"]
# Windows path with colon notation: C:\path\app.py:app
result = import_app(f"{app_file}:app", "app", False)
assert isinstance(result, MockFastAPI)
class TestPathDetectionHelpers:
"""Test path detection logic for cross-platform compatibility."""
def test_is_absolute_path_detection_unix(self):
"""Test absolute path detection for Unix paths."""
from pathlib import Path
# Unix absolute paths
assert Path("/home/user/app.py").is_absolute() is True
assert Path("/app.py").is_absolute() is True
# Relative paths
assert Path("app.py").is_absolute() is False
assert Path("./app.py").is_absolute() is False
assert Path("subdir/app.py").is_absolute() is False
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
def test_is_absolute_path_detection_windows(self):
"""Test absolute path detection for Windows paths."""
from pathlib import Path
# Windows absolute paths
assert Path("C:\\Users\\app.py").is_absolute() is True
assert Path("D:/Projects/app.py").is_absolute() is True
# Relative paths
assert Path("app.py").is_absolute() is False
assert Path(".\\app.py").is_absolute() is False
def test_colon_notation_vs_windows_drive(self):
"""Test distinguishing module:name notation from Windows drive letters."""
# These should be recognized as module:name notation
module_notations = [
"module:app",
"package.module:app",
"my_app.main:create_app",
]
for notation in module_notations:
# Has colon and is not a Windows drive letter pattern
assert ":" in notation
# First char before colon is not a single letter (drive)
parts = notation.split(":")
assert len(parts[0]) > 1 or not parts[0].isalpha()
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
def test_windows_drive_letter_detection(self):
"""Test detection of Windows drive letters vs colon notation."""
from pathlib import Path
# Windows paths with drive letters
windows_paths = [
"C:\\app.py",
"D:/Projects/app.py",
"E:\\Users\\test\\app.py",
]
for path_str in windows_paths:
path = Path(path_str)
# Should be detected as absolute (has drive)
assert path.is_absolute()
# Drive should be detected
assert path.drive != ""
# Windows path WITH colon notation (e.g., C:\path\app.py:myapp)
complex_path = "C:\\Projects\\app.py:myapp"
# This has multiple colons - drive colon + notation colon
assert complex_path.count(":") == 2
@pytest.mark.asyncio
async def test_get_apps_json_creates_missing_file(tmp_path):
main = _load_main_with_mocks()

View File

@@ -131,7 +131,11 @@ def collect_routers(target_dir: str) -> list[str]:
full_path = os.path.join(root, name)
# Convert the full path to a module path
relative_path = os.path.relpath(full_path, base_path)
module_path = relative_path.replace("/", ".").replace(".py", "")
module_path = (
relative_path.replace("\\", ".")
.replace("/", ".")
.replace(".py", "")
)
routers.append(module_path)
return routers
@@ -163,9 +167,9 @@ def collect_router_functions(loaded_routers: list) -> dict:
def find_decorator(file_path: str, function_name: str) -> str:
"""Find the @router.command decorator of the function in the file, supporting multiline decorators."""
this_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(
this_dir.split("openbb_platform/")[0], "openbb_platform", file_path
)
normalized_dir = this_dir.replace("\\", "/")
base_path = normalized_dir.split("openbb_platform/")[0]
file_path = os.path.join(base_path, "openbb_platform", file_path)
with open(file_path) as file:
lines = file.readlines()