|
| 1 | +"""Helpers for the app-tier tests: walk Dash layouts without a browser.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import re |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +from dash.development.base_component import Component |
| 8 | + |
| 9 | +ROOT = Path(__file__).resolve().parents[1] |
| 10 | +_ID_IN_SOURCE = re.compile(r"""\bid\s*=\s*["']([\w\-:.]+)["']""") |
| 11 | + |
| 12 | + |
| 13 | +def walk(node): |
| 14 | + """Yield every Dash component in a layout tree (children and component-valued props).""" |
| 15 | + if isinstance(node, Component): |
| 16 | + yield node |
| 17 | + for prop in node._prop_names: |
| 18 | + value = getattr(node, prop, None) |
| 19 | + if isinstance(value, Component | list | tuple): |
| 20 | + yield from walk(value) |
| 21 | + elif isinstance(node, list | tuple): |
| 22 | + for item in node: |
| 23 | + yield from walk(item) |
| 24 | + |
| 25 | + |
| 26 | +def component_ids(layout) -> set[str]: |
| 27 | + ids = set() |
| 28 | + for comp in walk(layout): |
| 29 | + cid = getattr(comp, "id", None) |
| 30 | + if isinstance(cid, str): |
| 31 | + ids.add(cid) |
| 32 | + return ids |
| 33 | + |
| 34 | + |
| 35 | +def find(layout, component_id: str) -> Component: |
| 36 | + for comp in walk(layout): |
| 37 | + if getattr(comp, "id", None) == component_id: |
| 38 | + return comp |
| 39 | + raise KeyError(component_id) |
| 40 | + |
| 41 | + |
| 42 | +def option_values(layout, component_id: str) -> list: |
| 43 | + """Values of a Select/SegmentedControl's `data` options, read from the live layout.""" |
| 44 | + return [opt["value"] for opt in find(layout, component_id).data] |
| 45 | + |
| 46 | + |
| 47 | +def ids_declared_in_source() -> set[str]: |
| 48 | + """Every literal id="..." in the app source, including components built at runtime.""" |
| 49 | + ids = set() |
| 50 | + for folder in ("pages", "layout"): |
| 51 | + for path in (ROOT / folder).glob("*.py"): |
| 52 | + ids.update(_ID_IN_SOURCE.findall(path.read_text())) |
| 53 | + ids.update(_ID_IN_SOURCE.findall((ROOT / "app.py").read_text())) |
| 54 | + return ids |
| 55 | + |
| 56 | + |
| 57 | +def callback_component_ids(dependencies: list[dict]) -> set[str]: |
| 58 | + """String component ids referenced by /_dash-dependencies (pattern-matching ids skipped).""" |
| 59 | + ids = set() |
| 60 | + for dep in dependencies: |
| 61 | + if not dep.get("no_output"): |
| 62 | + for output in dep["output"].strip(".").split("..."): |
| 63 | + ids.add(output.rsplit(".", 1)[0]) |
| 64 | + for item in dep["inputs"] + dep["state"]: |
| 65 | + if isinstance(item["id"], str): |
| 66 | + ids.add(item["id"]) |
| 67 | + return {i for i in ids if not i.startswith("{")} |
| 68 | + |
| 69 | + |
| 70 | +def figure_has_data(fig) -> bool: |
| 71 | + fig = json.loads(fig.to_json()) if hasattr(fig, "to_json") else fig |
| 72 | + return any(trace for trace in fig.get("data", [])) |
0 commit comments