This is an automated email from the ASF dual-hosted git repository.

sadpandajoe pushed a commit to branch fix-api-chart-screenshot-pivot-truncated
in repository https://gitbox.apache.org/repos/asf/superset.git

commit afef04ef570d3d0dad43b191057f2c999e9f7d24
Author: Joe Li <[email protected]>
AuthorDate: Sat Nov 14 20:55:56 2026 +0000

    fix(screenshot): un-clip table content before capturing a chart
    
    A long pivot table was cut off at the window height in chart screenshots.
    The pivot scrolls inside a class-styled overflow: auto div under a 
fixed-height
    parent, neither of which carries an inline style, so the generic expansion
    pass never reached them and .chart-container, the box a single-chart capture
    is clipped to, stayed at the window height.
    
    Add a separate script that, for a single-chart capture only, lifts the
    clipping nodes between each non-ag-Grid table and .chart-container. It does
    nothing for dashboard captures, charts inside a dashboard tile, ag-Grid 
hosts,
    or content without a table (legends, canvas hosts), and never touches
    ancestors of .chart-container. The generic pass is left unchanged: widening 
it
    to computed styles would also un-clip dashboard tiles and scrolling legends.
    
    Other table-shaped charts that match the same chain are covered only
    incidentally.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 superset/utils/screenshot_utils.py              |  49 ++++++
 superset/utils/webdriver.py                     |  19 +++
 tests/unit_tests/utils/test_screenshot_utils.py | 214 ++++++++++++++++++++----
 tests/unit_tests/utils/webdriver_test.py        | 106 +++++++++++-
 4 files changed, 349 insertions(+), 39 deletions(-)

diff --git a/superset/utils/screenshot_utils.py 
b/superset/utils/screenshot_utils.py
index 96fe1f32ee2..05cd5b09cfb 100644
--- a/superset/utils/screenshot_utils.py
+++ b/superset/utils/screenshot_utils.py
@@ -819,6 +819,55 @@ async (maxWaitMs) => {{
 """
 
 
+# A table-shaped chart (e.g. a pivot table) can be clipped by containers that
+# carry their height and overflow in stylesheet classes rather than inline
+# `style`, so neither `GENERIC_SCROLLABLE_DESCENDANT_SELECTOR` nor the
+# `.slice_container` reset above reaches them and `.chart-container`, the box a
+# single-chart capture is clipped to, stays at the window height.
+#
+# This is a separate script, run only when `.chart-container` is the capture
+# target, because the generic pass above cannot be widened to computed styles:
+# it also runs for dashboard captures, where tiles clip their charts on purpose
+# (`.dashboard-chart` is `overflow: hidden`), and it would un-clip scrolling
+# legends and other bounded widgets that hold no table. Hence the scope: only
+# the parent chain from each table up to `.chart-container`, only nodes that
+# actually clip, and a no-op unless exactly one chart container exists outside 
a
+# dashboard tile. ag-Grid is excluded (its own print layout handles it above).
+#
+# Nothing above `.chart-container` is touched. The chart-only page's shell
+# grows with its content, so lifting the chain below it is enough; shells that
+# pin ancestors to the viewport height (e.g. 6.1.0's `html, body, #app`) are 
out
+# of scope.
+EXPAND_CHART_TABLE_CLIP_JS = f"""
+() => {{
+    const containers = document.querySelectorAll('{CHART_CONTAINER_SELECTOR}');
+    if (containers.length !== 1 || containers[0].closest('.dashboard-chart')) 
{{
+        return;
+    }}
+    const chain = new Set();
+    containers[0].querySelectorAll('table, [role="table"]').forEach((table) => 
{{
+        if (table.closest('{AG_GRID_HOST_SELECTOR}')) {{ return; }}
+        for (let el = table.parentElement; el && el !== containers[0];
+             el = el.parentElement) {{
+            chain.add(el);
+        }}
+    }});
+    for (let pass = 0; pass < 5; pass += 1) {{
+        // Read every node before writing any, so each pass costs one layout.
+        const clipped = Array.from(chain).filter(
+            (el) => el.scrollHeight > el.clientHeight + 1
+        );
+        if (!clipped.length) {{ break; }}
+        clipped.forEach((el) => {{
+            el.style.overflow = 'visible';
+            el.style.height = 'auto';
+            el.style.maxHeight = 'none';
+        }});
+    }}
+}}
+"""
+
+
 def combine_screenshot_tiles(
     screenshot_tiles: list[bytes],
     *,
diff --git a/superset/utils/webdriver.py b/superset/utils/webdriver.py
index a5b6b247b03..940eec330a2 100644
--- a/superset/utils/webdriver.py
+++ b/superset/utils/webdriver.py
@@ -40,6 +40,7 @@ from superset.utils.screenshot_utils import (
     CHART_HOLDERS_READY_JS,
     DASHBOARD_ALL_CHART_HOLDERS_READY_JS,
     DASHBOARD_LAYOUT_READY_JS,
+    EXPAND_CHART_TABLE_CLIP_JS,
     EXPAND_SCROLLABLE_CONTENT_JS,
     EXPAND_SCROLLABLE_CONTENT_MAX_WAIT_SECONDS,
     FIND_ALL_CHART_HOLDER_STATES_JS,
@@ -544,6 +545,7 @@ class WebDriverPlaywright(WebDriverProxy):
         page: Page,
         log_context: str | None = None,
         report_execution_context: ReportExecutionContext | None = None,
+        element_name: str | None = None,
     ) -> None:
         """
         Un-clip chart content that is fully present in the DOM but visually
@@ -551,6 +553,10 @@ class WebDriverPlaywright(WebDriverProxy):
         than the space its dashboard tile gives it) before the page is
         captured.
 
+        When the capture target is a single chart (`element_name` is
+        "chart-container"), table content clipped by class-styled containers
+        is un-clipped as well; dashboard captures never run that extra step.
+
         The ag-Grid branch of this step polls for a stable row count, so it
         is bounded by the report's own deadline the same way every other
         wait in this method is, rather than an unconditional fixed sleep.
@@ -575,6 +581,16 @@ class WebDriverPlaywright(WebDriverProxy):
                 f" [{log_context}]" if log_context else "",
                 exc_info=True,
             )
+        if element_name != "chart-container":
+            return
+        try:
+            page.evaluate(EXPAND_CHART_TABLE_CLIP_JS)
+        except PlaywrightError:
+            logger.warning(
+                "Failed to expand clipped table content before screenshot%s",
+                f" [{log_context}]" if log_context else "",
+                exc_info=True,
+            )
 
     @staticmethod
     def _wait_for_charts_ready(  # noqa: C901
@@ -1131,6 +1147,7 @@ class WebDriverPlaywright(WebDriverProxy):
                     page,
                     log_context=log_context,
                     report_execution_context=report_execution_context,
+                    element_name=element_name,
                 )
 
                 # Detect large dashboards and use tiled screenshots if enabled
@@ -1304,6 +1321,7 @@ class WebDriverPlaywright(WebDriverProxy):
                             page,
                             log_context=log_context,
                             report_execution_context=report_execution_context,
+                            element_name=element_name,
                         )
                         if selenium_animation_wait > 0:
                             if report_execution_context:
@@ -1376,6 +1394,7 @@ class WebDriverPlaywright(WebDriverProxy):
                         page,
                         log_context=log_context,
                         report_execution_context=report_execution_context,
+                        element_name=element_name,
                     )
                     if selenium_animation_wait > 0:
                         if report_execution_context:
diff --git a/tests/unit_tests/utils/test_screenshot_utils.py 
b/tests/unit_tests/utils/test_screenshot_utils.py
index d501255cd83..0cb079f751f 100644
--- a/tests/unit_tests/utils/test_screenshot_utils.py
+++ b/tests/unit_tests/utils/test_screenshot_utils.py
@@ -22,6 +22,7 @@ import subprocess
 import zlib
 from collections.abc import Callable, Iterator
 from contextlib import contextmanager
+from pathlib import Path
 from typing import TYPE_CHECKING
 from unittest.mock import MagicMock, patch
 from uuid import UUID
@@ -2616,8 +2617,10 @@ def 
test_expand_scrollable_content_resolves_nested_ancestor_clip() -> None:
 # `.shell-*` is the app shell above `.chart-container`: a growable flex `body`
 # (`min-height: 100vh`, GlobalStyles) over flex-column wrappers that fill it, 
down
 # to the ExploreChartPanel wrapper (`flex: 1; min-height: 0; overflow: 
hidden`).
-# No ancestor has an explicit height, so the wrapper grows with its content. 
(The
-# 6.1.0 shell pinned `html, body, #app` to `height: 100%`, which did clamp it.)
+# There is no fixed viewport-height ancestor clamp (percentage heights remain, 
but
+# they resolve against content-driven parents), so the wrapper grows with its
+# content. The 6.1.0 shell pinned `html, body, #app` to `height: 100%`, which 
did
+# clamp it; that layout is out of scope here.
 _CHART_CAPTURE_FIXTURE_CSS = """
 html { height: 100%; }
 body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; }
@@ -2637,6 +2640,10 @@ body { margin: 0; min-height: 100vh; display: flex; 
flex-direction: column; }
 .dashboard-chart .slice_container { height: 400px; }
 .pivot-styles { margin: 16px; height: 568px; width: 760px; }
 .pivot-wrapper { height: 100%; max-width: inherit; overflow: auto; }
+.handlebars-styles { height: 568px; width: 760px; padding: 16px;
+  overflow: auto; }
+.ag-parent { height: 568px; }
+.ag-host { height: 100%; overflow: auto; }
 .legend-viewport { max-height: 100px; overflow-x: hidden; overflow-y: auto;
   width: 100%; }
 td { height: 24px; padding: 0 4px; border: 1px solid #888; font: 12px 
sans-serif; }
@@ -2679,6 +2686,28 @@ def _inline_overflow_chart_body(n_rows: int) -> str:
     )
 
 
+def _handlebars_style_chart_body(n_rows: int) -> str:
+    """A class-styled fixed-height scroller around a user-templated table, the
+    shape of the Handlebars chart. Covered only incidentally: the table chain
+    policy does not know which chart type it is looking at."""
+    return (
+        '<div class="handlebars-styles">'
+        f'<table 
id="content"><tbody>{_chart_capture_rows(n_rows)}</tbody></table>'
+        "</div>"
+    )
+
+
+def _ag_grid_chart_body(n_rows: int) -> str:
+    """A table inside an ag-Grid host whose box is class-styled. No grid API is
+    attached, so the print-layout mechanism has nothing to act on and any 
change
+    to the box would have to come from the table-chain pass."""
+    return (
+        '<div class="ag-parent"><div class="ag-host" 
data-themed-ag-grid="true">'
+        f'<table 
id="content"><tbody>{_chart_capture_rows(n_rows)}</tbody></table>'
+        "</div></div>"
+    )
+
+
 def _legend_and_canvas_chart_body(_n_rows: int) -> str:
     """Intentionally bounded, non-table content: a legend that scrolls inside a
     `max-height` box (class-styled, like the ECharts legend viewport) and a
@@ -2739,6 +2768,37 @@ def _chart_capture_page(html: str) -> Iterator["Page"]:
             browser.close()
 
 
+def _measure_markers(page: "Page") -> dict[str, tuple[int, int]]:
+    """Top and bottom of the first, middle and last row, relative to the top of
+    `.chart-container`."""
+    top = page.locator(".chart-container").bounding_box()
+    assert top is not None
+    markers = {}
+    for name in ("first", "middle", "last"):
+        box = page.locator(f"#row-{name}").bounding_box()
+        assert box is not None
+        markers[name] = (
+            round(box["y"] - top["y"]),
+            round(box["y"] + box["height"] - top["y"]),
+        )
+    return markers
+
+
+def _assert_markers_painted(png: bytes, markers: dict[str, tuple[int, int]]) 
-> None:
+    image = Image.open(io.BytesIO(png)).convert("L")
+    for name, (y0, y1) in markers.items():
+        assert image.height >= y1, (
+            f"screenshot is {image.height}px tall but the {name} row ends 
{y1}px "
+            "below the top of the chart: rows are cut off"
+        )
+        dark = image.crop((0, y0, 200, y1)).point(lambda v: 255 if v < 80 else 
0)
+        painted = sum(1 for v in dark.getdata() if v) / (200 * (y1 - y0))
+        assert painted > 0.5, (
+            f"the {name} row (y={y0}..{y1}) is not painted in the capture "
+            f"({painted:.0%} of its marker cell)"
+        )
+
+
 @pytest.mark.parametrize(
     ("body", "n_rows", "layout"),
     [
@@ -2756,6 +2816,13 @@ def _chart_capture_page(html: str) -> Iterator["Page"]:
             "shell",
             id="control-long-inline-overflow-scroller-in-shell",
         ),
+        # Incidental coverage: the same policy also un-clips this table shape.
+        pytest.param(
+            _handlebars_style_chart_body,
+            _CHART_CAPTURE_ROWS,
+            "shell",
+            id="incidental-handlebars-style-table",
+        ),
         # The reported bug: a long pivot table.
         pytest.param(
             _pivot_chart_body,
@@ -2788,41 +2855,24 @@ def 
test_chart_container_screenshot_captures_whole_content(
 
     with _chart_capture_page(_wrap_chart_capture(body(n_rows), layout)) as 
page:
         chart_container = page.locator(".chart-container")
-        WebDriverPlaywright._expand_scrollable_content(page)
-
-        top = chart_container.bounding_box()
-        assert top is not None
-        markers = {}
-        for name in ("first", "middle", "last"):
-            box = page.locator(f"#row-{name}").bounding_box()
-            assert box is not None
-            markers[name] = (
-                round(box["y"] - top["y"]),
-                round(box["y"] + box["height"] - top["y"]),
-            )
-
+        WebDriverPlaywright._expand_scrollable_content(
+            page, element_name="chart-container"
+        )
+        markers = _measure_markers(page)
         png = WebDriverPlaywright._get_screenshot(
             page, chart_container, "chart-container"
         )
 
-    image = Image.open(io.BytesIO(png)).convert("L")
-    for name, (y0, y1) in markers.items():
-        assert image.height >= y1, (
-            f"screenshot is {image.height}px tall but the {name} row ends 
{y1}px "
-            "below the top of the chart: rows are cut off"
-        )
-        dark = image.crop((0, y0, 200, y1)).point(lambda v: 255 if v < 80 else 
0)
-        painted = sum(1 for v in dark.getdata() if v) / (200 * (y1 - y0))
-        assert painted > 0.5, (
-            f"the {name} row (y={y0}..{y1}) is not painted in the capture "
-            f"({painted:.0%} of its marker cell)"
-        )
+    _assert_markers_painted(png, markers)
 
 
-def test_expansion_leaves_dashboard_chart_clip_alone() -> None:
[email protected]("element_name", ["standalone", "chart-container"])
+def test_expansion_leaves_dashboard_chart_clip_alone(element_name: str) -> 
None:
     """A dashboard tile clips its chart on purpose (`.dashboard-chart` is
     `overflow: hidden` at a fixed height). The expansion script also runs for
-    dashboard captures, so it must not un-clip the tile or resize it."""
+    dashboard captures, so it must not un-clip the tile or resize it: the
+    table pass is not run for a dashboard target, and refuses on its own when
+    pointed at a chart inside a tile."""
     from superset.utils.webdriver import WebDriverPlaywright
 
     html = _wrap_chart_capture(_pivot_chart_body(_CHART_CAPTURE_ROWS), 
"dashboard")
@@ -2838,7 +2888,7 @@ def test_expansion_leaves_dashboard_chart_clip_alone() -> 
None:
             };
         }"""
         before = page.evaluate(measure)
-        WebDriverPlaywright._expand_scrollable_content(page)
+        WebDriverPlaywright._expand_scrollable_content(page, 
element_name=element_name)
         after = page.evaluate(measure)
 
     assert before["tileOverflow"] == "hidden"
@@ -2896,9 +2946,111 @@ def 
test_expansion_leaves_bounded_non_table_widgets_alone() -> None:
             };
         }"""
         before = page.evaluate(measure)
-        WebDriverPlaywright._expand_scrollable_content(page)
+        WebDriverPlaywright._expand_scrollable_content(
+            page, element_name="chart-container"
+        )
         after = page.evaluate(measure)
 
     # The legend really does scroll before, so "unchanged" is meaningful.
     assert before["legendScroll"] > before["legendClient"]
     assert after == before
+
+
+def test_table_pass_excludes_ag_grid_hosts() -> None:
+    """A table inside an ag-Grid host is not the table pass's business: ag-Grid
+    is un-clipped through its own print layout, so the host's box and its
+    parent's must stay as they are."""
+    from superset.utils.webdriver import WebDriverPlaywright
+
+    html = _wrap_chart_capture(_ag_grid_chart_body(_CHART_CAPTURE_ROWS), 
"shell")
+    with _chart_capture_page(html) as page:
+        measure = """() => {
+            const host = document.querySelector('.ag-host');
+            return {
+                hostOverflow: getComputedStyle(host).overflowY,
+                hostHeight: host.getBoundingClientRect().height,
+                parentHeight: 
host.parentElement.getBoundingClientRect().height,
+                chartHeight: document.querySelector('.chart-container')
+                    .getBoundingClientRect().height,
+            };
+        }"""
+        before = page.evaluate(measure)
+        WebDriverPlaywright._expand_scrollable_content(
+            page, element_name="chart-container"
+        )
+        after = page.evaluate(measure)
+
+    # The host really does clip before, so "unchanged" is meaningful.
+    assert before["hostOverflow"] == "auto"
+    assert after == before
+
+
+def test_tiled_capture_of_tall_chart_paints_whole_content(tmp_path: Path) -> 
None:
+    """The production `get_screenshot` decision, with the tiling thresholds
+    lowered so a modest fixture takes the tiled branch: once the pivot is
+    un-clipped the chart is tall enough for `take_tiled_screenshot`, and the
+    combined image must still reach and paint the first, middle and last row.
+
+    Runs against a local HTML file in real Chromium, with the app config and
+    the browser manager standing in for the Flask app and the worker's
+    long-lived browser."""
+    pytest.importorskip("playwright.sync_api")
+    from playwright.sync_api import Error as PlaywrightError, sync_playwright
+
+    from superset.utils import webdriver
+    from superset.utils.webdriver import WebDriverPlaywright
+
+    html = _wrap_chart_capture(_pivot_chart_body(120), "bare")
+    page_file = tmp_path / "chart.html"
+    page_file.write_text(html)
+
+    config = {
+        "WEBDRIVER_OPTION_ARGS": [],
+        "WEBDRIVER_WINDOW": {"pixel_density": 1},
+        "SCREENSHOT_PLAYWRIGHT_DEFAULT_TIMEOUT": 30000,
+        "SCREENSHOT_PLAYWRIGHT_WAIT_EVENT": "load",
+        "SCREENSHOT_SELENIUM_HEADSTART": 0,
+        "SCREENSHOT_SELENIUM_ANIMATION_WAIT": 0,
+        "SCREENSHOT_REPLACE_UNEXPECTED_ERRORS": False,
+        "SCREENSHOT_LOCATE_WAIT": 10,
+        "SCREENSHOT_LOAD_WAIT": 10,
+        "SCREENSHOT_TILED_ENABLED": True,
+        "SCREENSHOT_TILED_CHART_THRESHOLD": 20,
+        "SCREENSHOT_TILED_HEIGHT_THRESHOLD": 1000,
+        "SCREENSHOT_TILED_VIEWPORT_HEIGHT": 1500,
+    }
+
+    with sync_playwright() as playwright:
+        try:
+            browser = playwright.chromium.launch()
+        except PlaywrightError as ex:
+            if "Executable doesn't exist" in str(ex):
+                pytest.skip(f"Chromium is not installed for Playwright: {ex}")
+            raise
+        try:
+            measuring_page = browser.new_page(viewport={"width": 800, 
"height": 600})
+            measuring_page.set_content(html)
+            WebDriverPlaywright._expand_scrollable_content(
+                measuring_page, element_name="chart-container"
+            )
+            markers = _measure_markers(measuring_page)
+
+            browser_manager = MagicMock()
+            browser_manager.get_browser.return_value = browser
+            with (
+                patch.object(webdriver, "app", MagicMock(config=config)),
+                patch.object(
+                    webdriver,
+                    "take_tiled_screenshot",
+                    wraps=webdriver.take_tiled_screenshot,
+                ) as tiled,
+            ):
+                png = WebDriverPlaywright(
+                    "chrome", (800, 600), browser_manager=browser_manager
+                ).get_screenshot(page_file.as_uri(), "chart-container")
+        finally:
+            browser.close()
+
+    tiled.assert_called_once()
+    assert png is not None
+    _assert_markers_painted(png, markers)
diff --git a/tests/unit_tests/utils/webdriver_test.py 
b/tests/unit_tests/utils/webdriver_test.py
index e7461f9e3ab..a6e6e36312b 100644
--- a/tests/unit_tests/utils/webdriver_test.py
+++ b/tests/unit_tests/utils/webdriver_test.py
@@ -584,11 +584,22 @@ class TestWebDriverPlaywrightFallback:
             "http://example.com";, wait_until="networkidle"
         )
 
+    @pytest.mark.parametrize(
+        ("element_name", "expected_order"),
+        [
+            # Dashboards never run the table-clip pass.
+            ("standalone", ["expand", "expand", "capture"]),
+            (
+                "chart-container",
+                ["expand", "table_clip", "expand", "table_clip", "capture"],
+            ),
+        ],
+    )
     @patch("superset.utils.webdriver.PLAYWRIGHT_AVAILABLE", True)
     @patch("superset.utils.webdriver._browser_manager")
     @patch("superset.utils.webdriver.app")
     def test_get_screenshot_expands_scrollable_content_before_capture(
-        self, mock_app, mock_browser_manager
+        self, mock_app, mock_browser_manager, element_name, expected_order
     ):
         """A dense table taller than its dashboard tile renders fully in the
         DOM but is visually clipped by a fixed height + internal scrollbar.
@@ -599,8 +610,15 @@ class TestWebDriverPlaywrightFallback:
         twice: once before the tiling decision, and again after chart
         readiness confirms every ag-Grid has actually mounted its API
         (@aminghadersohi's review on #43979 -- the earlier call can miss a
-        grid whose GridReady hasn't fired yet)."""
-        from superset.utils.screenshot_utils import 
EXPAND_SCROLLABLE_CONTENT_JS
+        grid whose GridReady hasn't fired yet).
+
+        The generic script runs for every capture target. The table-clip
+        script runs only for a single-chart capture (`chart-container`), at
+        both expansion points, and never for a dashboard (`standalone`)."""
+        from superset.utils.screenshot_utils import (
+            EXPAND_CHART_TABLE_CLIP_JS,
+            EXPAND_SCROLLABLE_CONTENT_JS,
+        )
 
         mock_user = MagicMock()
         mock_user.username = "test_user"
@@ -634,20 +652,27 @@ class TestWebDriverPlaywrightFallback:
             if script == EXPAND_SCROLLABLE_CONTENT_JS:
                 capture_order.append("expand")
                 return None
+            if script == EXPAND_CHART_TABLE_CLIP_JS:
+                capture_order.append("table_clip")
+                return None
             # FIND_CHART_HOLDER_STATES_JS (readiness diagnostics) expects an
             # iterable of holder states; every other call in this (non-tiled,
             # non-report) path is only ever logged, not branched on.
             return []
 
         mock_page.evaluate.side_effect = evaluate_side_effect
-        mock_page.screenshot.side_effect = lambda **k: (
-            capture_order.append("capture") or b"fake_screenshot"
-        )
+
+        def capture(**_kwargs):
+            capture_order.append("capture")
+            return b"fake_screenshot"
+
+        mock_page.screenshot.side_effect = capture
+        mock_element.screenshot.side_effect = capture
 
         with patch.object(WebDriverPlaywright, "auth", 
return_value=mock_context):
             driver = WebDriverPlaywright("chrome")
             result = driver.get_screenshot(
-                "http://example.com";, "standalone", mock_user
+                "http://example.com";, element_name, mock_user
             )
 
         assert result == b"fake_screenshot"
@@ -660,7 +685,13 @@ class TestWebDriverPlaywrightFallback:
         # A concrete millisecond budget is passed as the second arg (bounded
         # by the report deadline when one exists; a fixed default otherwise).
         assert all(isinstance(call.args[1], float) for call in expand_calls)
-        assert capture_order == ["expand", "expand", "capture"]
+        # The table-clip script takes no wait budget: it has nothing to poll.
+        assert all(
+            call.args == (EXPAND_CHART_TABLE_CLIP_JS,)
+            for call in mock_page.evaluate.call_args_list
+            if call.args[0] == EXPAND_CHART_TABLE_CLIP_JS
+        )
+        assert capture_order == expected_order
 
     @patch("superset.utils.webdriver.PLAYWRIGHT_AVAILABLE", True)
     @patch("superset.utils.webdriver._browser_manager")
@@ -803,6 +834,65 @@ class TestWebDriverPlaywrightErrorHandling:
             EXPAND_SCROLLABLE_CONTENT_MAX_WAIT_SECONDS * 1000,
         )
 
+    def 
test_expand_scrollable_content_runs_table_clip_only_for_chart_container(
+        self,
+    ):
+        """The table-clip script is gated on the capture target: a dashboard
+        (`standalone`) or an unspecified target gets the generic script 
only."""
+        from superset.utils.screenshot_utils import (
+            EXPAND_CHART_TABLE_CLIP_JS,
+            EXPAND_SCROLLABLE_CONTENT_JS,
+        )
+
+        for element_name in (None, "standalone"):
+            mock_page = MagicMock()
+            WebDriverPlaywright._expand_scrollable_content(
+                mock_page, element_name=element_name
+            )
+            scripts = [call.args[0] for call in 
mock_page.evaluate.call_args_list]
+            assert scripts == [EXPAND_SCROLLABLE_CONTENT_JS]
+
+        mock_page = MagicMock()
+        WebDriverPlaywright._expand_scrollable_content(
+            mock_page, element_name="chart-container"
+        )
+        scripts = [call.args[0] for call in mock_page.evaluate.call_args_list]
+        assert scripts == [EXPAND_SCROLLABLE_CONTENT_JS, 
EXPAND_CHART_TABLE_CLIP_JS]
+
+    @patch("superset.utils.webdriver.logger")
+    def test_expand_scrollable_content_failures_are_independent(self, 
mock_logger):
+        """Neither script's failure aborts the screenshot or skips the other:
+        a clipped-but-present capture beats none at all."""
+        from superset.utils.screenshot_utils import (
+            EXPAND_CHART_TABLE_CLIP_JS,
+            EXPAND_SCROLLABLE_CONTENT_JS,
+        )
+        from superset.utils.webdriver import PlaywrightError
+
+        for failing_script, warning in (
+            (
+                EXPAND_SCROLLABLE_CONTENT_JS,
+                "Failed to expand scrollable chart content",
+            ),
+            (EXPAND_CHART_TABLE_CLIP_JS, "Failed to expand clipped table 
content"),
+        ):
+            mock_logger.reset_mock()
+            mock_page = MagicMock()
+
+            def evaluate(script, *_args, _failing=failing_script):
+                if script == _failing:
+                    raise PlaywrightError("boom")
+
+            mock_page.evaluate.side_effect = evaluate
+
+            WebDriverPlaywright._expand_scrollable_content(
+                mock_page, element_name="chart-container"
+            )
+
+            assert mock_page.evaluate.call_count == 2
+            mock_logger.warning.assert_called_once()
+            assert warning in mock_logger.warning.call_args.args[0]
+
     def test_expand_scrollable_content_bounds_wait_to_report_deadline(self):
         """This step must respect the report's remaining budget like every
         other wait in the capture path, rather than an unconditional fixed

Reply via email to