diff --git a/pageindex/page_index_md.py b/pageindex/page_index_md.py index 86ef2a145..97311cf18 100644 --- a/pageindex/page_index_md.py +++ b/pageindex/page_index_md.py @@ -2,9 +2,10 @@ import json import re import os -try: +if __package__: from .utils import * -except: +else: + # Run as a script (no parent package): resolve utils from the same directory. from utils import * async def get_node_summary(node, summary_token_threshold=200, model=None): diff --git a/tests/test_page_index_md.py b/tests/test_page_index_md.py index 0f4581090..dbac3ecdd 100644 --- a/tests/test_page_index_md.py +++ b/tests/test_page_index_md.py @@ -1,8 +1,30 @@ +import subprocess +import sys import unittest +from pathlib import Path from pageindex.page_index_md import extract_nodes_from_markdown +class UtilsImportFallbackTest(unittest.TestCase): + def test_script_mode_import_resolves_sibling_utils(self): + # Without a parent package the module must fall back to `from utils import *`. + module_dir = Path(__file__).resolve().parents[1] / "pageindex" + result = subprocess.run( + [sys.executable, "-c", "import page_index_md; print(page_index_md.count_tokens.__name__)"], + cwd=module_dir, + capture_output=True, + text=True, + timeout=120, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), "count_tokens") + + def test_package_import_does_not_swallow_errors(self): + source = (Path(__file__).resolve().parents[1] / "pageindex" / "page_index_md.py").read_text() + self.assertNotIn("except:", source) + + class ExtractNodesFromMarkdownTest(unittest.TestCase): def test_skips_bold_heading_with_only_whitespace(self): nodes, _ = extract_nodes_from_markdown("** **\n**Valid heading**")