Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 40 additions & 18 deletions nitrostack/cli/widget_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
route, and a call to a *factory*, meaning a function whose parameter reaches
``WidgetOptions(route=...)`` (``@widget(my_widget("pizza-map"))``).

``widget`` and ``WidgetOptions`` only count when they resolve to the SDK's own, directly,
through ``import nitrostack``, or through a project module that re-exports them, so
``@pytest.mark.widget("smoke")`` is ignored.

A factory call only counts when the name resolves, through the calling module's own
definitions and imports, to a real factory, and the string sits in the argument that
feeds ``route``. So ``panel("x")`` is ignored when ``panel`` never passes that argument
Expand All @@ -24,6 +28,7 @@
_LEGACY_OPTIONS_RE = re.compile(r"""WidgetOptions\(\s*route\s*=\s*["']([^"']+)["']""")

_WIDGET_OPTIONS = object() # the SDK's WidgetOptions class
_WIDGET = object() # the SDK's @widget decorator
_NITROSTACK = object() # the nitrostack package or one of its submodules
_PLAIN = object() # a project function or class that is not a factory

Expand Down Expand Up @@ -142,31 +147,48 @@ def _find(self, dotted: str) -> Optional[_Module]:
matches = [m for key, m in self.modules.items() if key.endswith("." + dotted)]
return matches[0] if len(matches) == 1 else None # e.g. a src/ layout

def _name(self, module: _Module, name: str) -> object:
@staticmethod
def _sdk(attr: str) -> object:
if attr == "WidgetOptions":
return _WIDGET_OPTIONS
return _WIDGET if attr == "widget" else _NITROSTACK

def _binding(self, module: _Module, name: str, seen: set) -> object:
"""What ``name`` means inside ``module``, following re-exports through project modules."""
if (module.name, name) in seen: # an import cycle
return None
seen.add((module.name, name))
if name in module.ns.defs:
return module.ns.defs[name]
imported = module.imports.get(name)
if imported:
source, attr = imported
if _is_nitrostack(source):
return _WIDGET_OPTIONS if attr == "WidgetOptions" else _NITROSTACK
if not attr:
found = self._find(source)
return found.ns if found else None
found = self._find(source)
if found and attr in found.ns.defs:
return found.ns.defs[attr]
sub = self._find(f"{source}.{attr}") # ``from pkg import module``
return sub.ns if sub else None
return _WIDGET_OPTIONS if name == "WidgetOptions" else None
if not imported:
return None
source, attr = imported
if _is_nitrostack(source):
return self._sdk(attr)
found = self._find(source)
if not attr:
return found.ns if found else None
if found:
bound = self._binding(found, attr, seen)
if bound is not None:
return bound
sub = self._find(f"{source}.{attr}") # ``from pkg import module``
return sub.ns if sub else None

def _name(self, module: _Module, name: str) -> object:
bound = self._binding(module, name, set())
if bound is None and name not in module.ns.defs and name not in module.imports:
return self._sdk(name) if name in ("WidgetOptions", "widget") else None
return bound

def resolve(self, expr: ast.AST, module: _Module) -> object:
if isinstance(expr, ast.Name):
return self._name(module, expr.id)
if isinstance(expr, ast.Attribute):
base = self.resolve(expr.value, module)
if base is _NITROSTACK:
return _WIDGET_OPTIONS if expr.attr == "WidgetOptions" else _NITROSTACK
return self._sdk(expr.attr)
if isinstance(base, _Namespace):
if expr.attr in base.defs:
return base.defs[expr.attr]
Expand Down Expand Up @@ -236,9 +258,9 @@ def routes_in(self, module: _Module) -> List[str]:
found: List[Tuple[int, int, str]] = []
for node in ast.walk(module.tree):
for decorator in getattr(node, "decorator_list", []):
func = getattr(decorator, "func", None)
is_widget = (isinstance(func, ast.Name) and func.id == "widget") or (
isinstance(func, ast.Attribute) and func.attr == "widget"
is_widget = (
isinstance(decorator, ast.Call)
and self.resolve(decorator.func, module) is _WIDGET
)
if isinstance(decorator, ast.Call) and is_widget and decorator.args:
route = self._decorator_route(decorator.args[0], module)
Expand Down
98 changes: 98 additions & 0 deletions tests/test_validate_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,3 +308,101 @@ def test_unimported_widget_options_alias_and_attribute_forms(tmp_path: Path):
def test_a_file_that_does_not_parse_still_yields_its_literal_routes(tmp_path: Path):
src = "@widget('legacy')\ndef f(:\n pass\nWidgetOptions(route='legacy-options')\n"
assert sorted(_routes(tmp_path, {"broken.py": src})) == ["legacy", "legacy-options"]


def test_widget_options_reexported_by_a_project_package_is_followed(tmp_path: Path):
files = {
"shared/__init__.py": "from nitrostack import WidgetOptions, widget\n",
"tools.py": (
"from shared import WidgetOptions, widget\n"
"@widget(WidgetOptions(route='missing-card'))\ndef a(): ...\n"
),
}
assert sorted(_routes(tmp_path, files)) == ["missing-card"]


def test_reexport_through_an_alias_and_two_hops_is_followed(tmp_path: Path):
files = {
"core/options.py": "from nitrostack import WidgetOptions as Options, widget as ui\n",
"core/__init__.py": "from .options import Options, ui\n",
"shared.py": "from core import Options as Opts, ui as sdk_widget\n",
"tools.py": (
"from shared import Opts, sdk_widget\n"
"@sdk_widget('direct')\ndef a(): ...\n"
"@sdk_widget(Opts(route='via-options'))\ndef b(): ...\n"
),
}
assert sorted(_routes(tmp_path, files)) == ["direct", "via-options"]


def test_reexported_factory_is_still_a_factory(tmp_path: Path):
files = {
"shared/__init__.py": "from .helpers import panel\n",
"shared/helpers.py": FACTORY,
"tools.py": "from nitrostack import widget\nfrom shared import panel\n@widget(panel('reexported'))\ndef a(): ...\n",
}
assert _routes(tmp_path, files) == ["reexported"]


def test_import_cycle_between_reexporting_modules_terminates(tmp_path: Path):
files = {
"a.py": "from b import thing\n",
"b.py": "from a import thing\n",
"tools.py": "from a import thing\n@thing('x')\ndef f(): ...\n",
}
assert _routes(tmp_path, files) == []


def test_a_name_reexported_from_a_non_sdk_module_is_not_the_sdk(tmp_path: Path):
files = {
"shared/__init__.py": "from .own import WidgetOptions\n",
"shared/own.py": "class WidgetOptions:\n def __init__(self, route): ...\n",
"tools.py": "from shared import WidgetOptions\nWidgetOptions(route='not-a-widget')\n",
}
assert _routes(tmp_path, files) == []


def test_missing_html_check_runs_for_a_reexported_widget_options(tmp_path: Path):
(tmp_path / "shared").mkdir()
(tmp_path / "shared" / "__init__.py").write_text("from nitrostack import WidgetOptions, widget\n")
(tmp_path / "tools.py").write_text(
"from shared import WidgetOptions, widget\n"
"@widget(WidgetOptions(route='missing-card'))\ndef a(): ...\n"
)
issues = validate_widgets(str(tmp_path))
assert [i.severity for i in issues] == ["warning"]
assert "missing-card.html" in issues[0].message


@pytest.mark.parametrize(
"decorator, imports",
[
("@pytest.mark.widget('smoke')", "import pytest\n"),
("@marks.widget('smoke')", "from tests import marks\n"),
("@widget('smoke')", "from other_lib import widget\n"),
("@widget('smoke')", "def widget(name):\n return lambda f: f\n"),
("@app.widget('smoke')", "from fastapi import FastAPI\napp = FastAPI()\n"),
],
)
def test_widget_decorators_that_are_not_the_sdks_are_ignored(tmp_path: Path, decorator, imports):
src = f"{imports}\n{decorator}\ndef test_it(): ...\n"
assert _routes(tmp_path, {"test_tools.py": src}) == []
assert validate_widgets(str(tmp_path)) == []


def test_pytest_widget_marker_does_not_hide_the_real_widget(tmp_path: Path):
src = (
"import pytest\nfrom nitrostack import widget\n"
"@pytest.mark.widget('smoke')\ndef test_it(): ...\n"
"@widget('card')\ndef real(): ...\n"
)
assert _routes(tmp_path, {"tools.py": src}) == ["card"]


def test_qualified_sdk_decorators_are_still_collected(tmp_path: Path):
src = (
"import nitrostack\nimport nitrostack.decorators as deco\n"
"@nitrostack.widget('top')\ndef a(): ...\n"
"@deco.widget('submodule')\ndef b(): ...\n"
)
assert sorted(_routes(tmp_path, {"tools.py": src})) == ["submodule", "top"]
Loading