|
| 1 | +import time |
| 2 | + |
| 3 | +import anywidget |
| 4 | +import panel as pn |
| 5 | +import traitlets |
| 6 | +from panel.io.server import serve |
| 7 | +from playwright.sync_api import expect, Page |
| 8 | + |
| 9 | + |
| 10 | +class CounterWidget(anywidget.AnyWidget): |
| 11 | + """Counter widget example.""" |
| 12 | + |
| 13 | + _esm = """ |
| 14 | + export function render(view) { |
| 15 | + let getCount = () => view.model.get("count"); |
| 16 | + let button = document.createElement("button"); |
| 17 | + button.classList.add("counter-button"); |
| 18 | + button.innerHTML = `${getCount()}`; |
| 19 | + button.addEventListener("click", () => { |
| 20 | + view.model.set("count", getCount() + 1); |
| 21 | + view.model.save_changes(); |
| 22 | + }); |
| 23 | + view.model.on("change:count", () => { |
| 24 | + button.innerHTML = `${getCount()}`; |
| 25 | + }); |
| 26 | + view.el.appendChild(button); |
| 27 | + } |
| 28 | + """ |
| 29 | + _css = """ |
| 30 | + .counter-button {background-color: #ea580c;} |
| 31 | + .counter-button:hover {background-color: #9a3412;} |
| 32 | + """ |
| 33 | + count = traitlets.Int(default_value=0).tag(sync=True) |
| 34 | + |
| 35 | + |
| 36 | +def test_anywidget(page: Page) -> None: |
| 37 | + """Test anywidget button counter example.""" |
| 38 | + # Port to run the panel server on. |
| 39 | + port = 5006 |
| 40 | + |
| 41 | + # Create an anywidget button and make it a panel object. |
| 42 | + widget = CounterWidget() |
| 43 | + panels = pn.panel(widget) |
| 44 | + |
| 45 | + # Serve the button using panel, the time delay is necessary for panel to start and |
| 46 | + # serve the widget. |
| 47 | + serve(panels=panels, port=port, show=False) |
| 48 | + time.sleep(0.2) |
| 49 | + |
| 50 | + # Go to the page and locate the widget using playwright. |
| 51 | + page.goto(f"http://localhost:{port}") |
| 52 | + button = page.locator(selector=".counter-button") |
| 53 | + |
| 54 | + # Click the button and monitor the results. |
| 55 | + expect(button).to_have_count(0) |
| 56 | + button.click() |
| 57 | + expect(button).to_have_count(1) |
0 commit comments